Debian Codegraph @

core/java/android/app/ActivityThread.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package android.app;
18
19 import static android.app.ActivityManager.PROCESS_STATE_UNKNOWN;
20 import static android.app.ConfigurationController.createNewConfigAndUpdateIfNotNull;
21 import static android.app.WindowConfiguration.WINDOWING_MODE_PINNED;
22 import static android.app.WindowConfiguration.WINDOWING_MODE_UNDEFINED;
23 import static android.app.servertransaction.ActivityLifecycleItem.ON_CREATE;
24 import static android.app.servertransaction.ActivityLifecycleItem.ON_DESTROY;
25 import static android.app.servertransaction.ActivityLifecycleItem.ON_PAUSE;
26 import static android.app.servertransaction.ActivityLifecycleItem.ON_RESUME;
27 import static android.app.servertransaction.ActivityLifecycleItem.ON_START;
28 import static android.app.servertransaction.ActivityLifecycleItem.ON_STOP;
29 import static android.app.servertransaction.ActivityLifecycleItem.PRE_ON_CREATE;
30 import static android.content.ContentResolver.DEPRECATE_DATA_COLUMNS;
31 import static android.content.ContentResolver.DEPRECATE_DATA_PREFIX;
32 import static android.view.Display.DEFAULT_DISPLAY;
33 import static android.view.Display.INVALID_DISPLAY;
34 import static android.window.ConfigurationHelper.freeTextLayoutCachesIfNeeded;
35 import static android.window.ConfigurationHelper.isDifferentDisplay;
36 import static android.window.ConfigurationHelper.shouldUpdateResources;
37
38 import static com.android.internal.annotations.VisibleForTesting.Visibility.PACKAGE;
39 import static com.android.internal.os.SafeZipPathValidatorCallback.VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL;
40
41 import android.annotation.NonNull;
42 import android.annotation.Nullable;
43 import android.app.RemoteServiceException.BadForegroundServiceNotificationException;
44 import android.app.RemoteServiceException.CannotPostForegroundServiceNotificationException;
45 import android.app.RemoteServiceException.CrashedByAdbException;
46 import android.app.RemoteServiceException.ForegroundServiceDidNotStartInTimeException;
47 import android.app.RemoteServiceException.MissingRequestPasswordComplexityPermissionException;
48 import android.app.assist.AssistContent;
49 import android.app.assist.AssistStructure;
50 import android.app.backup.BackupAgent;
51 import android.app.compat.CompatChanges;
52 import android.app.servertransaction.ActivityLifecycleItem;
53 import android.app.servertransaction.ActivityLifecycleItem.LifecycleState;
54 import android.app.servertransaction.ActivityRelaunchItem;
55 import android.app.servertransaction.ActivityResultItem;
56 import android.app.servertransaction.ClientTransaction;
57 import android.app.servertransaction.ClientTransactionItem;
58 import android.app.servertransaction.PauseActivityItem;
59 import android.app.servertransaction.PendingTransactionActions;
60 import android.app.servertransaction.PendingTransactionActions.StopInfo;
61 import android.app.servertransaction.ResumeActivityItem;
62 import android.app.servertransaction.TransactionExecutor;
63 import android.app.servertransaction.TransactionExecutorHelper;
64 import android.bluetooth.BluetoothFrameworkInitializer;
65 import android.compat.annotation.UnsupportedAppUsage;
66 import android.content.AttributionSource;
67 import android.content.AutofillOptions;
68 import android.content.BroadcastReceiver;
69 import android.content.ComponentCallbacks2;
70 import android.content.ComponentName;
71 import android.content.ContentCaptureOptions;
72 import android.content.ContentProvider;
73 import android.content.ContentResolver;
74 import android.content.Context;
75 import android.content.IContentProvider;
76 import android.content.IIntentReceiver;
77 import android.content.Intent;
78 import android.content.pm.ActivityInfo;
79 import android.content.pm.ApplicationInfo;
80 import android.content.pm.ComponentInfo;
81 import android.content.pm.IPackageManager;
82 import android.content.pm.InstrumentationInfo;
83 import android.content.pm.PackageInfo;
84 import android.content.pm.PackageManager;
85 import android.content.pm.PackageManager.NameNotFoundException;
86 import android.content.pm.ParceledListSlice;
87 import android.content.pm.PermissionInfo;
88 import android.content.pm.ProviderInfo;
89 import android.content.pm.ProviderInfoList;
90 import android.content.pm.ServiceInfo;
91 import android.content.res.AssetManager;
92 import android.content.res.CompatibilityInfo;
93 import android.content.res.Configuration;
94 import android.content.res.Resources;
95 import android.content.res.loader.ResourcesLoader;
96 import android.database.sqlite.SQLiteDatabase;
97 import android.database.sqlite.SQLiteDebug;
98 import android.database.sqlite.SQLiteDebug.DbStats;
99 import android.graphics.Bitmap;
100 import android.graphics.Canvas;
101 import android.graphics.HardwareRenderer;
102 import android.graphics.Typeface;
103 import android.hardware.display.DisplayManagerGlobal;
104 import android.media.MediaFrameworkInitializer;
105 import android.media.MediaFrameworkPlatformInitializer;
106 import android.media.MediaServiceManager;
107 import android.net.ConnectivityManager;
108 import android.net.Proxy;
109 import android.net.TrafficStats;
110 import android.net.Uri;
111 import android.nfc.NfcFrameworkInitializer;
112 import android.nfc.NfcServiceManager;
113 import android.os.AsyncTask;
114 import android.os.Binder;
115 import android.os.BluetoothServiceManager;
116 import android.os.Build;
117 import android.os.Bundle;
118 import android.os.CancellationSignal;
119 import android.os.Debug;
120 import android.os.Environment;
121 import android.os.FileUtils;
122 import android.os.GraphicsEnvironment;
123 import android.os.Handler;
124 import android.os.HandlerExecutor;
125 import android.os.IBinder;
126 import android.os.ICancellationSignal;
127 import android.os.LocaleList;
128 import android.os.Looper;
129 import android.os.Message;
130 import android.os.MessageQueue;
131 import android.os.Parcel;
132 import android.os.ParcelFileDescriptor;
133 import android.os.PersistableBundle;
134 import android.os.Process;
135 import android.os.RemoteCallback;
136 import android.os.RemoteException;
137 import android.os.ServiceManager;
138 import android.os.SharedMemory;
139 import android.os.StatsFrameworkInitializer;
140 import android.os.StatsServiceManager;
141 import android.os.StrictMode;
142 import android.os.SystemClock;
143 import android.os.SystemProperties;
144 import android.os.TelephonyServiceManager;
145 import android.os.Trace;
146 import android.os.UserHandle;
147 import android.os.UserManager;
148 import android.permission.IPermissionManager;
149 import android.provider.BlockedNumberContract;
150 import android.provider.CalendarContract;
151 import android.provider.CallLog;
152 import android.provider.ContactsContract;
153 import android.provider.Downloads;
154 import android.provider.FontsContract;
155 import android.provider.Settings;
156 import android.renderscript.RenderScriptCacheDir;
157 import android.security.NetworkSecurityPolicy;
158 import android.security.net.config.NetworkSecurityConfigProvider;
159 import android.system.ErrnoException;
160 import android.system.OsConstants;
161 import android.system.StructStat;
162 import android.telephony.TelephonyFrameworkInitializer;
163 import android.util.AndroidRuntimeException;
164 import android.util.ArrayMap;
165 import android.util.DisplayMetrics;
166 import android.util.EventLog;
167 import android.util.Log;
168 import android.util.LogPrinter;
169 import android.util.MergedConfiguration;
170 import android.util.Pair;
171 import android.util.PrintWriterPrinter;
172 import android.util.Slog;
173 import android.util.SparseArray;
174 import android.util.SuperNotCalledException;
175 import android.util.UtilConfig;
176 import android.util.proto.ProtoOutputStream;
177 import android.view.Choreographer;
178 import android.view.Display;
179 import android.view.DisplayAdjustments;
180 import android.view.SurfaceControl;
181 import android.view.ThreadedRenderer;
182 import android.view.View;
183 import android.view.ViewDebug;
184 import android.view.ViewManager;
185 import android.view.ViewRootImpl;
186 import android.view.ViewTreeObserver;
187 import android.view.Window;
188 import android.view.WindowManager;
189 import android.view.WindowManagerGlobal;
190 import android.view.autofill.AutofillId;
191 import android.view.contentcapture.IContentCaptureManager;
192 import android.view.contentcapture.IContentCaptureOptionsCallback;
193 import android.view.translation.TranslationSpec;
194 import android.view.translation.UiTranslationSpec;
195 import android.webkit.WebView;
196 import android.window.SizeConfigurationBuckets;
197 import android.window.SplashScreen;
198 import android.window.SplashScreenView;
199 import android.window.WindowProviderService;
200
201 import com.android.internal.annotations.GuardedBy;
202 import com.android.internal.annotations.VisibleForTesting;
203 import com.android.internal.app.IVoiceInteractor;
204 import com.android.internal.content.ReferrerIntent;
205 import com.android.internal.os.BinderCallsStats;
206 import com.android.internal.os.BinderInternal;
207 import com.android.internal.os.RuntimeInit;
208 import com.android.internal.os.SafeZipPathValidatorCallback;
209 import com.android.internal.os.SomeArgs;
210 import com.android.internal.policy.DecorView;
211 import com.android.internal.util.ArrayUtils;
212 import com.android.internal.util.FastPrintWriter;
213 import com.android.internal.util.Preconditions;
214 import com.android.internal.util.function.pooled.PooledLambda;
215 import com.android.org.conscrypt.OpenSSLSocketImpl;
216 import com.android.org.conscrypt.TrustedCertificateStore;
217 import com.android.server.am.MemInfoDumpProto;
218
219 import dalvik.system.AppSpecializationHooks;
220 import dalvik.system.CloseGuard;
221 import dalvik.system.VMDebug;
222 import dalvik.system.VMRuntime;
223 import dalvik.system.ZipPathValidator;
224
225 import libcore.io.ForwardingOs;
226 import libcore.io.IoUtils;
227 import libcore.io.Os;
228 import libcore.net.event.NetworkEventDispatcher;
229
230 import org.apache.harmony.dalvik.ddmc.DdmVmInternal;
231
232 import java.io.File;
233 import java.io.FileDescriptor;
234 import java.io.FileNotFoundException;
235 import java.io.FileOutputStream;
236 import java.io.IOException;
237 import java.io.PrintWriter;
238 import java.lang.ref.WeakReference;
239 import java.lang.reflect.Method;
240 import java.net.InetAddress;
241 import java.nio.file.DirectoryStream;
242 import java.nio.file.Files;
243 import java.nio.file.Path;
244 import java.nio.file.StandardCopyOption;
245 import java.text.DateFormat;
246 import java.util.ArrayList;
247 import java.util.Arrays;
248 import java.util.Collections;
249 import java.util.List;
250 import java.util.Map;
251 import java.util.Objects;
252 import java.util.TimeZone;
253 import java.util.concurrent.Executor;
254 import java.util.concurrent.atomic.AtomicInteger;
255 import java.util.function.Consumer;
256
257 /**
258 * This manages the execution of the main thread in an
259 * application process, scheduling and executing activities,
260 * broadcasts, and other operations on it as the activity
261 * manager requests.
262 *
263 * {@hide}
264 */
265 public final class ActivityThread extends ClientTransactionHandler
266 implements ActivityThreadInternal {
267 /** @hide */
268 public static final String TAG = "ActivityThread";
269 private static final android.graphics.Bitmap.Config THUMBNAIL_FORMAT = Bitmap.Config.RGB_565;
270 static final boolean localLOGV = false;
271 static final boolean DEBUG_MESSAGES = false;
272 /** @hide */
273 public static final boolean DEBUG_BROADCAST = false;
274 private static final boolean DEBUG_RESULTS = false;
275 private static final boolean DEBUG_BACKUP = false;
276 public static final boolean DEBUG_CONFIGURATION = false;
277 private static final boolean DEBUG_SERVICE = false;
278 public static final boolean DEBUG_MEMORY_TRIM = false;
279 private static final boolean DEBUG_PROVIDER = false;
280 public static final boolean DEBUG_ORDER = false;
281 private static final long MIN_TIME_BETWEEN_GCS = 5*1000;
282 /**
283 * The delay to release the provider when it has no more references. It reduces the number of
284 * transactions for acquiring and releasing provider if the client accesses the provider
285 * frequently in a short time.
286 */
287 private static final long CONTENT_PROVIDER_RETAIN_TIME = 1000;
288 private static final int SQLITE_MEM_RELEASED_EVENT_LOG_TAG = 75003;
289
290 /** Type for IActivityManager.serviceDoneExecuting: anonymous operation */
291 public static final int SERVICE_DONE_EXECUTING_ANON = 0;
292 /** Type for IActivityManager.serviceDoneExecuting: done with an onStart call */
293 public static final int SERVICE_DONE_EXECUTING_START = 1;
294 /** Type for IActivityManager.serviceDoneExecuting: done stopping (destroying) service */
295 public static final int SERVICE_DONE_EXECUTING_STOP = 2;
296
297 /** Use foreground GC policy (less pause time) and higher JIT weight. */
298 private static final int VM_PROCESS_STATE_JANK_PERCEPTIBLE = 0;
299 /** Use background GC policy and default JIT threshold. */
300 private static final int VM_PROCESS_STATE_JANK_IMPERCEPTIBLE = 1;
301
302 /** The delay time for retrying to request DirectActions. */
303 private static final long REQUEST_DIRECT_ACTIONS_RETRY_TIME_MS = 200;
304 /** The max count for retrying to request DirectActions. */
305 private static final int REQUEST_DIRECT_ACTIONS_RETRY_MAX_COUNT = 7;
306
307 /**
308 * Denotes an invalid sequence number corresponding to a process state change.
309 */
310 public static final long INVALID_PROC_STATE_SEQ = -1;
311
312 /**
313 * Identifier for the sequence no. associated with this process start. It will be provided
314 * as one of the arguments when the process starts.
315 */
316 public static final String PROC_START_SEQ_IDENT = "seq=";
317
318 private final Object mNetworkPolicyLock = new Object();
319
320 private static final String DEFAULT_FULL_BACKUP_AGENT = "android.app.backup.FullBackupAgent";
321
322 /**
323 * Denotes the sequence number of the process state change for which the main thread needs
324 * to block until the network rules are updated for it.
325 *
326 * Value of {@link #INVALID_PROC_STATE_SEQ} indicates there is no need for blocking.
327 */
328 @GuardedBy("mNetworkPolicyLock")
329 private long mNetworkBlockSeq = INVALID_PROC_STATE_SEQ;
330
331 @UnsupportedAppUsage
332 private ContextImpl mSystemContext;
333 @GuardedBy("this")
334 private SparseArray<ContextImpl> mDisplaySystemUiContexts;
335
336 @UnsupportedAppUsage
337 static volatile IPackageManager sPackageManager;
338 private static volatile IPermissionManager sPermissionManager;
339
340 @UnsupportedAppUsage
341 final ApplicationThread mAppThread = new ApplicationThread();
342 @UnsupportedAppUsage
343 final Looper mLooper = Looper.myLooper();
344 @UnsupportedAppUsage
345 final H mH = new H();
346 final Executor mExecutor = new HandlerExecutor(mH);
347 /**
348 * Maps from activity token to local record of running activities in this process.
349 *
350 * This variable is readable if the code is running in activity thread or holding {@link
351 * #mResourcesManager}. It's only writable if the code is running in activity thread and holding
352 * {@link #mResourcesManager}.
353 */
354 @UnsupportedAppUsage
355 final ArrayMap<IBinder, ActivityClientRecord> mActivities = new ArrayMap<>();
356 /** Maps from activity token to the pending override configuration. */
357 @GuardedBy("mPendingOverrideConfigs")
358 private final ArrayMap<IBinder, Configuration> mPendingOverrideConfigs = new ArrayMap<>();
359 /** The activities to be truly destroyed (not include relaunch). */
360 final Map<IBinder, ClientTransactionItem> mActivitiesToBeDestroyed =
361 Collections.synchronizedMap(new ArrayMap<IBinder, ClientTransactionItem>());
362 // List of new activities (via ActivityRecord.nextIdle) that should
363 // be reported when next we idle.
364 ActivityClientRecord mNewActivities = null;
365 // Number of activities that are currently visible on-screen.
366 @UnsupportedAppUsage
367 int mNumVisibleActivities = 0;
368 private final AtomicInteger mNumLaunchingActivities = new AtomicInteger();
369 @GuardedBy("mAppThread")
370 private int mLastProcessState = PROCESS_STATE_UNKNOWN;
371 ArrayList<WeakReference<AssistStructure>> mLastAssistStructures = new ArrayList<>();
372 private int mLastSessionId;
373 final ArrayMap<IBinder, CreateServiceData> mServicesData = new ArrayMap<>();
374 @UnsupportedAppUsage
375 final ArrayMap<IBinder, Service> mServices = new ArrayMap<>();
376 @UnsupportedAppUsage
377 AppBindData mBoundApplication;
378 Profiler mProfiler;
379 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553,
380 publicAlternatives = "Use {@code Context#getResources()#getConfiguration()#densityDpi} "
381 + "instead.")
382 int mCurDefaultDisplayDpi;
383 @UnsupportedAppUsage
384 boolean mDensityCompatMode;
385 @UnsupportedAppUsage(trackingBug = 176961850, maxTargetSdk = Build.VERSION_CODES.R,
386 publicAlternatives = "Use {@code Context#getResources()#getConfiguration()} instead.")
387 Configuration mConfiguration;
388 @GuardedBy("this")
389 private boolean mUpdateHttpProxyOnBind = false;
390 @UnsupportedAppUsage
391 Application mInitialApplication;
392 @UnsupportedAppUsage
393 final ArrayList<Application> mAllApplications = new ArrayList<>();
394 /**
395 * Bookkeeping of instantiated backup agents indexed first by user id, then by package name.
396 * Indexing by user id supports parallel backups across users on system packages as they run in
397 * the same process with the same package name. Indexing by package name supports multiple
398 * distinct applications running in the same process.
399 */
400 private final SparseArray<ArrayMap<String, BackupAgent>> mBackupAgentsByUser =
401 new SparseArray<>();
402 /** Reference to singleton {@link ActivityThread} */
403 @UnsupportedAppUsage
404 private static volatile ActivityThread sCurrentActivityThread;
405 @UnsupportedAppUsage
406 Instrumentation mInstrumentation;
407 String mInstrumentationPackageName = null;
408 @UnsupportedAppUsage
409 String mInstrumentationAppDir = null;
410 String[] mInstrumentationSplitAppDirs = null;
411 String mInstrumentationLibDir = null;
412 @UnsupportedAppUsage
413 String mInstrumentedAppDir = null;
414 String[] mInstrumentedSplitAppDirs = null;
415 String mInstrumentedLibDir = null;
416 boolean mInstrumentingWithoutRestart;
417 boolean mSystemThread = false;
418 boolean mSomeActivitiesChanged = false;
419 /* package */ boolean mHiddenApiWarningShown = false;
420
421 // These can be accessed by multiple threads; mResourcesManager is the lock.
422 // XXX For now we keep around information about all packages we have
423 // seen, not removing entries from this map.
424 // NOTE: The activity and window managers need to call in to
425 // ActivityThread to do things like update resource configurations,
426 // which means this lock gets held while the activity and window managers
427 // holds their own lock. Thus you MUST NEVER call back into the activity manager
428 // or window manager or anything that depends on them while holding this lock.
429 // These LoadedApk are only valid for the userId that we're running as.
430 @GuardedBy("mResourcesManager")
431 @UnsupportedAppUsage
432 final ArrayMap<String, WeakReference<LoadedApk>> mPackages = new ArrayMap<>();
433 @GuardedBy("mResourcesManager")
434 @UnsupportedAppUsage
435 final ArrayMap<String, WeakReference<LoadedApk>> mResourcePackages = new ArrayMap<>();
436 @GuardedBy("mResourcesManager")
437 final ArrayList<ActivityClientRecord> mRelaunchingActivities = new ArrayList<>();
438 @GuardedBy("mResourcesManager")
439 @UnsupportedAppUsage(trackingBug = 176961850, maxTargetSdk = Build.VERSION_CODES.R,
440 publicAlternatives = "Use {@code Context#getResources()#getConfiguration()} instead.")
441 Configuration mPendingConfiguration = null;
442 // An executor that performs multi-step transactions.
443 private final TransactionExecutor mTransactionExecutor = new TransactionExecutor(this);
444
445 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
446 private final ResourcesManager mResourcesManager;
447
448 /** The active adjustments that override the {@link DisplayAdjustments} in resources. */
449 private ArrayList<Pair<IBinder, Consumer<DisplayAdjustments>>> mActiveRotationAdjustments;
450
451 // Registry of remote cancellation transports pending a reply with reply handles.
452 @GuardedBy("this")
453 private @Nullable Map<SafeCancellationTransport, CancellationSignal> mRemoteCancellations;
454
455 private final Map<IBinder, Integer> mLastReportedWindowingMode = Collections.synchronizedMap(
456 new ArrayMap<>());
457
458 private static final class ProviderKey {
459 final String authority;
460 final int userId;
461
462 @GuardedBy("mLock")
463 ContentProviderHolder mHolder; // Temp holder to be used between notifier and waiter
464 final Object mLock; // The lock to be used to get notified when the provider is ready
465
466 public ProviderKey(String authority, int userId) {
467 this.authority = authority;
468 this.userId = userId;
469 this.mLock = new Object();
470 }
471
472 @Override
473 public boolean equals(@Nullable Object o) {
474 if (o instanceof ProviderKey) {
475 final ProviderKey other = (ProviderKey) o;
476 return Objects.equals(authority, other.authority) && userId == other.userId;
477 }
478 return false;
479 }
480
481 @Override
482 public int hashCode() {
483 return ((authority != null) ? authority.hashCode() : 0) ^ userId;
484 }
485 }
486
487 // The lock of mProviderMap protects the following variables.
488 @UnsupportedAppUsage
489 final ArrayMap<ProviderKey, ProviderClientRecord> mProviderMap
490 = new ArrayMap<ProviderKey, ProviderClientRecord>();
491 @UnsupportedAppUsage
492 final ArrayMap<IBinder, ProviderRefCount> mProviderRefCountMap
493 = new ArrayMap<IBinder, ProviderRefCount>();
494 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
495 final ArrayMap<IBinder, ProviderClientRecord> mLocalProviders
496 = new ArrayMap<IBinder, ProviderClientRecord>();
497 @UnsupportedAppUsage
498 final ArrayMap<ComponentName, ProviderClientRecord> mLocalProvidersByName
499 = new ArrayMap<ComponentName, ProviderClientRecord>();
500
501 // Mitigation for b/74523247: Used to serialize calls to AM.getContentProvider().
502 // Note we never removes items from this map but that's okay because there are only so many
503 // users and so many authorities.
504 @GuardedBy("mGetProviderKeys")
505 final ArrayMap<ProviderKey, ProviderKey> mGetProviderKeys = new ArrayMap<>();
506
507 final ArrayMap<Activity, ArrayList<OnActivityPausedListener>> mOnPauseListeners
508 = new ArrayMap<Activity, ArrayList<OnActivityPausedListener>>();
509
510 private SplashScreen.SplashScreenManagerGlobal mSplashScreenGlobal;
511
512 final GcIdler mGcIdler = new GcIdler();
513 final PurgeIdler mPurgeIdler = new PurgeIdler();
514
515 boolean mPurgeIdlerScheduled = false;
516 boolean mGcIdlerScheduled = false;
517
518 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
519 static volatile Handler sMainThreadHandler; // set once in main()
520
521 Bundle mCoreSettings = null;
522
523 /**
524 * The lock word for the {@link #mCoreSettings}.
525 */
526 private final Object mCoreSettingsLock = new Object();
527
528 boolean mHasImeComponent = false;
529
530 private IContentCaptureOptionsCallback.Stub mContentCaptureOptionsCallback = null;
531
532 /** A client side controller to handle process level configuration changes. */
533 private ConfigurationController mConfigurationController;
534
535 /** Activity client record, used for bookkeeping for the real {@link Activity} instance. */
536 public static final class ActivityClientRecord {
537 @UnsupportedAppUsage
538 public IBinder token;
539 public IBinder assistToken;
540 // A reusable token for other purposes, e.g. content capture, translation. It shouldn't be
541 // used without security checks
542 public IBinder shareableActivityToken;
543 // The token of the TaskFragment that embedded this activity.
544 @Nullable public IBinder mTaskFragmentToken;
545 int ident;
546 @UnsupportedAppUsage
547 Intent intent;
548 String referrer;
549 IVoiceInteractor voiceInteractor;
550 Bundle state;
551 PersistableBundle persistentState;
552 @UnsupportedAppUsage
553 Activity activity;
554 Window window;
555 Activity parent;
556 String embeddedID;
557 Activity.NonConfigurationInstances lastNonConfigurationInstances;
558 // TODO(lifecycler): Use mLifecycleState instead.
559 @UnsupportedAppUsage
560 boolean paused;
561 @UnsupportedAppUsage
562 boolean stopped;
563 boolean hideForNow;
564 Configuration createdConfig;
565 Configuration overrideConfig;
566 // Used for consolidating configs before sending on to Activity.
567 private Configuration tmpConfig = new Configuration();
568 // Callback used for updating activity override config and camera compat control state.
569 ViewRootImpl.ActivityConfigCallback activityConfigCallback;
570 ActivityClientRecord nextIdle;
571
572 // Indicates whether this activity is currently the topmost resumed one in the system.
573 // This holds the last reported value from server.
574 boolean isTopResumedActivity;
575 // This holds the value last sent to the activity. This is needed, because an update from
576 // server may come at random time, but we always need to report changes between ON_RESUME
577 // and ON_PAUSE to the app.
578 boolean lastReportedTopResumedState;
579
580 ProfilerInfo profilerInfo;
581
582 @UnsupportedAppUsage
583 ActivityInfo activityInfo;
584 @UnsupportedAppUsage
585 CompatibilityInfo compatInfo;
586 @UnsupportedAppUsage
587 public LoadedApk packageInfo;
588
589 List<ResultInfo> pendingResults;
590 List<ReferrerIntent> pendingIntents;
591
592 boolean startsNotResumed;
593 public final boolean isForward;
594 int pendingConfigChanges;
595 // Whether we are in the process of performing on user leaving.
596 boolean mIsUserLeaving;
597
598 Window mPendingRemoveWindow;
599 WindowManager mPendingRemoveWindowManager;
600 @UnsupportedAppUsage
601 boolean mPreserveWindow;
602
603 /** The options for scene transition. */
604 ActivityOptions mActivityOptions;
605
606 /** Whether this activiy was launched from a bubble. */
607 boolean mLaunchedFromBubble;
608
609 @LifecycleState
610 private int mLifecycleState = PRE_ON_CREATE;
611
612 private SizeConfigurationBuckets mSizeConfigurations;
613
614 @VisibleForTesting
615 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
616 public ActivityClientRecord() {
617 this.isForward = false;
618 init();
619 }
620
621 public ActivityClientRecord(IBinder token, Intent intent, int ident,
622 ActivityInfo info, Configuration overrideConfig, CompatibilityInfo compatInfo,
623 String referrer, IVoiceInteractor voiceInteractor, Bundle state,
624 PersistableBundle persistentState, List<ResultInfo> pendingResults,
625 List<ReferrerIntent> pendingNewIntents, ActivityOptions activityOptions,
626 boolean isForward, ProfilerInfo profilerInfo, ClientTransactionHandler client,
627 IBinder assistToken, IBinder shareableActivityToken, boolean launchedFromBubble,
628 IBinder taskFragmentToken) {
629 this.token = token;
630 this.assistToken = assistToken;
631 this.shareableActivityToken = shareableActivityToken;
632 this.ident = ident;
633 this.intent = intent;
634 this.referrer = referrer;
635 this.voiceInteractor = voiceInteractor;
636 this.activityInfo = info;
637 this.compatInfo = compatInfo;
638 this.state = state;
639 this.persistentState = persistentState;
640 this.pendingResults = pendingResults;
641 this.pendingIntents = pendingNewIntents;
642 this.isForward = isForward;
643 this.profilerInfo = profilerInfo;
644 this.overrideConfig = overrideConfig;
645 this.packageInfo = client.getPackageInfoNoCheck(activityInfo.applicationInfo,
646 compatInfo);
647 mActivityOptions = activityOptions;
648 mLaunchedFromBubble = launchedFromBubble;
649 mTaskFragmentToken = taskFragmentToken;
650 init();
651 }
652
653 /** Common initializer for all constructors. */
654 private void init() {
655 parent = null;
656 embeddedID = null;
657 paused = false;
658 stopped = false;
659 hideForNow = false;
660 nextIdle = null;
661 activityConfigCallback = new ViewRootImpl.ActivityConfigCallback() {
662 @Override
663 public void onConfigurationChanged(Configuration overrideConfig,
664 int newDisplayId) {
665 if (activity == null) {
666 throw new IllegalStateException(
667 "Received config update for non-existing activity");
668 }
669 activity.mMainThread.handleActivityConfigurationChanged(
670 ActivityClientRecord.this, overrideConfig, newDisplayId);
671 }
672
673 @Override
674 public void requestCompatCameraControl(boolean showControl,
675 boolean transformationApplied, ICompatCameraControlCallback callback) {
676 if (activity == null) {
677 throw new IllegalStateException(
678 "Received camera compat control update for non-existing activity");
679 }
680 ActivityClient.getInstance().requestCompatCameraControl(
681 activity.getResources(), token, showControl, transformationApplied,
682 callback);
683 }
684
685 };
686 }
687
688 /** Get the current lifecycle state. */
689 public int getLifecycleState() {
690 return mLifecycleState;
691 }
692
693 /** Update the current lifecycle state for internal bookkeeping. */
694 public void setState(@LifecycleState int newLifecycleState) {
695 mLifecycleState = newLifecycleState;
696 switch (mLifecycleState) {
697 case ON_CREATE:
698 paused = true;
699 stopped = true;
700 break;
701 case ON_START:
702 paused = true;
703 stopped = false;
704 break;
705 case ON_RESUME:
706 paused = false;
707 stopped = false;
708 break;
709 case ON_PAUSE:
710 paused = true;
711 stopped = false;
712 break;
713 case ON_STOP:
714 paused = true;
715 stopped = true;
716 break;
717 }
718 }
719
720 private boolean isPreHoneycomb() {
721 return activity != null && activity.getApplicationInfo().targetSdkVersion
722 < android.os.Build.VERSION_CODES.HONEYCOMB;
723 }
724
725 private boolean isPreP() {
726 return activity != null && activity.getApplicationInfo().targetSdkVersion
727 < android.os.Build.VERSION_CODES.P;
728 }
729
730 public boolean isPersistable() {
731 return activityInfo.persistableMode == ActivityInfo.PERSIST_ACROSS_REBOOTS;
732 }
733
734 public boolean isVisibleFromServer() {
735 return activity != null && activity.mVisibleFromServer;
736 }
737
738 public String toString() {
739 ComponentName componentName = intent != null ? intent.getComponent() : null;
740 return "ActivityRecord{"
741 + Integer.toHexString(System.identityHashCode(this))
742 + " token=" + token + " " + (componentName == null
743 ? "no component name" : componentName.toShortString())
744 + "}";
745 }
746
747 public String getStateString() {
748 StringBuilder sb = new StringBuilder();
749 sb.append("ActivityClientRecord{");
750 sb.append("paused=").append(paused);
751 sb.append(", stopped=").append(stopped);
752 sb.append(", hideForNow=").append(hideForNow);
753 sb.append(", startsNotResumed=").append(startsNotResumed);
754 sb.append(", isForward=").append(isForward);
755 sb.append(", pendingConfigChanges=").append(pendingConfigChanges);
756 sb.append(", preserveWindow=").append(mPreserveWindow);
757 if (activity != null) {
758 sb.append(", Activity{");
759 sb.append("resumed=").append(activity.mResumed);
760 sb.append(", stopped=").append(activity.mStopped);
761 sb.append(", finished=").append(activity.isFinishing());
762 sb.append(", destroyed=").append(activity.isDestroyed());
763 sb.append(", startedActivity=").append(activity.mStartedActivity);
764 sb.append(", changingConfigurations=").append(activity.mChangingConfigurations);
765 sb.append("}");
766 }
767 sb.append("}");
768 return sb.toString();
769 }
770 }
771
772 final class ProviderClientRecord {
773 final String[] mNames;
774 @UnsupportedAppUsage
775 final IContentProvider mProvider;
776 @UnsupportedAppUsage
777 final ContentProvider mLocalProvider;
778 @UnsupportedAppUsage
779 final ContentProviderHolder mHolder;
780
781 ProviderClientRecord(String[] names, IContentProvider provider,
782 ContentProvider localProvider, ContentProviderHolder holder) {
783 mNames = names;
784 mProvider = provider;
785 mLocalProvider = localProvider;
786 mHolder = holder;
787 }
788 }
789
790 static final class ReceiverData extends BroadcastReceiver.PendingResult {
791 public ReceiverData(Intent intent, int resultCode, String resultData, Bundle resultExtras,
792 boolean ordered, boolean sticky, IBinder token, int sendingUser) {
793 super(resultCode, resultData, resultExtras, TYPE_COMPONENT, ordered, sticky,
794 token, sendingUser, intent.getFlags());
795 this.intent = intent;
796 }
797
798 @UnsupportedAppUsage
799 Intent intent;
800 @UnsupportedAppUsage
801 ActivityInfo info;
802 @UnsupportedAppUsage
803 CompatibilityInfo compatInfo;
804 public String toString() {
805 return "ReceiverData{intent=" + intent + " packageName=" +
806 info.packageName + " resultCode=" + getResultCode()
807 + " resultData=" + getResultData() + " resultExtras="
808 + getResultExtras(false) + "}";
809 }
810 }
811
812 static final class CreateBackupAgentData {
813 ApplicationInfo appInfo;
814 CompatibilityInfo compatInfo;
815 int backupMode;
816 int userId;
817 int operationType;
818 public String toString() {
819 return "CreateBackupAgentData{appInfo=" + appInfo
820 + " backupAgent=" + appInfo.backupAgentName
821 + " mode=" + backupMode + " userId=" + userId + "}";
822 }
823 }
824
825 static final class CreateServiceData {
826 @UnsupportedAppUsage
827 CreateServiceData() {
828 }
829 @UnsupportedAppUsage
830 IBinder token;
831 @UnsupportedAppUsage
832 ServiceInfo info;
833 @UnsupportedAppUsage
834 CompatibilityInfo compatInfo;
835 @UnsupportedAppUsage
836 Intent intent;
837 public String toString() {
838 return "CreateServiceData{token=" + token + " className="
839 + info.name + " packageName=" + info.packageName
840 + " intent=" + intent + "}";
841 }
842 }
843
844 static final class BindServiceData {
845 @UnsupportedAppUsage
846 IBinder token;
847 @UnsupportedAppUsage
848 Intent intent;
849 boolean rebind;
850 public String toString() {
851 return "BindServiceData{token=" + token + " intent=" + intent + "}";
852 }
853 }
854
855 static final class ServiceArgsData {
856 @UnsupportedAppUsage
857 IBinder token;
858 boolean taskRemoved;
859 int startId;
860 int flags;
861 @UnsupportedAppUsage
862 Intent args;
863 public String toString() {
864 return "ServiceArgsData{token=" + token + " startId=" + startId
865 + " args=" + args + "}";
866 }
867 }
868
869 static final class AppBindData {
870 @UnsupportedAppUsage
871 AppBindData() {
872 }
873 @UnsupportedAppUsage
874 LoadedApk info;
875 @UnsupportedAppUsage
876 String processName;
877 @UnsupportedAppUsage
878 ApplicationInfo appInfo;
879 String sdkSandboxClientAppVolumeUuid;
880 String sdkSandboxClientAppPackage;
881 @UnsupportedAppUsage
882 List<ProviderInfo> providers;
883 ComponentName instrumentationName;
884 @UnsupportedAppUsage
885 Bundle instrumentationArgs;
886 IInstrumentationWatcher instrumentationWatcher;
887 IUiAutomationConnection instrumentationUiAutomationConnection;
888 int debugMode;
889 boolean enableBinderTracking;
890 boolean trackAllocation;
891 @UnsupportedAppUsage
892 boolean restrictedBackupMode;
893 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
894 boolean persistent;
895 Configuration config;
896 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
897 CompatibilityInfo compatInfo;
898 String buildSerial;
899
900 /** Initial values for {@link Profiler}. */
901 ProfilerInfo initProfilerInfo;
902
903 AutofillOptions autofillOptions;
904
905 /**
906 * Content capture options for the application - when null, it means ContentCapture is not
907 * enabled for the package.
908 */
909 @Nullable
910 ContentCaptureOptions contentCaptureOptions;
911
912 long[] disabledCompatChanges;
913
914 SharedMemory mSerializedSystemFontMap;
915
916 long startRequestedElapsedTime;
917 long startRequestedUptime;
918
919 @Override
920 public String toString() {
921 return "AppBindData{appInfo=" + appInfo + "}";
922 }
923 }
924
925 static final class Profiler {
926 String profileFile;
927 ParcelFileDescriptor profileFd;
928 int samplingInterval;
929 boolean autoStopProfiler;
930 boolean streamingOutput;
931 int mClockType;
932 boolean profiling;
933 boolean handlingProfiling;
934 public void setProfiler(ProfilerInfo profilerInfo) {
935 ParcelFileDescriptor fd = profilerInfo.profileFd;
936 if (profiling) {
937 if (fd != null) {
938 try {
939 fd.close();
940 } catch (IOException e) {
941 // Ignore
942 }
943 }
944 return;
945 }
946 if (profileFd != null) {
947 try {
948 profileFd.close();
949 } catch (IOException e) {
950 // Ignore
951 }
952 }
953 profileFile = profilerInfo.profileFile;
954 profileFd = fd;
955 samplingInterval = profilerInfo.samplingInterval;
956 autoStopProfiler = profilerInfo.autoStopProfiler;
957 streamingOutput = profilerInfo.streamingOutput;
958 mClockType = profilerInfo.clockType;
959 }
960 public void startProfiling() {
961 if (profileFd == null || profiling) {
962 return;
963 }
964 try {
965 int bufferSize = SystemProperties.getInt("debug.traceview-buffer-size-mb", 8);
966 VMDebug.startMethodTracing(profileFile, profileFd.getFileDescriptor(),
967 bufferSize * 1024 * 1024, mClockType, samplingInterval != 0,
968 samplingInterval, streamingOutput);
969 profiling = true;
970 } catch (RuntimeException e) {
971 Slog.w(TAG, "Profiling failed on path " + profileFile, e);
972 try {
973 profileFd.close();
974 profileFd = null;
975 } catch (IOException e2) {
976 Slog.w(TAG, "Failure closing profile fd", e2);
977 }
978 }
979 }
980 public void stopProfiling() {
981 if (profiling) {
982 profiling = false;
983 Debug.stopMethodTracing();
984 if (profileFd != null) {
985 try {
986 profileFd.close();
987 } catch (IOException e) {
988 }
989 }
990 profileFd = null;
991 profileFile = null;
992 }
993 }
994 }
995
996 static final class DumpComponentInfo {
997 ParcelFileDescriptor fd;
998 IBinder token;
999 String prefix;
1000 String[] args;
1001 }
1002
1003 static final class ContextCleanupInfo {
1004 ContextImpl context;
1005 String what;
1006 String who;
1007 }
1008
1009 static final class DumpHeapData {
1010 // Whether to dump the native or managed heap.
1011 public boolean managed;
1012 public boolean mallocInfo;
1013 public boolean runGc;
1014 String path;
1015 ParcelFileDescriptor fd;
1016 RemoteCallback finishCallback;
1017 }
1018
1019 static final class DumpResourcesData {
1020 public ParcelFileDescriptor fd;
1021 public RemoteCallback finishCallback;
1022 }
1023
1024 static final class UpdateCompatibilityData {
1025 String pkg;
1026 CompatibilityInfo info;
1027 }
1028
1029 static final class RequestAssistContextExtras {
1030 IBinder activityToken;
1031 IBinder requestToken;
1032 int requestType;
1033 int sessionId;
1034 int flags;
1035 }
1036
1037 private class ApplicationThread extends IApplicationThread.Stub {
1038 private static final String DB_INFO_FORMAT = " %8s %8s %14s %14s %s";
1039
1040 public final void scheduleReceiver(Intent intent, ActivityInfo info,
1041 CompatibilityInfo compatInfo, int resultCode, String data, Bundle extras,
1042 boolean sync, int sendingUser, int processState) {
1043 updateProcessState(processState, false);
1044 ReceiverData r = new ReceiverData(intent, resultCode, data, extras,
1045 sync, false, mAppThread.asBinder(), sendingUser);
1046 r.info = info;
1047 r.compatInfo = compatInfo;
1048 sendMessage(H.RECEIVER, r);
1049 }
1050
1051 public final void scheduleCreateBackupAgent(ApplicationInfo app,
1052 CompatibilityInfo compatInfo, int backupMode, int userId, int operationType) {
1053 CreateBackupAgentData d = new CreateBackupAgentData();
1054 d.appInfo = app;
1055 d.compatInfo = compatInfo;
1056 d.backupMode = backupMode;
1057 d.userId = userId;
1058 d.operationType = operationType;
1059
1060 sendMessage(H.CREATE_BACKUP_AGENT, d);
1061 }
1062
1063 public final void scheduleDestroyBackupAgent(ApplicationInfo app,
1064 CompatibilityInfo compatInfo, int userId) {
1065 CreateBackupAgentData d = new CreateBackupAgentData();
1066 d.appInfo = app;
1067 d.compatInfo = compatInfo;
1068 d.userId = userId;
1069
1070 sendMessage(H.DESTROY_BACKUP_AGENT, d);
1071 }
1072
1073 public final void scheduleCreateService(IBinder token,
1074 ServiceInfo info, CompatibilityInfo compatInfo, int processState) {
1075 updateProcessState(processState, false);
1076 CreateServiceData s = new CreateServiceData();
1077 s.token = token;
1078 s.info = info;
1079 s.compatInfo = compatInfo;
1080
1081 sendMessage(H.CREATE_SERVICE, s);
1082 }
1083
1084 public final void scheduleBindService(IBinder token, Intent intent,
1085 boolean rebind, int processState) {
1086 updateProcessState(processState, false);
1087 BindServiceData s = new BindServiceData();
1088 s.token = token;
1089 s.intent = intent;
1090 s.rebind = rebind;
1091
1092 if (DEBUG_SERVICE)
1093 Slog.v(TAG, "scheduleBindService token=" + token + " intent=" + intent + " uid="
1094 + Binder.getCallingUid() + " pid=" + Binder.getCallingPid());
1095 sendMessage(H.BIND_SERVICE, s);
1096 }
1097
1098 public final void scheduleUnbindService(IBinder token, Intent intent) {
1099 BindServiceData s = new BindServiceData();
1100 s.token = token;
1101 s.intent = intent;
1102
1103 sendMessage(H.UNBIND_SERVICE, s);
1104 }
1105
1106 public final void scheduleServiceArgs(IBinder token, ParceledListSlice args) {
1107 List<ServiceStartArgs> list = args.getList();
1108
1109 for (int i = 0; i < list.size(); i++) {
1110 ServiceStartArgs ssa = list.get(i);
1111 ServiceArgsData s = new ServiceArgsData();
1112 s.token = token;
1113 s.taskRemoved = ssa.taskRemoved;
1114 s.startId = ssa.startId;
1115 s.flags = ssa.flags;
1116 s.args = ssa.args;
1117
1118 sendMessage(H.SERVICE_ARGS, s);
1119 }
1120 }
1121
1122 public final void scheduleStopService(IBinder token) {
1123 sendMessage(H.STOP_SERVICE, token);
1124 }
1125
1126 @Override
1127 public final void bindApplication(String processName, ApplicationInfo appInfo,
1128 String sdkSandboxClientAppVolumeUuid, String sdkSandboxClientAppPackage,
1129 ProviderInfoList providerList, ComponentName instrumentationName,
1130 ProfilerInfo profilerInfo, Bundle instrumentationArgs,
1131 IInstrumentationWatcher instrumentationWatcher,
1132 IUiAutomationConnection instrumentationUiConnection, int debugMode,
1133 boolean enableBinderTracking, boolean trackAllocation,
1134 boolean isRestrictedBackupMode, boolean persistent, Configuration config,
1135 CompatibilityInfo compatInfo, Map services, Bundle coreSettings,
1136 String buildSerial, AutofillOptions autofillOptions,
1137 ContentCaptureOptions contentCaptureOptions, long[] disabledCompatChanges,
1138 SharedMemory serializedSystemFontMap,
1139 long startRequestedElapsedTime, long startRequestedUptime) {
1140 if (services != null) {
1141 if (false) {
1142 // Test code to make sure the app could see the passed-in services.
1143 for (Object oname : services.keySet()) {
1144 if (services.get(oname) == null) {
1145 continue; // AM just passed in a null service.
1146 }
1147 String name = (String) oname;
1148
1149 // See b/79378449 about the following exemption.
1150 switch (name) {
1151 case "package":
1152 case Context.WINDOW_SERVICE:
1153 continue;
1154 }
1155
1156 if (ServiceManager.getService(name) == null) {
1157 Log.wtf(TAG, "Service " + name + " should be accessible by this app");
1158 }
1159 }
1160 }
1161
1162 // Setup the service cache in the ServiceManager
1163 ServiceManager.initServiceCache(services);
1164 }
1165
1166 setCoreSettings(coreSettings);
1167
1168 AppBindData data = new AppBindData();
1169 data.processName = processName;
1170 data.appInfo = appInfo;
1171 data.sdkSandboxClientAppVolumeUuid = sdkSandboxClientAppVolumeUuid;
1172 data.sdkSandboxClientAppPackage = sdkSandboxClientAppPackage;
1173 data.providers = providerList.getList();
1174 data.instrumentationName = instrumentationName;
1175 data.instrumentationArgs = instrumentationArgs;
1176 data.instrumentationWatcher = instrumentationWatcher;
1177 data.instrumentationUiAutomationConnection = instrumentationUiConnection;
1178 data.debugMode = debugMode;
1179 data.enableBinderTracking = enableBinderTracking;
1180 data.trackAllocation = trackAllocation;
1181 data.restrictedBackupMode = isRestrictedBackupMode;
1182 data.persistent = persistent;
1183 data.config = config;
1184 data.compatInfo = compatInfo;
1185 data.initProfilerInfo = profilerInfo;
1186 data.buildSerial = buildSerial;
1187 data.autofillOptions = autofillOptions;
1188 data.contentCaptureOptions = contentCaptureOptions;
1189 data.disabledCompatChanges = disabledCompatChanges;
1190 data.mSerializedSystemFontMap = serializedSystemFontMap;
1191 data.startRequestedElapsedTime = startRequestedElapsedTime;
1192 data.startRequestedUptime = startRequestedUptime;
1193 sendMessage(H.BIND_APPLICATION, data);
1194 }
1195
1196 public final void runIsolatedEntryPoint(String entryPoint, String[] entryPointArgs) {
1197 SomeArgs args = SomeArgs.obtain();
1198 args.arg1 = entryPoint;
1199 args.arg2 = entryPointArgs;
1200 sendMessage(H.RUN_ISOLATED_ENTRY_POINT, args);
1201 }
1202
1203 public final void scheduleExit() {
1204 sendMessage(H.EXIT_APPLICATION, null);
1205 }
1206
1207 public final void scheduleSuicide() {
1208 sendMessage(H.SUICIDE, null);
1209 }
1210
1211 public void scheduleApplicationInfoChanged(ApplicationInfo ai) {
1212 mResourcesManager.appendPendingAppInfoUpdate(new String[]{ai.sourceDir}, ai);
1213 mH.removeMessages(H.APPLICATION_INFO_CHANGED, ai);
1214 sendMessage(H.APPLICATION_INFO_CHANGED, ai);
1215 }
1216
1217 public void updateTimeZone() {
1218 TimeZone.setDefault(null);
1219 }
1220
1221 public void clearDnsCache() {
1222 // a non-standard API to get this to libcore
1223 InetAddress.clearDnsCache();
1224 // Allow libcore to perform the necessary actions as it sees fit upon a network
1225 // configuration change.
1226 NetworkEventDispatcher.getInstance().dispatchNetworkConfigurationChange();
1227 }
1228
1229 public void updateHttpProxy() {
1230 final Application app;
1231 synchronized (ActivityThread.this) {
1232 app = getApplication();
1233 if (null == app) {
1234 // The app is not bound yet. Make a note to update the HTTP proxy when the
1235 // app is bound.
1236 mUpdateHttpProxyOnBind = true;
1237 return;
1238 }
1239 }
1240 // App is present, update the proxy inline.
1241 ActivityThread.updateHttpProxy(app);
1242 }
1243
1244 public void processInBackground() {
1245 mH.removeMessages(H.GC_WHEN_IDLE);
1246 mH.sendMessage(mH.obtainMessage(H.GC_WHEN_IDLE));
1247 }
1248
1249 public void dumpService(ParcelFileDescriptor pfd, IBinder servicetoken, String[] args) {
1250 DumpComponentInfo data = new DumpComponentInfo();
1251 try {
1252 data.fd = pfd.dup();
1253 data.token = servicetoken;
1254 data.args = args;
1255 sendMessage(H.DUMP_SERVICE, data, 0, 0, true /*async*/);
1256 } catch (IOException e) {
1257 Slog.w(TAG, "dumpService failed", e);
1258 } finally {
1259 IoUtils.closeQuietly(pfd);
1260 }
1261 }
1262
1263 // This function exists to make sure all receiver dispatching is
1264 // correctly ordered, since these are one-way calls and the binder driver
1265 // applies transaction ordering per object for such calls.
1266 public void scheduleRegisteredReceiver(IIntentReceiver receiver, Intent intent,
1267 int resultCode, String dataStr, Bundle extras, boolean ordered,
1268 boolean sticky, int sendingUser, int processState) throws RemoteException {
1269 updateProcessState(processState, false);
1270 receiver.performReceive(intent, resultCode, dataStr, extras, ordered,
1271 sticky, sendingUser);
1272 }
1273
1274 @Override
1275 public void scheduleLowMemory() {
1276 sendMessage(H.LOW_MEMORY, null);
1277 }
1278
1279 @Override
1280 public void profilerControl(boolean start, ProfilerInfo profilerInfo, int profileType) {
1281 sendMessage(H.PROFILER_CONTROL, profilerInfo, start ? 1 : 0, profileType);
1282 }
1283
1284 @Override
1285 public void dumpHeap(boolean managed, boolean mallocInfo, boolean runGc, String path,
1286 ParcelFileDescriptor fd, RemoteCallback finishCallback) {
1287 DumpHeapData dhd = new DumpHeapData();
1288 dhd.managed = managed;
1289 dhd.mallocInfo = mallocInfo;
1290 dhd.runGc = runGc;
1291 dhd.path = path;
1292 try {
1293 // Since we're going to dump the heap asynchronously, dup the file descriptor before
1294 // it's closed on returning from the IPC call.
1295 dhd.fd = fd.dup();
1296 } catch (IOException e) {
1297 Slog.e(TAG, "Failed to duplicate heap dump file descriptor", e);
1298 return;
1299 } finally {
1300 IoUtils.closeQuietly(fd);
1301 }
1302 dhd.finishCallback = finishCallback;
1303 sendMessage(H.DUMP_HEAP, dhd, 0, 0, true /*async*/);
1304 }
1305
1306 public void attachAgent(String agent) {
1307 sendMessage(H.ATTACH_AGENT, agent);
1308 }
1309
1310 public void attachStartupAgents(String dataDir) {
1311 sendMessage(H.ATTACH_STARTUP_AGENTS, dataDir);
1312 }
1313
1314 public void setSchedulingGroup(int group) {
1315 // Note: do this immediately, since going into the foreground
1316 // should happen regardless of what pending work we have to do
1317 // and the activity manager will wait for us to report back that
1318 // we are done before sending us to the background.
1319 try {
1320 Process.setProcessGroup(Process.myPid(), group);
1321 } catch (Exception e) {
1322 Slog.w(TAG, "Failed setting process group to " + group, e);
1323 }
1324 }
1325
1326 public void dispatchPackageBroadcast(int cmd, String[] packages) {
1327 sendMessage(H.DISPATCH_PACKAGE_BROADCAST, packages, cmd);
1328 }
1329
1330 @Override
1331 public void scheduleCrash(String msg, int typeId, @Nullable Bundle extras) {
1332 SomeArgs args = SomeArgs.obtain();
1333 args.arg1 = msg;
1334 args.arg2 = extras;
1335 sendMessage(H.SCHEDULE_CRASH, args, typeId);
1336 }
1337
1338 @Override
1339 public void dumpResources(ParcelFileDescriptor fd, RemoteCallback callback) {
1340 DumpResourcesData data = new DumpResourcesData();
1341 try {
1342 data.fd = fd.dup();
1343 data.finishCallback = callback;
1344 sendMessage(H.DUMP_RESOURCES, data, 0, 0, false /*async*/);
1345 } catch (IOException e) {
1346 Slog.w(TAG, "dumpResources failed", e);
1347 } finally {
1348 IoUtils.closeQuietly(fd);
1349 }
1350 }
1351
1352 public void dumpActivity(ParcelFileDescriptor pfd, IBinder activitytoken,
1353 String prefix, String[] args) {
1354 DumpComponentInfo data = new DumpComponentInfo();
1355 try {
1356 data.fd = pfd.dup();
1357 data.token = activitytoken;
1358 data.prefix = prefix;
1359 data.args = args;
1360 sendMessage(H.DUMP_ACTIVITY, data, 0, 0, true /*async*/);
1361 } catch (IOException e) {
1362 Slog.w(TAG, "dumpActivity failed", e);
1363 } finally {
1364 IoUtils.closeQuietly(pfd);
1365 }
1366 }
1367
1368 public void dumpProvider(ParcelFileDescriptor pfd, IBinder providertoken,
1369 String[] args) {
1370 DumpComponentInfo data = new DumpComponentInfo();
1371 try {
1372 data.fd = pfd.dup();
1373 data.token = providertoken;
1374 data.args = args;
1375 sendMessage(H.DUMP_PROVIDER, data, 0, 0, true /*async*/);
1376 } catch (IOException e) {
1377 Slog.w(TAG, "dumpProvider failed", e);
1378 } finally {
1379 IoUtils.closeQuietly(pfd);
1380 }
1381 }
1382
1383 @Override
1384 public void dumpMemInfo(ParcelFileDescriptor pfd, Debug.MemoryInfo mem, boolean checkin,
1385 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
1386 boolean dumpUnreachable, String[] args) {
1387 FileOutputStream fout = new FileOutputStream(pfd.getFileDescriptor());
1388 PrintWriter pw = new FastPrintWriter(fout);
1389 try {
1390 dumpMemInfo(pw, mem, checkin, dumpFullInfo, dumpDalvik, dumpSummaryOnly, dumpUnreachable);
1391 } finally {
1392 pw.flush();
1393 IoUtils.closeQuietly(pfd);
1394 }
1395 }
1396
1397 private void dumpMemInfo(PrintWriter pw, Debug.MemoryInfo memInfo, boolean checkin,
1398 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly, boolean dumpUnreachable) {
1399 long nativeMax = Debug.getNativeHeapSize() / 1024;
1400 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1401 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1402
1403 Runtime runtime = Runtime.getRuntime();
1404 runtime.gc(); // Do GC since countInstancesOfClass counts unreachable objects.
1405 long dalvikMax = runtime.totalMemory() / 1024;
1406 long dalvikFree = runtime.freeMemory() / 1024;
1407 long dalvikAllocated = dalvikMax - dalvikFree;
1408
1409 Class[] classesToCount = new Class[] {
1410 ContextImpl.class,
1411 Activity.class,
1412 WebView.class,
1413 OpenSSLSocketImpl.class
1414 };
1415 long[] instanceCounts = VMDebug.countInstancesOfClasses(classesToCount, true);
1416 long appContextInstanceCount = instanceCounts[0];
1417 long activityInstanceCount = instanceCounts[1];
1418 long webviewInstanceCount = instanceCounts[2];
1419 long openSslSocketCount = instanceCounts[3];
1420
1421 long viewInstanceCount = ViewDebug.getViewInstanceCount();
1422 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
1423 int globalAssetCount = AssetManager.getGlobalAssetCount();
1424 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1425 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1426 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1427 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
1428 long parcelSize = Parcel.getGlobalAllocSize();
1429 long parcelCount = Parcel.getGlobalAllocCount();
1430 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
1431
1432 dumpMemInfoTable(pw, memInfo, checkin, dumpFullInfo, dumpDalvik, dumpSummaryOnly,
1433 Process.myPid(),
1434 (mBoundApplication != null) ? mBoundApplication.processName : "unknown",
1435 nativeMax, nativeAllocated, nativeFree,
1436 dalvikMax, dalvikAllocated, dalvikFree);
1437
1438 if (checkin) {
1439 // NOTE: if you change anything significant below, also consider changing
1440 // ACTIVITY_THREAD_CHECKIN_VERSION.
1441
1442 // Object counts
1443 pw.print(viewInstanceCount); pw.print(',');
1444 pw.print(viewRootInstanceCount); pw.print(',');
1445 pw.print(appContextInstanceCount); pw.print(',');
1446 pw.print(activityInstanceCount); pw.print(',');
1447
1448 pw.print(globalAssetCount); pw.print(',');
1449 pw.print(globalAssetManagerCount); pw.print(',');
1450 pw.print(binderLocalObjectCount); pw.print(',');
1451 pw.print(binderProxyObjectCount); pw.print(',');
1452
1453 pw.print(binderDeathObjectCount); pw.print(',');
1454 pw.print(openSslSocketCount); pw.print(',');
1455
1456 // SQL
1457 pw.print(stats.memoryUsed / 1024); pw.print(',');
1458 pw.print(stats.memoryUsed / 1024); pw.print(',');
1459 pw.print(stats.pageCacheOverflow / 1024); pw.print(',');
1460 pw.print(stats.largestMemAlloc / 1024);
1461 for (int i = 0; i < stats.dbStats.size(); i++) {
1462 DbStats dbStats = stats.dbStats.get(i);
1463 pw.print(','); pw.print(dbStats.dbName);
1464 pw.print(','); pw.print(dbStats.pageSize);
1465 pw.print(','); pw.print(dbStats.dbSize);
1466 pw.print(','); pw.print(dbStats.lookaside);
1467 pw.print(','); pw.print(dbStats.cache);
1468 pw.print(','); pw.print(dbStats.cache);
1469 }
1470 pw.println();
1471
1472 return;
1473 }
1474
1475 pw.println(" ");
1476 pw.println(" Objects");
1477 printRow(pw, TWO_COUNT_COLUMNS, "Views:", viewInstanceCount, "ViewRootImpl:",
1478 viewRootInstanceCount);
1479
1480 printRow(pw, TWO_COUNT_COLUMNS, "AppContexts:", appContextInstanceCount,
1481 "Activities:", activityInstanceCount);
1482
1483 printRow(pw, TWO_COUNT_COLUMNS, "Assets:", globalAssetCount,
1484 "AssetManagers:", globalAssetManagerCount);
1485
1486 printRow(pw, TWO_COUNT_COLUMNS, "Local Binders:", binderLocalObjectCount,
1487 "Proxy Binders:", binderProxyObjectCount);
1488 printRow(pw, TWO_COUNT_COLUMNS, "Parcel memory:", parcelSize/1024,
1489 "Parcel count:", parcelCount);
1490 printRow(pw, TWO_COUNT_COLUMNS, "Death Recipients:", binderDeathObjectCount,
1491 "OpenSSL Sockets:", openSslSocketCount);
1492 printRow(pw, ONE_COUNT_COLUMN, "WebViews:", webviewInstanceCount);
1493
1494 // SQLite mem info
1495 pw.println(" ");
1496 pw.println(" SQL");
1497 printRow(pw, ONE_COUNT_COLUMN, "MEMORY_USED:", stats.memoryUsed / 1024);
1498 printRow(pw, TWO_COUNT_COLUMNS, "PAGECACHE_OVERFLOW:",
1499 stats.pageCacheOverflow / 1024, "MALLOC_SIZE:", stats.largestMemAlloc / 1024);
1500 pw.println(" ");
1501 int N = stats.dbStats.size();
1502 if (N > 0) {
1503 pw.println(" DATABASES");
1504 printRow(pw, DB_INFO_FORMAT, "pgsz", "dbsz", "Lookaside(b)", "cache",
1505 "Dbname");
1506 for (int i = 0; i < N; i++) {
1507 DbStats dbStats = stats.dbStats.get(i);
1508 printRow(pw, DB_INFO_FORMAT,
1509 (dbStats.pageSize > 0) ? String.valueOf(dbStats.pageSize) : " ",
1510 (dbStats.dbSize > 0) ? String.valueOf(dbStats.dbSize) : " ",
1511 (dbStats.lookaside > 0) ? String.valueOf(dbStats.lookaside) : " ",
1512 dbStats.cache, dbStats.dbName);
1513 }
1514 }
1515
1516 // Asset details.
1517 String assetAlloc = AssetManager.getAssetAllocations();
1518 if (assetAlloc != null) {
1519 pw.println(" ");
1520 pw.println(" Asset Allocations");
1521 pw.print(assetAlloc);
1522 }
1523
1524 // Unreachable native memory
1525 if (dumpUnreachable) {
1526 boolean showContents = ((mBoundApplication != null)
1527 && ((mBoundApplication.appInfo.flags&ApplicationInfo.FLAG_DEBUGGABLE) != 0))
1528 || android.os.Build.IS_DEBUGGABLE;
1529 pw.println(" ");
1530 pw.println(" Unreachable memory");
1531 pw.print(Debug.getUnreachableMemory(100, showContents));
1532 }
1533 }
1534
1535 @Override
1536 public void dumpMemInfoProto(ParcelFileDescriptor pfd, Debug.MemoryInfo mem,
1537 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
1538 boolean dumpUnreachable, String[] args) {
1539 ProtoOutputStream proto = new ProtoOutputStream(pfd.getFileDescriptor());
1540 try {
1541 dumpMemInfo(proto, mem, dumpFullInfo, dumpDalvik, dumpSummaryOnly, dumpUnreachable);
1542 } finally {
1543 proto.flush();
1544 IoUtils.closeQuietly(pfd);
1545 }
1546 }
1547
1548 private void dumpMemInfo(ProtoOutputStream proto, Debug.MemoryInfo memInfo,
1549 boolean dumpFullInfo, boolean dumpDalvik,
1550 boolean dumpSummaryOnly, boolean dumpUnreachable) {
1551 long nativeMax = Debug.getNativeHeapSize() / 1024;
1552 long nativeAllocated = Debug.getNativeHeapAllocatedSize() / 1024;
1553 long nativeFree = Debug.getNativeHeapFreeSize() / 1024;
1554
1555 Runtime runtime = Runtime.getRuntime();
1556 runtime.gc(); // Do GC since countInstancesOfClass counts unreachable objects.
1557 long dalvikMax = runtime.totalMemory() / 1024;
1558 long dalvikFree = runtime.freeMemory() / 1024;
1559 long dalvikAllocated = dalvikMax - dalvikFree;
1560
1561 Class[] classesToCount = new Class[] {
1562 ContextImpl.class,
1563 Activity.class,
1564 WebView.class,
1565 OpenSSLSocketImpl.class
1566 };
1567 long[] instanceCounts = VMDebug.countInstancesOfClasses(classesToCount, true);
1568 long appContextInstanceCount = instanceCounts[0];
1569 long activityInstanceCount = instanceCounts[1];
1570 long webviewInstanceCount = instanceCounts[2];
1571 long openSslSocketCount = instanceCounts[3];
1572
1573 long viewInstanceCount = ViewDebug.getViewInstanceCount();
1574 long viewRootInstanceCount = ViewDebug.getViewRootImplCount();
1575 int globalAssetCount = AssetManager.getGlobalAssetCount();
1576 int globalAssetManagerCount = AssetManager.getGlobalAssetManagerCount();
1577 int binderLocalObjectCount = Debug.getBinderLocalObjectCount();
1578 int binderProxyObjectCount = Debug.getBinderProxyObjectCount();
1579 int binderDeathObjectCount = Debug.getBinderDeathObjectCount();
1580 long parcelSize = Parcel.getGlobalAllocSize();
1581 long parcelCount = Parcel.getGlobalAllocCount();
1582 SQLiteDebug.PagerStats stats = SQLiteDebug.getDatabaseInfo();
1583
1584 final long mToken = proto.start(MemInfoDumpProto.AppData.PROCESS_MEMORY);
1585 proto.write(MemInfoDumpProto.ProcessMemory.PID, Process.myPid());
1586 proto.write(MemInfoDumpProto.ProcessMemory.PROCESS_NAME,
1587 (mBoundApplication != null) ? mBoundApplication.processName : "unknown");
1588 dumpMemInfoTable(proto, memInfo, dumpDalvik, dumpSummaryOnly,
1589 nativeMax, nativeAllocated, nativeFree,
1590 dalvikMax, dalvikAllocated, dalvikFree);
1591 proto.end(mToken);
1592
1593 final long oToken = proto.start(MemInfoDumpProto.AppData.OBJECTS);
1594 proto.write(MemInfoDumpProto.AppData.ObjectStats.VIEW_INSTANCE_COUNT,
1595 viewInstanceCount);
1596 proto.write(MemInfoDumpProto.AppData.ObjectStats.VIEW_ROOT_INSTANCE_COUNT,
1597 viewRootInstanceCount);
1598 proto.write(MemInfoDumpProto.AppData.ObjectStats.APP_CONTEXT_INSTANCE_COUNT,
1599 appContextInstanceCount);
1600 proto.write(MemInfoDumpProto.AppData.ObjectStats.ACTIVITY_INSTANCE_COUNT,
1601 activityInstanceCount);
1602 proto.write(MemInfoDumpProto.AppData.ObjectStats.GLOBAL_ASSET_COUNT,
1603 globalAssetCount);
1604 proto.write(MemInfoDumpProto.AppData.ObjectStats.GLOBAL_ASSET_MANAGER_COUNT,
1605 globalAssetManagerCount);
1606 proto.write(MemInfoDumpProto.AppData.ObjectStats.LOCAL_BINDER_OBJECT_COUNT,
1607 binderLocalObjectCount);
1608 proto.write(MemInfoDumpProto.AppData.ObjectStats.PROXY_BINDER_OBJECT_COUNT,
1609 binderProxyObjectCount);
1610 proto.write(MemInfoDumpProto.AppData.ObjectStats.PARCEL_MEMORY_KB,
1611 parcelSize / 1024);
1612 proto.write(MemInfoDumpProto.AppData.ObjectStats.PARCEL_COUNT, parcelCount);
1613 proto.write(MemInfoDumpProto.AppData.ObjectStats.BINDER_OBJECT_DEATH_COUNT,
1614 binderDeathObjectCount);
1615 proto.write(MemInfoDumpProto.AppData.ObjectStats.OPEN_SSL_SOCKET_COUNT,
1616 openSslSocketCount);
1617 proto.write(MemInfoDumpProto.AppData.ObjectStats.WEBVIEW_INSTANCE_COUNT,
1618 webviewInstanceCount);
1619 proto.end(oToken);
1620
1621 // SQLite mem info
1622 final long sToken = proto.start(MemInfoDumpProto.AppData.SQL);
1623 proto.write(MemInfoDumpProto.AppData.SqlStats.MEMORY_USED_KB,
1624 stats.memoryUsed / 1024);
1625 proto.write(MemInfoDumpProto.AppData.SqlStats.PAGECACHE_OVERFLOW_KB,
1626 stats.pageCacheOverflow / 1024);
1627 proto.write(MemInfoDumpProto.AppData.SqlStats.MALLOC_SIZE_KB,
1628 stats.largestMemAlloc / 1024);
1629 int n = stats.dbStats.size();
1630 for (int i = 0; i < n; i++) {
1631 DbStats dbStats = stats.dbStats.get(i);
1632
1633 final long dToken = proto.start(MemInfoDumpProto.AppData.SqlStats.DATABASES);
1634 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.NAME, dbStats.dbName);
1635 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.PAGE_SIZE, dbStats.pageSize);
1636 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.DB_SIZE, dbStats.dbSize);
1637 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.LOOKASIDE_B,
1638 dbStats.lookaside);
1639 proto.write(MemInfoDumpProto.AppData.SqlStats.Database.CACHE, dbStats.cache);
1640 proto.end(dToken);
1641 }
1642 proto.end(sToken);
1643
1644 // Asset details.
1645 String assetAlloc = AssetManager.getAssetAllocations();
1646 if (assetAlloc != null) {
1647 proto.write(MemInfoDumpProto.AppData.ASSET_ALLOCATIONS, assetAlloc);
1648 }
1649
1650 // Unreachable native memory
1651 if (dumpUnreachable) {
1652 int flags = mBoundApplication == null ? 0 : mBoundApplication.appInfo.flags;
1653 boolean showContents = (flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0
1654 || android.os.Build.IS_DEBUGGABLE;
1655 proto.write(MemInfoDumpProto.AppData.UNREACHABLE_MEMORY,
1656 Debug.getUnreachableMemory(100, showContents));
1657 }
1658 }
1659
1660 @Override
1661 public void dumpGfxInfo(ParcelFileDescriptor pfd, String[] args) {
1662 DumpComponentInfo data = new DumpComponentInfo();
1663 try {
1664 data.fd = pfd.dup();
1665 data.token = null;
1666 data.args = args;
1667 sendMessage(H.DUMP_GFXINFO, data, 0, 0, true /*async*/);
1668 } catch (IOException e) {
1669 Slog.w(TAG, "dumpGfxInfo failed", e);
1670 } finally {
1671 IoUtils.closeQuietly(pfd);
1672 }
1673 }
1674
1675 @Override
1676 public void dumpCacheInfo(ParcelFileDescriptor pfd, String[] args) {
1677 PropertyInvalidatedCache.dumpCacheInfo(pfd, args);
1678 IoUtils.closeQuietly(pfd);
1679 }
1680
1681 private File getDatabasesDir(Context context) {
1682 // There's no simple way to get the databases/ path, so do it this way.
1683 return context.getDatabasePath("a").getParentFile();
1684 }
1685
1686 private void dumpDatabaseInfo(ParcelFileDescriptor pfd, String[] args, boolean isSystem) {
1687 PrintWriter pw = new FastPrintWriter(
1688 new FileOutputStream(pfd.getFileDescriptor()));
1689 PrintWriterPrinter printer = new PrintWriterPrinter(pw);
1690 SQLiteDebug.dump(printer, args, isSystem);
1691 pw.flush();
1692 }
1693
1694 @Override
1695 public void dumpDbInfo(final ParcelFileDescriptor pfd, final String[] args) {
1696 if (mSystemThread) {
1697 // Ensure this invocation is asynchronous to prevent writer waiting if buffer cannot
1698 // be consumed. But it must duplicate the file descriptor first, since caller might
1699 // be closing it.
1700 final ParcelFileDescriptor dup;
1701 try {
1702 dup = pfd.dup();
1703 } catch (IOException e) {
1704 Log.w(TAG, "Could not dup FD " + pfd.getFileDescriptor().getInt$());
1705 return;
1706 } finally {
1707 IoUtils.closeQuietly(pfd);
1708 }
1709
1710 AsyncTask.THREAD_POOL_EXECUTOR.execute(new Runnable() {
1711 @Override
1712 public void run() {
1713 try {
1714 dumpDatabaseInfo(dup, args, true);
1715 } finally {
1716 IoUtils.closeQuietly(dup);
1717 }
1718 }
1719 });
1720 } else {
1721 dumpDatabaseInfo(pfd, args, false);
1722 IoUtils.closeQuietly(pfd);
1723 }
1724 }
1725
1726 @Override
1727 public void unstableProviderDied(IBinder provider) {
1728 sendMessage(H.UNSTABLE_PROVIDER_DIED, provider);
1729 }
1730
1731 @Override
1732 public void requestAssistContextExtras(IBinder activityToken, IBinder requestToken,
1733 int requestType, int sessionId, int flags) {
1734 RequestAssistContextExtras cmd = new RequestAssistContextExtras();
1735 cmd.activityToken = activityToken;
1736 cmd.requestToken = requestToken;
1737 cmd.requestType = requestType;
1738 cmd.sessionId = sessionId;
1739 cmd.flags = flags;
1740 sendMessage(H.REQUEST_ASSIST_CONTEXT_EXTRAS, cmd);
1741 }
1742
1743 public void setCoreSettings(Bundle coreSettings) {
1744 sendMessage(H.SET_CORE_SETTINGS, coreSettings);
1745 }
1746
1747 public void updatePackageCompatibilityInfo(String pkg, CompatibilityInfo info) {
1748 UpdateCompatibilityData ucd = new UpdateCompatibilityData();
1749 ucd.pkg = pkg;
1750 ucd.info = info;
1751 sendMessage(H.UPDATE_PACKAGE_COMPATIBILITY_INFO, ucd);
1752 }
1753
1754 public void scheduleTrimMemory(int level) {
1755 final Runnable r = PooledLambda.obtainRunnable(ActivityThread::handleTrimMemory,
1756 ActivityThread.this, level).recycleOnUse();
1757 // Schedule trimming memory after drawing the frame to minimize jank-risk.
1758 Choreographer choreographer = Choreographer.getMainThreadInstance();
1759 if (choreographer != null) {
1760 choreographer.postCallback(Choreographer.CALLBACK_COMMIT, r, null);
1761 } else {
1762 mH.post(r);
1763 }
1764 }
1765
1766 public void scheduleTranslucentConversionComplete(IBinder token, boolean drawComplete) {
1767 sendMessage(H.TRANSLUCENT_CONVERSION_COMPLETE, token, drawComplete ? 1 : 0);
1768 }
1769
1770 public void scheduleOnNewActivityOptions(IBinder token, Bundle options) {
1771 sendMessage(H.ON_NEW_ACTIVITY_OPTIONS,
1772 new Pair<IBinder, ActivityOptions>(token, ActivityOptions.fromBundle(options)));
1773 }
1774
1775 public void setProcessState(int state) {
1776 updateProcessState(state, true);
1777 }
1778
1779 /**
1780 * Updates {@link #mNetworkBlockSeq}. This is used by ActivityManagerService to inform
1781 * the main thread that it needs to wait for the network rules to get updated before
1782 * launching an activity.
1783 */
1784 @Override
1785 public void setNetworkBlockSeq(long procStateSeq) {
1786 synchronized (mNetworkPolicyLock) {
1787 mNetworkBlockSeq = procStateSeq;
1788 }
1789 }
1790
1791 @Override
1792 public void scheduleInstallProvider(ProviderInfo provider) {
1793 sendMessage(H.INSTALL_PROVIDER, provider);
1794 }
1795
1796 @Override
1797 public final void updateTimePrefs(int timeFormatPreference) {
1798 final Boolean timeFormatPreferenceBool;
1799 // For convenience we are using the Intent extra values.
1800 if (timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_12_HOUR) {
1801 timeFormatPreferenceBool = Boolean.FALSE;
1802 } else if (timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_24_HOUR) {
1803 timeFormatPreferenceBool = Boolean.TRUE;
1804 } else {
1805 // timeFormatPreference == Intent.EXTRA_TIME_PREF_VALUE_USE_LOCALE_DEFAULT
1806 // (or unknown).
1807 timeFormatPreferenceBool = null;
1808 }
1809 DateFormat.set24HourTimePref(timeFormatPreferenceBool);
1810 }
1811
1812 @Override
1813 public void scheduleEnterAnimationComplete(IBinder token) {
1814 sendMessage(H.ENTER_ANIMATION_COMPLETE, token);
1815 }
1816
1817 @Override
1818 public void notifyCleartextNetwork(byte[] firstPacket) {
1819 if (StrictMode.vmCleartextNetworkEnabled()) {
1820 StrictMode.onCleartextNetworkDetected(firstPacket);
1821 }
1822 }
1823
1824 @Override
1825 public void startBinderTracking() {
1826 sendMessage(H.START_BINDER_TRACKING, null);
1827 }
1828
1829 @Override
1830 public void stopBinderTrackingAndDump(ParcelFileDescriptor pfd) {
1831 try {
1832 sendMessage(H.STOP_BINDER_TRACKING_AND_DUMP, pfd.dup());
1833 } catch (IOException e) {
1834 } finally {
1835 IoUtils.closeQuietly(pfd);
1836 }
1837 }
1838
1839 @Override
1840 public void scheduleLocalVoiceInteractionStarted(IBinder token,
1841 IVoiceInteractor voiceInteractor) throws RemoteException {
1842 SomeArgs args = SomeArgs.obtain();
1843 args.arg1 = token;
1844 args.arg2 = voiceInteractor;
1845 sendMessage(H.LOCAL_VOICE_INTERACTION_STARTED, args);
1846 }
1847
1848 @Override
1849 public void handleTrustStorageUpdate() {
1850 NetworkSecurityPolicy.getInstance().handleTrustStorageUpdate();
1851 }
1852
1853 @Override
1854 public void scheduleTransaction(ClientTransaction transaction) throws RemoteException {
1855 ActivityThread.this.scheduleTransaction(transaction);
1856 }
1857
1858 @Override
1859 public void requestDirectActions(@NonNull IBinder activityToken,
1860 @NonNull IVoiceInteractor interactor, @Nullable RemoteCallback cancellationCallback,
1861 @NonNull RemoteCallback callback) {
1862 final CancellationSignal cancellationSignal = new CancellationSignal();
1863 if (cancellationCallback != null) {
1864 final ICancellationSignal transport = createSafeCancellationTransport(
1865 cancellationSignal);
1866 final Bundle cancellationResult = new Bundle();
1867 cancellationResult.putBinder(VoiceInteractor.KEY_CANCELLATION_SIGNAL,
1868 transport.asBinder());
1869 cancellationCallback.sendResult(cancellationResult);
1870 }
1871 mH.sendMessage(PooledLambda.obtainMessage(ActivityThread::handleRequestDirectActions,
1872 ActivityThread.this, activityToken, interactor, cancellationSignal, callback,
1873 REQUEST_DIRECT_ACTIONS_RETRY_MAX_COUNT));
1874 }
1875
1876 @Override
1877 public void performDirectAction(@NonNull IBinder activityToken, @NonNull String actionId,
1878 @Nullable Bundle arguments, @Nullable RemoteCallback cancellationCallback,
1879 @NonNull RemoteCallback resultCallback) {
1880 final CancellationSignal cancellationSignal = new CancellationSignal();
1881 if (cancellationCallback != null) {
1882 final ICancellationSignal transport = createSafeCancellationTransport(
1883 cancellationSignal);
1884 final Bundle cancellationResult = new Bundle();
1885 cancellationResult.putBinder(VoiceInteractor.KEY_CANCELLATION_SIGNAL,
1886 transport.asBinder());
1887 cancellationCallback.sendResult(cancellationResult);
1888 }
1889 mH.sendMessage(PooledLambda.obtainMessage(ActivityThread::handlePerformDirectAction,
1890 ActivityThread.this, activityToken, actionId, arguments,
1891 cancellationSignal, resultCallback));
1892 }
1893
1894 @Override
1895 public void notifyContentProviderPublishStatus(@NonNull ContentProviderHolder holder,
1896 @NonNull String authorities, int userId, boolean published) {
1897 final String auths[] = authorities.split(";");
1898 for (String auth: auths) {
1899 final ProviderKey key = getGetProviderKey(auth, userId);
1900 synchronized (key.mLock) {
1901 key.mHolder = holder;
1902 key.mLock.notifyAll();
1903 }
1904 }
1905 }
1906
1907 @Override
1908 public void instrumentWithoutRestart(ComponentName instrumentationName,
1909 Bundle instrumentationArgs, IInstrumentationWatcher instrumentationWatcher,
1910 IUiAutomationConnection instrumentationUiConnection, ApplicationInfo targetInfo) {
1911 AppBindData data = new AppBindData();
1912 data.instrumentationName = instrumentationName;
1913 data.instrumentationArgs = instrumentationArgs;
1914 data.instrumentationWatcher = instrumentationWatcher;
1915 data.instrumentationUiAutomationConnection = instrumentationUiConnection;
1916 data.appInfo = targetInfo;
1917 sendMessage(H.INSTRUMENT_WITHOUT_RESTART, data);
1918 }
1919
1920 @Override
1921 public void updateUiTranslationState(IBinder activityToken, int state,
1922 TranslationSpec sourceSpec, TranslationSpec targetSpec, List<AutofillId> viewIds,
1923 UiTranslationSpec uiTranslationSpec) {
1924 SomeArgs args = SomeArgs.obtain();
1925 args.arg1 = activityToken;
1926 args.arg2 = state;
1927 args.arg3 = sourceSpec;
1928 args.arg4 = targetSpec;
1929 args.arg5 = viewIds;
1930 args.arg6 = uiTranslationSpec;
1931 sendMessage(H.UPDATE_UI_TRANSLATION_STATE, args);
1932 }
1933 }
1934
1935 private @NonNull SafeCancellationTransport createSafeCancellationTransport(
1936 @NonNull CancellationSignal cancellationSignal) {
1937 synchronized (ActivityThread.this) {
1938 if (mRemoteCancellations == null) {
1939 mRemoteCancellations = new ArrayMap<>();
1940 }
1941 final SafeCancellationTransport transport = new SafeCancellationTransport(
1942 this, cancellationSignal);
1943 mRemoteCancellations.put(transport, cancellationSignal);
1944 return transport;
1945 }
1946 }
1947
1948 private @NonNull CancellationSignal removeSafeCancellationTransport(
1949 @NonNull SafeCancellationTransport transport) {
1950 synchronized (ActivityThread.this) {
1951 final CancellationSignal cancellation = mRemoteCancellations.remove(transport);
1952 if (mRemoteCancellations.isEmpty()) {
1953 mRemoteCancellations = null;
1954 }
1955 return cancellation;
1956 }
1957 }
1958
1959 private static final class SafeCancellationTransport extends ICancellationSignal.Stub {
1960 private final @NonNull WeakReference<ActivityThread> mWeakActivityThread;
1961
1962 SafeCancellationTransport(@NonNull ActivityThread activityThread,
1963 @NonNull CancellationSignal cancellation) {
1964 mWeakActivityThread = new WeakReference<>(activityThread);
1965 }
1966
1967 @Override
1968 public void cancel() {
1969 final ActivityThread activityThread = mWeakActivityThread.get();
1970 if (activityThread != null) {
1971 final CancellationSignal cancellation = activityThread
1972 .removeSafeCancellationTransport(this);
1973 if (cancellation != null) {
1974 cancellation.cancel();
1975 }
1976 }
1977 }
1978 }
1979
1980 private void throwRemoteServiceException(String message, int typeId, @Nullable Bundle extras) {
1981 // Use a switch to ensure all the type IDs are unique.
1982 switch (typeId) {
1983 case ForegroundServiceDidNotStartInTimeException.TYPE_ID:
1984 throw generateForegroundServiceDidNotStartInTimeException(message, extras);
1985
1986 case CannotPostForegroundServiceNotificationException.TYPE_ID:
1987 throw new CannotPostForegroundServiceNotificationException(message);
1988
1989 case BadForegroundServiceNotificationException.TYPE_ID:
1990 throw new BadForegroundServiceNotificationException(message);
1991
1992 case MissingRequestPasswordComplexityPermissionException.TYPE_ID:
1993 throw new MissingRequestPasswordComplexityPermissionException(message);
1994
1995 case CrashedByAdbException.TYPE_ID:
1996 throw new CrashedByAdbException(message);
1997
1998 default:
1999 throw new RemoteServiceException(message
2000 + " (with unwknown typeId:" + typeId + ")");
2001 }
2002 }
2003
2004 private ForegroundServiceDidNotStartInTimeException
2005 generateForegroundServiceDidNotStartInTimeException(String message, Bundle extras) {
2006 final String serviceClassName =
2007 ForegroundServiceDidNotStartInTimeException.getServiceClassNameFromExtras(extras);
2008 final Exception inner = (serviceClassName == null) ? null
2009 : Service.getStartForegroundServiceStackTrace(serviceClassName);
2010 throw new ForegroundServiceDidNotStartInTimeException(message, inner);
2011 }
2012
2013 class H extends Handler {
2014 public static final int BIND_APPLICATION = 110;
2015 @UnsupportedAppUsage
2016 public static final int EXIT_APPLICATION = 111;
2017 @UnsupportedAppUsage
2018 public static final int RECEIVER = 113;
2019 @UnsupportedAppUsage
2020 public static final int CREATE_SERVICE = 114;
2021 @UnsupportedAppUsage
2022 public static final int SERVICE_ARGS = 115;
2023 @UnsupportedAppUsage
2024 public static final int STOP_SERVICE = 116;
2025
2026 public static final int CONFIGURATION_CHANGED = 118;
2027 public static final int CLEAN_UP_CONTEXT = 119;
2028 @UnsupportedAppUsage
2029 public static final int GC_WHEN_IDLE = 120;
2030 @UnsupportedAppUsage
2031 public static final int BIND_SERVICE = 121;
2032 @UnsupportedAppUsage
2033 public static final int UNBIND_SERVICE = 122;
2034 public static final int DUMP_SERVICE = 123;
2035 public static final int LOW_MEMORY = 124;
2036 public static final int PROFILER_CONTROL = 127;
2037 public static final int CREATE_BACKUP_AGENT = 128;
2038 public static final int DESTROY_BACKUP_AGENT = 129;
2039 public static final int SUICIDE = 130;
2040 @UnsupportedAppUsage
2041 public static final int REMOVE_PROVIDER = 131;
2042 public static final int DISPATCH_PACKAGE_BROADCAST = 133;
2043 @UnsupportedAppUsage
2044 public static final int SCHEDULE_CRASH = 134;
2045 public static final int DUMP_HEAP = 135;
2046 public static final int DUMP_ACTIVITY = 136;
2047 public static final int SLEEPING = 137;
2048 public static final int SET_CORE_SETTINGS = 138;
2049 public static final int UPDATE_PACKAGE_COMPATIBILITY_INFO = 139;
2050 @UnsupportedAppUsage
2051 public static final int DUMP_PROVIDER = 141;
2052 public static final int UNSTABLE_PROVIDER_DIED = 142;
2053 public static final int REQUEST_ASSIST_CONTEXT_EXTRAS = 143;
2054 public static final int TRANSLUCENT_CONVERSION_COMPLETE = 144;
2055 @UnsupportedAppUsage
2056 public static final int INSTALL_PROVIDER = 145;
2057 public static final int ON_NEW_ACTIVITY_OPTIONS = 146;
2058 @UnsupportedAppUsage
2059 public static final int ENTER_ANIMATION_COMPLETE = 149;
2060 public static final int START_BINDER_TRACKING = 150;
2061 public static final int STOP_BINDER_TRACKING_AND_DUMP = 151;
2062 public static final int LOCAL_VOICE_INTERACTION_STARTED = 154;
2063 public static final int ATTACH_AGENT = 155;
2064 public static final int APPLICATION_INFO_CHANGED = 156;
2065 public static final int RUN_ISOLATED_ENTRY_POINT = 158;
2066 public static final int EXECUTE_TRANSACTION = 159;
2067 public static final int RELAUNCH_ACTIVITY = 160;
2068 public static final int PURGE_RESOURCES = 161;
2069 public static final int ATTACH_STARTUP_AGENTS = 162;
2070 public static final int UPDATE_UI_TRANSLATION_STATE = 163;
2071 public static final int SET_CONTENT_CAPTURE_OPTIONS_CALLBACK = 164;
2072 public static final int DUMP_GFXINFO = 165;
2073 public static final int DUMP_RESOURCES = 166;
2074
2075 public static final int INSTRUMENT_WITHOUT_RESTART = 170;
2076 public static final int FINISH_INSTRUMENTATION_WITHOUT_RESTART = 171;
2077
2078 String codeToString(int code) {
2079 if (DEBUG_MESSAGES) {
2080 switch (code) {
2081 case BIND_APPLICATION: return "BIND_APPLICATION";
2082 case EXIT_APPLICATION: return "EXIT_APPLICATION";
2083 case RECEIVER: return "RECEIVER";
2084 case CREATE_SERVICE: return "CREATE_SERVICE";
2085 case SERVICE_ARGS: return "SERVICE_ARGS";
2086 case STOP_SERVICE: return "STOP_SERVICE";
2087 case CONFIGURATION_CHANGED: return "CONFIGURATION_CHANGED";
2088 case CLEAN_UP_CONTEXT: return "CLEAN_UP_CONTEXT";
2089 case GC_WHEN_IDLE: return "GC_WHEN_IDLE";
2090 case BIND_SERVICE: return "BIND_SERVICE";
2091 case UNBIND_SERVICE: return "UNBIND_SERVICE";
2092 case DUMP_SERVICE: return "DUMP_SERVICE";
2093 case LOW_MEMORY: return "LOW_MEMORY";
2094 case PROFILER_CONTROL: return "PROFILER_CONTROL";
2095 case CREATE_BACKUP_AGENT: return "CREATE_BACKUP_AGENT";
2096 case DESTROY_BACKUP_AGENT: return "DESTROY_BACKUP_AGENT";
2097 case SUICIDE: return "SUICIDE";
2098 case REMOVE_PROVIDER: return "REMOVE_PROVIDER";
2099 case DISPATCH_PACKAGE_BROADCAST: return "DISPATCH_PACKAGE_BROADCAST";
2100 case SCHEDULE_CRASH: return "SCHEDULE_CRASH";
2101 case DUMP_HEAP: return "DUMP_HEAP";
2102 case DUMP_ACTIVITY: return "DUMP_ACTIVITY";
2103 case SET_CORE_SETTINGS: return "SET_CORE_SETTINGS";
2104 case UPDATE_PACKAGE_COMPATIBILITY_INFO: return "UPDATE_PACKAGE_COMPATIBILITY_INFO";
2105 case DUMP_PROVIDER: return "DUMP_PROVIDER";
2106 case UNSTABLE_PROVIDER_DIED: return "UNSTABLE_PROVIDER_DIED";
2107 case REQUEST_ASSIST_CONTEXT_EXTRAS: return "REQUEST_ASSIST_CONTEXT_EXTRAS";
2108 case TRANSLUCENT_CONVERSION_COMPLETE: return "TRANSLUCENT_CONVERSION_COMPLETE";
2109 case INSTALL_PROVIDER: return "INSTALL_PROVIDER";
2110 case ON_NEW_ACTIVITY_OPTIONS: return "ON_NEW_ACTIVITY_OPTIONS";
2111 case ENTER_ANIMATION_COMPLETE: return "ENTER_ANIMATION_COMPLETE";
2112 case LOCAL_VOICE_INTERACTION_STARTED: return "LOCAL_VOICE_INTERACTION_STARTED";
2113 case ATTACH_AGENT: return "ATTACH_AGENT";
2114 case APPLICATION_INFO_CHANGED: return "APPLICATION_INFO_CHANGED";
2115 case RUN_ISOLATED_ENTRY_POINT: return "RUN_ISOLATED_ENTRY_POINT";
2116 case EXECUTE_TRANSACTION: return "EXECUTE_TRANSACTION";
2117 case RELAUNCH_ACTIVITY: return "RELAUNCH_ACTIVITY";
2118 case PURGE_RESOURCES: return "PURGE_RESOURCES";
2119 case ATTACH_STARTUP_AGENTS: return "ATTACH_STARTUP_AGENTS";
2120 case UPDATE_UI_TRANSLATION_STATE: return "UPDATE_UI_TRANSLATION_STATE";
2121 case SET_CONTENT_CAPTURE_OPTIONS_CALLBACK:
2122 return "SET_CONTENT_CAPTURE_OPTIONS_CALLBACK";
2123 case DUMP_GFXINFO: return "DUMP GFXINFO";
2124 case INSTRUMENT_WITHOUT_RESTART: return "INSTRUMENT_WITHOUT_RESTART";
2125 case FINISH_INSTRUMENTATION_WITHOUT_RESTART:
2126 return "FINISH_INSTRUMENTATION_WITHOUT_RESTART";
2127 case DUMP_RESOURCES: return "DUMP_RESOURCES";
2128 }
2129 }
2130 return Integer.toString(code);
2131 }
2132 public void handleMessage(Message msg) {
2133 if (DEBUG_MESSAGES) Slog.v(TAG, ">>> handling: " + codeToString(msg.what));
2134 switch (msg.what) {
2135 case BIND_APPLICATION:
2136 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "bindApplication");
2137 AppBindData data = (AppBindData)msg.obj;
2138 handleBindApplication(data);
2139 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
2140 break;
2141 case EXIT_APPLICATION:
2142 if (mInitialApplication != null) {
2143 mInitialApplication.onTerminate();
2144 }
2145 Looper.myLooper().quit();
2146 break;
2147 case RECEIVER:
2148 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
2149 ReceiverData rec = (ReceiverData) msg.obj;
2150 if (rec.intent != null) {
2151 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
2152 "broadcastReceiveComp: " + rec.intent.getAction());
2153 } else {
2154 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
2155 "broadcastReceiveComp");
2156 }
2157 }
2158 handleReceiver((ReceiverData)msg.obj);
2159 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
2160 break;
2161 case CREATE_SERVICE:
2162 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
2163 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
2164 ("serviceCreate: " + String.valueOf(msg.obj)));
2165 }
2166 handleCreateService((CreateServiceData)msg.obj);
2167 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
2168 break;
2169 case BIND_SERVICE:
2170 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceBind");
2171 handleBindService((BindServiceData)msg.obj);
2172 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
2173 break;
2174 case UNBIND_SERVICE:
2175 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceUnbind");
2176 handleUnbindService((BindServiceData)msg.obj);
2177 schedulePurgeIdler();
2178 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
2179 break;
2180 case SERVICE_ARGS:
2181 if (Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) {
2182 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER,
2183 ("serviceStart: " + String.valueOf(msg.obj)));
2184 }
2185 handleServiceArgs((ServiceArgsData)msg.obj);
2186 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
2187 break;
2188 case STOP_SERVICE:
2189 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "serviceStop");
2190 handleStopService((IBinder)msg.obj);
2191 schedulePurgeIdler();
2192 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
2193 break;
2194 case CONFIGURATION_CHANGED:
2195 mConfigurationController.handleConfigurationChanged((Configuration) msg.obj);
2196 break;
2197 case CLEAN_UP_CONTEXT:
2198 ContextCleanupInfo cci = (ContextCleanupInfo)msg.obj;
2199 cci.context.performFinalCleanup(cci.who, cci.what);
2200 break;
2201 case GC_WHEN_IDLE:
2202 scheduleGcIdler();
2203 break;
2204 case DUMP_SERVICE:
2205 handleDumpService((DumpComponentInfo)msg.obj);
2206 break;
2207 case DUMP_GFXINFO:
2208 handleDumpGfxInfo((DumpComponentInfo) msg.obj);
2209 break;
2210 case LOW_MEMORY:
2211 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "lowMemory");
2212 handleLowMemory();
2213 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
2214 break;
2215 case PROFILER_CONTROL:
2216 handleProfilerControl(msg.arg1 != 0, (ProfilerInfo)msg.obj, msg.arg2);
2217 break;
2218 case CREATE_BACKUP_AGENT:
2219 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupCreateAgent");
2220 handleCreateBackupAgent((CreateBackupAgentData)msg.obj);
2221 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
2222 break;
2223 case DESTROY_BACKUP_AGENT:
2224 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "backupDestroyAgent");
2225 handleDestroyBackupAgent((CreateBackupAgentData)msg.obj);
2226 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
2227 break;
2228 case SUICIDE:
2229 Process.killProcess(Process.myPid());
2230 break;
2231 case REMOVE_PROVIDER:
2232 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "providerRemove");
2233 completeRemoveProvider((ProviderRefCount)msg.obj);
2234 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
2235 break;
2236 case DISPATCH_PACKAGE_BROADCAST:
2237 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "broadcastPackage");
2238 handleDispatchPackageBroadcast(msg.arg1, (String[])msg.obj);
2239 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
2240 break;
2241 case SCHEDULE_CRASH: {
2242 SomeArgs args = (SomeArgs) msg.obj;
2243 String message = (String) args.arg1;
2244 Bundle extras = (Bundle) args.arg2;
2245 args.recycle();
2246 throwRemoteServiceException(message, msg.arg1, extras);
2247 break;
2248 }
2249 case DUMP_HEAP:
2250 handleDumpHeap((DumpHeapData) msg.obj);
2251 break;
2252 case DUMP_RESOURCES:
2253 handleDumpResources((DumpResourcesData) msg.obj);
2254 break;
2255 case DUMP_ACTIVITY:
2256 handleDumpActivity((DumpComponentInfo)msg.obj);
2257 break;
2258 case DUMP_PROVIDER:
2259 handleDumpProvider((DumpComponentInfo)msg.obj);
2260 break;
2261 case SET_CORE_SETTINGS:
2262 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setCoreSettings");
2263 handleSetCoreSettings((Bundle) msg.obj);
2264 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
2265 break;
2266 case UPDATE_PACKAGE_COMPATIBILITY_INFO:
2267 handleUpdatePackageCompatibilityInfo((UpdateCompatibilityData)msg.obj);
2268 break;
2269 case UNSTABLE_PROVIDER_DIED:
2270 handleUnstableProviderDied((IBinder)msg.obj, false);
2271 break;
2272 case REQUEST_ASSIST_CONTEXT_EXTRAS:
2273 handleRequestAssistContextExtras((RequestAssistContextExtras)msg.obj);
2274 break;
2275 case TRANSLUCENT_CONVERSION_COMPLETE:
2276 handleTranslucentConversionComplete((IBinder)msg.obj, msg.arg1 == 1);
2277 break;
2278 case INSTALL_PROVIDER:
2279 handleInstallProvider((ProviderInfo) msg.obj);
2280 break;
2281 case ON_NEW_ACTIVITY_OPTIONS:
2282 Pair<IBinder, ActivityOptions> pair = (Pair<IBinder, ActivityOptions>) msg.obj;
2283 onNewActivityOptions(pair.first, pair.second);
2284 break;
2285 case ENTER_ANIMATION_COMPLETE:
2286 handleEnterAnimationComplete((IBinder) msg.obj);
2287 break;
2288 case START_BINDER_TRACKING:
2289 handleStartBinderTracking();
2290 break;
2291 case STOP_BINDER_TRACKING_AND_DUMP:
2292 handleStopBinderTrackingAndDump((ParcelFileDescriptor) msg.obj);
2293 break;
2294 case LOCAL_VOICE_INTERACTION_STARTED:
2295 handleLocalVoiceInteractionStarted((IBinder) ((SomeArgs) msg.obj).arg1,
2296 (IVoiceInteractor) ((SomeArgs) msg.obj).arg2);
2297 break;
2298 case ATTACH_AGENT: {
2299 Application app = getApplication();
2300 handleAttachAgent((String) msg.obj, app != null ? app.mLoadedApk : null);
2301 break;
2302 }
2303 case APPLICATION_INFO_CHANGED:
2304 handleApplicationInfoChanged((ApplicationInfo) msg.obj);
2305 break;
2306 case RUN_ISOLATED_ENTRY_POINT:
2307 handleRunIsolatedEntryPoint((String) ((SomeArgs) msg.obj).arg1,
2308 (String[]) ((SomeArgs) msg.obj).arg2);
2309 break;
2310 case EXECUTE_TRANSACTION:
2311 final ClientTransaction transaction = (ClientTransaction) msg.obj;
2312 mTransactionExecutor.execute(transaction);
2313 if (isSystem()) {
2314 // Client transactions inside system process are recycled on the client side
2315 // instead of ClientLifecycleManager to avoid being cleared before this
2316 // message is handled.
2317 transaction.recycle();
2318 }
2319 // TODO(lifecycler): Recycle locally scheduled transactions.
2320 break;
2321 case RELAUNCH_ACTIVITY:
2322 handleRelaunchActivityLocally((IBinder) msg.obj);
2323 break;
2324 case PURGE_RESOURCES:
2325 schedulePurgeIdler();
2326 break;
2327 case ATTACH_STARTUP_AGENTS:
2328 handleAttachStartupAgents((String) msg.obj);
2329 break;
2330 case UPDATE_UI_TRANSLATION_STATE:
2331 final SomeArgs args = (SomeArgs) msg.obj;
2332 updateUiTranslationState((IBinder) args.arg1, (int) args.arg2,
2333 (TranslationSpec) args.arg3, (TranslationSpec) args.arg4,
2334 (List<AutofillId>) args.arg5, (UiTranslationSpec) args.arg6);
2335 break;
2336 case SET_CONTENT_CAPTURE_OPTIONS_CALLBACK:
2337 handleSetContentCaptureOptionsCallback((String) msg.obj);
2338 break;
2339 case INSTRUMENT_WITHOUT_RESTART:
2340 handleInstrumentWithoutRestart((AppBindData) msg.obj);
2341 break;
2342 case FINISH_INSTRUMENTATION_WITHOUT_RESTART:
2343 handleFinishInstrumentationWithoutRestart();
2344 break;
2345 }
2346 Object obj = msg.obj;
2347 if (obj instanceof SomeArgs) {
2348 ((SomeArgs) obj).recycle();
2349 }
2350 if (DEBUG_MESSAGES) Slog.v(TAG, "<<< done: " + codeToString(msg.what));
2351 }
2352 }
2353
2354 private class Idler implements MessageQueue.IdleHandler {
2355 @Override
2356 public final boolean queueIdle() {
2357 ActivityClientRecord a = mNewActivities;
2358 boolean stopProfiling = false;
2359 if (mBoundApplication != null && mProfiler.profileFd != null
2360 && mProfiler.autoStopProfiler) {
2361 stopProfiling = true;
2362 }
2363 if (a != null) {
2364 mNewActivities = null;
2365 final ActivityClient ac = ActivityClient.getInstance();
2366 ActivityClientRecord prev;
2367 do {
2368 if (localLOGV) Slog.v(
2369 TAG, "Reporting idle of " + a +
2370 " finished=" +
2371 (a.activity != null && a.activity.mFinished));
2372 if (a.activity != null && !a.activity.mFinished) {
2373 ac.activityIdle(a.token, a.createdConfig, stopProfiling);
2374 a.createdConfig = null;
2375 }
2376 prev = a;
2377 a = a.nextIdle;
2378 prev.nextIdle = null;
2379 } while (a != null);
2380 }
2381 if (stopProfiling) {
2382 mProfiler.stopProfiling();
2383 }
2384 return false;
2385 }
2386 }
2387
2388 final class GcIdler implements MessageQueue.IdleHandler {
2389 @Override
2390 public final boolean queueIdle() {
2391 doGcIfNeeded();
2392 purgePendingResources();
2393 return false;
2394 }
2395 }
2396
2397 final class PurgeIdler implements MessageQueue.IdleHandler {
2398 @Override
2399 public boolean queueIdle() {
2400 purgePendingResources();
2401 return false;
2402 }
2403 }
2404
2405 @UnsupportedAppUsage
2406 public static ActivityThread currentActivityThread() {
2407 return sCurrentActivityThread;
2408 }
2409
2410 public static boolean isSystem() {
2411 return (sCurrentActivityThread != null) ? sCurrentActivityThread.mSystemThread : false;
2412 }
2413
2414 public static String currentOpPackageName() {
2415 ActivityThread am = currentActivityThread();
2416 return (am != null && am.getApplication() != null)
2417 ? am.getApplication().getOpPackageName() : null;
2418 }
2419
2420 public static AttributionSource currentAttributionSource() {
2421 ActivityThread am = currentActivityThread();
2422 return (am != null && am.getApplication() != null)
2423 ? am.getApplication().getAttributionSource() : null;
2424 }
2425
2426 @UnsupportedAppUsage
2427 public static String currentPackageName() {
2428 ActivityThread am = currentActivityThread();
2429 return (am != null && am.mBoundApplication != null)
2430 ? am.mBoundApplication.appInfo.packageName : null;
2431 }
2432
2433 @UnsupportedAppUsage
2434 public static String currentProcessName() {
2435 ActivityThread am = currentActivityThread();
2436 return (am != null && am.mBoundApplication != null)
2437 ? am.mBoundApplication.processName : null;
2438 }
2439
2440 @UnsupportedAppUsage
2441 public static Application currentApplication() {
2442 ActivityThread am = currentActivityThread();
2443 return am != null ? am.mInitialApplication : null;
2444 }
2445
2446 @UnsupportedAppUsage
2447 public static IPackageManager getPackageManager() {
2448 if (sPackageManager != null) {
2449 return sPackageManager;
2450 }
2451 final IBinder b = ServiceManager.getService("package");
2452 sPackageManager = IPackageManager.Stub.asInterface(b);
2453 return sPackageManager;
2454 }
2455
2456 /** Returns the permission manager */
2457 public static IPermissionManager getPermissionManager() {
2458 if (sPermissionManager != null) {
2459 return sPermissionManager;
2460 }
2461 final IBinder b = ServiceManager.getService("permissionmgr");
2462 sPermissionManager = IPermissionManager.Stub.asInterface(b);
2463 return sPermissionManager;
2464 }
2465
2466 /**
2467 * Creates the top level resources for the given package. Will return an existing
2468 * Resources if one has already been created.
2469 */
2470 Resources getTopLevelResources(String resDir, String[] splitResDirs, String[] legacyOverlayDirs,
2471 String[] overlayPaths, String[] libDirs, LoadedApk pkgInfo,
2472 Configuration overrideConfig) {
2473 return mResourcesManager.getResources(null, resDir, splitResDirs, legacyOverlayDirs,
2474 overlayPaths, libDirs, null, overrideConfig, pkgInfo.getCompatibilityInfo(),
2475 pkgInfo.getClassLoader(), null);
2476 }
2477
2478 @UnsupportedAppUsage
2479 public Handler getHandler() {
2480 return mH;
2481 }
2482
2483 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
2484 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
2485 int flags) {
2486 return getPackageInfo(packageName, compatInfo, flags, UserHandle.myUserId());
2487 }
2488
2489 public final LoadedApk getPackageInfo(String packageName, CompatibilityInfo compatInfo,
2490 int flags, int userId) {
2491 final boolean differentUser = (UserHandle.myUserId() != userId);
2492 ApplicationInfo ai = PackageManager.getApplicationInfoAsUserCached(
2493 packageName,
2494 PackageManager.GET_SHARED_LIBRARY_FILES
2495 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
2496 (userId < 0) ? UserHandle.myUserId() : userId);
2497 synchronized (mResourcesManager) {
2498 WeakReference<LoadedApk> ref;
2499 if (differentUser) {
2500 // Caching not supported across users
2501 ref = null;
2502 } else if ((flags & Context.CONTEXT_INCLUDE_CODE) != 0) {
2503 ref = mPackages.get(packageName);
2504 } else {
2505 ref = mResourcePackages.get(packageName);
2506 }
2507
2508 LoadedApk packageInfo = ref != null ? ref.get() : null;
2509 if (ai != null && packageInfo != null) {
2510 if (!isLoadedApkResourceDirsUpToDate(packageInfo, ai)) {
2511 List<String> oldPaths = new ArrayList<>();
2512 LoadedApk.makePaths(this, ai, oldPaths);
2513 packageInfo.updateApplicationInfo(ai, oldPaths);
2514 }
2515
2516 if (packageInfo.isSecurityViolation()
2517 && (flags&Context.CONTEXT_IGNORE_SECURITY) == 0) {
2518 throw new SecurityException(
2519 "Requesting code from " + packageName
2520 + " to be run in process "
2521 + mBoundApplication.processName
2522 + "/" + mBoundApplication.appInfo.uid);
2523 }
2524 return packageInfo;
2525 }
2526 }
2527
2528 if (ai != null) {
2529 return getPackageInfo(ai, compatInfo, flags);
2530 }
2531
2532 return null;
2533 }
2534
2535 @UnsupportedAppUsage(trackingBug = 171933273)
2536 public final LoadedApk getPackageInfo(ApplicationInfo ai, CompatibilityInfo compatInfo,
2537 int flags) {
2538 boolean includeCode = (flags&Context.CONTEXT_INCLUDE_CODE) != 0;
2539 boolean securityViolation = includeCode && ai.uid != 0
2540 && ai.uid != Process.SYSTEM_UID && (mBoundApplication != null
2541 ? !UserHandle.isSameApp(ai.uid, mBoundApplication.appInfo.uid)
2542 : true);
2543 boolean registerPackage = includeCode && (flags&Context.CONTEXT_REGISTER_PACKAGE) != 0;
2544 if ((flags&(Context.CONTEXT_INCLUDE_CODE
2545 |Context.CONTEXT_IGNORE_SECURITY))
2546 == Context.CONTEXT_INCLUDE_CODE) {
2547 if (securityViolation) {
2548 String msg = "Requesting code from " + ai.packageName
2549 + " (with uid " + ai.uid + ")";
2550 if (mBoundApplication != null) {
2551 msg = msg + " to be run in process "
2552 + mBoundApplication.processName + " (with uid "
2553 + mBoundApplication.appInfo.uid + ")";
2554 }
2555 throw new SecurityException(msg);
2556 }
2557 }
2558 return getPackageInfo(ai, compatInfo, null, securityViolation, includeCode,
2559 registerPackage);
2560 }
2561
2562 @Override
2563 @UnsupportedAppUsage
2564 public final LoadedApk getPackageInfoNoCheck(ApplicationInfo ai,
2565 CompatibilityInfo compatInfo) {
2566 return getPackageInfo(ai, compatInfo, null, false, true, false);
2567 }
2568
2569 private LoadedApk getPackageInfoNoCheck(ApplicationInfo ai, CompatibilityInfo compatInfo,
2570 boolean isSdkSandbox) {
2571 return getPackageInfo(ai, compatInfo, null, false, true, false, isSdkSandbox);
2572 }
2573
2574 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
2575 public final LoadedApk peekPackageInfo(String packageName, boolean includeCode) {
2576 synchronized (mResourcesManager) {
2577 WeakReference<LoadedApk> ref;
2578 if (includeCode) {
2579 ref = mPackages.get(packageName);
2580 } else {
2581 ref = mResourcePackages.get(packageName);
2582 }
2583 return ref != null ? ref.get() : null;
2584 }
2585 }
2586
2587 private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
2588 ClassLoader baseLoader, boolean securityViolation, boolean includeCode,
2589 boolean registerPackage) {
2590 return getPackageInfo(aInfo, compatInfo, baseLoader, securityViolation, includeCode,
2591 registerPackage, /*isSdkSandbox=*/false);
2592 }
2593
2594 private LoadedApk getPackageInfo(ApplicationInfo aInfo, CompatibilityInfo compatInfo,
2595 ClassLoader baseLoader, boolean securityViolation, boolean includeCode,
2596 boolean registerPackage, boolean isSdkSandbox) {
2597 final boolean differentUser = (UserHandle.myUserId() != UserHandle.getUserId(aInfo.uid));
2598 synchronized (mResourcesManager) {
2599 WeakReference<LoadedApk> ref;
2600 if (differentUser || isSdkSandbox) {
2601 // Caching not supported across users and for sdk sandboxes
2602 ref = null;
2603 } else if (includeCode) {
2604 ref = mPackages.get(aInfo.packageName);
2605 } else {
2606 ref = mResourcePackages.get(aInfo.packageName);
2607 }
2608
2609 LoadedApk packageInfo = ref != null ? ref.get() : null;
2610
2611 if (packageInfo != null) {
2612 if (!isLoadedApkResourceDirsUpToDate(packageInfo, aInfo)) {
2613 if (packageInfo.getApplicationInfo().createTimestamp > aInfo.createTimestamp) {
2614 // The cached loaded apk is newer than the one passed in, we should not
2615 // update the cached version
2616 Slog.w(TAG, "getPackageInfo() called with an older ApplicationInfo "
2617 + "than the cached version for package " + aInfo.packageName);
2618 } else {
2619 Slog.v(TAG, "getPackageInfo() caused update to cached ApplicationInfo "
2620 + "for package " + aInfo.packageName);
2621 List<String> oldPaths = new ArrayList<>();
2622 LoadedApk.makePaths(this, aInfo, oldPaths);
2623 packageInfo.updateApplicationInfo(aInfo, oldPaths);
2624 }
2625 }
2626
2627 return packageInfo;
2628 }
2629
2630 if (localLOGV) {
2631 Slog.v(TAG, (includeCode ? "Loading code package "
2632 : "Loading resource-only package ") + aInfo.packageName
2633 + " (in " + (mBoundApplication != null
2634 ? mBoundApplication.processName : null)
2635 + ")");
2636 }
2637
2638 packageInfo =
2639 new LoadedApk(this, aInfo, compatInfo, baseLoader,
2640 securityViolation, includeCode
2641 && (aInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0, registerPackage);
2642
2643 if (mSystemThread && "android".equals(aInfo.packageName)) {
2644 packageInfo.installSystemApplicationInfo(aInfo,
2645 getSystemContext().mPackageInfo.getClassLoader());
2646 }
2647
2648 if (differentUser || isSdkSandbox) {
2649 // Caching not supported across users and for sdk sandboxes
2650 } else if (includeCode) {
2651 mPackages.put(aInfo.packageName,
2652 new WeakReference<LoadedApk>(packageInfo));
2653 } else {
2654 mResourcePackages.put(aInfo.packageName,
2655 new WeakReference<LoadedApk>(packageInfo));
2656 }
2657
2658 return packageInfo;
2659 }
2660 }
2661
2662 private static boolean isLoadedApkResourceDirsUpToDate(LoadedApk loadedApk,
2663 ApplicationInfo appInfo) {
2664 Resources packageResources = loadedApk.mResources;
2665 boolean resourceDirsUpToDate = Arrays.equals(
2666 ArrayUtils.defeatNullable(appInfo.resourceDirs),
2667 ArrayUtils.defeatNullable(loadedApk.getOverlayDirs()));
2668 boolean overlayPathsUpToDate = Arrays.equals(
2669 ArrayUtils.defeatNullable(appInfo.overlayPaths),
2670 ArrayUtils.defeatNullable(loadedApk.getOverlayPaths()));
2671
2672 return (packageResources == null || packageResources.getAssets().isUpToDate())
2673 && resourceDirsUpToDate && overlayPathsUpToDate;
2674 }
2675
2676 @UnsupportedAppUsage
2677 ActivityThread() {
2678 mResourcesManager = ResourcesManager.getInstance();
2679 }
2680
2681 @UnsupportedAppUsage
2682 public ApplicationThread getApplicationThread()
2683 {
2684 return mAppThread;
2685 }
2686
2687 @UnsupportedAppUsage
2688 public Instrumentation getInstrumentation()
2689 {
2690 return mInstrumentation;
2691 }
2692
2693 public boolean isProfiling() {
2694 return mProfiler != null && mProfiler.profileFile != null
2695 && mProfiler.profileFd == null;
2696 }
2697
2698 public String getProfileFilePath() {
2699 return mProfiler.profileFile;
2700 }
2701
2702 @UnsupportedAppUsage
2703 public Looper getLooper() {
2704 return mLooper;
2705 }
2706
2707 public Executor getExecutor() {
2708 return mExecutor;
2709 }
2710
2711 @Override
2712 @UnsupportedAppUsage
2713 public Application getApplication() {
2714 return mInitialApplication;
2715 }
2716
2717 @UnsupportedAppUsage
2718 public String getProcessName() {
2719 return mBoundApplication.processName;
2720 }
2721
2722 @Override
2723 @UnsupportedAppUsage
2724 public ContextImpl getSystemContext() {
2725 synchronized (this) {
2726 if (mSystemContext == null) {
2727 mSystemContext = ContextImpl.createSystemContext(this);
2728 }
2729 return mSystemContext;
2730 }
2731 }
2732
2733 @NonNull
2734 public ContextImpl getSystemUiContext() {
2735 return getSystemUiContext(DEFAULT_DISPLAY);
2736 }
2737
2738 /**
2739 * Gets the context instance base on system resources & display information which used for UI.
2740 * @param displayId The ID of the display where the UI is shown.
2741 * @see ContextImpl#createSystemUiContext(ContextImpl, int)
2742 */
2743 @NonNull
2744 public ContextImpl getSystemUiContext(int displayId) {
2745 synchronized (this) {
2746 if (mDisplaySystemUiContexts == null) {
2747 mDisplaySystemUiContexts = new SparseArray<>();
2748 }
2749 ContextImpl systemUiContext = mDisplaySystemUiContexts.get(displayId);
2750 if (systemUiContext == null) {
2751 systemUiContext = ContextImpl.createSystemUiContext(getSystemContext(), displayId);
2752 mDisplaySystemUiContexts.put(displayId, systemUiContext);
2753 }
2754 return systemUiContext;
2755 }
2756 }
2757
2758 @Nullable
2759 @Override
2760 public ContextImpl getSystemUiContextNoCreate() {
2761 synchronized (this) {
2762 if (mDisplaySystemUiContexts == null) return null;
2763 return mDisplaySystemUiContexts.get(DEFAULT_DISPLAY);
2764 }
2765 }
2766
2767 void onSystemUiContextCleanup(ContextImpl context) {
2768 synchronized (this) {
2769 if (mDisplaySystemUiContexts == null) return;
2770 final int index = mDisplaySystemUiContexts.indexOfValue(context);
2771 if (index >= 0) {
2772 mDisplaySystemUiContexts.removeAt(index);
2773 }
2774 }
2775 }
2776
2777 public void installSystemApplicationInfo(ApplicationInfo info, ClassLoader classLoader) {
2778 synchronized (this) {
2779 getSystemContext().installSystemApplicationInfo(info, classLoader);
2780 getSystemUiContext().installSystemApplicationInfo(info, classLoader);
2781
2782 // give ourselves a default profiler
2783 mProfiler = new Profiler();
2784 }
2785 }
2786
2787 @UnsupportedAppUsage
2788 void scheduleGcIdler() {
2789 if (!mGcIdlerScheduled) {
2790 mGcIdlerScheduled = true;
2791 Looper.myQueue().addIdleHandler(mGcIdler);
2792 }
2793 mH.removeMessages(H.GC_WHEN_IDLE);
2794 }
2795
2796 void unscheduleGcIdler() {
2797 if (mGcIdlerScheduled) {
2798 mGcIdlerScheduled = false;
2799 Looper.myQueue().removeIdleHandler(mGcIdler);
2800 }
2801 mH.removeMessages(H.GC_WHEN_IDLE);
2802 }
2803
2804 void schedulePurgeIdler() {
2805 if (!mPurgeIdlerScheduled) {
2806 mPurgeIdlerScheduled = true;
2807 Looper.myQueue().addIdleHandler(mPurgeIdler);
2808 }
2809 mH.removeMessages(H.PURGE_RESOURCES);
2810 }
2811
2812 void unschedulePurgeIdler() {
2813 if (mPurgeIdlerScheduled) {
2814 mPurgeIdlerScheduled = false;
2815 Looper.myQueue().removeIdleHandler(mPurgeIdler);
2816 }
2817 mH.removeMessages(H.PURGE_RESOURCES);
2818 }
2819
2820 void doGcIfNeeded() {
2821 doGcIfNeeded("bg");
2822 }
2823
2824 void doGcIfNeeded(String reason) {
2825 mGcIdlerScheduled = false;
2826 final long now = SystemClock.uptimeMillis();
2827 //Slog.i(TAG, "**** WE MIGHT WANT TO GC: then=" + Binder.getLastGcTime()
2828 // + "m now=" + now);
2829 if ((BinderInternal.getLastGcTime()+MIN_TIME_BETWEEN_GCS) < now) {
2830 //Slog.i(TAG, "**** WE DO, WE DO WANT TO GC!");
2831 BinderInternal.forceGc(reason);
2832 }
2833 }
2834
2835 private static final String HEAP_FULL_COLUMN =
2836 "%13s %8s %8s %8s %8s %8s %8s %8s %8s %8s %8s %8s";
2837 private static final String HEAP_COLUMN =
2838 "%13s %8s %8s %8s %8s %8s %8s %8s %8s";
2839 private static final String ONE_COUNT_COLUMN = "%21s %8d";
2840 private static final String TWO_COUNT_COLUMNS = "%21s %8d %21s %8d";
2841 private static final String THREE_COUNT_COLUMNS = "%21s %8d %21s %8s %21s %8d";
2842 private static final String TWO_COUNT_COLUMN_HEADER = "%21s %8s %21s %8s";
2843 private static final String ONE_ALT_COUNT_COLUMN = "%21s %8s %21s %8d";
2844
2845 // Formatting for checkin service - update version if row format changes
2846 private static final int ACTIVITY_THREAD_CHECKIN_VERSION = 4;
2847
2848 static void printRow(PrintWriter pw, String format, Object...objs) {
2849 pw.println(String.format(format, objs));
2850 }
2851
2852 public static void dumpMemInfoTable(PrintWriter pw, Debug.MemoryInfo memInfo, boolean checkin,
2853 boolean dumpFullInfo, boolean dumpDalvik, boolean dumpSummaryOnly,
2854 int pid, String processName,
2855 long nativeMax, long nativeAllocated, long nativeFree,
2856 long dalvikMax, long dalvikAllocated, long dalvikFree) {
2857
2858 // For checkin, we print one long comma-separated list of values
2859 if (checkin) {
2860 // NOTE: if you change anything significant below, also consider changing
2861 // ACTIVITY_THREAD_CHECKIN_VERSION.
2862
2863 // Header
2864 pw.print(ACTIVITY_THREAD_CHECKIN_VERSION); pw.print(',');
2865 pw.print(pid); pw.print(',');
2866 pw.print(processName); pw.print(',');
2867
2868 // Heap info - max
2869 pw.print(nativeMax); pw.print(',');
2870 pw.print(dalvikMax); pw.print(',');
2871 pw.print("N/A,");
2872 pw.print(nativeMax + dalvikMax); pw.print(',');
2873
2874 // Heap info - allocated
2875 pw.print(nativeAllocated); pw.print(',');
2876 pw.print(dalvikAllocated); pw.print(',');
2877 pw.print("N/A,");
2878 pw.print(nativeAllocated + dalvikAllocated); pw.print(',');
2879
2880 // Heap info - free
2881 pw.print(nativeFree); pw.print(',');
2882 pw.print(dalvikFree); pw.print(',');
2883 pw.print("N/A,");
2884 pw.print(nativeFree + dalvikFree); pw.print(',');
2885
2886 // Heap info - proportional set size
2887 pw.print(memInfo.nativePss); pw.print(',');
2888 pw.print(memInfo.dalvikPss); pw.print(',');
2889 pw.print(memInfo.otherPss); pw.print(',');
2890 pw.print(memInfo.getTotalPss()); pw.print(',');
2891
2892 // Heap info - swappable set size
2893 pw.print(memInfo.nativeSwappablePss); pw.print(',');
2894 pw.print(memInfo.dalvikSwappablePss); pw.print(',');
2895 pw.print(memInfo.otherSwappablePss); pw.print(',');
2896 pw.print(memInfo.getTotalSwappablePss()); pw.print(',');
2897
2898 // Heap info - shared dirty
2899 pw.print(memInfo.nativeSharedDirty); pw.print(',');
2900 pw.print(memInfo.dalvikSharedDirty); pw.print(',');
2901 pw.print(memInfo.otherSharedDirty); pw.print(',');
2902 pw.print(memInfo.getTotalSharedDirty()); pw.print(',');
2903
2904 // Heap info - shared clean
2905 pw.print(memInfo.nativeSharedClean); pw.print(',');
2906 pw.print(memInfo.dalvikSharedClean); pw.print(',');
2907 pw.print(memInfo.otherSharedClean); pw.print(',');
2908 pw.print(memInfo.getTotalSharedClean()); pw.print(',');
2909
2910 // Heap info - private Dirty
2911 pw.print(memInfo.nativePrivateDirty); pw.print(',');
2912 pw.print(memInfo.dalvikPrivateDirty); pw.print(',');
2913 pw.print(memInfo.otherPrivateDirty); pw.print(',');
2914 pw.print(memInfo.getTotalPrivateDirty()); pw.print(',');
2915
2916 // Heap info - private Clean
2917 pw.print(memInfo.nativePrivateClean); pw.print(',');
2918 pw.print(memInfo.dalvikPrivateClean); pw.print(',');
2919 pw.print(memInfo.otherPrivateClean); pw.print(',');
2920 pw.print(memInfo.getTotalPrivateClean()); pw.print(',');
2921
2922 // Heap info - swapped out
2923 pw.print(memInfo.nativeSwappedOut); pw.print(',');
2924 pw.print(memInfo.dalvikSwappedOut); pw.print(',');
2925 pw.print(memInfo.otherSwappedOut); pw.print(',');
2926 pw.print(memInfo.getTotalSwappedOut()); pw.print(',');
2927
2928 // Heap info - swapped out pss
2929 if (memInfo.hasSwappedOutPss) {
2930 pw.print(memInfo.nativeSwappedOutPss); pw.print(',');
2931 pw.print(memInfo.dalvikSwappedOutPss); pw.print(',');
2932 pw.print(memInfo.otherSwappedOutPss); pw.print(',');
2933 pw.print(memInfo.getTotalSwappedOutPss()); pw.print(',');
2934 } else {
2935 pw.print("N/A,");
2936 pw.print("N/A,");
2937 pw.print("N/A,");
2938 pw.print("N/A,");
2939 }
2940
2941 // Heap info - other areas
2942 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
2943 pw.print(Debug.MemoryInfo.getOtherLabel(i)); pw.print(',');
2944 pw.print(memInfo.getOtherPss(i)); pw.print(',');
2945 pw.print(memInfo.getOtherSwappablePss(i)); pw.print(',');
2946 pw.print(memInfo.getOtherSharedDirty(i)); pw.print(',');
2947 pw.print(memInfo.getOtherSharedClean(i)); pw.print(',');
2948 pw.print(memInfo.getOtherPrivateDirty(i)); pw.print(',');
2949 pw.print(memInfo.getOtherPrivateClean(i)); pw.print(',');
2950 pw.print(memInfo.getOtherSwappedOut(i)); pw.print(',');
2951 if (memInfo.hasSwappedOutPss) {
2952 pw.print(memInfo.getOtherSwappedOutPss(i)); pw.print(',');
2953 } else {
2954 pw.print("N/A,");
2955 }
2956 }
2957 return;
2958 }
2959
2960 if (!dumpSummaryOnly) {
2961 if (dumpFullInfo) {
2962 printRow(pw, HEAP_FULL_COLUMN, "", "Pss", "Pss", "Shared", "Private",
2963 "Shared", "Private", memInfo.hasSwappedOutPss ? "SwapPss" : "Swap",
2964 "Rss", "Heap", "Heap", "Heap");
2965 printRow(pw, HEAP_FULL_COLUMN, "", "Total", "Clean", "Dirty", "Dirty",
2966 "Clean", "Clean", "Dirty", "Total",
2967 "Size", "Alloc", "Free");
2968 printRow(pw, HEAP_FULL_COLUMN, "", "------", "------", "------", "------",
2969 "------", "------", "------", "------", "------", "------", "------");
2970 printRow(pw, HEAP_FULL_COLUMN, "Native Heap", memInfo.nativePss,
2971 memInfo.nativeSwappablePss, memInfo.nativeSharedDirty,
2972 memInfo.nativePrivateDirty, memInfo.nativeSharedClean,
2973 memInfo.nativePrivateClean, memInfo.hasSwappedOutPss ?
2974 memInfo.nativeSwappedOutPss : memInfo.nativeSwappedOut,
2975 memInfo.nativeRss, nativeMax, nativeAllocated, nativeFree);
2976 printRow(pw, HEAP_FULL_COLUMN, "Dalvik Heap", memInfo.dalvikPss,
2977 memInfo.dalvikSwappablePss, memInfo.dalvikSharedDirty,
2978 memInfo.dalvikPrivateDirty, memInfo.dalvikSharedClean,
2979 memInfo.dalvikPrivateClean, memInfo.hasSwappedOutPss ?
2980 memInfo.dalvikSwappedOutPss : memInfo.dalvikSwappedOut,
2981 memInfo.dalvikRss, dalvikMax, dalvikAllocated, dalvikFree);
2982 } else {
2983 printRow(pw, HEAP_COLUMN, "", "Pss", "Private",
2984 "Private", memInfo.hasSwappedOutPss ? "SwapPss" : "Swap",
2985 "Rss", "Heap", "Heap", "Heap");
2986 printRow(pw, HEAP_COLUMN, "", "Total", "Dirty",
2987 "Clean", "Dirty", "Total", "Size", "Alloc", "Free");
2988 printRow(pw, HEAP_COLUMN, "", "------", "------", "------",
2989 "------", "------", "------", "------", "------", "------");
2990 printRow(pw, HEAP_COLUMN, "Native Heap", memInfo.nativePss,
2991 memInfo.nativePrivateDirty,
2992 memInfo.nativePrivateClean,
2993 memInfo.hasSwappedOutPss ? memInfo.nativeSwappedOutPss :
2994 memInfo.nativeSwappedOut, memInfo.nativeRss,
2995 nativeMax, nativeAllocated, nativeFree);
2996 printRow(pw, HEAP_COLUMN, "Dalvik Heap", memInfo.dalvikPss,
2997 memInfo.dalvikPrivateDirty,
2998 memInfo.dalvikPrivateClean,
2999 memInfo.hasSwappedOutPss ? memInfo.dalvikSwappedOutPss :
3000 memInfo.dalvikSwappedOut, memInfo.dalvikRss,
3001 dalvikMax, dalvikAllocated, dalvikFree);
3002 }
3003
3004 int otherPss = memInfo.otherPss;
3005 int otherSwappablePss = memInfo.otherSwappablePss;
3006 int otherSharedDirty = memInfo.otherSharedDirty;
3007 int otherPrivateDirty = memInfo.otherPrivateDirty;
3008 int otherSharedClean = memInfo.otherSharedClean;
3009 int otherPrivateClean = memInfo.otherPrivateClean;
3010 int otherSwappedOut = memInfo.otherSwappedOut;
3011 int otherSwappedOutPss = memInfo.otherSwappedOutPss;
3012 int otherRss = memInfo.otherRss;
3013
3014 for (int i=0; i<Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
3015 final int myPss = memInfo.getOtherPss(i);
3016 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
3017 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
3018 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
3019 final int mySharedClean = memInfo.getOtherSharedClean(i);
3020 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
3021 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
3022 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
3023 final int myRss = memInfo.getOtherRss(i);
3024 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
3025 || mySharedClean != 0 || myPrivateClean != 0 || myRss != 0
3026 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
3027 if (dumpFullInfo) {
3028 printRow(pw, HEAP_FULL_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
3029 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
3030 mySharedClean, myPrivateClean,
3031 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
3032 myRss, "", "", "");
3033 } else {
3034 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
3035 myPss, myPrivateDirty,
3036 myPrivateClean,
3037 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
3038 myRss, "", "", "");
3039 }
3040 otherPss -= myPss;
3041 otherSwappablePss -= mySwappablePss;
3042 otherSharedDirty -= mySharedDirty;
3043 otherPrivateDirty -= myPrivateDirty;
3044 otherSharedClean -= mySharedClean;
3045 otherPrivateClean -= myPrivateClean;
3046 otherSwappedOut -= mySwappedOut;
3047 otherSwappedOutPss -= mySwappedOutPss;
3048 otherRss -= myRss;
3049 }
3050 }
3051
3052 if (dumpFullInfo) {
3053 printRow(pw, HEAP_FULL_COLUMN, "Unknown", otherPss, otherSwappablePss,
3054 otherSharedDirty, otherPrivateDirty, otherSharedClean, otherPrivateClean,
3055 memInfo.hasSwappedOutPss ? otherSwappedOutPss : otherSwappedOut,
3056 otherRss, "", "", "");
3057 printRow(pw, HEAP_FULL_COLUMN, "TOTAL", memInfo.getTotalPss(),
3058 memInfo.getTotalSwappablePss(),
3059 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
3060 memInfo.getTotalSharedClean(), memInfo.getTotalPrivateClean(),
3061 memInfo.hasSwappedOutPss ? memInfo.getTotalSwappedOutPss() :
3062 memInfo.getTotalSwappedOut(), memInfo.getTotalRss(),
3063 nativeMax+dalvikMax, nativeAllocated+dalvikAllocated,
3064 nativeFree+dalvikFree);
3065 } else {
3066 printRow(pw, HEAP_COLUMN, "Unknown", otherPss,
3067 otherPrivateDirty, otherPrivateClean,
3068 memInfo.hasSwappedOutPss ? otherSwappedOutPss : otherSwappedOut,
3069 otherRss, "", "", "");
3070 printRow(pw, HEAP_COLUMN, "TOTAL", memInfo.getTotalPss(),
3071 memInfo.getTotalPrivateDirty(),
3072 memInfo.getTotalPrivateClean(),
3073 memInfo.hasSwappedOutPss ? memInfo.getTotalSwappedOutPss() :
3074 memInfo.getTotalSwappedOut(), memInfo.getTotalRss(),
3075 nativeMax+dalvikMax,
3076 nativeAllocated+dalvikAllocated, nativeFree+dalvikFree);
3077 }
3078
3079 if (dumpDalvik) {
3080 pw.println(" ");
3081 pw.println(" Dalvik Details");
3082
3083 for (int i=Debug.MemoryInfo.NUM_OTHER_STATS;
3084 i<Debug.MemoryInfo.NUM_OTHER_STATS + Debug.MemoryInfo.NUM_DVK_STATS; i++) {
3085 final int myPss = memInfo.getOtherPss(i);
3086 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
3087 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
3088 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
3089 final int mySharedClean = memInfo.getOtherSharedClean(i);
3090 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
3091 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
3092 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
3093 final int myRss = memInfo.getOtherRss(i);
3094 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
3095 || mySharedClean != 0 || myPrivateClean != 0
3096 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
3097 if (dumpFullInfo) {
3098 printRow(pw, HEAP_FULL_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
3099 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
3100 mySharedClean, myPrivateClean,
3101 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
3102 myRss, "", "", "");
3103 } else {
3104 printRow(pw, HEAP_COLUMN, Debug.MemoryInfo.getOtherLabel(i),
3105 myPss, myPrivateDirty,
3106 myPrivateClean,
3107 memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut,
3108 myRss, "", "", "");
3109 }
3110 }
3111 }
3112 }
3113 }
3114
3115 pw.println(" ");
3116 pw.println(" App Summary");
3117 printRow(pw, TWO_COUNT_COLUMN_HEADER, "", "Pss(KB)", "", "Rss(KB)");
3118 printRow(pw, TWO_COUNT_COLUMN_HEADER, "", "------", "", "------");
3119 printRow(pw, TWO_COUNT_COLUMNS,
3120 "Java Heap:", memInfo.getSummaryJavaHeap(), "", memInfo.getSummaryJavaHeapRss());
3121 printRow(pw, TWO_COUNT_COLUMNS,
3122 "Native Heap:", memInfo.getSummaryNativeHeap(), "",
3123 memInfo.getSummaryNativeHeapRss());
3124 printRow(pw, TWO_COUNT_COLUMNS,
3125 "Code:", memInfo.getSummaryCode(), "", memInfo.getSummaryCodeRss());
3126 printRow(pw, TWO_COUNT_COLUMNS,
3127 "Stack:", memInfo.getSummaryStack(), "", memInfo.getSummaryStackRss());
3128 printRow(pw, TWO_COUNT_COLUMNS,
3129 "Graphics:", memInfo.getSummaryGraphics(), "", memInfo.getSummaryGraphicsRss());
3130 printRow(pw, ONE_COUNT_COLUMN,
3131 "Private Other:", memInfo.getSummaryPrivateOther());
3132 printRow(pw, ONE_COUNT_COLUMN,
3133 "System:", memInfo.getSummarySystem());
3134 printRow(pw, ONE_ALT_COUNT_COLUMN,
3135 "Unknown:", "", "", memInfo.getSummaryUnknownRss());
3136 pw.println(" ");
3137 if (memInfo.hasSwappedOutPss) {
3138 printRow(pw, THREE_COUNT_COLUMNS,
3139 "TOTAL PSS:", memInfo.getSummaryTotalPss(),
3140 "TOTAL RSS:", memInfo.getTotalRss(),
3141 "TOTAL SWAP PSS:", memInfo.getSummaryTotalSwapPss());
3142 } else {
3143 printRow(pw, THREE_COUNT_COLUMNS,
3144 "TOTAL PSS:", memInfo.getSummaryTotalPss(),
3145 "TOTAL RSS:", memInfo.getTotalRss(),
3146 "TOTAL SWAP (KB):", memInfo.getSummaryTotalSwap());
3147 }
3148 }
3149
3150 /**
3151 * Dump heap info to proto.
3152 *
3153 * @param hasSwappedOutPss determines whether to use dirtySwap or dirtySwapPss
3154 */
3155 private static void dumpMemoryInfo(ProtoOutputStream proto, long fieldId, String name,
3156 int pss, int cleanPss, int sharedDirty, int privateDirty,
3157 int sharedClean, int privateClean,
3158 boolean hasSwappedOutPss, int dirtySwap, int dirtySwapPss, int rss) {
3159 final long token = proto.start(fieldId);
3160
3161 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.NAME, name);
3162 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.TOTAL_PSS_KB, pss);
3163 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.CLEAN_PSS_KB, cleanPss);
3164 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.SHARED_DIRTY_KB, sharedDirty);
3165 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.PRIVATE_DIRTY_KB, privateDirty);
3166 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.SHARED_CLEAN_KB, sharedClean);
3167 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.PRIVATE_CLEAN_KB, privateClean);
3168 if (hasSwappedOutPss) {
3169 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.DIRTY_SWAP_PSS_KB, dirtySwapPss);
3170 } else {
3171 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.DIRTY_SWAP_KB, dirtySwap);
3172 }
3173 proto.write(MemInfoDumpProto.ProcessMemory.MemoryInfo.TOTAL_RSS_KB, rss);
3174
3175 proto.end(token);
3176 }
3177
3178 /**
3179 * Dump mem info data to proto.
3180 */
3181 public static void dumpMemInfoTable(ProtoOutputStream proto, Debug.MemoryInfo memInfo,
3182 boolean dumpDalvik, boolean dumpSummaryOnly,
3183 long nativeMax, long nativeAllocated, long nativeFree,
3184 long dalvikMax, long dalvikAllocated, long dalvikFree) {
3185
3186 if (!dumpSummaryOnly) {
3187 final long nhToken = proto.start(MemInfoDumpProto.ProcessMemory.NATIVE_HEAP);
3188 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "Native Heap",
3189 memInfo.nativePss, memInfo.nativeSwappablePss, memInfo.nativeSharedDirty,
3190 memInfo.nativePrivateDirty, memInfo.nativeSharedClean,
3191 memInfo.nativePrivateClean, memInfo.hasSwappedOutPss,
3192 memInfo.nativeSwappedOut, memInfo.nativeSwappedOutPss,
3193 memInfo.nativeRss);
3194 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB, nativeMax);
3195 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB, nativeAllocated);
3196 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB, nativeFree);
3197 proto.end(nhToken);
3198
3199 final long dvToken = proto.start(MemInfoDumpProto.ProcessMemory.DALVIK_HEAP);
3200 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "Dalvik Heap",
3201 memInfo.dalvikPss, memInfo.dalvikSwappablePss, memInfo.dalvikSharedDirty,
3202 memInfo.dalvikPrivateDirty, memInfo.dalvikSharedClean,
3203 memInfo.dalvikPrivateClean, memInfo.hasSwappedOutPss,
3204 memInfo.dalvikSwappedOut, memInfo.dalvikSwappedOutPss,
3205 memInfo.dalvikRss);
3206 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB, dalvikMax);
3207 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB, dalvikAllocated);
3208 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB, dalvikFree);
3209 proto.end(dvToken);
3210
3211 int otherPss = memInfo.otherPss;
3212 int otherSwappablePss = memInfo.otherSwappablePss;
3213 int otherSharedDirty = memInfo.otherSharedDirty;
3214 int otherPrivateDirty = memInfo.otherPrivateDirty;
3215 int otherSharedClean = memInfo.otherSharedClean;
3216 int otherPrivateClean = memInfo.otherPrivateClean;
3217 int otherSwappedOut = memInfo.otherSwappedOut;
3218 int otherSwappedOutPss = memInfo.otherSwappedOutPss;
3219 int otherRss = memInfo.otherRss;
3220
3221 for (int i = 0; i < Debug.MemoryInfo.NUM_OTHER_STATS; i++) {
3222 final int myPss = memInfo.getOtherPss(i);
3223 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
3224 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
3225 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
3226 final int mySharedClean = memInfo.getOtherSharedClean(i);
3227 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
3228 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
3229 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
3230 final int myRss = memInfo.getOtherRss(i);
3231 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
3232 || mySharedClean != 0 || myPrivateClean != 0 || myRss != 0
3233 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
3234 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.OTHER_HEAPS,
3235 Debug.MemoryInfo.getOtherLabel(i),
3236 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
3237 mySharedClean, myPrivateClean,
3238 memInfo.hasSwappedOutPss, mySwappedOut, mySwappedOutPss, myRss);
3239
3240 otherPss -= myPss;
3241 otherSwappablePss -= mySwappablePss;
3242 otherSharedDirty -= mySharedDirty;
3243 otherPrivateDirty -= myPrivateDirty;
3244 otherSharedClean -= mySharedClean;
3245 otherPrivateClean -= myPrivateClean;
3246 otherSwappedOut -= mySwappedOut;
3247 otherSwappedOutPss -= mySwappedOutPss;
3248 otherRss -= myRss;
3249 }
3250 }
3251
3252 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.UNKNOWN_HEAP, "Unknown",
3253 otherPss, otherSwappablePss,
3254 otherSharedDirty, otherPrivateDirty, otherSharedClean, otherPrivateClean,
3255 memInfo.hasSwappedOutPss, otherSwappedOut, otherSwappedOutPss, otherRss);
3256 final long tToken = proto.start(MemInfoDumpProto.ProcessMemory.TOTAL_HEAP);
3257 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.HeapInfo.MEM_INFO, "TOTAL",
3258 memInfo.getTotalPss(), memInfo.getTotalSwappablePss(),
3259 memInfo.getTotalSharedDirty(), memInfo.getTotalPrivateDirty(),
3260 memInfo.getTotalSharedClean(), memInfo.getTotalPrivateClean(),
3261 memInfo.hasSwappedOutPss, memInfo.getTotalSwappedOut(),
3262 memInfo.getTotalSwappedOutPss(), memInfo.getTotalRss());
3263 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_SIZE_KB,
3264 nativeMax + dalvikMax);
3265 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_ALLOC_KB,
3266 nativeAllocated + dalvikAllocated);
3267 proto.write(MemInfoDumpProto.ProcessMemory.HeapInfo.HEAP_FREE_KB,
3268 nativeFree + dalvikFree);
3269 proto.end(tToken);
3270
3271 if (dumpDalvik) {
3272 for (int i = Debug.MemoryInfo.NUM_OTHER_STATS;
3273 i < Debug.MemoryInfo.NUM_OTHER_STATS + Debug.MemoryInfo.NUM_DVK_STATS;
3274 i++) {
3275 final int myPss = memInfo.getOtherPss(i);
3276 final int mySwappablePss = memInfo.getOtherSwappablePss(i);
3277 final int mySharedDirty = memInfo.getOtherSharedDirty(i);
3278 final int myPrivateDirty = memInfo.getOtherPrivateDirty(i);
3279 final int mySharedClean = memInfo.getOtherSharedClean(i);
3280 final int myPrivateClean = memInfo.getOtherPrivateClean(i);
3281 final int mySwappedOut = memInfo.getOtherSwappedOut(i);
3282 final int mySwappedOutPss = memInfo.getOtherSwappedOutPss(i);
3283 final int myRss = memInfo.getOtherRss(i);
3284 if (myPss != 0 || mySharedDirty != 0 || myPrivateDirty != 0
3285 || mySharedClean != 0 || myPrivateClean != 0
3286 || (memInfo.hasSwappedOutPss ? mySwappedOutPss : mySwappedOut) != 0) {
3287 dumpMemoryInfo(proto, MemInfoDumpProto.ProcessMemory.DALVIK_DETAILS,
3288 Debug.MemoryInfo.getOtherLabel(i),
3289 myPss, mySwappablePss, mySharedDirty, myPrivateDirty,
3290 mySharedClean, myPrivateClean,
3291 memInfo.hasSwappedOutPss, mySwappedOut, mySwappedOutPss, myRss);
3292 }
3293 }
3294 }
3295 }
3296
3297 final long asToken = proto.start(MemInfoDumpProto.ProcessMemory.APP_SUMMARY);
3298 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.JAVA_HEAP_PSS_KB,
3299 memInfo.getSummaryJavaHeap());
3300 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.NATIVE_HEAP_PSS_KB,
3301 memInfo.getSummaryNativeHeap());
3302 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.CODE_PSS_KB,
3303 memInfo.getSummaryCode());
3304 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.STACK_PSS_KB,
3305 memInfo.getSummaryStack());
3306 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.GRAPHICS_PSS_KB,
3307 memInfo.getSummaryGraphics());
3308 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.PRIVATE_OTHER_PSS_KB,
3309 memInfo.getSummaryPrivateOther());
3310 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.SYSTEM_PSS_KB,
3311 memInfo.getSummarySystem());
3312 if (memInfo.hasSwappedOutPss) {
3313 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.TOTAL_SWAP_PSS,
3314 memInfo.getSummaryTotalSwapPss());
3315 } else {
3316 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.TOTAL_SWAP_PSS,
3317 memInfo.getSummaryTotalSwap());
3318 }
3319 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.JAVA_HEAP_RSS_KB,
3320 memInfo.getSummaryJavaHeapRss());
3321 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.NATIVE_HEAP_RSS_KB,
3322 memInfo.getSummaryNativeHeapRss());
3323 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.CODE_RSS_KB,
3324 memInfo.getSummaryCodeRss());
3325 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.STACK_RSS_KB,
3326 memInfo.getSummaryStackRss());
3327 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.GRAPHICS_RSS_KB,
3328 memInfo.getSummaryGraphicsRss());
3329 proto.write(MemInfoDumpProto.ProcessMemory.AppSummary.UNKNOWN_RSS_KB,
3330 memInfo.getSummaryUnknownRss());
3331
3332 proto.end(asToken);
3333 }
3334
3335 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3336 public void registerOnActivityPausedListener(Activity activity,
3337 OnActivityPausedListener listener) {
3338 synchronized (mOnPauseListeners) {
3339 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
3340 if (list == null) {
3341 list = new ArrayList<OnActivityPausedListener>();
3342 mOnPauseListeners.put(activity, list);
3343 }
3344 list.add(listener);
3345 }
3346 }
3347
3348 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
3349 public void unregisterOnActivityPausedListener(Activity activity,
3350 OnActivityPausedListener listener) {
3351 synchronized (mOnPauseListeners) {
3352 ArrayList<OnActivityPausedListener> list = mOnPauseListeners.get(activity);
3353 if (list != null) {
3354 list.remove(listener);
3355 }
3356 }
3357 }
3358
3359 public final ActivityInfo resolveActivityInfo(Intent intent) {
3360 ActivityInfo aInfo = intent.resolveActivityInfo(
3361 mInitialApplication.getPackageManager(), PackageManager.GET_SHARED_LIBRARY_FILES);
3362 if (aInfo == null) {
3363 // Throw an exception.
3364 Instrumentation.checkStartActivityResult(
3365 ActivityManager.START_CLASS_NOT_FOUND, intent);
3366 }
3367 return aInfo;
3368 }
3369
3370 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
3371 public final Activity startActivityNow(Activity parent, String id,
3372 Intent intent, ActivityInfo activityInfo, IBinder token, Bundle state,
3373 Activity.NonConfigurationInstances lastNonConfigurationInstances, IBinder assistToken,
3374 IBinder shareableActivityToken) {
3375 ActivityClientRecord r = new ActivityClientRecord();
3376 r.token = token;
3377 r.assistToken = assistToken;
3378 r.shareableActivityToken = shareableActivityToken;
3379 r.ident = 0;
3380 r.intent = intent;
3381 r.state = state;
3382 r.parent = parent;
3383 r.embeddedID = id;
3384 r.activityInfo = activityInfo;
3385 r.lastNonConfigurationInstances = lastNonConfigurationInstances;
3386 if (localLOGV) {
3387 ComponentName compname = intent.getComponent();
3388 String name;
3389 if (compname != null) {
3390 name = compname.toShortString();
3391 } else {
3392 name = "(Intent " + intent + ").getComponent() returned null";
3393 }
3394 Slog.v(TAG, "Performing launch: action=" + intent.getAction()
3395 + ", comp=" + name
3396 + ", token=" + token);
3397 }
3398 // TODO(lifecycler): Can't switch to use #handleLaunchActivity() because it will try to
3399 // call #reportSizeConfigurations(), but the server might not know anything about the
3400 // activity if it was launched from LocalAcvitivyManager.
3401 return performLaunchActivity(r, null /* customIntent */);
3402 }
3403
3404 @UnsupportedAppUsage
3405 public final Activity getActivity(IBinder token) {
3406 final ActivityClientRecord activityRecord = mActivities.get(token);
3407 return activityRecord != null ? activityRecord.activity : null;
3408 }
3409
3410 @Override
3411 public ActivityClientRecord getActivityClient(IBinder token) {
3412 return mActivities.get(token);
3413 }
3414
3415 @VisibleForTesting(visibility = PACKAGE)
3416 public Configuration getConfiguration() {
3417 return mConfigurationController.getConfiguration();
3418 }
3419
3420 @Override
3421 public void updatePendingConfiguration(Configuration config) {
3422 final Configuration updatedConfig =
3423 mConfigurationController.updatePendingConfiguration(config);
3424 // This is only done to maintain @UnsupportedAppUsage and should be removed someday.
3425 if (updatedConfig != null) {
3426 mPendingConfiguration = updatedConfig;
3427 }
3428 }
3429
3430 @Override
3431 public void updateProcessState(int processState, boolean fromIpc) {
3432 synchronized (mAppThread) {
3433 if (mLastProcessState == processState) {
3434 return;
3435 }
3436 // Do not issue a transitional GC if we are transitioning between 2 cached states.
3437 // Only update if the state flips between cached and uncached or vice versa
3438 if (ActivityManager.isProcStateCached(mLastProcessState)
3439 != ActivityManager.isProcStateCached(processState)) {
3440 updateVmProcessState(processState);
3441 }
3442 mLastProcessState = processState;
3443 if (localLOGV) {
3444 Slog.i(TAG, "******************* PROCESS STATE CHANGED TO: " + processState
3445 + (fromIpc ? " (from ipc" : ""));
3446 }
3447 }
3448 }
3449
3450 /** Update VM state based on ActivityManager.PROCESS_STATE_* constants. */
3451 // Currently ART VM only uses state updates for Transitional GC, and thus
3452 // this function initiates a Transitional GC for transitions into Cached apps states.
3453 private void updateVmProcessState(int processState) {
3454 // Only a transition into Cached state should result in a Transitional GC request
3455 // to the ART runtime. Update VM state to JANK_IMPERCEPTIBLE in that case.
3456 // Note that there are 4 possible cached states currently, all of which are
3457 // JANK_IMPERCEPTIBLE from GC point of view.
3458 final int state = ActivityManager.isProcStateCached(processState)
3459 ? VM_PROCESS_STATE_JANK_IMPERCEPTIBLE
3460 : VM_PROCESS_STATE_JANK_PERCEPTIBLE;
3461 VMRuntime.getRuntime().updateProcessState(state);
3462 }
3463
3464 @Override
3465 public void countLaunchingActivities(int num) {
3466 mNumLaunchingActivities.getAndAdd(num);
3467 }
3468
3469 @UnsupportedAppUsage
3470 public final void sendActivityResult(
3471 IBinder token, String id, int requestCode,
3472 int resultCode, Intent data) {
3473 if (DEBUG_RESULTS) Slog.v(TAG, "sendActivityResult: id=" + id
3474 + " req=" + requestCode + " res=" + resultCode + " data=" + data);
3475 ArrayList<ResultInfo> list = new ArrayList<ResultInfo>();
3476 list.add(new ResultInfo(id, requestCode, resultCode, data));
3477 final ClientTransaction clientTransaction = ClientTransaction.obtain(mAppThread, token);
3478 clientTransaction.addCallback(ActivityResultItem.obtain(list));
3479 try {
3480 mAppThread.scheduleTransaction(clientTransaction);
3481 } catch (RemoteException e) {
3482 // Local scheduling
3483 }
3484 }
3485
3486 @Override
3487 TransactionExecutor getTransactionExecutor() {
3488 return mTransactionExecutor;
3489 }
3490
3491 void sendMessage(int what, Object obj) {
3492 sendMessage(what, obj, 0, 0, false);
3493 }
3494
3495 private void sendMessage(int what, Object obj, int arg1) {
3496 sendMessage(what, obj, arg1, 0, false);
3497 }
3498
3499 private void sendMessage(int what, Object obj, int arg1, int arg2) {
3500 sendMessage(what, obj, arg1, arg2, false);
3501 }
3502
3503 private void sendMessage(int what, Object obj, int arg1, int arg2, boolean async) {
3504 if (DEBUG_MESSAGES) {
3505 Slog.v(TAG,
3506 "SCHEDULE " + what + " " + mH.codeToString(what) + ": " + arg1 + " / " + obj);
3507 }
3508 Message msg = Message.obtain();
3509 msg.what = what;
3510 msg.obj = obj;
3511 msg.arg1 = arg1;
3512 msg.arg2 = arg2;
3513 if (async) {
3514 msg.setAsynchronous(true);
3515 }
3516 mH.sendMessage(msg);
3517 }
3518
3519 final void scheduleContextCleanup(ContextImpl context, String who,
3520 String what) {
3521 ContextCleanupInfo cci = new ContextCleanupInfo();
3522 cci.context = context;
3523 cci.who = who;
3524 cci.what = what;
3525 sendMessage(H.CLEAN_UP_CONTEXT, cci);
3526 }
3527
3528 /** Core implementation of activity launch. */
3529 private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
3530 ActivityInfo aInfo = r.activityInfo;
3531 if (r.packageInfo == null) {
3532 r.packageInfo = getPackageInfo(aInfo.applicationInfo, r.compatInfo,
3533 Context.CONTEXT_INCLUDE_CODE);
3534 }
3535
3536 ComponentName component = r.intent.getComponent();
3537 if (component == null) {
3538 component = r.intent.resolveActivity(
3539 mInitialApplication.getPackageManager());
3540 r.intent.setComponent(component);
3541 }
3542
3543 if (r.activityInfo.targetActivity != null) {
3544 component = new ComponentName(r.activityInfo.packageName,
3545 r.activityInfo.targetActivity);
3546 }
3547
3548 ContextImpl appContext = createBaseContextForActivity(r);
3549 Activity activity = null;
3550 try {
3551 java.lang.ClassLoader cl = appContext.getClassLoader();
3552 activity = mInstrumentation.newActivity(
3553 cl, component.getClassName(), r.intent);
3554 StrictMode.incrementExpectedActivityCount(activity.getClass());
3555 r.intent.setExtrasClassLoader(cl);
3556 r.intent.prepareToEnterProcess(isProtectedComponent(r.activityInfo),
3557 appContext.getAttributionSource());
3558 if (r.state != null) {
3559 r.state.setClassLoader(cl);
3560 }
3561 } catch (Exception e) {
3562 if (!mInstrumentation.onException(activity, e)) {
3563 throw new RuntimeException(
3564 "Unable to instantiate activity " + component
3565 + ": " + e.toString(), e);
3566 }
3567 }
3568
3569 try {
3570 Application app = r.packageInfo.makeApplicationInner(false, mInstrumentation);
3571
3572 if (localLOGV) Slog.v(TAG, "Performing launch of " + r);
3573 if (localLOGV) Slog.v(
3574 TAG, r + ": app=" + app
3575 + ", appName=" + app.getPackageName()
3576 + ", pkg=" + r.packageInfo.getPackageName()
3577 + ", comp=" + r.intent.getComponent().toShortString()
3578 + ", dir=" + r.packageInfo.getAppDir());
3579
3580 // updatePendingActivityConfiguration() reads from mActivities to update
3581 // ActivityClientRecord which runs in a different thread. Protect modifications to
3582 // mActivities to avoid race.
3583 synchronized (mResourcesManager) {
3584 mActivities.put(r.token, r);
3585 }
3586
3587 if (activity != null) {
3588 CharSequence title = r.activityInfo.loadLabel(appContext.getPackageManager());
3589 Configuration config =
3590 new Configuration(mConfigurationController.getCompatConfiguration());
3591 if (r.overrideConfig != null) {
3592 config.updateFrom(r.overrideConfig);
3593 }
3594 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Launching activity "
3595 + r.activityInfo.name + " with config " + config);
3596 Window window = null;
3597 if (r.mPendingRemoveWindow != null && r.mPreserveWindow) {
3598 window = r.mPendingRemoveWindow;
3599 r.mPendingRemoveWindow = null;
3600 r.mPendingRemoveWindowManager = null;
3601 }
3602
3603 // Activity resources must be initialized with the same loaders as the
3604 // application context.
3605 appContext.getResources().addLoaders(
3606 app.getResources().getLoaders().toArray(new ResourcesLoader[0]));
3607
3608 appContext.setOuterContext(activity);
3609 activity.attach(appContext, this, getInstrumentation(), r.token,
3610 r.ident, app, r.intent, r.activityInfo, title, r.parent,
3611 r.embeddedID, r.lastNonConfigurationInstances, config,
3612 r.referrer, r.voiceInteractor, window, r.activityConfigCallback,
3613 r.assistToken, r.shareableActivityToken);
3614
3615 if (customIntent != null) {
3616 activity.mIntent = customIntent;
3617 }
3618 r.lastNonConfigurationInstances = null;
3619 checkAndBlockForNetworkAccess();
3620 activity.mStartedActivity = false;
3621 int theme = r.activityInfo.getThemeResource();
3622 if (theme != 0) {
3623 activity.setTheme(theme);
3624 }
3625
3626 if (r.mActivityOptions != null) {
3627 activity.mPendingOptions = r.mActivityOptions;
3628 r.mActivityOptions = null;
3629 }
3630 activity.mLaunchedFromBubble = r.mLaunchedFromBubble;
3631 activity.mCalled = false;
3632 // Assigning the activity to the record before calling onCreate() allows
3633 // ActivityThread#getActivity() lookup for the callbacks triggered from
3634 // ActivityLifecycleCallbacks#onActivityCreated() or
3635 // ActivityLifecycleCallback#onActivityPostCreated().
3636 r.activity = activity;
3637 if (r.isPersistable()) {
3638 mInstrumentation.callActivityOnCreate(activity, r.state, r.persistentState);
3639 } else {
3640 mInstrumentation.callActivityOnCreate(activity, r.state);
3641 }
3642 if (!activity.mCalled) {
3643 throw new SuperNotCalledException(
3644 "Activity " + r.intent.getComponent().toShortString() +
3645 " did not call through to super.onCreate()");
3646 }
3647 mLastReportedWindowingMode.put(activity.getActivityToken(),
3648 config.windowConfiguration.getWindowingMode());
3649 }
3650 r.setState(ON_CREATE);
3651
3652 } catch (SuperNotCalledException e) {
3653 throw e;
3654
3655 } catch (Exception e) {
3656 if (!mInstrumentation.onException(activity, e)) {
3657 throw new RuntimeException(
3658 "Unable to start activity " + component
3659 + ": " + e.toString(), e);
3660 }
3661 }
3662
3663 return activity;
3664 }
3665
3666 @Override
3667 public void handleStartActivity(ActivityClientRecord r,
3668 PendingTransactionActions pendingActions, ActivityOptions activityOptions) {
3669 final Activity activity = r.activity;
3670 if (!r.stopped) {
3671 throw new IllegalStateException("Can't start activity that is not stopped.");
3672 }
3673 if (r.activity.mFinished) {
3674 // TODO(lifecycler): How can this happen?
3675 return;
3676 }
3677
3678 unscheduleGcIdler();
3679 if (activityOptions != null) {
3680 activity.mPendingOptions = activityOptions;
3681 }
3682
3683 // Start
3684 activity.performStart("handleStartActivity");
3685 r.setState(ON_START);
3686
3687 if (pendingActions == null) {
3688 // No more work to do.
3689 return;
3690 }
3691
3692 // Restore instance state
3693 if (pendingActions.shouldRestoreInstanceState()) {
3694 if (r.isPersistable()) {
3695 if (r.state != null || r.persistentState != null) {
3696 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state,
3697 r.persistentState);
3698 }
3699 } else if (r.state != null) {
3700 mInstrumentation.callActivityOnRestoreInstanceState(activity, r.state);
3701 }
3702 }
3703
3704 // Call postOnCreate()
3705 if (pendingActions.shouldCallOnPostCreate()) {
3706 activity.mCalled = false;
3707 if (r.isPersistable()) {
3708 mInstrumentation.callActivityOnPostCreate(activity, r.state,
3709 r.persistentState);
3710 } else {
3711 mInstrumentation.callActivityOnPostCreate(activity, r.state);
3712 }
3713 if (!activity.mCalled) {
3714 throw new SuperNotCalledException(
3715 "Activity " + r.intent.getComponent().toShortString()
3716 + " did not call through to super.onPostCreate()");
3717 }
3718 }
3719
3720 updateVisibility(r, true /* show */);
3721 mSomeActivitiesChanged = true;
3722 }
3723
3724 /**
3725 * Checks if {@link #mNetworkBlockSeq} is {@link #INVALID_PROC_STATE_SEQ} and if so, returns
3726 * immediately. Otherwise, makes a blocking call to ActivityManagerService to wait for the
3727 * network rules to get updated.
3728 */
3729 private void checkAndBlockForNetworkAccess() {
3730 synchronized (mNetworkPolicyLock) {
3731 if (mNetworkBlockSeq != INVALID_PROC_STATE_SEQ) {
3732 try {
3733 ActivityManager.getService().waitForNetworkStateUpdate(mNetworkBlockSeq);
3734 mNetworkBlockSeq = INVALID_PROC_STATE_SEQ;
3735 } catch (RemoteException ignored) {}
3736 }
3737 }
3738 }
3739
3740 private ContextImpl createBaseContextForActivity(ActivityClientRecord r) {
3741 final int displayId = ActivityClient.getInstance().getDisplayId(r.token);
3742 ContextImpl appContext = ContextImpl.createActivityContext(
3743 this, r.packageInfo, r.activityInfo, r.token, displayId, r.overrideConfig);
3744
3745 final DisplayManagerGlobal dm = DisplayManagerGlobal.getInstance();
3746 // For debugging purposes, if the activity's package name contains the value of
3747 // the "debug.use-second-display" system property as a substring, then show
3748 // its content on a secondary display if there is one.
3749 String pkgName = SystemProperties.get("debug.second-display.pkg");
3750 if (pkgName != null && !pkgName.isEmpty()
3751 && r.packageInfo.mPackageName.contains(pkgName)) {
3752 for (int id : dm.getDisplayIds()) {
3753 if (id != DEFAULT_DISPLAY) {
3754 Display display =
3755 dm.getCompatibleDisplay(id, appContext.getResources());
3756 appContext = (ContextImpl) appContext.createDisplayContext(display);
3757 break;
3758 }
3759 }
3760 }
3761 return appContext;
3762 }
3763
3764 /**
3765 * Extended implementation of activity launch. Used when server requests a launch or relaunch.
3766 */
3767 @Override
3768 public Activity handleLaunchActivity(ActivityClientRecord r,
3769 PendingTransactionActions pendingActions, Intent customIntent) {
3770 // If we are getting ready to gc after going to the background, well
3771 // we are back active so skip it.
3772 unscheduleGcIdler();
3773 mSomeActivitiesChanged = true;
3774
3775 if (r.profilerInfo != null) {
3776 mProfiler.setProfiler(r.profilerInfo);
3777 mProfiler.startProfiling();
3778 }
3779
3780 // Make sure we are running with the most recent config.
3781 mConfigurationController.handleConfigurationChanged(null, null);
3782
3783 if (localLOGV) Slog.v(
3784 TAG, "Handling launch of " + r);
3785
3786 // Initialize before creating the activity
3787 if (ThreadedRenderer.sRendererEnabled
3788 && (r.activityInfo.flags & ActivityInfo.FLAG_HARDWARE_ACCELERATED) != 0) {
3789 HardwareRenderer.preload();
3790 }
3791 WindowManagerGlobal.initialize();
3792
3793 // Hint the GraphicsEnvironment that an activity is launching on the process.
3794 GraphicsEnvironment.hintActivityLaunch();
3795
3796 final Activity a = performLaunchActivity(r, customIntent);
3797
3798 if (a != null) {
3799 r.createdConfig = new Configuration(mConfigurationController.getConfiguration());
3800 reportSizeConfigurations(r);
3801 if (!r.activity.mFinished && pendingActions != null) {
3802 pendingActions.setOldState(r.state);
3803 pendingActions.setRestoreInstanceState(true);
3804 pendingActions.setCallOnPostCreate(true);
3805 }
3806 } else {
3807 // If there was an error, for any reason, tell the activity manager to stop us.
3808 ActivityClient.getInstance().finishActivity(r.token, Activity.RESULT_CANCELED,
3809 null /* resultData */, Activity.DONT_FINISH_TASK_WITH_ACTIVITY);
3810 }
3811
3812 return a;
3813 }
3814
3815 private void reportSizeConfigurations(ActivityClientRecord r) {
3816 if (mActivitiesToBeDestroyed.containsKey(r.token)) {
3817 // Size configurations of a destroyed activity is meaningless.
3818 return;
3819 }
3820 Configuration[] configurations = r.activity.getResources().getSizeConfigurations();
3821 if (configurations == null) {
3822 return;
3823 }
3824 r.mSizeConfigurations = new SizeConfigurationBuckets(configurations);
3825 ActivityClient.getInstance().reportSizeConfigurations(r.token, r.mSizeConfigurations);
3826 }
3827
3828 private void deliverNewIntents(ActivityClientRecord r, List<ReferrerIntent> intents) {
3829 final int N = intents.size();
3830 for (int i=0; i<N; i++) {
3831 ReferrerIntent intent = intents.get(i);
3832 intent.setExtrasClassLoader(r.activity.getClassLoader());
3833 intent.prepareToEnterProcess(isProtectedComponent(r.activityInfo),
3834 r.activity.getAttributionSource());
3835 r.activity.mFragments.noteStateNotSaved();
3836 mInstrumentation.callActivityOnNewIntent(r.activity, intent);
3837 }
3838 }
3839
3840 @Override
3841 public void handleNewIntent(ActivityClientRecord r, List<ReferrerIntent> intents) {
3842 checkAndBlockForNetworkAccess();
3843 deliverNewIntents(r, intents);
3844 }
3845
3846 public void handleRequestAssistContextExtras(RequestAssistContextExtras cmd) {
3847 // Filling for autofill has a few differences:
3848 // - it does not need an AssistContent
3849 // - it does not call onProvideAssistData()
3850 // - it needs an IAutoFillCallback
3851 boolean forAutofill = cmd.requestType == ActivityManager.ASSIST_CONTEXT_AUTOFILL;
3852 // When only the AssistContent is requested, omit the AsssistStructure
3853 boolean requestedOnlyContent = cmd.requestType == ActivityManager.ASSIST_CONTEXT_CONTENT;
3854
3855 // TODO: decide if lastSessionId logic applies to autofill sessions
3856 if (mLastSessionId != cmd.sessionId) {
3857 // Clear the existing structures
3858 mLastSessionId = cmd.sessionId;
3859 for (int i = mLastAssistStructures.size() - 1; i >= 0; i--) {
3860 AssistStructure structure = mLastAssistStructures.get(i).get();
3861 if (structure != null) {
3862 structure.clearSendChannel();
3863 }
3864 mLastAssistStructures.remove(i);
3865 }
3866 }
3867
3868 Bundle data = new Bundle();
3869 AssistStructure structure = null;
3870 AssistContent content = forAutofill ? null : new AssistContent();
3871 final long startTime = SystemClock.uptimeMillis();
3872 ActivityClientRecord r = mActivities.get(cmd.activityToken);
3873 Uri referrer = null;
3874 if (r != null) {
3875 if (!forAutofill) {
3876 r.activity.getApplication().dispatchOnProvideAssistData(r.activity, data);
3877 r.activity.onProvideAssistData(data);
3878 referrer = r.activity.onProvideReferrer();
3879 }
3880 if (cmd.requestType == ActivityManager.ASSIST_CONTEXT_FULL || forAutofill
3881 || requestedOnlyContent) {
3882 if (!requestedOnlyContent) {
3883 structure = new AssistStructure(r.activity, forAutofill, cmd.flags);
3884 }
3885 Intent activityIntent = r.activity.getIntent();
3886 boolean notSecure = r.window == null ||
3887 (r.window.getAttributes().flags
3888 & WindowManager.LayoutParams.FLAG_SECURE) == 0;
3889 if (activityIntent != null && notSecure) {
3890 if (!forAutofill) {
3891 Intent intent = new Intent(activityIntent);
3892 intent.setFlags(intent.getFlags() & ~(Intent.FLAG_GRANT_WRITE_URI_PERMISSION
3893 | Intent.FLAG_GRANT_PERSISTABLE_URI_PERMISSION));
3894 content.setDefaultIntent(intent);
3895 }
3896 } else {
3897 if (!forAutofill) {
3898 content.setDefaultIntent(new Intent());
3899 }
3900 }
3901 if (!forAutofill) {
3902 r.activity.onProvideAssistContent(content);
3903 }
3904 }
3905 }
3906
3907 if (!requestedOnlyContent) {
3908 if (structure == null) {
3909 structure = new AssistStructure();
3910 }
3911
3912 // TODO: decide if lastSessionId logic applies to autofill sessions
3913
3914 structure.setAcquisitionStartTime(startTime);
3915 structure.setAcquisitionEndTime(SystemClock.uptimeMillis());
3916
3917 mLastAssistStructures.add(new WeakReference<>(structure));
3918 }
3919
3920 IActivityTaskManager mgr = ActivityTaskManager.getService();
3921 try {
3922 mgr.reportAssistContextExtras(cmd.requestToken, data, structure, content, referrer);
3923 } catch (RemoteException e) {
3924 throw e.rethrowFromSystemServer();
3925 }
3926 }
3927
3928 /** Fetches the user actions for the corresponding activity */
3929 private void handleRequestDirectActions(@NonNull IBinder activityToken,
3930 @NonNull IVoiceInteractor interactor, @NonNull CancellationSignal cancellationSignal,
3931 @NonNull RemoteCallback callback, int retryCount) {
3932 final ActivityClientRecord r = mActivities.get(activityToken);
3933 if (r == null) {
3934 Log.w(TAG, "requestDirectActions(): no activity for " + activityToken);
3935 callback.sendResult(null);
3936 return;
3937 }
3938 final int lifecycleState = r.getLifecycleState();
3939 if (lifecycleState < ON_START) {
3940 // TODO(b/234173463): requestDirectActions callback should indicate errors
3941 if (retryCount > 0) {
3942 mH.sendMessageDelayed(
3943 PooledLambda.obtainMessage(ActivityThread::handleRequestDirectActions,
3944 ActivityThread.this, activityToken, interactor, cancellationSignal,
3945 callback, retryCount - 1), REQUEST_DIRECT_ACTIONS_RETRY_TIME_MS);
3946 return;
3947 }
3948 Log.w(TAG, "requestDirectActions(" + r + "): wrong lifecycle: " + lifecycleState);
3949 callback.sendResult(null);
3950 return;
3951 }
3952 if (lifecycleState >= ON_STOP) {
3953 Log.w(TAG, "requestDirectActions(" + r + "): wrong lifecycle: " + lifecycleState);
3954 callback.sendResult(null);
3955 return;
3956 }
3957 if (r.activity.mVoiceInteractor == null
3958 || r.activity.mVoiceInteractor.mInteractor.asBinder()
3959 != interactor.asBinder()) {
3960 if (r.activity.mVoiceInteractor != null) {
3961 r.activity.mVoiceInteractor.destroy();
3962 }
3963 r.activity.mVoiceInteractor = new VoiceInteractor(interactor, r.activity,
3964 r.activity, Looper.myLooper());
3965 }
3966 r.activity.onGetDirectActions(cancellationSignal, (actions) -> {
3967 Objects.requireNonNull(actions);
3968 Preconditions.checkCollectionElementsNotNull(actions, "actions");
3969 if (!actions.isEmpty()) {
3970 final int actionCount = actions.size();
3971 for (int i = 0; i < actionCount; i++) {
3972 final DirectAction action = actions.get(i);
3973 action.setSource(r.activity.getTaskId(), r.activity.getAssistToken());
3974 }
3975 final Bundle result = new Bundle();
3976 result.putParcelable(DirectAction.KEY_ACTIONS_LIST,
3977 new ParceledListSlice<>(actions));
3978 callback.sendResult(result);
3979 } else {
3980 callback.sendResult(null);
3981 }
3982 });
3983 }
3984
3985 /** Performs an actions in the corresponding activity */
3986 private void handlePerformDirectAction(@NonNull IBinder activityToken,
3987 @NonNull String actionId, @Nullable Bundle arguments,
3988 @NonNull CancellationSignal cancellationSignal,
3989 @NonNull RemoteCallback resultCallback) {
3990 final ActivityClientRecord r = mActivities.get(activityToken);
3991 if (r != null) {
3992 final int lifecycleState = r.getLifecycleState();
3993 if (lifecycleState < ON_START || lifecycleState >= ON_STOP) {
3994 resultCallback.sendResult(null);
3995 return;
3996 }
3997 final Bundle nonNullArguments = (arguments != null) ? arguments : Bundle.EMPTY;
3998 r.activity.onPerformDirectAction(actionId, nonNullArguments, cancellationSignal,
3999 resultCallback::sendResult);
4000 } else {
4001 resultCallback.sendResult(null);
4002 }
4003 }
4004
4005 public void handleTranslucentConversionComplete(IBinder token, boolean drawComplete) {
4006 ActivityClientRecord r = mActivities.get(token);
4007 if (r != null) {
4008 r.activity.onTranslucentConversionComplete(drawComplete);
4009 }
4010 }
4011
4012 public void onNewActivityOptions(IBinder token, ActivityOptions options) {
4013 ActivityClientRecord r = mActivities.get(token);
4014 if (r != null) {
4015 r.activity.onNewActivityOptions(options);
4016 }
4017 }
4018
4019 public void handleInstallProvider(ProviderInfo info) {
4020 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
4021 try {
4022 installContentProviders(mInitialApplication, Arrays.asList(info));
4023 } finally {
4024 StrictMode.setThreadPolicy(oldPolicy);
4025 }
4026 }
4027
4028 private void handleEnterAnimationComplete(IBinder token) {
4029 ActivityClientRecord r = mActivities.get(token);
4030 if (r != null) {
4031 r.activity.dispatchEnterAnimationComplete();
4032 }
4033 }
4034
4035 private void handleStartBinderTracking() {
4036 Binder.enableStackTracking();
4037 }
4038
4039 private void handleStopBinderTrackingAndDump(ParcelFileDescriptor fd) {
4040 try {
4041 Binder.disableStackTracking();
4042 Binder.getTransactionTracker().writeTracesToFile(fd);
4043 } finally {
4044 IoUtils.closeQuietly(fd);
4045 Binder.getTransactionTracker().clearTraces();
4046 }
4047 }
4048
4049 @Override
4050 public void handlePictureInPictureRequested(ActivityClientRecord r) {
4051 final boolean receivedByApp = r.activity.onPictureInPictureRequested();
4052 if (!receivedByApp) {
4053 // Previous recommendation was for apps to enter picture-in-picture in
4054 // onUserLeavingHint() for cases such as the app being put into the background. For
4055 // backwards compatibility with apps that are not using the newer
4056 // onPictureInPictureRequested() callback, we schedule the life cycle events needed to
4057 // trigger onUserLeavingHint(), then we return the activity to its previous state.
4058 schedulePauseWithUserLeaveHintAndReturnToCurrentState(r);
4059 }
4060 }
4061
4062 @Override
4063 public void handlePictureInPictureStateChanged(@NonNull ActivityClientRecord r,
4064 PictureInPictureUiState pipState) {
4065 r.activity.onPictureInPictureUiStateChanged(pipState);
4066 }
4067
4068 /**
4069 * Register a splash screen manager to this process.
4070 */
4071 public void registerSplashScreenManager(
4072 @NonNull SplashScreen.SplashScreenManagerGlobal manager) {
4073 synchronized (this) {
4074 mSplashScreenGlobal = manager;
4075 }
4076 }
4077
4078 @Override
4079 public boolean isHandleSplashScreenExit(@NonNull IBinder token) {
4080 synchronized (this) {
4081 return mSplashScreenGlobal != null && mSplashScreenGlobal.containsExitListener(token);
4082 }
4083 }
4084
4085 @Override
4086 public void handleAttachSplashScreenView(@NonNull ActivityClientRecord r,
4087 @Nullable SplashScreenView.SplashScreenViewParcelable parcelable,
4088 @NonNull SurfaceControl startingWindowLeash) {
4089 final DecorView decorView = (DecorView) r.window.peekDecorView();
4090 if (parcelable != null && decorView != null) {
4091 createSplashScreen(r, decorView, parcelable, startingWindowLeash);
4092 } else {
4093 // shouldn't happen!
4094 Slog.e(TAG, "handleAttachSplashScreenView failed, unable to attach");
4095 }
4096 }
4097
4098 private void createSplashScreen(ActivityClientRecord r, DecorView decorView,
4099 SplashScreenView.SplashScreenViewParcelable parcelable,
4100 @NonNull SurfaceControl startingWindowLeash) {
4101 final SplashScreenView.Builder builder = new SplashScreenView.Builder(r.activity);
4102 final SplashScreenView view = builder.createFromParcel(parcelable).build();
4103 view.attachHostWindow(r.window);
4104 decorView.addView(view);
4105 view.requestLayout();
4106
4107 view.getViewTreeObserver().addOnDrawListener(new ViewTreeObserver.OnDrawListener() {
4108 private boolean mHandled = false;
4109 @Override
4110 public void onDraw() {
4111 if (mHandled) {
4112 return;
4113 }
4114 mHandled = true;
4115 // Transfer the splash screen view from shell to client.
4116 // Call syncTransferSplashscreenViewTransaction at the first onDraw so we can ensure
4117 // the client view is ready to show and we can use applyTransactionOnDraw to make
4118 // all transitions happen at the same frame.
4119 syncTransferSplashscreenViewTransaction(
4120 view, r.token, decorView, startingWindowLeash);
4121 view.post(() -> view.getViewTreeObserver().removeOnDrawListener(this));
4122 }
4123 });
4124 }
4125
4126 private void reportSplashscreenViewShown(IBinder token, SplashScreenView view) {
4127 ActivityClient.getInstance().reportSplashScreenAttached(token);
4128 synchronized (this) {
4129 if (mSplashScreenGlobal != null) {
4130 mSplashScreenGlobal.handOverSplashScreenView(token, view);
4131 }
4132 }
4133 }
4134
4135 private void syncTransferSplashscreenViewTransaction(SplashScreenView view, IBinder token,
4136 View decorView, @NonNull SurfaceControl startingWindowLeash) {
4137 // Ensure splash screen view is shown before remove the splash screen window.
4138 // Once the copied splash screen view is onDrawn on decor view, use applyTransactionOnDraw
4139 // to ensure the transfer of surface view and hide starting window are happen at the same
4140 // frame.
4141 final SurfaceControl.Transaction transaction = new SurfaceControl.Transaction();
4142 transaction.hide(startingWindowLeash);
4143
4144 decorView.getViewRootImpl().applyTransactionOnDraw(transaction);
4145 view.syncTransferSurfaceOnDraw();
4146 // Tell server we can remove the starting window
4147 decorView.postOnAnimation(() -> reportSplashscreenViewShown(token, view));
4148 }
4149
4150 /**
4151 * Cycle activity through onPause and onUserLeaveHint so that PIP is entered if supported, then
4152 * return to its previous state. This allows activities that rely on onUserLeaveHint instead of
4153 * onPictureInPictureRequested to enter picture-in-picture.
4154 */
4155 private void schedulePauseWithUserLeaveHintAndReturnToCurrentState(ActivityClientRecord r) {
4156 final int prevState = r.getLifecycleState();
4157 if (prevState != ON_RESUME && prevState != ON_PAUSE) {
4158 return;
4159 }
4160
4161 switch (prevState) {
4162 case ON_RESUME:
4163 // Schedule a PAUSE then return to RESUME.
4164 schedulePauseWithUserLeavingHint(r);
4165 scheduleResume(r);
4166 break;
4167 case ON_PAUSE:
4168 // Schedule a RESUME then return to PAUSE.
4169 scheduleResume(r);
4170 schedulePauseWithUserLeavingHint(r);
4171 break;
4172 }
4173 }
4174
4175 private void schedulePauseWithUserLeavingHint(ActivityClientRecord r) {
4176 final ClientTransaction transaction = ClientTransaction.obtain(this.mAppThread, r.token);
4177 transaction.setLifecycleStateRequest(PauseActivityItem.obtain(r.activity.isFinishing(),
4178 /* userLeaving */ true, r.activity.mConfigChangeFlags, /* dontReport */ false,
4179 /* autoEnteringPip */ false));
4180 executeTransaction(transaction);
4181 }
4182
4183 private void scheduleResume(ActivityClientRecord r) {
4184 final ClientTransaction transaction = ClientTransaction.obtain(this.mAppThread, r.token);
4185 transaction.setLifecycleStateRequest(ResumeActivityItem.obtain(/* isForward */ false,
4186 /* shouldSendCompatFakeFocus */ false));
4187 executeTransaction(transaction);
4188 }
4189
4190 private void handleLocalVoiceInteractionStarted(IBinder token, IVoiceInteractor interactor) {
4191 final ActivityClientRecord r = mActivities.get(token);
4192 if (r != null) {
4193 r.voiceInteractor = interactor;
4194 r.activity.setVoiceInteractor(interactor);
4195 if (interactor == null) {
4196 r.activity.onLocalVoiceInteractionStopped();
4197 } else {
4198 r.activity.onLocalVoiceInteractionStarted();
4199 }
4200 }
4201 }
4202
4203 private static boolean attemptAttachAgent(String agent, ClassLoader classLoader) {
4204 try {
4205 VMDebug.attachAgent(agent, classLoader);
4206 return true;
4207 } catch (IOException e) {
4208 Slog.e(TAG, "Attaching agent with " + classLoader + " failed: " + agent);
4209 return false;
4210 }
4211 }
4212
4213 static void handleAttachAgent(String agent, LoadedApk loadedApk) {
4214 ClassLoader classLoader = loadedApk != null ? loadedApk.getClassLoader() : null;
4215 if (attemptAttachAgent(agent, classLoader)) {
4216 return;
4217 }
4218 if (classLoader != null) {
4219 attemptAttachAgent(agent, null);
4220 }
4221 }
4222
4223 static void handleAttachStartupAgents(String dataDir) {
4224 try {
4225 Path codeCache = ContextImpl.getCodeCacheDirBeforeBind(new File(dataDir)).toPath();
4226 if (!Files.exists(codeCache)) {
4227 return;
4228 }
4229 Path startupPath = codeCache.resolve("startup_agents");
4230 if (Files.exists(startupPath)) {
4231 try (DirectoryStream<Path> startupFiles = Files.newDirectoryStream(startupPath)) {
4232 for (Path p : startupFiles) {
4233 handleAttachAgent(
4234 p.toAbsolutePath().toString()
4235 + "="
4236 + dataDir,
4237 null);
4238 }
4239 }
4240 }
4241 } catch (Exception e) {
4242 // Ignored.
4243 }
4244 }
4245
4246 private void updateUiTranslationState(IBinder activityToken, int state,
4247 TranslationSpec sourceSpec, TranslationSpec targetSpec, List<AutofillId> viewIds,
4248 UiTranslationSpec uiTranslationSpec) {
4249 final ActivityClientRecord r = mActivities.get(activityToken);
4250 if (r == null) {
4251 Log.w(TAG, "updateUiTranslationState(): no activity for " + activityToken);
4252 return;
4253 }
4254 r.activity.updateUiTranslationState(
4255 state, sourceSpec, targetSpec, viewIds, uiTranslationSpec);
4256 }
4257
4258 private static final ThreadLocal<Intent> sCurrentBroadcastIntent = new ThreadLocal<Intent>();
4259
4260 /**
4261 * Return the Intent that's currently being handled by a
4262 * BroadcastReceiver on this thread, or null if none.
4263 * @hide
4264 */
4265 public static Intent getIntentBeingBroadcast() {
4266 return sCurrentBroadcastIntent.get();
4267 }
4268
4269 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.P, trackingBug = 115609023)
4270 private void handleReceiver(ReceiverData data) {
4271 // If we are getting ready to gc after going to the background, well
4272 // we are back active so skip it.
4273 unscheduleGcIdler();
4274
4275 String component = data.intent.getComponent().getClassName();
4276
4277 LoadedApk packageInfo = getPackageInfoNoCheck(
4278 data.info.applicationInfo, data.compatInfo);
4279
4280 IActivityManager mgr = ActivityManager.getService();
4281
4282 Application app;
4283 BroadcastReceiver receiver;
4284 ContextImpl context;
4285 try {
4286 app = packageInfo.makeApplicationInner(false, mInstrumentation);
4287 context = (ContextImpl) app.getBaseContext();
4288 if (data.info.splitName != null) {
4289 context = (ContextImpl) context.createContextForSplit(data.info.splitName);
4290 }
4291 if (data.info.attributionTags != null && data.info.attributionTags.length > 0) {
4292 final String attributionTag = data.info.attributionTags[0];
4293 context = (ContextImpl) context.createAttributionContext(attributionTag);
4294 }
4295 java.lang.ClassLoader cl = context.getClassLoader();
4296 data.intent.setExtrasClassLoader(cl);
4297 data.intent.prepareToEnterProcess(
4298 isProtectedComponent(data.info) || isProtectedBroadcast(data.intent),
4299 context.getAttributionSource());
4300 data.setExtrasClassLoader(cl);
4301 receiver = packageInfo.getAppFactory()
4302 .instantiateReceiver(cl, data.info.name, data.intent);
4303 } catch (Exception e) {
4304 if (DEBUG_BROADCAST) Slog.i(TAG,
4305 "Finishing failed broadcast to " + data.intent.getComponent());
4306 data.sendFinished(mgr);
4307 throw new RuntimeException(
4308 "Unable to instantiate receiver " + component
4309 + ": " + e.toString(), e);
4310 }
4311
4312 try {
4313 if (localLOGV) Slog.v(
4314 TAG, "Performing receive of " + data.intent
4315 + ": app=" + app
4316 + ", appName=" + app.getPackageName()
4317 + ", pkg=" + packageInfo.getPackageName()
4318 + ", comp=" + data.intent.getComponent().toShortString()
4319 + ", dir=" + packageInfo.getAppDir());
4320
4321 sCurrentBroadcastIntent.set(data.intent);
4322 receiver.setPendingResult(data);
4323 receiver.onReceive(context.getReceiverRestrictedContext(),
4324 data.intent);
4325 } catch (Exception e) {
4326 if (DEBUG_BROADCAST) Slog.i(TAG,
4327 "Finishing failed broadcast to " + data.intent.getComponent());
4328 data.sendFinished(mgr);
4329 if (!mInstrumentation.onException(receiver, e)) {
4330 throw new RuntimeException(
4331 "Unable to start receiver " + component
4332 + ": " + e.toString(), e);
4333 }
4334 } finally {
4335 sCurrentBroadcastIntent.set(null);
4336 }
4337
4338 if (receiver.getPendingResult() != null) {
4339 data.finish();
4340 }
4341 }
4342
4343 // Instantiate a BackupAgent and tell it that it's alive
4344 private void handleCreateBackupAgent(CreateBackupAgentData data) {
4345 if (DEBUG_BACKUP) Slog.v(TAG, "handleCreateBackupAgent: " + data);
4346
4347 // Validity check the requested target package's uid against ours
4348 try {
4349 PackageInfo requestedPackage = getPackageManager().getPackageInfo(
4350 data.appInfo.packageName, 0, UserHandle.myUserId());
4351 if (requestedPackage.applicationInfo.uid != Process.myUid()) {
4352 Slog.w(TAG, "Asked to instantiate non-matching package "
4353 + data.appInfo.packageName);
4354 return;
4355 }
4356 } catch (RemoteException e) {
4357 throw e.rethrowFromSystemServer();
4358 }
4359
4360 // no longer idle; we have backup work to do
4361 unscheduleGcIdler();
4362
4363 // instantiate the BackupAgent class named in the manifest
4364 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
4365 String packageName = packageInfo.mPackageName;
4366 if (packageName == null) {
4367 Slog.d(TAG, "Asked to create backup agent for nonexistent package");
4368 return;
4369 }
4370
4371 String classname = getBackupAgentName(data);
4372
4373 try {
4374 IBinder binder = null;
4375 ArrayMap<String, BackupAgent> backupAgents = getBackupAgentsForUser(data.userId);
4376 BackupAgent agent = backupAgents.get(packageName);
4377 if (agent != null) {
4378 // reusing the existing instance
4379 if (DEBUG_BACKUP) {
4380 Slog.v(TAG, "Reusing existing agent instance");
4381 }
4382 binder = agent.onBind();
4383 } else {
4384 try {
4385 if (DEBUG_BACKUP) Slog.v(TAG, "Initializing agent class " + classname);
4386
4387 java.lang.ClassLoader cl = packageInfo.getClassLoader();
4388 agent = (BackupAgent) cl.loadClass(classname).newInstance();
4389
4390 // set up the agent's context
4391 ContextImpl context = ContextImpl.createAppContext(this, packageInfo);
4392 context.setOuterContext(agent);
4393 agent.attach(context);
4394
4395 agent.onCreate(UserHandle.of(data.userId), data.operationType);
4396 binder = agent.onBind();
4397 backupAgents.put(packageName, agent);
4398 } catch (Exception e) {
4399 // If this is during restore, fail silently; otherwise go
4400 // ahead and let the user see the crash.
4401 Slog.e(TAG, "Agent threw during creation: " + e);
4402 if (data.backupMode != ApplicationThreadConstants.BACKUP_MODE_RESTORE
4403 && data.backupMode !=
4404 ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL) {
4405 throw e;
4406 }
4407 // falling through with 'binder' still null
4408 }
4409 }
4410
4411 // tell the OS that we're live now
4412 try {
4413 ActivityManager.getService().backupAgentCreated(packageName, binder, data.userId);
4414 } catch (RemoteException e) {
4415 throw e.rethrowFromSystemServer();
4416 }
4417 } catch (Exception e) {
4418 throw new RuntimeException("Unable to create BackupAgent "
4419 + classname + ": " + e.toString(), e);
4420 }
4421 }
4422
4423 private String getBackupAgentName(CreateBackupAgentData data) {
4424 String agentName = data.appInfo.backupAgentName;
4425 // full backup operation but no app-supplied agent? use the default implementation
4426 if (agentName == null && (data.backupMode == ApplicationThreadConstants.BACKUP_MODE_FULL
4427 || data.backupMode == ApplicationThreadConstants.BACKUP_MODE_RESTORE_FULL)) {
4428 agentName = DEFAULT_FULL_BACKUP_AGENT;
4429 }
4430 return agentName;
4431 }
4432
4433 // Tear down a BackupAgent
4434 private void handleDestroyBackupAgent(CreateBackupAgentData data) {
4435 if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
4436
4437 LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
4438 String packageName = packageInfo.mPackageName;
4439 ArrayMap<String, BackupAgent> backupAgents = getBackupAgentsForUser(data.userId);
4440 BackupAgent agent = backupAgents.get(packageName);
4441 if (agent != null) {
4442 try {
4443 agent.onDestroy();
4444 } catch (Exception e) {
4445 Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
4446 e.printStackTrace();
4447 }
4448 backupAgents.remove(packageName);
4449 } else {
4450 Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
4451 }
4452 }
4453
4454 private ArrayMap<String, BackupAgent> getBackupAgentsForUser(int userId) {
4455 ArrayMap<String, BackupAgent> backupAgents = mBackupAgentsByUser.get(userId);
4456 if (backupAgents == null) {
4457 backupAgents = new ArrayMap<>();
4458 mBackupAgentsByUser.put(userId, backupAgents);
4459 }
4460 return backupAgents;
4461 }
4462
4463 @UnsupportedAppUsage
4464 private void handleCreateService(CreateServiceData data) {
4465 // If we are getting ready to gc after going to the background, well
4466 // we are back active so skip it.
4467 unscheduleGcIdler();
4468
4469 LoadedApk packageInfo = getPackageInfoNoCheck(
4470 data.info.applicationInfo, data.compatInfo);
4471 Service service = null;
4472 try {
4473 if (localLOGV) Slog.v(TAG, "Creating service " + data.info.name);
4474
4475 Application app = packageInfo.makeApplicationInner(false, mInstrumentation);
4476
4477 final java.lang.ClassLoader cl;
4478 if (data.info.splitName != null) {
4479 cl = packageInfo.getSplitClassLoader(data.info.splitName);
4480 } else {
4481 cl = packageInfo.getClassLoader();
4482 }
4483 service = packageInfo.getAppFactory()
4484 .instantiateService(cl, data.info.name, data.intent);
4485 ContextImpl context = ContextImpl.getImpl(service
4486 .createServiceBaseContext(this, packageInfo));
4487 if (data.info.splitName != null) {
4488 context = (ContextImpl) context.createContextForSplit(data.info.splitName);
4489 }
4490 if (data.info.attributionTags != null && data.info.attributionTags.length > 0) {
4491 final String attributionTag = data.info.attributionTags[0];
4492 context = (ContextImpl) context.createAttributionContext(attributionTag);
4493 }
4494 // Service resources must be initialized with the same loaders as the application
4495 // context.
4496 context.getResources().addLoaders(
4497 app.getResources().getLoaders().toArray(new ResourcesLoader[0]));
4498
4499 context.setOuterContext(service);
4500 service.attach(context, this, data.info.name, data.token, app,
4501 ActivityManager.getService());
4502 service.onCreate();
4503 mServicesData.put(data.token, data);
4504 mServices.put(data.token, service);
4505 try {
4506 ActivityManager.getService().serviceDoneExecuting(
4507 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
4508 } catch (RemoteException e) {
4509 throw e.rethrowFromSystemServer();
4510 }
4511 } catch (Exception e) {
4512 if (!mInstrumentation.onException(service, e)) {
4513 throw new RuntimeException(
4514 "Unable to create service " + data.info.name
4515 + ": " + e.toString(), e);
4516 }
4517 }
4518 }
4519
4520 private void handleBindService(BindServiceData data) {
4521 CreateServiceData createData = mServicesData.get(data.token);
4522 Service s = mServices.get(data.token);
4523 if (DEBUG_SERVICE)
4524 Slog.v(TAG, "handleBindService s=" + s + " rebind=" + data.rebind);
4525 if (s != null) {
4526 try {
4527 data.intent.setExtrasClassLoader(s.getClassLoader());
4528 data.intent.prepareToEnterProcess(isProtectedComponent(createData.info),
4529 s.getAttributionSource());
4530 try {
4531 if (!data.rebind) {
4532 IBinder binder = s.onBind(data.intent);
4533 ActivityManager.getService().publishService(
4534 data.token, data.intent, binder);
4535 } else {
4536 s.onRebind(data.intent);
4537 ActivityManager.getService().serviceDoneExecuting(
4538 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
4539 }
4540 } catch (RemoteException ex) {
4541 throw ex.rethrowFromSystemServer();
4542 }
4543 } catch (Exception e) {
4544 if (!mInstrumentation.onException(s, e)) {
4545 throw new RuntimeException(
4546 "Unable to bind to service " + s
4547 + " with " + data.intent + ": " + e.toString(), e);
4548 }
4549 }
4550 }
4551 }
4552
4553 private void handleUnbindService(BindServiceData data) {
4554 CreateServiceData createData = mServicesData.get(data.token);
4555 Service s = mServices.get(data.token);
4556 if (s != null) {
4557 try {
4558 data.intent.setExtrasClassLoader(s.getClassLoader());
4559 data.intent.prepareToEnterProcess(isProtectedComponent(createData.info),
4560 s.getAttributionSource());
4561 boolean doRebind = s.onUnbind(data.intent);
4562 try {
4563 if (doRebind) {
4564 ActivityManager.getService().unbindFinished(
4565 data.token, data.intent, doRebind);
4566 } else {
4567 ActivityManager.getService().serviceDoneExecuting(
4568 data.token, SERVICE_DONE_EXECUTING_ANON, 0, 0);
4569 }
4570 } catch (RemoteException ex) {
4571 throw ex.rethrowFromSystemServer();
4572 }
4573 } catch (Exception e) {
4574 if (!mInstrumentation.onException(s, e)) {
4575 throw new RuntimeException(
4576 "Unable to unbind to service " + s
4577 + " with " + data.intent + ": " + e.toString(), e);
4578 }
4579 }
4580 }
4581 }
4582
4583 private void handleDumpGfxInfo(DumpComponentInfo info) {
4584 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
4585 try {
4586 ThreadedRenderer.handleDumpGfxInfo(info.fd.getFileDescriptor(), info.args);
4587 } catch (Exception e) {
4588 Log.w(TAG, "Caught exception from dumpGfxInfo()", e);
4589 } finally {
4590 IoUtils.closeQuietly(info.fd);
4591 StrictMode.setThreadPolicy(oldPolicy);
4592 }
4593 }
4594
4595 private void handleDumpService(DumpComponentInfo info) {
4596 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
4597 try {
4598 Service s = mServices.get(info.token);
4599 if (s != null) {
4600 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
4601 info.fd.getFileDescriptor()));
4602 s.dump(info.fd.getFileDescriptor(), pw, info.args);
4603 pw.flush();
4604 }
4605 } finally {
4606 IoUtils.closeQuietly(info.fd);
4607 StrictMode.setThreadPolicy(oldPolicy);
4608 }
4609 }
4610
4611 private void handleDumpResources(DumpResourcesData info) {
4612 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
4613 try {
4614 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
4615 info.fd.getFileDescriptor()));
4616
4617 Resources.dumpHistory(pw, "");
4618 pw.flush();
4619 if (info.finishCallback != null) {
4620 info.finishCallback.sendResult(null);
4621 }
4622 } finally {
4623 IoUtils.closeQuietly(info.fd);
4624 StrictMode.setThreadPolicy(oldPolicy);
4625 }
4626 }
4627
4628 private void handleDumpActivity(DumpComponentInfo info) {
4629 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
4630 try {
4631 ActivityClientRecord r = mActivities.get(info.token);
4632 if (r != null && r.activity != null) {
4633 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
4634 info.fd.getFileDescriptor()));
4635 r.activity.dumpInternal(info.prefix, info.fd.getFileDescriptor(), pw, info.args);
4636 pw.flush();
4637 }
4638 } finally {
4639 IoUtils.closeQuietly(info.fd);
4640 StrictMode.setThreadPolicy(oldPolicy);
4641 }
4642 }
4643
4644 private void handleDumpProvider(DumpComponentInfo info) {
4645 final StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskWrites();
4646 try {
4647 ProviderClientRecord r = mLocalProviders.get(info.token);
4648 if (r != null && r.mLocalProvider != null) {
4649 PrintWriter pw = new FastPrintWriter(new FileOutputStream(
4650 info.fd.getFileDescriptor()));
4651 r.mLocalProvider.dump(info.fd.getFileDescriptor(), pw, info.args);
4652 pw.flush();
4653 }
4654 } finally {
4655 IoUtils.closeQuietly(info.fd);
4656 StrictMode.setThreadPolicy(oldPolicy);
4657 }
4658 }
4659
4660 private void handleServiceArgs(ServiceArgsData data) {
4661 CreateServiceData createData = mServicesData.get(data.token);
4662 Service s = mServices.get(data.token);
4663 if (s != null) {
4664 try {
4665 if (data.args != null) {
4666 data.args.setExtrasClassLoader(s.getClassLoader());
4667 data.args.prepareToEnterProcess(isProtectedComponent(createData.info),
4668 s.getAttributionSource());
4669 }
4670 int res;
4671 if (!data.taskRemoved) {
4672 res = s.onStartCommand(data.args, data.flags, data.startId);
4673 } else {
4674 s.onTaskRemoved(data.args);
4675 res = Service.START_TASK_REMOVED_COMPLETE;
4676 }
4677
4678 QueuedWork.waitToFinish();
4679
4680 try {
4681 ActivityManager.getService().serviceDoneExecuting(
4682 data.token, SERVICE_DONE_EXECUTING_START, data.startId, res);
4683 } catch (RemoteException e) {
4684 throw e.rethrowFromSystemServer();
4685 }
4686 } catch (Exception e) {
4687 if (!mInstrumentation.onException(s, e)) {
4688 throw new RuntimeException(
4689 "Unable to start service " + s
4690 + " with " + data.args + ": " + e.toString(), e);
4691 }
4692 }
4693 }
4694 }
4695
4696 private void handleStopService(IBinder token) {
4697 mServicesData.remove(token);
4698 Service s = mServices.remove(token);
4699 if (s != null) {
4700 try {
4701 if (localLOGV) Slog.v(TAG, "Destroying service " + s);
4702 s.onDestroy();
4703 s.detachAndCleanUp();
4704 Context context = s.getBaseContext();
4705 if (context instanceof ContextImpl) {
4706 final String who = s.getClassName();
4707 ((ContextImpl) context).scheduleFinalCleanup(who, "Service");
4708 }
4709
4710 QueuedWork.waitToFinish();
4711
4712 try {
4713 ActivityManager.getService().serviceDoneExecuting(
4714 token, SERVICE_DONE_EXECUTING_STOP, 0, 0);
4715 } catch (RemoteException e) {
4716 throw e.rethrowFromSystemServer();
4717 }
4718 } catch (Exception e) {
4719 if (!mInstrumentation.onException(s, e)) {
4720 throw new RuntimeException(
4721 "Unable to stop service " + s
4722 + ": " + e.toString(), e);
4723 }
4724 Slog.i(TAG, "handleStopService: exception for " + token, e);
4725 }
4726 } else {
4727 Slog.i(TAG, "handleStopService: token=" + token + " not found.");
4728 }
4729 //Slog.i(TAG, "Running services: " + mServices);
4730 }
4731
4732 /**
4733 * Resume the activity.
4734 * @param r Target activity record.
4735 * @param finalStateRequest Flag indicating if this is part of final state resolution for a
4736 * transaction.
4737 * @param reason Reason for performing the action.
4738 *
4739 * @return {@code true} that was resumed, {@code false} otherwise.
4740 */
4741 @VisibleForTesting
4742 public boolean performResumeActivity(ActivityClientRecord r, boolean finalStateRequest,
4743 String reason) {
4744 if (localLOGV) {
4745 Slog.v(TAG, "Performing resume of " + r + " finished=" + r.activity.mFinished);
4746 }
4747 if (r.activity.mFinished) {
4748 return false;
4749 }
4750 if (r.getLifecycleState() == ON_RESUME) {
4751 if (!finalStateRequest) {
4752 final RuntimeException e = new IllegalStateException(
4753 "Trying to resume activity which is already resumed");
4754 Slog.e(TAG, e.getMessage(), e);
4755 Slog.e(TAG, r.getStateString());
4756 // TODO(lifecycler): A double resume request is possible when an activity
4757 // receives two consequent transactions with relaunch requests and "resumed"
4758 // final state requests and the second relaunch is omitted. We still try to
4759 // handle two resume requests for the final state. For cases other than this
4760 // one, we don't expect it to happen.
4761 }
4762 return false;
4763 }
4764 if (finalStateRequest) {
4765 r.hideForNow = false;
4766 r.activity.mStartedActivity = false;
4767 }
4768 try {
4769 r.activity.onStateNotSaved();
4770 r.activity.mFragments.noteStateNotSaved();
4771 checkAndBlockForNetworkAccess();
4772 if (r.pendingIntents != null) {
4773 deliverNewIntents(r, r.pendingIntents);
4774 r.pendingIntents = null;
4775 }
4776 if (r.pendingResults != null) {
4777 deliverResults(r, r.pendingResults, reason);
4778 r.pendingResults = null;
4779 }
4780 r.activity.performResume(r.startsNotResumed, reason);
4781
4782 r.state = null;
4783 r.persistentState = null;
4784 r.setState(ON_RESUME);
4785
4786 reportTopResumedActivityChanged(r, r.isTopResumedActivity, "topWhenResuming");
4787 } catch (Exception e) {
4788 if (!mInstrumentation.onException(r.activity, e)) {
4789 throw new RuntimeException("Unable to resume activity "
4790 + r.intent.getComponent().toShortString() + ": " + e.toString(), e);
4791 }
4792 }
4793 return true;
4794 }
4795
4796 static final void cleanUpPendingRemoveWindows(ActivityClientRecord r, boolean force) {
4797 if (r.mPreserveWindow && !force) {
4798 return;
4799 }
4800 if (r.mPendingRemoveWindow != null) {
4801 r.mPendingRemoveWindowManager.removeViewImmediate(
4802 r.mPendingRemoveWindow.getDecorView());
4803 IBinder wtoken = r.mPendingRemoveWindow.getDecorView().getWindowToken();
4804 if (wtoken != null) {
4805 WindowManagerGlobal.getInstance().closeAll(wtoken,
4806 r.activity.getClass().getName(), "Activity");
4807 }
4808 }
4809 r.mPendingRemoveWindow = null;
4810 r.mPendingRemoveWindowManager = null;
4811 }
4812
4813 @Override
4814 public void handleResumeActivity(ActivityClientRecord r, boolean finalStateRequest,
4815 boolean isForward, boolean shouldSendCompatFakeFocus, String reason) {
4816 // If we are getting ready to gc after going to the background, well
4817 // we are back active so skip it.
4818 unscheduleGcIdler();
4819 mSomeActivitiesChanged = true;
4820
4821 // TODO Push resumeArgs into the activity for consideration
4822 // skip below steps for double-resume and r.mFinish = true case.
4823 if (!performResumeActivity(r, finalStateRequest, reason)) {
4824 return;
4825 }
4826 if (mActivitiesToBeDestroyed.containsKey(r.token)) {
4827 // Although the activity is resumed, it is going to be destroyed. So the following
4828 // UI operations are unnecessary and also prevents exception because its token may
4829 // be gone that window manager cannot recognize it. All necessary cleanup actions
4830 // performed below will be done while handling destruction.
4831 return;
4832 }
4833
4834 final Activity a = r.activity;
4835
4836 if (localLOGV) {
4837 Slog.v(TAG, "Resume " + r + " started activity: " + a.mStartedActivity
4838 + ", hideForNow: " + r.hideForNow + ", finished: " + a.mFinished);
4839 }
4840
4841 final int forwardBit = isForward
4842 ? WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION : 0;
4843
4844 // If the window hasn't yet been added to the window manager,
4845 // and this guy didn't finish itself or start another activity,
4846 // then go ahead and add the window.
4847 boolean willBeVisible = !a.mStartedActivity;
4848 if (!willBeVisible) {
4849 willBeVisible = ActivityClient.getInstance().willActivityBeVisible(
4850 a.getActivityToken());
4851 }
4852 if (r.window == null && !a.mFinished && willBeVisible) {
4853 r.window = r.activity.getWindow();
4854 View decor = r.window.getDecorView();
4855 decor.setVisibility(View.INVISIBLE);
4856 ViewManager wm = a.getWindowManager();
4857 WindowManager.LayoutParams l = r.window.getAttributes();
4858 a.mDecor = decor;
4859 l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;
4860 l.softInputMode |= forwardBit;
4861 if (r.mPreserveWindow) {
4862 a.mWindowAdded = true;
4863 r.mPreserveWindow = false;
4864 // Normally the ViewRoot sets up callbacks with the Activity
4865 // in addView->ViewRootImpl#setView. If we are instead reusing
4866 // the decor view we have to notify the view root that the
4867 // callbacks may have changed.
4868 ViewRootImpl impl = decor.getViewRootImpl();
4869 if (impl != null) {
4870 impl.notifyChildRebuilt();
4871 }
4872 }
4873 if (a.mVisibleFromClient) {
4874 if (!a.mWindowAdded) {
4875 a.mWindowAdded = true;
4876 wm.addView(decor, l);
4877 } else {
4878 // The activity will get a callback for this {@link LayoutParams} change
4879 // earlier. However, at that time the decor will not be set (this is set
4880 // in this method), so no action will be taken. This call ensures the
4881 // callback occurs with the decor set.
4882 a.onWindowAttributesChanged(l);
4883 }
4884 }
4885
4886 // If the window has already been added, but during resume
4887 // we started another activity, then don't yet make the
4888 // window visible.
4889 } else if (!willBeVisible) {
4890 if (localLOGV) Slog.v(TAG, "Launch " + r + " mStartedActivity set");
4891 r.hideForNow = true;
4892 }
4893
4894 // Get rid of anything left hanging around.
4895 cleanUpPendingRemoveWindows(r, false /* force */);
4896
4897 // The window is now visible if it has been added, we are not
4898 // simply finishing, and we are not starting another activity.
4899 if (!r.activity.mFinished && willBeVisible && r.activity.mDecor != null && !r.hideForNow) {
4900 if (localLOGV) Slog.v(TAG, "Resuming " + r + " with isForward=" + isForward);
4901 ViewRootImpl impl = r.window.getDecorView().getViewRootImpl();
4902 WindowManager.LayoutParams l = impl != null
4903 ? impl.mWindowAttributes : r.window.getAttributes();
4904 if ((l.softInputMode
4905 & WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION)
4906 != forwardBit) {
4907 l.softInputMode = (l.softInputMode
4908 & (~WindowManager.LayoutParams.SOFT_INPUT_IS_FORWARD_NAVIGATION))
4909 | forwardBit;
4910 if (r.activity.mVisibleFromClient) {
4911 ViewManager wm = a.getWindowManager();
4912 View decor = r.window.getDecorView();
4913 wm.updateViewLayout(decor, l);
4914 }
4915 }
4916
4917 r.activity.mVisibleFromServer = true;
4918 mNumVisibleActivities++;
4919 if (r.activity.mVisibleFromClient) {
4920 r.activity.makeVisible();
4921 }
4922
4923 if (shouldSendCompatFakeFocus) {
4924 // Attaching to a window is asynchronous with the activity being resumed,
4925 // so it's possible we will need to send a fake focus event after attaching
4926 if (impl != null) {
4927 impl.dispatchCompatFakeFocus();
4928 } else {
4929 r.window.getDecorView().fakeFocusAfterAttachingToWindow();
4930 }
4931 }
4932 }
4933
4934 r.nextIdle = mNewActivities;
4935 mNewActivities = r;
4936 if (localLOGV) Slog.v(TAG, "Scheduling idle handler for " + r);
4937 Looper.myQueue().addIdleHandler(new Idler());
4938 }
4939
4940
4941 @Override
4942 public void handleTopResumedActivityChanged(ActivityClientRecord r, boolean onTop,
4943 String reason) {
4944 if (DEBUG_ORDER) {
4945 Slog.d(TAG, "Received position change to top: " + onTop + " for activity: " + r);
4946 }
4947
4948 if (r.isTopResumedActivity == onTop) {
4949 if (!Build.IS_DEBUGGABLE) {
4950 Slog.w(TAG, "Activity top position already set to onTop=" + onTop);
4951 return;
4952 }
4953 // TODO(b/209744518): Remove this short-term workaround while fixing the binder failure.
4954 Slog.e(TAG, "Activity top position already set to onTop=" + onTop);
4955 }
4956
4957 r.isTopResumedActivity = onTop;
4958
4959 if (r.getLifecycleState() == ON_RESUME) {
4960 reportTopResumedActivityChanged(r, onTop, "topStateChangedWhenResumed");
4961 } else {
4962 if (DEBUG_ORDER) {
4963 Slog.d(TAG, "Won't deliver top position change in state=" + r.getLifecycleState());
4964 }
4965 }
4966 }
4967
4968 /**
4969 * Call {@link Activity#onTopResumedActivityChanged(boolean)} if its top resumed state changed
4970 * since the last report.
4971 */
4972 private void reportTopResumedActivityChanged(ActivityClientRecord r, boolean onTop,
4973 String reason) {
4974 if (r.lastReportedTopResumedState != onTop) {
4975 r.lastReportedTopResumedState = onTop;
4976 r.activity.performTopResumedActivityChanged(onTop, reason);
4977 }
4978 }
4979
4980 @Override
4981 public void handlePauseActivity(ActivityClientRecord r, boolean finished, boolean userLeaving,
4982 int configChanges, boolean autoEnteringPip, PendingTransactionActions pendingActions,
4983 String reason) {
4984 if (userLeaving) {
4985 performUserLeavingActivity(r);
4986 }
4987
4988 r.activity.mConfigChangeFlags |= configChanges;
4989 if (autoEnteringPip) {
4990 // Set mIsInPictureInPictureMode earlier in case of auto-enter-pip, see also
4991 // {@link Activity#enterPictureInPictureMode(PictureInPictureParams)}.
4992 r.activity.mIsInPictureInPictureMode = true;
4993 }
4994 performPauseActivity(r, finished, reason, pendingActions);
4995
4996 // Make sure any pending writes are now committed.
4997 if (r.isPreHoneycomb()) {
4998 QueuedWork.waitToFinish();
4999 }
5000 mSomeActivitiesChanged = true;
5001 }
5002
5003 final void performUserLeavingActivity(ActivityClientRecord r) {
5004 mInstrumentation.callActivityOnPictureInPictureRequested(r.activity);
5005 mInstrumentation.callActivityOnUserLeaving(r.activity);
5006 }
5007
5008 final Bundle performPauseActivity(IBinder token, boolean finished, String reason,
5009 PendingTransactionActions pendingActions) {
5010 ActivityClientRecord r = mActivities.get(token);
5011 return r != null ? performPauseActivity(r, finished, reason, pendingActions) : null;
5012 }
5013
5014 /**
5015 * Pause the activity.
5016 * @return Saved instance state for pre-Honeycomb apps if it was saved, {@code null} otherwise.
5017 */
5018 private Bundle performPauseActivity(ActivityClientRecord r, boolean finished, String reason,
5019 PendingTransactionActions pendingActions) {
5020 if (r.paused) {
5021 if (r.activity.mFinished) {
5022 // If we are finishing, we won't call onResume() in certain cases.
5023 // So here we likewise don't want to call onPause() if the activity
5024 // isn't resumed.
5025 return null;
5026 }
5027 RuntimeException e = new RuntimeException(
5028 "Performing pause of activity that is not resumed: "
5029 + r.intent.getComponent().toShortString());
5030 Slog.e(TAG, e.getMessage(), e);
5031 }
5032 if (finished) {
5033 r.activity.mFinished = true;
5034 }
5035
5036 // Pre-Honeycomb apps always save their state before pausing
5037 final boolean shouldSaveState = !r.activity.mFinished && r.isPreHoneycomb();
5038 if (shouldSaveState) {
5039 callActivityOnSaveInstanceState(r);
5040 }
5041
5042 performPauseActivityIfNeeded(r, reason);
5043
5044 // Notify any outstanding on paused listeners
5045 ArrayList<OnActivityPausedListener> listeners;
5046 synchronized (mOnPauseListeners) {
5047 listeners = mOnPauseListeners.remove(r.activity);
5048 }
5049 int size = (listeners != null ? listeners.size() : 0);
5050 for (int i = 0; i < size; i++) {
5051 listeners.get(i).onPaused(r.activity);
5052 }
5053
5054 final Bundle oldState = pendingActions != null ? pendingActions.getOldState() : null;
5055 if (oldState != null) {
5056 // We need to keep around the original state, in case we need to be created again.
5057 // But we only do this for pre-Honeycomb apps, which always save their state when
5058 // pausing, so we can not have them save their state when restarting from a paused
5059 // state. For HC and later, we want to (and can) let the state be saved as the
5060 // normal part of stopping the activity.
5061 if (r.isPreHoneycomb()) {
5062 r.state = oldState;
5063 }
5064 }
5065
5066 return shouldSaveState ? r.state : null;
5067 }
5068
5069 private void performPauseActivityIfNeeded(ActivityClientRecord r, String reason) {
5070 if (r.paused) {
5071 // You are already paused silly...
5072 return;
5073 }
5074
5075 // Always reporting top resumed position loss when pausing an activity. If necessary, it
5076 // will be restored in performResumeActivity().
5077 reportTopResumedActivityChanged(r, false /* onTop */, "pausing");
5078
5079 try {
5080 r.activity.mCalled = false;
5081 mInstrumentation.callActivityOnPause(r.activity);
5082 if (!r.activity.mCalled) {
5083 throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
5084 + " did not call through to super.onPause()");
5085 }
5086 } catch (SuperNotCalledException e) {
5087 throw e;
5088 } catch (Exception e) {
5089 if (!mInstrumentation.onException(r.activity, e)) {
5090 throw new RuntimeException("Unable to pause activity "
5091 + safeToComponentShortString(r.intent) + ": " + e.toString(), e);
5092 }
5093 }
5094 r.setState(ON_PAUSE);
5095 }
5096
5097 // TODO(b/176961850): Make LocalActivityManager call performStopActivityInner. We cannot remove
5098 // this since it's a high usage hidden API.
5099 /** Called from {@link LocalActivityManager}. */
5100 @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 176961850,
5101 publicAlternatives = "{@code N/A}")
5102 final void performStopActivity(IBinder token, boolean saveState, String reason) {
5103 ActivityClientRecord r = mActivities.get(token);
5104 performStopActivityInner(r, null /* stopInfo */, saveState, false /* finalStateRequest */,
5105 reason);
5106 }
5107
5108 private static final class ProviderRefCount {
5109 public final ContentProviderHolder holder;
5110 public final ProviderClientRecord client;
5111 public int stableCount;
5112 public int unstableCount;
5113
5114 // When this is set, the stable and unstable ref counts are 0 and
5115 // we have a pending operation scheduled to remove the ref count
5116 // from the activity manager. On the activity manager we are still
5117 // holding an unstable ref, though it is not reflected in the counts
5118 // here.
5119 public boolean removePending;
5120
5121 ProviderRefCount(ContentProviderHolder inHolder,
5122 ProviderClientRecord inClient, int sCount, int uCount) {
5123 holder = inHolder;
5124 client = inClient;
5125 stableCount = sCount;
5126 unstableCount = uCount;
5127 }
5128 }
5129
5130 /**
5131 * Core implementation of stopping an activity.
5132 * @param r Target activity client record.
5133 * @param info Action that will report activity stop to server.
5134 * @param saveState Flag indicating whether the activity state should be saved.
5135 * @param finalStateRequest Flag indicating if this call is handling final lifecycle state
5136 * request for a transaction.
5137 * @param reason Reason for performing this operation.
5138 */
5139 private void performStopActivityInner(ActivityClientRecord r, StopInfo info,
5140 boolean saveState, boolean finalStateRequest, String reason) {
5141 if (localLOGV) Slog.v(TAG, "Performing stop of " + r);
5142 if (r.stopped) {
5143 if (r.activity.mFinished) {
5144 // If we are finishing, we won't call onResume() in certain
5145 // cases. So here we likewise don't want to call onStop()
5146 // if the activity isn't resumed.
5147 return;
5148 }
5149 if (!finalStateRequest) {
5150 final RuntimeException e = new RuntimeException(
5151 "Performing stop of activity that is already stopped: "
5152 + r.intent.getComponent().toShortString());
5153 Slog.e(TAG, e.getMessage(), e);
5154 Slog.e(TAG, r.getStateString());
5155 }
5156 }
5157
5158 // One must first be paused before stopped...
5159 performPauseActivityIfNeeded(r, reason);
5160
5161 if (info != null) {
5162 try {
5163 // First create a thumbnail for the activity...
5164 // For now, don't create the thumbnail here; we are
5165 // doing that by doing a screen snapshot.
5166 info.setDescription(r.activity.onCreateDescription());
5167 } catch (Exception e) {
5168 if (!mInstrumentation.onException(r.activity, e)) {
5169 throw new RuntimeException(
5170 "Unable to save state of activity "
5171 + r.intent.getComponent().toShortString()
5172 + ": " + e.toString(), e);
5173 }
5174 }
5175 }
5176
5177 callActivityOnStop(r, saveState, reason);
5178 }
5179
5180 /**
5181 * Calls {@link Activity#onStop()} and {@link Activity#onSaveInstanceState(Bundle)}, and updates
5182 * the client record's state.
5183 * All calls to stop an activity must be done through this method to make sure that
5184 * {@link Activity#onSaveInstanceState(Bundle)} is also executed in the same call.
5185 */
5186 private void callActivityOnStop(ActivityClientRecord r, boolean saveState, String reason) {
5187 // Before P onSaveInstanceState was called before onStop, starting with P it's
5188 // called after. Before Honeycomb state was always saved before onPause.
5189 final boolean shouldSaveState = saveState && !r.activity.mFinished && r.state == null
5190 && !r.isPreHoneycomb();
5191 final boolean isPreP = r.isPreP();
5192 if (shouldSaveState && isPreP) {
5193 callActivityOnSaveInstanceState(r);
5194 }
5195
5196 try {
5197 r.activity.performStop(r.mPreserveWindow, reason);
5198 } catch (SuperNotCalledException e) {
5199 throw e;
5200 } catch (Exception e) {
5201 if (!mInstrumentation.onException(r.activity, e)) {
5202 throw new RuntimeException(
5203 "Unable to stop activity "
5204 + r.intent.getComponent().toShortString()
5205 + ": " + e.toString(), e);
5206 }
5207 }
5208 r.setState(ON_STOP);
5209
5210 if (shouldSaveState && !isPreP) {
5211 callActivityOnSaveInstanceState(r);
5212 }
5213 }
5214
5215 private void updateVisibility(ActivityClientRecord r, boolean show) {
5216 View v = r.activity.mDecor;
5217 if (v != null) {
5218 if (show) {
5219 if (!r.activity.mVisibleFromServer) {
5220 r.activity.mVisibleFromServer = true;
5221 mNumVisibleActivities++;
5222 if (r.activity.mVisibleFromClient) {
5223 r.activity.makeVisible();
5224 }
5225 }
5226 } else {
5227 if (r.activity.mVisibleFromServer) {
5228 r.activity.mVisibleFromServer = false;
5229 mNumVisibleActivities--;
5230 v.setVisibility(View.INVISIBLE);
5231 }
5232 }
5233 }
5234 }
5235
5236 @Override
5237 public void handleStopActivity(ActivityClientRecord r, int configChanges,
5238 PendingTransactionActions pendingActions, boolean finalStateRequest, String reason) {
5239 r.activity.mConfigChangeFlags |= configChanges;
5240
5241 final StopInfo stopInfo = new StopInfo();
5242 performStopActivityInner(r, stopInfo, true /* saveState */, finalStateRequest,
5243 reason);
5244
5245 if (localLOGV) Slog.v(
5246 TAG, "Finishing stop of " + r + ": win=" + r.window);
5247
5248 updateVisibility(r, false);
5249
5250 // Make sure any pending writes are now committed.
5251 if (!r.isPreHoneycomb()) {
5252 QueuedWork.waitToFinish();
5253 }
5254
5255 stopInfo.setActivity(r);
5256 stopInfo.setState(r.state);
5257 stopInfo.setPersistentState(r.persistentState);
5258 pendingActions.setStopInfo(stopInfo);
5259 mSomeActivitiesChanged = true;
5260 }
5261
5262 /**
5263 * Schedule the call to tell the activity manager we have stopped. We don't do this
5264 * immediately, because we want to have a chance for any other pending work (in particular
5265 * memory trim requests) to complete before you tell the activity manager to proceed and allow
5266 * us to go fully into the background.
5267 */
5268 @Override
5269 public void reportStop(PendingTransactionActions pendingActions) {
5270 mH.post(pendingActions.getStopInfo());
5271 }
5272
5273 @Override
5274 public void performRestartActivity(ActivityClientRecord r, boolean start) {
5275 if (r.stopped) {
5276 r.activity.performRestart(start, "performRestartActivity");
5277 if (start) {
5278 r.setState(ON_START);
5279 }
5280 }
5281 }
5282
5283 @Override
5284 public void reportRefresh(ActivityClientRecord r) {
5285 ActivityClient.getInstance().activityRefreshed(r.token);
5286 }
5287
5288 private void handleSetCoreSettings(Bundle coreSettings) {
5289 synchronized (mCoreSettingsLock) {
5290 mCoreSettings = coreSettings;
5291 }
5292 onCoreSettingsChange();
5293 }
5294
5295 private void onCoreSettingsChange() {
5296 if (updateDebugViewAttributeState()) {
5297 // request all activities to relaunch for the changes to take place
5298 relaunchAllActivities(false /* preserveWindows */, "onCoreSettingsChange");
5299 }
5300 }
5301
5302 private boolean updateDebugViewAttributeState() {
5303 boolean previousState = View.sDebugViewAttributes;
5304
5305 // mCoreSettings is only updated from the main thread, while this function is only called
5306 // from main thread as well, so no need to lock here.
5307 View.sDebugViewAttributesApplicationPackage = mCoreSettings.getString(
5308 Settings.Global.DEBUG_VIEW_ATTRIBUTES_APPLICATION_PACKAGE, "");
5309 String currentPackage = (mBoundApplication != null && mBoundApplication.appInfo != null)
5310 ? mBoundApplication.appInfo.packageName : "<unknown-app>";
5311 View.sDebugViewAttributes =
5312 mCoreSettings.getInt(Settings.Global.DEBUG_VIEW_ATTRIBUTES, 0) != 0
5313 || View.sDebugViewAttributesApplicationPackage.equals(currentPackage);
5314 return previousState != View.sDebugViewAttributes;
5315 }
5316
5317 private void relaunchAllActivities(boolean preserveWindows, String reason) {
5318 Log.i(TAG, "Relaunch all activities: " + reason);
5319 for (int i = mActivities.size() - 1; i >= 0; i--) {
5320 scheduleRelaunchActivityIfPossible(mActivities.valueAt(i), preserveWindows);
5321 }
5322 }
5323
5324 private void handleUpdatePackageCompatibilityInfo(UpdateCompatibilityData data) {
5325 LoadedApk apk = peekPackageInfo(data.pkg, false);
5326 if (apk != null) {
5327 apk.setCompatibilityInfo(data.info);
5328 }
5329 apk = peekPackageInfo(data.pkg, true);
5330 if (apk != null) {
5331 apk.setCompatibilityInfo(data.info);
5332 }
5333 mConfigurationController.handleConfigurationChanged(data.info);
5334 }
5335
5336 private void deliverResults(ActivityClientRecord r, List<ResultInfo> results, String reason) {
5337 final int N = results.size();
5338 for (int i=0; i<N; i++) {
5339 ResultInfo ri = results.get(i);
5340 try {
5341 if (ri.mData != null) {
5342 ri.mData.setExtrasClassLoader(r.activity.getClassLoader());
5343 ri.mData.prepareToEnterProcess(isProtectedComponent(r.activityInfo),
5344 r.activity.getAttributionSource());
5345 }
5346 if (DEBUG_RESULTS) Slog.v(TAG,
5347 "Delivering result to activity " + r + " : " + ri);
5348 r.activity.dispatchActivityResult(ri.mResultWho,
5349 ri.mRequestCode, ri.mResultCode, ri.mData, reason);
5350 } catch (Exception e) {
5351 if (!mInstrumentation.onException(r.activity, e)) {
5352 throw new RuntimeException(
5353 "Failure delivering result " + ri + " to activity "
5354 + r.intent.getComponent().toShortString()
5355 + ": " + e.toString(), e);
5356 }
5357 }
5358 }
5359 }
5360
5361 @Override
5362 public void handleSendResult(ActivityClientRecord r, List<ResultInfo> results, String reason) {
5363 if (DEBUG_RESULTS) Slog.v(TAG, "Handling send result to " + r);
5364 final boolean resumed = !r.paused;
5365 if (!r.activity.mFinished && r.activity.mDecor != null
5366 && r.hideForNow && resumed) {
5367 // We had hidden the activity because it started another
5368 // one... we have gotten a result back and we are not
5369 // paused, so make sure our window is visible.
5370 updateVisibility(r, true);
5371 }
5372 if (resumed) {
5373 try {
5374 // Now we are idle.
5375 r.activity.mCalled = false;
5376 mInstrumentation.callActivityOnPause(r.activity);
5377 if (!r.activity.mCalled) {
5378 throw new SuperNotCalledException(
5379 "Activity " + r.intent.getComponent().toShortString()
5380 + " did not call through to super.onPause()");
5381 }
5382 } catch (SuperNotCalledException e) {
5383 throw e;
5384 } catch (Exception e) {
5385 if (!mInstrumentation.onException(r.activity, e)) {
5386 throw new RuntimeException(
5387 "Unable to pause activity "
5388 + r.intent.getComponent().toShortString()
5389 + ": " + e.toString(), e);
5390 }
5391 }
5392 }
5393 checkAndBlockForNetworkAccess();
5394 deliverResults(r, results, reason);
5395 if (resumed) {
5396 r.activity.performResume(false, reason);
5397 }
5398 }
5399
5400 /** Core implementation of activity destroy call. */
5401 void performDestroyActivity(ActivityClientRecord r, boolean finishing,
5402 int configChanges, boolean getNonConfigInstance, String reason) {
5403 Class<? extends Activity> activityClass = null;
5404 if (localLOGV) Slog.v(TAG, "Performing finish of " + r);
5405 activityClass = r.activity.getClass();
5406 r.activity.mConfigChangeFlags |= configChanges;
5407 if (finishing) {
5408 r.activity.mFinished = true;
5409 }
5410
5411 performPauseActivityIfNeeded(r, "destroy");
5412
5413 if (!r.stopped) {
5414 callActivityOnStop(r, false /* saveState */, "destroy");
5415 }
5416 if (getNonConfigInstance) {
5417 try {
5418 r.lastNonConfigurationInstances = r.activity.retainNonConfigurationInstances();
5419 } catch (Exception e) {
5420 if (!mInstrumentation.onException(r.activity, e)) {
5421 throw new RuntimeException("Unable to retain activity "
5422 + r.intent.getComponent().toShortString() + ": " + e.toString(), e);
5423 }
5424 }
5425 }
5426 try {
5427 r.activity.mCalled = false;
5428 mInstrumentation.callActivityOnDestroy(r.activity);
5429 if (!r.activity.mCalled) {
5430 throw new SuperNotCalledException("Activity " + safeToComponentShortString(r.intent)
5431 + " did not call through to super.onDestroy()");
5432 }
5433 if (r.window != null) {
5434 r.window.closeAllPanels();
5435 }
5436 } catch (SuperNotCalledException e) {
5437 throw e;
5438 } catch (Exception e) {
5439 if (!mInstrumentation.onException(r.activity, e)) {
5440 throw new RuntimeException("Unable to destroy activity "
5441 + safeToComponentShortString(r.intent) + ": " + e.toString(), e);
5442 }
5443 }
5444 r.setState(ON_DESTROY);
5445 mLastReportedWindowingMode.remove(r.activity.getActivityToken());
5446 schedulePurgeIdler();
5447 synchronized (this) {
5448 if (mSplashScreenGlobal != null) {
5449 mSplashScreenGlobal.tokenDestroyed(r.token);
5450 }
5451 }
5452 // updatePendingActivityConfiguration() reads from mActivities to update
5453 // ActivityClientRecord which runs in a different thread. Protect modifications to
5454 // mActivities to avoid race.
5455 synchronized (mResourcesManager) {
5456 mActivities.remove(r.token);
5457 }
5458 StrictMode.decrementExpectedActivityCount(activityClass);
5459 }
5460
5461 private static String safeToComponentShortString(Intent intent) {
5462 ComponentName component = intent.getComponent();
5463 return component == null ? "[Unknown]" : component.toShortString();
5464 }
5465
5466 @Override
5467 public Map<IBinder, ClientTransactionItem> getActivitiesToBeDestroyed() {
5468 return mActivitiesToBeDestroyed;
5469 }
5470
5471 @Override
5472 public void handleDestroyActivity(ActivityClientRecord r, boolean finishing, int configChanges,
5473 boolean getNonConfigInstance, String reason) {
5474 performDestroyActivity(r, finishing, configChanges, getNonConfigInstance, reason);
5475 cleanUpPendingRemoveWindows(r, finishing);
5476 WindowManager wm = r.activity.getWindowManager();
5477 View v = r.activity.mDecor;
5478 if (v != null) {
5479 if (r.activity.mVisibleFromServer) {
5480 mNumVisibleActivities--;
5481 }
5482 IBinder wtoken = v.getWindowToken();
5483 if (r.activity.mWindowAdded) {
5484 if (r.mPreserveWindow) {
5485 // Hold off on removing this until the new activity's window is being added.
5486 r.mPendingRemoveWindow = r.window;
5487 r.mPendingRemoveWindowManager = wm;
5488 // We can only keep the part of the view hierarchy that we control,
5489 // everything else must be removed, because it might not be able to
5490 // behave properly when activity is relaunching.
5491 r.window.clearContentView();
5492 } else {
5493 final ViewRootImpl viewRoot = v.getViewRootImpl();
5494 if (viewRoot != null) {
5495 // Clear callbacks to avoid the destroyed activity from receiving
5496 // configuration or camera compat changes that are no longer effective.
5497 viewRoot.setActivityConfigCallback(null);
5498 }
5499 wm.removeViewImmediate(v);
5500 }
5501 }
5502 if (wtoken != null && r.mPendingRemoveWindow == null) {
5503 WindowManagerGlobal.getInstance().closeAll(wtoken,
5504 r.activity.getClass().getName(), "Activity");
5505 } else if (r.mPendingRemoveWindow != null) {
5506 // We're preserving only one window, others should be closed so app views
5507 // will be detached before the final tear down. It should be done now because
5508 // some components (e.g. WebView) rely on detach callbacks to perform receiver
5509 // unregister and other cleanup.
5510 WindowManagerGlobal.getInstance().closeAllExceptView(r.token, v,
5511 r.activity.getClass().getName(), "Activity");
5512 }
5513 r.activity.mDecor = null;
5514 }
5515 if (r.mPendingRemoveWindow == null) {
5516 // If we are delaying the removal of the activity window, then
5517 // we can't clean up all windows here. Note that we can't do
5518 // so later either, which means any windows that aren't closed
5519 // by the app will leak. Well we try to warning them a lot
5520 // about leaking windows, because that is a bug, so if they are
5521 // using this recreate facility then they get to live with leaks.
5522 WindowManagerGlobal.getInstance().closeAll(r.token,
5523 r.activity.getClass().getName(), "Activity");
5524 }
5525
5526 // Mocked out contexts won't be participating in the normal
5527 // process lifecycle, but if we're running with a proper
5528 // ApplicationContext we need to have it tear down things
5529 // cleanly.
5530 Context c = r.activity.getBaseContext();
5531 if (c instanceof ContextImpl) {
5532 ((ContextImpl) c).scheduleFinalCleanup(r.activity.getClass().getName(), "Activity");
5533 }
5534 if (finishing) {
5535 ActivityClient.getInstance().activityDestroyed(r.token);
5536 }
5537 mSomeActivitiesChanged = true;
5538 }
5539
5540 @Override
5541 public ActivityClientRecord prepareRelaunchActivity(IBinder token,
5542 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingNewIntents,
5543 int configChanges, MergedConfiguration config, boolean preserveWindow) {
5544 ActivityClientRecord target = null;
5545 boolean scheduleRelaunch = false;
5546
5547 synchronized (mResourcesManager) {
5548 for (int i=0; i<mRelaunchingActivities.size(); i++) {
5549 ActivityClientRecord r = mRelaunchingActivities.get(i);
5550 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: " + this + ", trying: " + r);
5551 if (r.token == token) {
5552 target = r;
5553 if (pendingResults != null) {
5554 if (r.pendingResults != null) {
5555 r.pendingResults.addAll(pendingResults);
5556 } else {
5557 r.pendingResults = pendingResults;
5558 }
5559 }
5560 if (pendingNewIntents != null) {
5561 if (r.pendingIntents != null) {
5562 r.pendingIntents.addAll(pendingNewIntents);
5563 } else {
5564 r.pendingIntents = pendingNewIntents;
5565 }
5566 }
5567 break;
5568 }
5569 }
5570
5571 if (target == null) {
5572 if (DEBUG_ORDER) Slog.d(TAG, "requestRelaunchActivity: target is null");
5573 target = new ActivityClientRecord();
5574 target.token = token;
5575 target.pendingResults = pendingResults;
5576 target.pendingIntents = pendingNewIntents;
5577 target.mPreserveWindow = preserveWindow;
5578 mRelaunchingActivities.add(target);
5579 scheduleRelaunch = true;
5580 }
5581 target.createdConfig = config.getGlobalConfiguration();
5582 target.overrideConfig = config.getOverrideConfiguration();
5583 target.pendingConfigChanges |= configChanges;
5584 }
5585
5586 return scheduleRelaunch ? target : null;
5587 }
5588
5589 @Override
5590 public void handleRelaunchActivity(ActivityClientRecord tmp,
5591 PendingTransactionActions pendingActions) {
5592 // If we are getting ready to gc after going to the background, well
5593 // we are back active so skip it.
5594 unscheduleGcIdler();
5595 mSomeActivitiesChanged = true;
5596
5597 int configChanges = 0;
5598
5599 // First: make sure we have the most recent configuration and most
5600 // recent version of the activity, or skip it if some previous call
5601 // had taken a more recent version.
5602 synchronized (mResourcesManager) {
5603 int N = mRelaunchingActivities.size();
5604 IBinder token = tmp.token;
5605 tmp = null;
5606 for (int i=0; i<N; i++) {
5607 ActivityClientRecord r = mRelaunchingActivities.get(i);
5608 if (r.token == token) {
5609 tmp = r;
5610 configChanges |= tmp.pendingConfigChanges;
5611 mRelaunchingActivities.remove(i);
5612 i--;
5613 N--;
5614 }
5615 }
5616
5617 if (tmp == null) {
5618 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Abort, activity not relaunching!");
5619 return;
5620 }
5621
5622 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
5623 + tmp.token + " with configChanges=0x"
5624 + Integer.toHexString(configChanges));
5625 }
5626
5627 Configuration changedConfig = mConfigurationController.getPendingConfiguration(
5628 true /* clearPending */);
5629 mPendingConfiguration = null;
5630
5631 if (tmp.createdConfig != null) {
5632 // If the activity manager is passing us its current config,
5633 // assume that is really what we want regardless of what we
5634 // may have pending.
5635 final Configuration config = mConfigurationController.getConfiguration();
5636 if (config == null
5637 || (tmp.createdConfig.isOtherSeqNewer(config)
5638 && config.diff(tmp.createdConfig) != 0)) {
5639 if (changedConfig == null
5640 || tmp.createdConfig.isOtherSeqNewer(changedConfig)) {
5641 changedConfig = tmp.createdConfig;
5642 }
5643 }
5644 }
5645
5646 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Relaunching activity "
5647 + tmp.token + ": changedConfig=" + changedConfig);
5648
5649 // If there was a pending configuration change, execute it first.
5650 if (changedConfig != null) {
5651 mConfigurationController.updateDefaultDensity(changedConfig.densityDpi);
5652 mConfigurationController.handleConfigurationChanged(changedConfig, null);
5653
5654 // These are only done to maintain @UnsupportedAppUsage and should be removed someday.
5655 mCurDefaultDisplayDpi = mConfigurationController.getCurDefaultDisplayDpi();
5656 mConfiguration = mConfigurationController.getConfiguration();
5657 }
5658
5659 ActivityClientRecord r = mActivities.get(tmp.token);
5660 if (DEBUG_CONFIGURATION) Slog.v(TAG, "Handling relaunch of " + r);
5661 if (r == null) {
5662 return;
5663 }
5664
5665 r.activity.mConfigChangeFlags |= configChanges;
5666 r.mPreserveWindow = tmp.mPreserveWindow;
5667
5668 r.activity.mChangingConfigurations = true;
5669
5670 // If we are preserving the main window across relaunches we would also like to preserve
5671 // the children. However the client side view system does not support preserving
5672 // the child views so we notify the window manager to expect these windows to
5673 // be replaced and defer requests to destroy or hide them. This way we can achieve
5674 // visual continuity. It's important that we do this here prior to pause and destroy
5675 // as that is when we may hide or remove the child views.
5676 //
5677 // There is another scenario, if we have decided locally to relaunch the app from a
5678 // call to recreate, then none of the windows will be prepared for replacement or
5679 // preserved by the server, so we want to notify it that we are preparing to replace
5680 // everything
5681 try {
5682 if (r.mPreserveWindow) {
5683 WindowManagerGlobal.getWindowSession().prepareToReplaceWindows(
5684 r.token, true /* childrenOnly */);
5685 }
5686 } catch (RemoteException e) {
5687 throw e.rethrowFromSystemServer();
5688 }
5689
5690 handleRelaunchActivityInner(r, configChanges, tmp.pendingResults, tmp.pendingIntents,
5691 pendingActions, tmp.startsNotResumed, tmp.overrideConfig, "handleRelaunchActivity");
5692 if (pendingActions != null) {
5693 // Only report a successful relaunch to WindowManager.
5694 pendingActions.setReportRelaunchToWindowManager(true);
5695 }
5696 }
5697
5698 void scheduleRelaunchActivity(IBinder token) {
5699 final ActivityClientRecord r = mActivities.get(token);
5700 if (r != null) {
5701 Log.i(TAG, "Schedule relaunch activity: " + r.activityInfo.name);
5702 scheduleRelaunchActivityIfPossible(r, !r.stopped /* preserveWindow */);
5703 }
5704 }
5705
5706 /**
5707 * Post a message to relaunch the activity. We do this instead of launching it immediately,
5708 * because this will destroy the activity from which it was called and interfere with the
5709 * lifecycle changes it was going through before. We need to make sure that we have finished
5710 * handling current transaction item before relaunching the activity.
5711 */
5712 private void scheduleRelaunchActivityIfPossible(@NonNull ActivityClientRecord r,
5713 boolean preserveWindow) {
5714 if ((r.activity != null && r.activity.mFinished) || r.token instanceof Binder) {
5715 // Do not schedule relaunch if the activity is finishing or is a local object (e.g.
5716 // created by ActivtiyGroup that server side doesn't recognize it).
5717 return;
5718 }
5719 if (preserveWindow && r.window != null) {
5720 r.mPreserveWindow = true;
5721 }
5722 mH.removeMessages(H.RELAUNCH_ACTIVITY, r.token);
5723 sendMessage(H.RELAUNCH_ACTIVITY, r.token);
5724 }
5725
5726 /** Performs the activity relaunch locally vs. requesting from system-server. */
5727 public void handleRelaunchActivityLocally(IBinder token) {
5728 final ActivityClientRecord r = mActivities.get(token);
5729 if (r == null) {
5730 Log.w(TAG, "Activity to relaunch no longer exists");
5731 return;
5732 }
5733
5734 final int prevState = r.getLifecycleState();
5735
5736 if (prevState < ON_START || prevState > ON_STOP) {
5737 Log.w(TAG, "Activity state must be in [ON_START..ON_STOP] in order to be relaunched,"
5738 + "current state is " + prevState);
5739 return;
5740 }
5741
5742 ActivityClient.getInstance().activityLocalRelaunch(r.token);
5743 // Initialize a relaunch request.
5744 final MergedConfiguration mergedConfiguration = new MergedConfiguration(
5745 r.createdConfig != null
5746 ? r.createdConfig : mConfigurationController.getConfiguration(),
5747 r.overrideConfig);
5748 final ActivityRelaunchItem activityRelaunchItem = ActivityRelaunchItem.obtain(
5749 null /* pendingResults */, null /* pendingIntents */, 0 /* configChanges */,
5750 mergedConfiguration, r.mPreserveWindow);
5751 // Make sure to match the existing lifecycle state in the end of the transaction.
5752 final ActivityLifecycleItem lifecycleRequest =
5753 TransactionExecutorHelper.getLifecycleRequestForCurrentState(r);
5754 // Schedule the transaction.
5755 final ClientTransaction transaction = ClientTransaction.obtain(this.mAppThread, r.token);
5756 transaction.addCallback(activityRelaunchItem);
5757 transaction.setLifecycleStateRequest(lifecycleRequest);
5758 executeTransaction(transaction);
5759 }
5760
5761 private void handleRelaunchActivityInner(ActivityClientRecord r, int configChanges,
5762 List<ResultInfo> pendingResults, List<ReferrerIntent> pendingIntents,
5763 PendingTransactionActions pendingActions, boolean startsNotResumed,
5764 Configuration overrideConfig, String reason) {
5765 // Preserve last used intent, it may be set from Activity#setIntent().
5766 final Intent customIntent = r.activity.mIntent;
5767 // Need to ensure state is saved.
5768 if (!r.paused) {
5769 performPauseActivity(r, false, reason, null /* pendingActions */);
5770 }
5771 if (!r.stopped) {
5772 callActivityOnStop(r, true /* saveState */, reason);
5773 }
5774
5775 handleDestroyActivity(r, false, configChanges, true, reason);
5776
5777 r.activity = null;
5778 r.window = null;
5779 r.hideForNow = false;
5780 r.nextIdle = null;
5781 // Merge any pending results and pending intents; don't just replace them
5782 if (pendingResults != null) {
5783 if (r.pendingResults == null) {
5784 r.pendingResults = pendingResults;
5785 } else {
5786 r.pendingResults.addAll(pendingResults);
5787 }
5788 }
5789 if (pendingIntents != null) {
5790 if (r.pendingIntents == null) {
5791 r.pendingIntents = pendingIntents;
5792 } else {
5793 r.pendingIntents.addAll(pendingIntents);
5794 }
5795 }
5796 r.startsNotResumed = startsNotResumed;
5797 r.overrideConfig = overrideConfig;
5798
5799 handleLaunchActivity(r, pendingActions, customIntent);
5800 }
5801
5802 @Override
5803 public void reportRelaunch(ActivityClientRecord r, PendingTransactionActions pendingActions) {
5804 ActivityClient.getInstance().activityRelaunched(r.token);
5805 if (pendingActions.shouldReportRelaunchToWindowManager() && r.window != null) {
5806 r.window.reportActivityRelaunched();
5807 }
5808 }
5809
5810 private void callActivityOnSaveInstanceState(ActivityClientRecord r) {
5811 r.state = new Bundle();
5812 r.state.setAllowFds(false);
5813 if (r.isPersistable()) {
5814 r.persistentState = new PersistableBundle();
5815 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state,
5816 r.persistentState);
5817 } else {
5818 mInstrumentation.callActivityOnSaveInstanceState(r.activity, r.state);
5819 }
5820 }
5821
5822 @Override
5823 public ArrayList<ComponentCallbacks2> collectComponentCallbacks(boolean includeUiContexts) {
5824 ArrayList<ComponentCallbacks2> callbacks
5825 = new ArrayList<ComponentCallbacks2>();
5826
5827 synchronized (mResourcesManager) {
5828 final int NAPP = mAllApplications.size();
5829 for (int i=0; i<NAPP; i++) {
5830 callbacks.add(mAllApplications.get(i));
5831 }
5832 if (includeUiContexts) {
5833 for (int i = mActivities.size() - 1; i >= 0; i--) {
5834 final Activity a = mActivities.valueAt(i).activity;
5835 if (a != null && !a.mFinished) {
5836 callbacks.add(a);
5837 }
5838 }
5839 }
5840 final int NSVC = mServices.size();
5841 for (int i=0; i<NSVC; i++) {
5842 final Service service = mServices.valueAt(i);
5843 // If {@code includeUiContext} is set to false, WindowProviderService should not be
5844 // collected because WindowProviderService is a UI Context.
5845 if (includeUiContexts || !(service instanceof WindowProviderService)) {
5846 callbacks.add(service);
5847 }
5848 }
5849 }
5850 synchronized (mProviderMap) {
5851 final int NPRV = mLocalProviders.size();
5852 for (int i=0; i<NPRV; i++) {
5853 callbacks.add(mLocalProviders.valueAt(i).mLocalProvider);
5854 }
5855 }
5856
5857 return callbacks;
5858 }
5859
5860 /**
5861 * Updates the configuration for an Activity. The ActivityClientRecord's
5862 * {@link ActivityClientRecord#overrideConfig} is used to compute the final Configuration for
5863 * that Activity. {@link ActivityClientRecord#tmpConfig} is used as a temporary for delivering
5864 * the updated Configuration.
5865 * @param r ActivityClientRecord representing the Activity.
5866 * @param newBaseConfig The new configuration to use. This may be augmented with
5867 * {@link ActivityClientRecord#overrideConfig}.
5868 * @param displayId The id of the display where the Activity currently resides.
5869 * @return {@link Configuration} instance sent to client, null if not sent.
5870 */
5871 private Configuration performConfigurationChangedForActivity(ActivityClientRecord r,
5872 Configuration newBaseConfig, int displayId) {
5873 r.tmpConfig.setTo(newBaseConfig);
5874 if (r.overrideConfig != null) {
5875 r.tmpConfig.updateFrom(r.overrideConfig);
5876 }
5877 final Configuration reportedConfig = performActivityConfigurationChanged(r.activity,
5878 r.tmpConfig, r.overrideConfig, displayId);
5879 freeTextLayoutCachesIfNeeded(r.activity.mCurrentConfig.diff(r.tmpConfig));
5880 return reportedConfig;
5881 }
5882
5883 /**
5884 * Decides whether to update an Activity's configuration and whether to inform it.
5885 * @param activity The activity to notify of configuration change.
5886 * @param newConfig The new configuration.
5887 * @param amOverrideConfig The override config that differentiates the Activity's configuration
5888 * from the base global configuration. This is supplied by
5889 * ActivityManager.
5890 * @param displayId Id of the display where activity currently resides.
5891 * @return Configuration sent to client, null if no changes and not moved to different display.
5892 */
5893 private Configuration performActivityConfigurationChanged(Activity activity,
5894 Configuration newConfig, Configuration amOverrideConfig, int displayId) {
5895 final IBinder activityToken = activity.getActivityToken();
5896
5897 // WindowConfiguration differences aren't considered as public, check it separately.
5898 // multi-window / pip mode changes, if any, should be sent before the configuration
5899 // change callback, see also PinnedStackTests#testConfigurationChangeOrderDuringTransition
5900 handleWindowingModeChangeIfNeeded(activity, newConfig);
5901
5902 final boolean movedToDifferentDisplay = isDifferentDisplay(activity.getDisplayId(),
5903 displayId);
5904 final Configuration currentResConfig = activity.getResources().getConfiguration();
5905 final int diff = currentResConfig.diffPublicOnly(newConfig);
5906 final boolean hasPublicResConfigChange = diff != 0;
5907 final ActivityClientRecord r = getActivityClient(activityToken);
5908 // TODO(b/173090263): Use diff instead after the improvement of AssetManager and
5909 // ResourcesImpl constructions.
5910 final boolean shouldUpdateResources = hasPublicResConfigChange
5911 || shouldUpdateResources(activityToken, currentResConfig, newConfig,
5912 amOverrideConfig, movedToDifferentDisplay, hasPublicResConfigChange);
5913 final boolean shouldReportChange = shouldReportChange(activity.mCurrentConfig, newConfig,
5914 r != null ? r.mSizeConfigurations : null,
5915 activity.mActivityInfo.getRealConfigChanged());
5916 // Nothing significant, don't proceed with updating and reporting.
5917 if (!shouldUpdateResources && !shouldReportChange) {
5918 return null;
5919 }
5920
5921 // Propagate the configuration change to ResourcesManager and Activity.
5922
5923 // ContextThemeWrappers may override the configuration for that context. We must check and
5924 // apply any overrides defined.
5925 Configuration contextThemeWrapperOverrideConfig = activity.getOverrideConfiguration();
5926
5927 // We only update an Activity's configuration if this is not a global configuration change.
5928 // This must also be done before the callback, or else we violate the contract that the new
5929 // resources are available in ComponentCallbacks2#onConfigurationChanged(Configuration).
5930 // Also apply the ContextThemeWrapper override if necessary.
5931 // NOTE: Make sure the configurations are not modified, as they are treated as immutable in
5932 // many places.
5933 final Configuration finalOverrideConfig = createNewConfigAndUpdateIfNotNull(
5934 amOverrideConfig, contextThemeWrapperOverrideConfig);
5935 mResourcesManager.updateResourcesForActivity(activityToken, finalOverrideConfig, displayId);
5936
5937 // Apply the ContextThemeWrapper override if necessary.
5938 // NOTE: Make sure the configurations are not modified, as they are treated as immutable
5939 // in many places.
5940 final Configuration configToReport = createNewConfigAndUpdateIfNotNull(newConfig,
5941 contextThemeWrapperOverrideConfig);
5942
5943 if (movedToDifferentDisplay) {
5944 activity.dispatchMovedToDisplay(displayId, configToReport);
5945 }
5946
5947 activity.mConfigChangeFlags = 0;
5948 if (shouldReportChange) {
5949 activity.mCalled = false;
5950 activity.mCurrentConfig = new Configuration(newConfig);
5951 activity.onConfigurationChanged(configToReport);
5952 if (!activity.mCalled) {
5953 throw new SuperNotCalledException("Activity " + activity.getLocalClassName() +
5954 " did not call through to super.onConfigurationChanged()");
5955 }
5956 }
5957
5958 return configToReport;
5959 }
5960
5961 /**
5962 * Returns {@code true} if {@link Activity#onConfigurationChanged(Configuration)} should be
5963 * dispatched.
5964 *
5965 * @param currentConfig The current configuration cached in {@link Activity#mCurrentConfig}.
5966 * It is {@code null} before the first config update from the server side.
5967 * @param newConfig The updated {@link Configuration}
5968 * @param sizeBuckets The Activity's {@link SizeConfigurationBuckets} if not {@code null}
5969 * @param handledConfigChanges Bit mask of configuration changes that the activity can handle
5970 * @return {@code true} if the config change should be reported to the Activity
5971 */
5972 @VisibleForTesting
5973 public static boolean shouldReportChange(@Nullable Configuration currentConfig,
5974 @NonNull Configuration newConfig, @Nullable SizeConfigurationBuckets sizeBuckets,
5975 int handledConfigChanges) {
5976 final int publicDiff = currentConfig.diffPublicOnly(newConfig);
5977 // Don't report the change if there's no public diff between current and new config.
5978 if (publicDiff == 0) {
5979 return false;
5980 }
5981 final int diffWithBucket = SizeConfigurationBuckets.filterDiff(publicDiff, currentConfig,
5982 newConfig, sizeBuckets);
5983 // Compare to the diff which filter the change without crossing size buckets with
5984 // {@code handledConfigChanges}. The small changes should not block Activity to receive
5985 // its handled config updates. Also, if Activity handles all small changes, we should
5986 // dispatch the updated config to it.
5987 final int diff = diffWithBucket != 0 ? diffWithBucket : publicDiff;
5988 // If this activity doesn't handle any of the config changes, then don't bother
5989 // calling onConfigurationChanged. Otherwise, report to the activity for the
5990 // changes.
5991 return (~handledConfigChanges & diff) == 0;
5992 }
5993
5994 public final void applyConfigurationToResources(Configuration config) {
5995 synchronized (mResourcesManager) {
5996 mResourcesManager.applyConfigurationToResources(config, null);
5997 }
5998 }
5999
6000 @Override
6001 public void handleConfigurationChanged(Configuration config) {
6002 mConfigurationController.handleConfigurationChanged(config);
6003
6004 // These are only done to maintain @UnsupportedAppUsage and should be removed someday.
6005 mCurDefaultDisplayDpi = mConfigurationController.getCurDefaultDisplayDpi();
6006 mConfiguration = mConfigurationController.getConfiguration();
6007 mPendingConfiguration = mConfigurationController.getPendingConfiguration(
6008 false /* clearPending */);
6009 }
6010
6011 /**
6012 * Sends windowing mode change callbacks to {@link Activity} if applicable.
6013 *
6014 * See also {@link Activity#onMultiWindowModeChanged(boolean, Configuration)} and
6015 * {@link Activity#onPictureInPictureModeChanged(boolean, Configuration)}
6016 */
6017 private void handleWindowingModeChangeIfNeeded(Activity activity,
6018 Configuration newConfiguration) {
6019 final int newWindowingMode = newConfiguration.windowConfiguration.getWindowingMode();
6020 final IBinder token = activity.getActivityToken();
6021 final int oldWindowingMode = mLastReportedWindowingMode.getOrDefault(token,
6022 WINDOWING_MODE_UNDEFINED);
6023 if (oldWindowingMode == newWindowingMode) return;
6024 // PiP callback is sent before the MW one.
6025 if (newWindowingMode == WINDOWING_MODE_PINNED) {
6026 activity.dispatchPictureInPictureModeChanged(true, newConfiguration);
6027 } else if (oldWindowingMode == WINDOWING_MODE_PINNED) {
6028 activity.dispatchPictureInPictureModeChanged(false, newConfiguration);
6029 }
6030 final boolean wasInMultiWindowMode = WindowConfiguration.inMultiWindowMode(
6031 oldWindowingMode);
6032 final boolean nowInMultiWindowMode = WindowConfiguration.inMultiWindowMode(
6033 newWindowingMode);
6034 if (wasInMultiWindowMode != nowInMultiWindowMode) {
6035 activity.dispatchMultiWindowModeChanged(nowInMultiWindowMode, newConfiguration);
6036 }
6037 mLastReportedWindowingMode.put(token, newWindowingMode);
6038 }
6039
6040 /**
6041 * Updates the application info.
6042 *
6043 * This only works in the system process. Must be called on the main thread.
6044 */
6045 public void handleSystemApplicationInfoChanged(@NonNull ApplicationInfo ai) {
6046 Preconditions.checkState(mSystemThread, "Must only be called in the system process");
6047 handleApplicationInfoChanged(ai);
6048 }
6049
6050 @VisibleForTesting(visibility = PACKAGE)
6051 public void handleApplicationInfoChanged(@NonNull final ApplicationInfo ai) {
6052 // Updates triggered by package installation go through a package update
6053 // receiver. Here we try to capture ApplicationInfo changes that are
6054 // caused by other sources, such as overlays. That means we want to be as conservative
6055 // about code changes as possible. Take the diff of the old ApplicationInfo and the new
6056 // to see if anything needs to change.
6057 LoadedApk apk;
6058 LoadedApk resApk;
6059 // Update all affected loaded packages with new package information
6060 synchronized (mResourcesManager) {
6061 WeakReference<LoadedApk> ref = mPackages.get(ai.packageName);
6062 apk = ref != null ? ref.get() : null;
6063 ref = mResourcePackages.get(ai.packageName);
6064 resApk = ref != null ? ref.get() : null;
6065 }
6066
6067 if (apk != null) {
6068 final ArrayList<String> oldPaths = new ArrayList<>();
6069 LoadedApk.makePaths(this, apk.getApplicationInfo(), oldPaths);
6070 apk.updateApplicationInfo(ai, oldPaths);
6071 }
6072 if (resApk != null) {
6073 final ArrayList<String> oldPaths = new ArrayList<>();
6074 LoadedApk.makePaths(this, resApk.getApplicationInfo(), oldPaths);
6075 resApk.updateApplicationInfo(ai, oldPaths);
6076 }
6077
6078 synchronized (mResourcesManager) {
6079 // Update all affected Resources objects to use new ResourcesImpl
6080 mResourcesManager.applyAllPendingAppInfoUpdates();
6081 }
6082 }
6083
6084 /**
6085 * Sets the supplied {@code overrideConfig} as pending for the {@code token}. Calling
6086 * this method prevents any calls to
6087 * {@link #handleActivityConfigurationChanged(ActivityClientRecord, Configuration, int)} from
6088 * processing any configurations older than {@code overrideConfig}.
6089 */
6090 @Override
6091 public void updatePendingActivityConfiguration(IBinder token, Configuration overrideConfig) {
6092 synchronized (mPendingOverrideConfigs) {
6093 final Configuration pendingOverrideConfig = mPendingOverrideConfigs.get(token);
6094 if (pendingOverrideConfig != null
6095 && !pendingOverrideConfig.isOtherSeqNewer(overrideConfig)) {
6096 if (DEBUG_CONFIGURATION) {
6097 Slog.v(TAG, "Activity has newer configuration pending so this transaction will"
6098 + " be dropped. overrideConfig=" + overrideConfig
6099 + " pendingOverrideConfig=" + pendingOverrideConfig);
6100 }
6101 return;
6102 }
6103 mPendingOverrideConfigs.put(token, overrideConfig);
6104 }
6105 }
6106
6107 /**
6108 * Handle new activity configuration and/or move to a different display. This method is a noop
6109 * if {@link #updatePendingActivityConfiguration(IBinder, Configuration)} has been
6110 * called with a newer config than {@code overrideConfig}.
6111 *
6112 * @param r Target activity record.
6113 * @param overrideConfig Activity override config.
6114 * @param displayId Id of the display where activity was moved to, -1 if there was no move and
6115 * value didn't change.
6116 */
6117 @Override
6118 public void handleActivityConfigurationChanged(ActivityClientRecord r,
6119 @NonNull Configuration overrideConfig, int displayId) {
6120 synchronized (mPendingOverrideConfigs) {
6121 final Configuration pendingOverrideConfig = mPendingOverrideConfigs.get(r.token);
6122 if (overrideConfig.isOtherSeqNewer(pendingOverrideConfig)) {
6123 if (DEBUG_CONFIGURATION) {
6124 Slog.v(TAG, "Activity has newer configuration pending so drop this"
6125 + " transaction. overrideConfig=" + overrideConfig
6126 + " pendingOverrideConfig=" + pendingOverrideConfig);
6127 }
6128 return;
6129 }
6130 mPendingOverrideConfigs.remove(r.token);
6131 }
6132
6133 if (displayId == INVALID_DISPLAY) {
6134 // If INVALID_DISPLAY is passed assume that the activity should keep its current
6135 // display.
6136 displayId = r.activity.getDisplayId();
6137 }
6138 final boolean movedToDifferentDisplay = isDifferentDisplay(
6139 r.activity.getDisplayId(), displayId);
6140 if (r.overrideConfig != null && !r.overrideConfig.isOtherSeqNewer(overrideConfig)
6141 && !movedToDifferentDisplay) {
6142 if (DEBUG_CONFIGURATION) {
6143 Slog.v(TAG, "Activity already handled newer configuration so drop this"
6144 + " transaction. overrideConfig=" + overrideConfig + " r.overrideConfig="
6145 + r.overrideConfig);
6146 }
6147 return;
6148 }
6149
6150 // Perform updates.
6151 r.overrideConfig = overrideConfig;
6152 final ViewRootImpl viewRoot = r.activity.mDecor != null
6153 ? r.activity.mDecor.getViewRootImpl() : null;
6154
6155 if (DEBUG_CONFIGURATION) {
6156 Slog.v(TAG, "Handle activity config changed, activity:"
6157 + r.activityInfo.name + ", displayId=" + r.activity.getDisplayId()
6158 + (movedToDifferentDisplay ? (", newDisplayId=" + displayId) : "")
6159 + ", config=" + overrideConfig);
6160 }
6161 final Configuration reportedConfig = performConfigurationChangedForActivity(r,
6162 mConfigurationController.getCompatConfiguration(),
6163 movedToDifferentDisplay ? displayId : r.activity.getDisplayId());
6164 // Notify the ViewRootImpl instance about configuration changes. It may have initiated this
6165 // update to make sure that resources are updated before updating itself.
6166 if (viewRoot != null) {
6167 if (movedToDifferentDisplay) {
6168 viewRoot.onMovedToDisplay(displayId, reportedConfig);
6169 }
6170 viewRoot.updateConfiguration(displayId);
6171 }
6172 mSomeActivitiesChanged = true;
6173 }
6174
6175 final void handleProfilerControl(boolean start, ProfilerInfo profilerInfo, int profileType) {
6176 if (start) {
6177 try {
6178 switch (profileType) {
6179 default:
6180 mProfiler.setProfiler(profilerInfo);
6181 mProfiler.startProfiling();
6182 break;
6183 }
6184 } catch (RuntimeException e) {
6185 Slog.w(TAG, "Profiling failed on path " + profilerInfo.profileFile
6186 + " -- can the process access this path?");
6187 } finally {
6188 profilerInfo.closeFd();
6189 }
6190 } else {
6191 switch (profileType) {
6192 default:
6193 mProfiler.stopProfiling();
6194 break;
6195 }
6196 }
6197 }
6198
6199 /**
6200 * Public entrypoint to stop profiling. This is required to end profiling when the app crashes,
6201 * so that profiler data won't be lost.
6202 *
6203 * @hide
6204 */
6205 public void stopProfiling() {
6206 if (mProfiler != null) {
6207 mProfiler.stopProfiling();
6208 }
6209 }
6210
6211 static void handleDumpHeap(DumpHeapData dhd) {
6212 if (dhd.runGc) {
6213 System.gc();
6214 System.runFinalization();
6215 System.gc();
6216 }
6217 try (ParcelFileDescriptor fd = dhd.fd) {
6218 if (dhd.managed) {
6219 Debug.dumpHprofData(dhd.path, fd.getFileDescriptor());
6220 } else if (dhd.mallocInfo) {
6221 Debug.dumpNativeMallocInfo(fd.getFileDescriptor());
6222 } else {
6223 Debug.dumpNativeHeap(fd.getFileDescriptor());
6224 }
6225 } catch (IOException e) {
6226 if (dhd.managed) {
6227 Slog.w(TAG, "Managed heap dump failed on path " + dhd.path
6228 + " -- can the process access this path?", e);
6229 } else {
6230 Slog.w(TAG, "Failed to dump heap", e);
6231 }
6232 } catch (RuntimeException e) {
6233 // This should no longer happening now that we're copying the file descriptor.
6234 Slog.wtf(TAG, "Heap dumper threw a runtime exception", e);
6235 }
6236 try {
6237 ActivityManager.getService().dumpHeapFinished(dhd.path);
6238 } catch (RemoteException e) {
6239 throw e.rethrowFromSystemServer();
6240 }
6241 if (dhd.finishCallback != null) {
6242 dhd.finishCallback.sendResult(null);
6243 }
6244 }
6245
6246 final void handleDispatchPackageBroadcast(int cmd, String[] packages) {
6247 boolean hasPkgInfo = false;
6248 switch (cmd) {
6249 case ApplicationThreadConstants.PACKAGE_REMOVED:
6250 case ApplicationThreadConstants.PACKAGE_REMOVED_DONT_KILL:
6251 {
6252 final boolean killApp = cmd == ApplicationThreadConstants.PACKAGE_REMOVED;
6253 if (packages == null) {
6254 break;
6255 }
6256 synchronized (mResourcesManager) {
6257 for (int i = packages.length - 1; i >= 0; i--) {
6258 if (!hasPkgInfo) {
6259 WeakReference<LoadedApk> ref = mPackages.get(packages[i]);
6260 if (ref != null && ref.get() != null) {
6261 hasPkgInfo = true;
6262 } else {
6263 ref = mResourcePackages.get(packages[i]);
6264 if (ref != null && ref.get() != null) {
6265 hasPkgInfo = true;
6266 }
6267 }
6268 }
6269 if (killApp) {
6270 mPackages.remove(packages[i]);
6271 mResourcePackages.remove(packages[i]);
6272 }
6273 }
6274 }
6275 break;
6276 }
6277 case ApplicationThreadConstants.PACKAGE_REPLACED:
6278 {
6279 if (packages == null) {
6280 break;
6281 }
6282
6283 List<String> packagesHandled = new ArrayList<>();
6284
6285 synchronized (mResourcesManager) {
6286 for (int i = packages.length - 1; i >= 0; i--) {
6287 String packageName = packages[i];
6288 WeakReference<LoadedApk> ref = mPackages.get(packageName);
6289 LoadedApk pkgInfo = ref != null ? ref.get() : null;
6290 if (pkgInfo != null) {
6291 hasPkgInfo = true;
6292 } else {
6293 ref = mResourcePackages.get(packageName);
6294 pkgInfo = ref != null ? ref.get() : null;
6295 if (pkgInfo != null) {
6296 hasPkgInfo = true;
6297 }
6298 }
6299 // If the package is being replaced, yet it still has a valid
6300 // LoadedApk object, the package was updated with _DONT_KILL.
6301 // Adjust it's internal references to the application info and
6302 // resources.
6303 if (pkgInfo != null) {
6304 packagesHandled.add(packageName);
6305 try {
6306 final ApplicationInfo aInfo =
6307 sPackageManager.getApplicationInfo(
6308 packageName,
6309 PackageManager.GET_SHARED_LIBRARY_FILES,
6310 UserHandle.myUserId());
6311
6312 if (mActivities.size() > 0) {
6313 for (ActivityClientRecord ar : mActivities.values()) {
6314 if (ar.activityInfo.applicationInfo.packageName
6315 .equals(packageName)) {
6316 ar.activityInfo.applicationInfo = aInfo;
6317 ar.packageInfo = pkgInfo;
6318 }
6319 }
6320 }
6321
6322 final String[] oldResDirs = { pkgInfo.getResDir() };
6323
6324 final ArrayList<String> oldPaths = new ArrayList<>();
6325 LoadedApk.makePaths(this, pkgInfo.getApplicationInfo(), oldPaths);
6326 pkgInfo.updateApplicationInfo(aInfo, oldPaths);
6327
6328 synchronized (mResourcesManager) {
6329 // Update affected Resources objects to use new ResourcesImpl
6330 mResourcesManager.appendPendingAppInfoUpdate(oldResDirs,
6331 aInfo);
6332 mResourcesManager.applyAllPendingAppInfoUpdates();
6333 }
6334 } catch (RemoteException e) {
6335 }
6336 }
6337 }
6338 }
6339
6340 try {
6341 getPackageManager().notifyPackagesReplacedReceived(
6342 packagesHandled.toArray(new String[0]));
6343 } catch (RemoteException ignored) {
6344 }
6345
6346 break;
6347 }
6348 }
6349 ApplicationPackageManager.handlePackageBroadcast(cmd, packages, hasPkgInfo);
6350 }
6351
6352 final void handleLowMemory() {
6353 final ArrayList<ComponentCallbacks2> callbacks =
6354 collectComponentCallbacks(true /* includeUiContexts */);
6355
6356 final int N = callbacks.size();
6357 for (int i=0; i<N; i++) {
6358 callbacks.get(i).onLowMemory();
6359 }
6360
6361 // Ask SQLite to free up as much memory as it can, mostly from its page caches.
6362 if (Process.myUid() != Process.SYSTEM_UID) {
6363 int sqliteReleased = SQLiteDatabase.releaseMemory();
6364 EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
6365 }
6366
6367 // Ask graphics to free up as much as possible (font/image caches)
6368 Canvas.freeCaches();
6369
6370 // Ask text layout engine to free also as much as possible
6371 Canvas.freeTextLayoutCaches();
6372
6373 BinderInternal.forceGc("mem");
6374 }
6375
6376 private void handleTrimMemory(int level) {
6377 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "trimMemory");
6378 if (DEBUG_MEMORY_TRIM) Slog.v(TAG, "Trimming memory to level: " + level);
6379
6380 if (level >= ComponentCallbacks2.TRIM_MEMORY_COMPLETE) {
6381 PropertyInvalidatedCache.onTrimMemory();
6382 }
6383
6384 final ArrayList<ComponentCallbacks2> callbacks =
6385 collectComponentCallbacks(true /* includeUiContexts */);
6386
6387 final int N = callbacks.size();
6388 for (int i = 0; i < N; i++) {
6389 callbacks.get(i).onTrimMemory(level);
6390 }
6391
6392 WindowManagerGlobal.getInstance().trimMemory(level);
6393 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6394
6395 if (SystemProperties.getInt("debug.am.run_gc_trim_level", Integer.MAX_VALUE) <= level) {
6396 unscheduleGcIdler();
6397 doGcIfNeeded("tm");
6398 }
6399 if (SystemProperties.getInt("debug.am.run_mallopt_trim_level", Integer.MAX_VALUE)
6400 <= level) {
6401 unschedulePurgeIdler();
6402 purgePendingResources();
6403 }
6404 }
6405
6406 private void setupGraphicsSupport(Context context) {
6407 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "setupGraphicsSupport");
6408
6409 // The system package doesn't have real data directories, so don't set up cache paths.
6410 if (!"android".equals(context.getPackageName())) {
6411 // This cache location probably points at credential-encrypted
6412 // storage which may not be accessible yet; assign it anyway instead
6413 // of pointing at device-encrypted storage.
6414 final File cacheDir = context.getCacheDir();
6415 if (cacheDir != null) {
6416 // Provide a usable directory for temporary files
6417 String tmpdir = cacheDir.getAbsolutePath();
6418 System.setProperty("java.io.tmpdir", tmpdir);
6419 try {
6420 android.system.Os.setenv("TMPDIR", tmpdir, true);
6421 } catch (ErrnoException ex) {
6422 Log.w(TAG, "Unable to initialize $TMPDIR", ex);
6423 }
6424 } else {
6425 Log.v(TAG, "Unable to initialize \"java.io.tmpdir\" property "
6426 + "due to missing cache directory");
6427 }
6428
6429 // Setup a location to store generated/compiled graphics code.
6430 final Context deviceContext = context.createDeviceProtectedStorageContext();
6431 final File codeCacheDir = deviceContext.getCodeCacheDir();
6432 if (codeCacheDir != null) {
6433 try {
6434 int uid = Process.myUid();
6435 String[] packages = getPackageManager().getPackagesForUid(uid);
6436 if (packages != null) {
6437 HardwareRenderer.setupDiskCache(codeCacheDir);
6438 RenderScriptCacheDir.setupDiskCache(codeCacheDir);
6439 }
6440 } catch (RemoteException e) {
6441 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6442 throw e.rethrowFromSystemServer();
6443 }
6444 } else {
6445 Log.w(TAG, "Unable to use shader/script cache: missing code-cache directory");
6446 }
6447 }
6448
6449 // mCoreSettings is only updated from the main thread, while this function is only called
6450 // from main thread as well, so no need to lock here.
6451 GraphicsEnvironment.getInstance().setup(context, mCoreSettings);
6452 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6453 }
6454
6455 /**
6456 * Returns the correct library directory for the current ABI.
6457 * <p>
6458 * If we're dealing with a multi-arch application that has both 32 and 64 bit shared
6459 * libraries, we might need to choose the secondary depending on what the current
6460 * runtime's instruction set is.
6461 */
6462 private String getInstrumentationLibrary(ApplicationInfo appInfo, InstrumentationInfo insInfo) {
6463 if (appInfo.primaryCpuAbi != null && appInfo.secondaryCpuAbi != null
6464 && appInfo.secondaryCpuAbi.equals(insInfo.secondaryCpuAbi)) {
6465 // Get the instruction set supported by the secondary ABI. In the presence
6466 // of a native bridge this might be different than the one secondary ABI used.
6467 String secondaryIsa =
6468 VMRuntime.getInstructionSet(appInfo.secondaryCpuAbi);
6469 final String secondaryDexCodeIsa =
6470 SystemProperties.get("ro.dalvik.vm.isa." + secondaryIsa);
6471 secondaryIsa = secondaryDexCodeIsa.isEmpty() ? secondaryIsa : secondaryDexCodeIsa;
6472
6473 final String runtimeIsa = VMRuntime.getRuntime().vmInstructionSet();
6474 if (runtimeIsa.equals(secondaryIsa)) {
6475 return insInfo.secondaryNativeLibraryDir;
6476 }
6477 }
6478 return insInfo.nativeLibraryDir;
6479 }
6480
6481 @UnsupportedAppUsage
6482 private void handleBindApplication(AppBindData data) {
6483 // Register the UI Thread as a sensitive thread to the runtime.
6484 VMRuntime.registerSensitiveThread();
6485 // In the case the stack depth property exists, pass it down to the runtime.
6486 String property = SystemProperties.get("debug.allocTracker.stackDepth");
6487 if (property.length() != 0) {
6488 VMDebug.setAllocTrackerStackDepth(Integer.parseInt(property));
6489 }
6490 if (data.trackAllocation) {
6491 DdmVmInternal.setRecentAllocationsTrackingEnabled(true);
6492 }
6493 // Note when this process has started.
6494 Process.setStartTimes(SystemClock.elapsedRealtime(), SystemClock.uptimeMillis(),
6495 data.startRequestedElapsedTime, data.startRequestedUptime);
6496
6497 AppCompatCallbacks.install(data.disabledCompatChanges);
6498 // Let libcore handle any compat changes after installing the list of compat changes.
6499 AppSpecializationHooks.handleCompatChangesBeforeBindingApplication();
6500
6501 // Initialize the zip path validator callback depending on the targetSdk.
6502 // This has to be after AppCompatCallbacks#install() so that the Compat
6503 // checks work accordingly.
6504 initZipPathValidatorCallback();
6505
6506 mBoundApplication = data;
6507 mConfigurationController.setConfiguration(data.config);
6508 mConfigurationController.setCompatConfiguration(data.config);
6509 mConfiguration = mConfigurationController.getConfiguration();
6510
6511 mProfiler = new Profiler();
6512 String agent = null;
6513 if (data.initProfilerInfo != null) {
6514 mProfiler.profileFile = data.initProfilerInfo.profileFile;
6515 mProfiler.profileFd = data.initProfilerInfo.profileFd;
6516 mProfiler.samplingInterval = data.initProfilerInfo.samplingInterval;
6517 mProfiler.autoStopProfiler = data.initProfilerInfo.autoStopProfiler;
6518 mProfiler.streamingOutput = data.initProfilerInfo.streamingOutput;
6519 mProfiler.mClockType = data.initProfilerInfo.clockType;
6520 if (data.initProfilerInfo.attachAgentDuringBind) {
6521 agent = data.initProfilerInfo.agent;
6522 }
6523 }
6524
6525 // send up app name; do this *before* waiting for debugger
6526 Process.setArgV0(data.processName);
6527 android.ddm.DdmHandleAppName.setAppName(data.processName,
6528 data.appInfo.packageName,
6529 UserHandle.myUserId());
6530 VMRuntime.setProcessPackageName(data.appInfo.packageName);
6531
6532 // Pass data directory path to ART. This is used for caching information and
6533 // should be set before any application code is loaded.
6534 VMRuntime.setProcessDataDirectory(data.appInfo.dataDir);
6535
6536 if (mProfiler.profileFd != null) {
6537 mProfiler.startProfiling();
6538 }
6539
6540 // If the app is Honeycomb MR1 or earlier, switch its AsyncTask
6541 // implementation to use the pool executor. Normally, we use the
6542 // serialized executor as the default. This has to happen in the
6543 // main thread so the main looper is set right.
6544 if (data.appInfo.targetSdkVersion <= android.os.Build.VERSION_CODES.HONEYCOMB_MR1) {
6545 AsyncTask.setDefaultExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
6546 }
6547
6548 // Let the util.*Array classes maintain "undefined" for apps targeting Pie or earlier.
6549 UtilConfig.setThrowExceptionForUpperArrayOutOfBounds(
6550 data.appInfo.targetSdkVersion >= Build.VERSION_CODES.Q);
6551
6552 Message.updateCheckRecycle(data.appInfo.targetSdkVersion);
6553
6554 // Supply the targetSdkVersion to the UI rendering module, which may
6555 // need it in cases where it does not have access to the appInfo.
6556 android.graphics.Compatibility.setTargetSdkVersion(data.appInfo.targetSdkVersion);
6557
6558 /*
6559 * Before spawning a new process, reset the time zone to be the system time zone.
6560 * This needs to be done because the system time zone could have changed after the
6561 * the spawning of this process. Without doing this this process would have the incorrect
6562 * system time zone.
6563 */
6564 TimeZone.setDefault(null);
6565
6566 /*
6567 * Set the LocaleList. This may change once we create the App Context.
6568 */
6569 LocaleList.setDefault(data.config.getLocales());
6570
6571 if (Typeface.ENABLE_LAZY_TYPEFACE_INITIALIZATION) {
6572 try {
6573 Typeface.setSystemFontMap(data.mSerializedSystemFontMap);
6574 } catch (IOException | ErrnoException e) {
6575 Slog.e(TAG, "Failed to parse serialized system font map");
6576 Typeface.loadPreinstalledSystemFontMap();
6577 }
6578 }
6579
6580 synchronized (mResourcesManager) {
6581 /*
6582 * Update the system configuration since its preloaded and might not
6583 * reflect configuration changes. The configuration object passed
6584 * in AppBindData can be safely assumed to be up to date
6585 */
6586 mResourcesManager.applyConfigurationToResources(data.config, data.compatInfo);
6587 mCurDefaultDisplayDpi = data.config.densityDpi;
6588
6589 // This calls mResourcesManager so keep it within the synchronized block.
6590 mConfigurationController.applyCompatConfiguration();
6591 }
6592
6593 final boolean isSdkSandbox = data.sdkSandboxClientAppPackage != null;
6594 data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo, isSdkSandbox);
6595 if (isSdkSandbox) {
6596 data.info.setSdkSandboxStorage(data.sdkSandboxClientAppVolumeUuid,
6597 data.sdkSandboxClientAppPackage);
6598 }
6599
6600 if (agent != null) {
6601 handleAttachAgent(agent, data.info);
6602 }
6603
6604 /**
6605 * Switch this process to density compatibility mode if needed.
6606 */
6607 if ((data.appInfo.flags&ApplicationInfo.FLAG_SUPPORTS_SCREEN_DENSITIES)
6608 == 0) {
6609 mDensityCompatMode = true;
6610 Bitmap.setDefaultDensity(DisplayMetrics.DENSITY_DEFAULT);
6611 }
6612 mConfigurationController.updateDefaultDensity(data.config.densityDpi);
6613
6614 // mCoreSettings is only updated from the main thread, while this function is only called
6615 // from main thread as well, so no need to lock here.
6616 final String use24HourSetting = mCoreSettings.getString(Settings.System.TIME_12_24);
6617 Boolean is24Hr = null;
6618 if (use24HourSetting != null) {
6619 is24Hr = "24".equals(use24HourSetting) ? Boolean.TRUE : Boolean.FALSE;
6620 }
6621 // null : use locale default for 12/24 hour formatting,
6622 // false : use 12 hour format,
6623 // true : use 24 hour format.
6624 DateFormat.set24HourTimePref(is24Hr);
6625
6626 updateDebugViewAttributeState();
6627
6628 StrictMode.initThreadDefaults(data.appInfo);
6629 StrictMode.initVmDefaults(data.appInfo);
6630
6631 if (data.debugMode != ApplicationThreadConstants.DEBUG_OFF) {
6632 // XXX should have option to change the port.
6633 Debug.changeDebugPort(8100);
6634 if (data.debugMode == ApplicationThreadConstants.DEBUG_WAIT) {
6635 Slog.w(TAG, "Application " + data.info.getPackageName()
6636 + " is waiting for the debugger on port 8100...");
6637
6638 IActivityManager mgr = ActivityManager.getService();
6639 try {
6640 mgr.showWaitingForDebugger(mAppThread, true);
6641 } catch (RemoteException ex) {
6642 throw ex.rethrowFromSystemServer();
6643 }
6644
6645 Debug.waitForDebugger();
6646
6647 try {
6648 mgr.showWaitingForDebugger(mAppThread, false);
6649 } catch (RemoteException ex) {
6650 throw ex.rethrowFromSystemServer();
6651 }
6652
6653 } else {
6654 Slog.w(TAG, "Application " + data.info.getPackageName()
6655 + " can be debugged on port 8100...");
6656 }
6657 }
6658
6659 // Allow binder tracing, and application-generated systrace messages if we're profileable.
6660 boolean isAppDebuggable = (data.appInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0;
6661 boolean isAppProfileable = isAppDebuggable || data.appInfo.isProfileable();
6662 Trace.setAppTracingAllowed(isAppProfileable);
6663 if ((isAppProfileable || Build.IS_DEBUGGABLE) && data.enableBinderTracking) {
6664 Binder.enableStackTracking();
6665 }
6666
6667 // Initialize heap profiling.
6668 if (isAppProfileable || Build.IS_DEBUGGABLE) {
6669 nInitZygoteChildHeapProfiling();
6670 }
6671
6672 // Allow renderer debugging features if we're debuggable.
6673 HardwareRenderer.setDebuggingEnabled(isAppDebuggable || Build.IS_DEBUGGABLE);
6674 HardwareRenderer.setPackageName(data.appInfo.packageName);
6675
6676 // Pass the current context to HardwareRenderer
6677 HardwareRenderer.setContextForInit(getSystemContext());
6678
6679 // Instrumentation info affects the class loader, so load it before
6680 // setting up the app context.
6681 final InstrumentationInfo ii;
6682 if (data.instrumentationName != null) {
6683 ii = prepareInstrumentation(data);
6684 } else {
6685 ii = null;
6686 }
6687
6688 final ContextImpl appContext = ContextImpl.createAppContext(this, data.info);
6689 mConfigurationController.updateLocaleListFromAppContext(appContext);
6690
6691 // Initialize the default http proxy in this process.
6692 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Setup proxies");
6693 try {
6694 // In pre-boot mode (doing initial launch to collect password), not all system is up.
6695 // This includes the connectivity service, so trying to obtain ConnectivityManager at
6696 // that point would return null. Check whether the ConnectivityService is available, and
6697 // avoid crashing with a NullPointerException if it is not.
6698 final IBinder b = ServiceManager.getService(Context.CONNECTIVITY_SERVICE);
6699 if (b != null) {
6700 final ConnectivityManager cm =
6701 appContext.getSystemService(ConnectivityManager.class);
6702 Proxy.setHttpProxyConfiguration(cm.getDefaultProxy());
6703 }
6704 } finally {
6705 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6706 }
6707
6708 if (!Process.isIsolated()) {
6709 final int oldMask = StrictMode.allowThreadDiskWritesMask();
6710 try {
6711 setupGraphicsSupport(appContext);
6712 } finally {
6713 StrictMode.setThreadPolicyMask(oldMask);
6714 }
6715 } else {
6716 HardwareRenderer.setIsolatedProcess(true);
6717 }
6718
6719 // Install the Network Security Config Provider. This must happen before the application
6720 // code is loaded to prevent issues with instances of TLS objects being created before
6721 // the provider is installed.
6722 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "NetworkSecurityConfigProvider.install");
6723 NetworkSecurityConfigProvider.install(appContext);
6724 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
6725
6726 // For backward compatibility, TrafficStats needs static access to the application context.
6727 // But for isolated apps which cannot access network related services, service discovery
6728 // is restricted. Hence, calling this would result in NPE.
6729 if (!Process.isIsolated()) {
6730 TrafficStats.init(appContext);
6731 }
6732
6733 // Continue loading instrumentation.
6734 if (ii != null) {
6735 initInstrumentation(ii, data, appContext);
6736 } else {
6737 mInstrumentation = new Instrumentation();
6738 mInstrumentation.basicInit(this);
6739 }
6740
6741 if ((data.appInfo.flags&ApplicationInfo.FLAG_LARGE_HEAP) != 0) {
6742 dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();
6743 } else {
6744 // Small heap, clamp to the current growth limit and let the heap release
6745 // pages after the growth limit to the non growth limit capacity. b/18387825
6746 dalvik.system.VMRuntime.getRuntime().clampGrowthLimit();
6747 }
6748
6749 // Allow disk access during application and provider setup. This could
6750 // block processing ordered broadcasts, but later processing would
6751 // probably end up doing the same disk access.
6752 Application app;
6753 final StrictMode.ThreadPolicy savedPolicy = StrictMode.allowThreadDiskWrites();
6754 final StrictMode.ThreadPolicy writesAllowedPolicy = StrictMode.getThreadPolicy();
6755 try {
6756 // If the app is being launched for full backup or restore, bring it up in
6757 // a restricted environment with the base application class.
6758 app = data.info.makeApplicationInner(data.restrictedBackupMode, null);
6759
6760 // Propagate autofill compat state
6761 app.setAutofillOptions(data.autofillOptions);
6762
6763 // Propagate Content Capture options
6764 app.setContentCaptureOptions(data.contentCaptureOptions);
6765 sendMessage(H.SET_CONTENT_CAPTURE_OPTIONS_CALLBACK, data.appInfo.packageName);
6766
6767 mInitialApplication = app;
6768 final boolean updateHttpProxy;
6769 synchronized (this) {
6770 updateHttpProxy = mUpdateHttpProxyOnBind;
6771 // This synchronized block ensures that any subsequent call to updateHttpProxy()
6772 // will see a non-null mInitialApplication.
6773 }
6774 if (updateHttpProxy) {
6775 ActivityThread.updateHttpProxy(app);
6776 }
6777
6778 // don't bring up providers in restricted mode; they may depend on the
6779 // app's custom Application class
6780 if (!data.restrictedBackupMode) {
6781 if (!ArrayUtils.isEmpty(data.providers)) {
6782 installContentProviders(app, data.providers);
6783 }
6784 }
6785
6786 // Do this after providers, since instrumentation tests generally start their
6787 // test thread at this point, and we don't want that racing.
6788 try {
6789 mInstrumentation.onCreate(data.instrumentationArgs);
6790 }
6791 catch (Exception e) {
6792 throw new RuntimeException(
6793 "Exception thrown in onCreate() of "
6794 + data.instrumentationName + ": " + e.toString(), e);
6795 }
6796 try {
6797 mInstrumentation.callApplicationOnCreate(app);
6798 } catch (Exception e) {
6799 if (!mInstrumentation.onException(app, e)) {
6800 throw new RuntimeException(
6801 "Unable to create application " + app.getClass().getName()
6802 + ": " + e.toString(), e);
6803 }
6804 }
6805 } finally {
6806 // If the app targets < O-MR1, or doesn't change the thread policy
6807 // during startup, clobber the policy to maintain behavior of b/36951662
6808 if (data.appInfo.targetSdkVersion < Build.VERSION_CODES.O_MR1
6809 || StrictMode.getThreadPolicy().equals(writesAllowedPolicy)) {
6810 StrictMode.setThreadPolicy(savedPolicy);
6811 }
6812 }
6813
6814 // Preload fonts resources
6815 FontsContract.setApplicationContextForResources(appContext);
6816 if (!Process.isIsolated()) {
6817 try {
6818 final ApplicationInfo info =
6819 getPackageManager().getApplicationInfo(
6820 data.appInfo.packageName,
6821 PackageManager.GET_META_DATA /*flags*/,
6822 UserHandle.myUserId());
6823 if (info.metaData != null) {
6824 final int preloadedFontsResource = info.metaData.getInt(
6825 ApplicationInfo.METADATA_PRELOADED_FONTS, 0);
6826 if (preloadedFontsResource != 0) {
6827 data.info.getResources().preloadFonts(preloadedFontsResource);
6828 }
6829 }
6830 } catch (RemoteException e) {
6831 throw e.rethrowFromSystemServer();
6832 }
6833 }
6834 }
6835
6836 /**
6837 * If targetSDK >= U: set the safe zip path validator callback which disallows dangerous zip
6838 * entry names.
6839 * Otherwise: clear the callback to the default validation.
6840 */
6841 private void initZipPathValidatorCallback() {
6842 if (CompatChanges.isChangeEnabled(VALIDATE_ZIP_PATH_FOR_PATH_TRAVERSAL)) {
6843 ZipPathValidator.setCallback(new SafeZipPathValidatorCallback());
6844 } else {
6845 ZipPathValidator.clearCallback();
6846 }
6847 }
6848
6849 private void handleSetContentCaptureOptionsCallback(String packageName) {
6850 if (mContentCaptureOptionsCallback != null) {
6851 return;
6852 }
6853
6854 IBinder b = ServiceManager.getService(Context.CONTENT_CAPTURE_MANAGER_SERVICE);
6855 if (b == null) {
6856 return;
6857 }
6858
6859 IContentCaptureManager service = IContentCaptureManager.Stub.asInterface(b);
6860 mContentCaptureOptionsCallback = new IContentCaptureOptionsCallback.Stub() {
6861 @Override
6862 public void setContentCaptureOptions(ContentCaptureOptions options)
6863 throws RemoteException {
6864 if (mInitialApplication != null) {
6865 mInitialApplication.setContentCaptureOptions(options);
6866 }
6867 }
6868 };
6869 try {
6870 service.registerContentCaptureOptionsCallback(packageName,
6871 mContentCaptureOptionsCallback);
6872 } catch (RemoteException e) {
6873 Slog.w(TAG, "registerContentCaptureOptionsCallback() failed: "
6874 + packageName, e);
6875 mContentCaptureOptionsCallback = null;
6876 }
6877 }
6878
6879 private void handleInstrumentWithoutRestart(AppBindData data) {
6880 try {
6881 data.compatInfo = CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO;
6882 data.info = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
6883 mInstrumentingWithoutRestart = true;
6884 final InstrumentationInfo ii = prepareInstrumentation(data);
6885 final ContextImpl appContext =
6886 ContextImpl.createAppContext(this, data.info);
6887
6888 initInstrumentation(ii, data, appContext);
6889
6890 try {
6891 mInstrumentation.onCreate(data.instrumentationArgs);
6892 } catch (Exception e) {
6893 throw new RuntimeException(
6894 "Exception thrown in onCreate() of "
6895 + data.instrumentationName + ": " + e.toString(), e);
6896 }
6897
6898 } catch (Exception e) {
6899 Slog.e(TAG, "Error in handleInstrumentWithoutRestart", e);
6900 }
6901 }
6902
6903 private InstrumentationInfo prepareInstrumentation(AppBindData data) {
6904 final InstrumentationInfo ii;
6905 try {
6906 ii = new ApplicationPackageManager(null, getPackageManager())
6907 .getInstrumentationInfo(data.instrumentationName, 0);
6908 } catch (PackageManager.NameNotFoundException e) {
6909 throw new RuntimeException(
6910 "Unable to find instrumentation info for: " + data.instrumentationName);
6911 }
6912
6913 // Warn of potential ABI mismatches.
6914 if (!Objects.equals(data.appInfo.primaryCpuAbi, ii.primaryCpuAbi)
6915 || !Objects.equals(data.appInfo.secondaryCpuAbi, ii.secondaryCpuAbi)) {
6916 Slog.w(TAG, "Package uses different ABI(s) than its instrumentation: "
6917 + "package[" + data.appInfo.packageName + "]: "
6918 + data.appInfo.primaryCpuAbi + ", " + data.appInfo.secondaryCpuAbi
6919 + " instrumentation[" + ii.packageName + "]: "
6920 + ii.primaryCpuAbi + ", " + ii.secondaryCpuAbi);
6921 }
6922
6923 mInstrumentationPackageName = ii.packageName;
6924 mInstrumentationAppDir = ii.sourceDir;
6925 mInstrumentationSplitAppDirs = ii.splitSourceDirs;
6926 mInstrumentationLibDir = getInstrumentationLibrary(data.appInfo, ii);
6927 mInstrumentedAppDir = data.info.getAppDir();
6928 mInstrumentedSplitAppDirs = data.info.getSplitAppDirs();
6929 mInstrumentedLibDir = data.info.getLibDir();
6930
6931 return ii;
6932 }
6933
6934 private void initInstrumentation(
6935 InstrumentationInfo ii, AppBindData data, ContextImpl appContext) {
6936 ApplicationInfo instrApp;
6937 try {
6938 instrApp = getPackageManager().getApplicationInfo(ii.packageName, 0,
6939 UserHandle.myUserId());
6940 } catch (RemoteException e) {
6941 instrApp = null;
6942 }
6943 if (instrApp == null) {
6944 instrApp = new ApplicationInfo();
6945 }
6946 ii.copyTo(instrApp);
6947 instrApp.initForUser(UserHandle.myUserId());
6948 final LoadedApk pi = getPackageInfo(instrApp, data.compatInfo,
6949 appContext.getClassLoader(), false, true, false);
6950
6951 // The test context's op package name == the target app's op package name, because
6952 // the app ops manager checks the op package name against the real calling UID,
6953 // which is what the target package name is associated with.
6954 final ContextImpl instrContext = ContextImpl.createAppContext(this, pi,
6955 appContext.getOpPackageName());
6956
6957 try {
6958 final ClassLoader cl = instrContext.getClassLoader();
6959 mInstrumentation = (Instrumentation)
6960 cl.loadClass(data.instrumentationName.getClassName()).newInstance();
6961 } catch (Exception e) {
6962 throw new RuntimeException(
6963 "Unable to instantiate instrumentation "
6964 + data.instrumentationName + ": " + e.toString(), e);
6965 }
6966
6967 final ComponentName component = new ComponentName(ii.packageName, ii.name);
6968 mInstrumentation.init(this, instrContext, appContext, component,
6969 data.instrumentationWatcher, data.instrumentationUiAutomationConnection);
6970
6971 if (mProfiler.profileFile != null && !ii.handleProfiling
6972 && mProfiler.profileFd == null) {
6973 mProfiler.handlingProfiling = true;
6974 final File file = new File(mProfiler.profileFile);
6975 file.getParentFile().mkdirs();
6976 Debug.startMethodTracing(file.toString(), 8 * 1024 * 1024);
6977 }
6978 }
6979
6980 private void handleFinishInstrumentationWithoutRestart() {
6981 mInstrumentation.onDestroy();
6982 mInstrumentationPackageName = null;
6983 mInstrumentationAppDir = null;
6984 mInstrumentationSplitAppDirs = null;
6985 mInstrumentationLibDir = null;
6986 mInstrumentedAppDir = null;
6987 mInstrumentedSplitAppDirs = null;
6988 mInstrumentedLibDir = null;
6989 mInstrumentingWithoutRestart = false;
6990 }
6991
6992 /*package*/ final void finishInstrumentation(int resultCode, Bundle results) {
6993 IActivityManager am = ActivityManager.getService();
6994 if (mProfiler.profileFile != null && mProfiler.handlingProfiling
6995 && mProfiler.profileFd == null) {
6996 Debug.stopMethodTracing();
6997 }
6998 //Slog.i(TAG, "am: " + ActivityManager.getService()
6999 // + ", app thr: " + mAppThread);
7000 try {
7001 am.finishInstrumentation(mAppThread, resultCode, results);
7002 } catch (RemoteException ex) {
7003 throw ex.rethrowFromSystemServer();
7004 }
7005 if (mInstrumentingWithoutRestart) {
7006 sendMessage(H.FINISH_INSTRUMENTATION_WITHOUT_RESTART, null);
7007 }
7008 }
7009
7010 @UnsupportedAppUsage
7011 private void installContentProviders(
7012 Context context, List<ProviderInfo> providers) {
7013 final ArrayList<ContentProviderHolder> results = new ArrayList<>();
7014
7015 for (ProviderInfo cpi : providers) {
7016 if (DEBUG_PROVIDER) {
7017 StringBuilder buf = new StringBuilder(128);
7018 buf.append("Pub ");
7019 buf.append(cpi.authority);
7020 buf.append(": ");
7021 buf.append(cpi.name);
7022 Log.i(TAG, buf.toString());
7023 }
7024 ContentProviderHolder cph = installProvider(context, null, cpi,
7025 false /*noisy*/, true /*noReleaseNeeded*/, true /*stable*/);
7026 if (cph != null) {
7027 cph.noReleaseNeeded = true;
7028 results.add(cph);
7029 }
7030 }
7031
7032 try {
7033 ActivityManager.getService().publishContentProviders(
7034 getApplicationThread(), results);
7035 } catch (RemoteException ex) {
7036 throw ex.rethrowFromSystemServer();
7037 }
7038 }
7039
7040 @UnsupportedAppUsage
7041 public final IContentProvider acquireProvider(
7042 Context c, String auth, int userId, boolean stable) {
7043 final IContentProvider provider = acquireExistingProvider(c, auth, userId, stable);
7044 if (provider != null) {
7045 return provider;
7046 }
7047
7048 // There is a possible race here. Another thread may try to acquire
7049 // the same provider at the same time. When this happens, we want to ensure
7050 // that the first one wins.
7051 // Note that we cannot hold the lock while acquiring and installing the
7052 // provider since it might take a long time to run and it could also potentially
7053 // be re-entrant in the case where the provider is in the same process.
7054 ContentProviderHolder holder = null;
7055 final ProviderKey key = getGetProviderKey(auth, userId);
7056 try {
7057 synchronized (key) {
7058 holder = ActivityManager.getService().getContentProvider(
7059 getApplicationThread(), c.getOpPackageName(), auth, userId, stable);
7060 // If the returned holder is non-null but its provider is null and it's not
7061 // local, we'll need to wait for the publishing of the provider.
7062 if (holder != null && holder.provider == null && !holder.mLocal) {
7063 synchronized (key.mLock) {
7064 if (key.mHolder != null) {
7065 if (DEBUG_PROVIDER) {
7066 Slog.i(TAG, "already received provider: " + auth);
7067 }
7068 } else {
7069 key.mLock.wait(ContentResolver.CONTENT_PROVIDER_READY_TIMEOUT_MILLIS);
7070 }
7071 holder = key.mHolder;
7072 }
7073 if (holder != null && holder.provider == null) {
7074 // probably timed out
7075 holder = null;
7076 }
7077 }
7078 }
7079 } catch (RemoteException ex) {
7080 throw ex.rethrowFromSystemServer();
7081 } catch (InterruptedException e) {
7082 holder = null;
7083 } finally {
7084 // Clear the holder from the key since the key itself is never cleared.
7085 synchronized (key.mLock) {
7086 key.mHolder = null;
7087 }
7088 }
7089 if (holder == null) {
7090 if (UserManager.get(c).isUserUnlocked(userId)) {
7091 Slog.e(TAG, "Failed to find provider info for " + auth);
7092 } else {
7093 Slog.w(TAG, "Failed to find provider info for " + auth + " (user not unlocked)");
7094 }
7095 return null;
7096 }
7097
7098 // Install provider will increment the reference count for us, and break
7099 // any ties in the race.
7100 holder = installProvider(c, holder, holder.info,
7101 true /*noisy*/, holder.noReleaseNeeded, stable);
7102 return holder.provider;
7103 }
7104
7105 private ProviderKey getGetProviderKey(String auth, int userId) {
7106 final ProviderKey key = new ProviderKey(auth, userId);
7107 synchronized (mGetProviderKeys) {
7108 ProviderKey lock = mGetProviderKeys.get(key);
7109 if (lock == null) {
7110 lock = key;
7111 mGetProviderKeys.put(key, lock);
7112 }
7113 return lock;
7114 }
7115 }
7116
7117 private final void incProviderRefLocked(ProviderRefCount prc, boolean stable) {
7118 if (stable) {
7119 prc.stableCount += 1;
7120 if (prc.stableCount == 1) {
7121 // We are acquiring a new stable reference on the provider.
7122 int unstableDelta;
7123 if (prc.removePending) {
7124 // We have a pending remove operation, which is holding the
7125 // last unstable reference. At this point we are converting
7126 // that unstable reference to our new stable reference.
7127 unstableDelta = -1;
7128 // Cancel the removal of the provider.
7129 if (DEBUG_PROVIDER) {
7130 Slog.v(TAG, "incProviderRef: stable "
7131 + "snatched provider from the jaws of death");
7132 }
7133 prc.removePending = false;
7134 // There is a race! It fails to remove the message, which
7135 // will be handled in completeRemoveProvider().
7136 mH.removeMessages(H.REMOVE_PROVIDER, prc);
7137 } else {
7138 unstableDelta = 0;
7139 }
7140 try {
7141 if (DEBUG_PROVIDER) {
7142 Slog.v(TAG, "incProviderRef Now stable - "
7143 + prc.holder.info.name + ": unstableDelta="
7144 + unstableDelta);
7145 }
7146 ActivityManager.getService().refContentProvider(
7147 prc.holder.connection, 1, unstableDelta);
7148 } catch (RemoteException e) {
7149 //do nothing content provider object is dead any way
7150 }
7151 }
7152 } else {
7153 prc.unstableCount += 1;
7154 if (prc.unstableCount == 1) {
7155 // We are acquiring a new unstable reference on the provider.
7156 if (prc.removePending) {
7157 // Oh look, we actually have a remove pending for the
7158 // provider, which is still holding the last unstable
7159 // reference. We just need to cancel that to take new
7160 // ownership of the reference.
7161 if (DEBUG_PROVIDER) {
7162 Slog.v(TAG, "incProviderRef: unstable "
7163 + "snatched provider from the jaws of death");
7164 }
7165 prc.removePending = false;
7166 mH.removeMessages(H.REMOVE_PROVIDER, prc);
7167 } else {
7168 // First unstable ref, increment our count in the
7169 // activity manager.
7170 try {
7171 if (DEBUG_PROVIDER) {
7172 Slog.v(TAG, "incProviderRef: Now unstable - "
7173 + prc.holder.info.name);
7174 }
7175 ActivityManager.getService().refContentProvider(
7176 prc.holder.connection, 0, 1);
7177 } catch (RemoteException e) {
7178 //do nothing content provider object is dead any way
7179 }
7180 }
7181 }
7182 }
7183 }
7184
7185 @UnsupportedAppUsage
7186 public final IContentProvider acquireExistingProvider(
7187 Context c, String auth, int userId, boolean stable) {
7188 synchronized (mProviderMap) {
7189 final ProviderKey key = new ProviderKey(auth, userId);
7190 final ProviderClientRecord pr = mProviderMap.get(key);
7191 if (pr == null) {
7192 return null;
7193 }
7194
7195 IContentProvider provider = pr.mProvider;
7196 IBinder jBinder = provider.asBinder();
7197 if (!jBinder.isBinderAlive()) {
7198 // The hosting process of the provider has died; we can't
7199 // use this one.
7200 Log.i(TAG, "Acquiring provider " + auth + " for user " + userId
7201 + ": existing object's process dead");
7202 handleUnstableProviderDiedLocked(jBinder, true);
7203 return null;
7204 }
7205
7206 // Only increment the ref count if we have one. If we don't then the
7207 // provider is not reference counted and never needs to be released.
7208 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
7209 if (prc != null) {
7210 incProviderRefLocked(prc, stable);
7211 }
7212 return provider;
7213 }
7214 }
7215
7216 @UnsupportedAppUsage
7217 public final boolean releaseProvider(IContentProvider provider, boolean stable) {
7218 if (provider == null) {
7219 return false;
7220 }
7221
7222 IBinder jBinder = provider.asBinder();
7223 synchronized (mProviderMap) {
7224 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
7225 if (prc == null) {
7226 // The provider has no ref count, no release is needed.
7227 return false;
7228 }
7229
7230 boolean lastRef = false;
7231 if (stable) {
7232 if (prc.stableCount == 0) {
7233 if (DEBUG_PROVIDER) Slog.v(TAG,
7234 "releaseProvider: stable ref count already 0, how?");
7235 return false;
7236 }
7237 prc.stableCount -= 1;
7238 if (prc.stableCount == 0) {
7239 // What we do at this point depends on whether there are
7240 // any unstable refs left: if there are, we just tell the
7241 // activity manager to decrement its stable count; if there
7242 // aren't, we need to enqueue this provider to be removed,
7243 // and convert to holding a single unstable ref while
7244 // doing so.
7245 lastRef = prc.unstableCount == 0;
7246 try {
7247 if (DEBUG_PROVIDER) {
7248 Slog.v(TAG, "releaseProvider: No longer stable w/lastRef="
7249 + lastRef + " - " + prc.holder.info.name);
7250 }
7251 ActivityManager.getService().refContentProvider(
7252 prc.holder.connection, -1, lastRef ? 1 : 0);
7253 } catch (RemoteException e) {
7254 //do nothing content provider object is dead any way
7255 }
7256 }
7257 } else {
7258 if (prc.unstableCount == 0) {
7259 if (DEBUG_PROVIDER) Slog.v(TAG,
7260 "releaseProvider: unstable ref count already 0, how?");
7261 return false;
7262 }
7263 prc.unstableCount -= 1;
7264 if (prc.unstableCount == 0) {
7265 // If this is the last reference, we need to enqueue
7266 // this provider to be removed instead of telling the
7267 // activity manager to remove it at this point.
7268 lastRef = prc.stableCount == 0;
7269 if (!lastRef) {
7270 try {
7271 if (DEBUG_PROVIDER) {
7272 Slog.v(TAG, "releaseProvider: No longer unstable - "
7273 + prc.holder.info.name);
7274 }
7275 ActivityManager.getService().refContentProvider(
7276 prc.holder.connection, 0, -1);
7277 } catch (RemoteException e) {
7278 //do nothing content provider object is dead any way
7279 }
7280 }
7281 }
7282 }
7283
7284 if (lastRef) {
7285 if (!prc.removePending) {
7286 // Schedule the actual remove asynchronously, since we don't know the context
7287 // this will be called in.
7288 if (DEBUG_PROVIDER) {
7289 Slog.v(TAG, "releaseProvider: Enqueueing pending removal - "
7290 + prc.holder.info.name);
7291 }
7292 prc.removePending = true;
7293 Message msg = mH.obtainMessage(H.REMOVE_PROVIDER, prc);
7294 mH.sendMessageDelayed(msg, CONTENT_PROVIDER_RETAIN_TIME);
7295 } else {
7296 Slog.w(TAG, "Duplicate remove pending of provider " + prc.holder.info.name);
7297 }
7298 }
7299 return true;
7300 }
7301 }
7302
7303 final void completeRemoveProvider(ProviderRefCount prc) {
7304 synchronized (mProviderMap) {
7305 if (!prc.removePending) {
7306 // There was a race! Some other client managed to acquire
7307 // the provider before the removal was completed.
7308 // Abort the removal. We will do it later.
7309 if (DEBUG_PROVIDER) Slog.v(TAG, "completeRemoveProvider: lost the race, "
7310 + "provider still in use");
7311 return;
7312 }
7313
7314 // More complicated race!! Some client managed to acquire the
7315 // provider and release it before the removal was completed.
7316 // Continue the removal, and abort the next remove message.
7317 prc.removePending = false;
7318
7319 final IBinder jBinder = prc.holder.provider.asBinder();
7320 ProviderRefCount existingPrc = mProviderRefCountMap.get(jBinder);
7321 if (existingPrc == prc) {
7322 mProviderRefCountMap.remove(jBinder);
7323 }
7324
7325 for (int i=mProviderMap.size()-1; i>=0; i--) {
7326 ProviderClientRecord pr = mProviderMap.valueAt(i);
7327 IBinder myBinder = pr.mProvider.asBinder();
7328 if (myBinder == jBinder) {
7329 mProviderMap.removeAt(i);
7330 }
7331 }
7332 }
7333
7334 try {
7335 if (DEBUG_PROVIDER) {
7336 Slog.v(TAG, "removeProvider: Invoking ActivityManagerService."
7337 + "removeContentProvider(" + prc.holder.info.name + ")");
7338 }
7339 ActivityManager.getService().removeContentProvider(
7340 prc.holder.connection, false);
7341 } catch (RemoteException e) {
7342 //do nothing content provider object is dead any way
7343 }
7344 }
7345
7346 @UnsupportedAppUsage
7347 final void handleUnstableProviderDied(IBinder provider, boolean fromClient) {
7348 synchronized (mProviderMap) {
7349 handleUnstableProviderDiedLocked(provider, fromClient);
7350 }
7351 }
7352
7353 final void handleUnstableProviderDiedLocked(IBinder provider, boolean fromClient) {
7354 ProviderRefCount prc = mProviderRefCountMap.get(provider);
7355 if (prc != null) {
7356 if (DEBUG_PROVIDER) Slog.v(TAG, "Cleaning up dead provider "
7357 + provider + " " + prc.holder.info.name);
7358 mProviderRefCountMap.remove(provider);
7359 for (int i=mProviderMap.size()-1; i>=0; i--) {
7360 ProviderClientRecord pr = mProviderMap.valueAt(i);
7361 if (pr != null && pr.mProvider.asBinder() == provider) {
7362 Slog.i(TAG, "Removing dead content provider:" + pr.mProvider.toString());
7363 mProviderMap.removeAt(i);
7364 }
7365 }
7366
7367 if (fromClient) {
7368 // We found out about this due to execution in our client
7369 // code. Tell the activity manager about it now, to ensure
7370 // that the next time we go to do anything with the provider
7371 // it knows it is dead (so we don't race with its death
7372 // notification).
7373 try {
7374 ActivityManager.getService().unstableProviderDied(
7375 prc.holder.connection);
7376 } catch (RemoteException e) {
7377 //do nothing content provider object is dead any way
7378 }
7379 }
7380 }
7381 }
7382
7383 final void appNotRespondingViaProvider(IBinder provider) {
7384 synchronized (mProviderMap) {
7385 ProviderRefCount prc = mProviderRefCountMap.get(provider);
7386 if (prc != null) {
7387 try {
7388 ActivityManager.getService()
7389 .appNotRespondingViaProvider(prc.holder.connection);
7390 } catch (RemoteException e) {
7391 throw e.rethrowFromSystemServer();
7392 }
7393 }
7394 }
7395 }
7396
7397 private ProviderClientRecord installProviderAuthoritiesLocked(IContentProvider provider,
7398 ContentProvider localProvider, ContentProviderHolder holder) {
7399 final String auths[] = holder.info.authority.split(";");
7400 final int userId = UserHandle.getUserId(holder.info.applicationInfo.uid);
7401
7402 if (provider != null) {
7403 // If this provider is hosted by the core OS and cannot be upgraded,
7404 // then I guess we're okay doing blocking calls to it.
7405 for (String auth : auths) {
7406 switch (auth) {
7407 case ContactsContract.AUTHORITY:
7408 case CallLog.AUTHORITY:
7409 case CallLog.SHADOW_AUTHORITY:
7410 case BlockedNumberContract.AUTHORITY:
7411 case CalendarContract.AUTHORITY:
7412 case Downloads.Impl.AUTHORITY:
7413 case "telephony":
7414 Binder.allowBlocking(provider.asBinder());
7415 }
7416 }
7417 }
7418
7419 final ProviderClientRecord pcr = new ProviderClientRecord(
7420 auths, provider, localProvider, holder);
7421 for (String auth : auths) {
7422 final ProviderKey key = new ProviderKey(auth, userId);
7423 final ProviderClientRecord existing = mProviderMap.get(key);
7424 if (existing != null) {
7425 Slog.w(TAG, "Content provider " + pcr.mHolder.info.name
7426 + " already published as " + auth);
7427 } else {
7428 mProviderMap.put(key, pcr);
7429 }
7430 }
7431 return pcr;
7432 }
7433
7434 /**
7435 * Installs the provider.
7436 *
7437 * Providers that are local to the process or that come from the system server
7438 * may be installed permanently which is indicated by setting noReleaseNeeded to true.
7439 * Other remote providers are reference counted. The initial reference count
7440 * for all reference counted providers is one. Providers that are not reference
7441 * counted do not have a reference count (at all).
7442 *
7443 * This method detects when a provider has already been installed. When this happens,
7444 * it increments the reference count of the existing provider (if appropriate)
7445 * and returns the existing provider. This can happen due to concurrent
7446 * attempts to acquire the same provider.
7447 */
7448 @UnsupportedAppUsage
7449 private ContentProviderHolder installProvider(Context context,
7450 ContentProviderHolder holder, ProviderInfo info,
7451 boolean noisy, boolean noReleaseNeeded, boolean stable) {
7452 ContentProvider localProvider = null;
7453 IContentProvider provider;
7454 if (holder == null || holder.provider == null) {
7455 if (DEBUG_PROVIDER || noisy) {
7456 Slog.d(TAG, "Loading provider " + info.authority + ": "
7457 + info.name);
7458 }
7459 Context c = null;
7460 ApplicationInfo ai = info.applicationInfo;
7461 if (context.getPackageName().equals(ai.packageName)) {
7462 c = context;
7463 } else if (mInitialApplication != null &&
7464 mInitialApplication.getPackageName().equals(ai.packageName)) {
7465 c = mInitialApplication;
7466 } else {
7467 try {
7468 c = context.createPackageContext(ai.packageName,
7469 Context.CONTEXT_INCLUDE_CODE);
7470 } catch (PackageManager.NameNotFoundException e) {
7471 // Ignore
7472 }
7473 }
7474 if (c == null) {
7475 Slog.w(TAG, "Unable to get context for package " +
7476 ai.packageName +
7477 " while loading content provider " +
7478 info.name);
7479 return null;
7480 }
7481
7482 if (info.splitName != null) {
7483 try {
7484 c = c.createContextForSplit(info.splitName);
7485 } catch (NameNotFoundException e) {
7486 throw new RuntimeException(e);
7487 }
7488 }
7489 if (info.attributionTags != null && info.attributionTags.length > 0) {
7490 final String attributionTag = info.attributionTags[0];
7491 c = c.createAttributionContext(attributionTag);
7492 }
7493
7494 try {
7495 final java.lang.ClassLoader cl = c.getClassLoader();
7496 LoadedApk packageInfo = peekPackageInfo(ai.packageName, true);
7497 if (packageInfo == null) {
7498 // System startup case.
7499 packageInfo = getSystemContext().mPackageInfo;
7500 }
7501 localProvider = packageInfo.getAppFactory()
7502 .instantiateProvider(cl, info.name);
7503 provider = localProvider.getIContentProvider();
7504 if (provider == null) {
7505 Slog.e(TAG, "Failed to instantiate class " +
7506 info.name + " from sourceDir " +
7507 info.applicationInfo.sourceDir);
7508 return null;
7509 }
7510 if (DEBUG_PROVIDER) Slog.v(
7511 TAG, "Instantiating local provider " + info.name);
7512 // XXX Need to create the correct context for this provider.
7513 localProvider.attachInfo(c, info);
7514 } catch (java.lang.Exception e) {
7515 if (!mInstrumentation.onException(null, e)) {
7516 throw new RuntimeException(
7517 "Unable to get provider " + info.name
7518 + ": " + e.toString(), e);
7519 }
7520 return null;
7521 }
7522 } else {
7523 provider = holder.provider;
7524 if (DEBUG_PROVIDER) Slog.v(TAG, "Installing external provider " + info.authority + ": "
7525 + info.name);
7526 }
7527
7528 ContentProviderHolder retHolder;
7529
7530 synchronized (mProviderMap) {
7531 if (DEBUG_PROVIDER) Slog.v(TAG, "Checking to add " + provider
7532 + " / " + info.name);
7533 IBinder jBinder = provider.asBinder();
7534 if (localProvider != null) {
7535 ComponentName cname = new ComponentName(info.packageName, info.name);
7536 ProviderClientRecord pr = mLocalProvidersByName.get(cname);
7537 if (pr != null) {
7538 if (DEBUG_PROVIDER) {
7539 Slog.v(TAG, "installProvider: lost the race, "
7540 + "using existing local provider");
7541 }
7542 provider = pr.mProvider;
7543 } else {
7544 holder = new ContentProviderHolder(info);
7545 holder.provider = provider;
7546 holder.noReleaseNeeded = true;
7547 pr = installProviderAuthoritiesLocked(provider, localProvider, holder);
7548 mLocalProviders.put(jBinder, pr);
7549 mLocalProvidersByName.put(cname, pr);
7550 }
7551 retHolder = pr.mHolder;
7552 } else {
7553 ProviderRefCount prc = mProviderRefCountMap.get(jBinder);
7554 if (prc != null) {
7555 if (DEBUG_PROVIDER) {
7556 Slog.v(TAG, "installProvider: lost the race, updating ref count");
7557 }
7558 // We need to transfer our new reference to the existing
7559 // ref count, releasing the old one... but only if
7560 // release is needed (that is, it is not running in the
7561 // system process).
7562 if (!noReleaseNeeded) {
7563 incProviderRefLocked(prc, stable);
7564 try {
7565 ActivityManager.getService().removeContentProvider(
7566 holder.connection, stable);
7567 } catch (RemoteException e) {
7568 //do nothing content provider object is dead any way
7569 }
7570 }
7571 } else {
7572 ProviderClientRecord client = installProviderAuthoritiesLocked(
7573 provider, localProvider, holder);
7574 if (noReleaseNeeded) {
7575 prc = new ProviderRefCount(holder, client, 1000, 1000);
7576 } else {
7577 prc = stable
7578 ? new ProviderRefCount(holder, client, 1, 0)
7579 : new ProviderRefCount(holder, client, 0, 1);
7580 }
7581 mProviderRefCountMap.put(jBinder, prc);
7582 }
7583 retHolder = prc.holder;
7584 }
7585 }
7586 return retHolder;
7587 }
7588
7589 private void handleRunIsolatedEntryPoint(String entryPoint, String[] entryPointArgs) {
7590 try {
7591 Method main = Class.forName(entryPoint).getMethod("main", String[].class);
7592 main.invoke(null, new Object[]{entryPointArgs});
7593 } catch (ReflectiveOperationException e) {
7594 throw new AndroidRuntimeException("runIsolatedEntryPoint failed", e);
7595 }
7596 // The process will be empty after this method returns; exit the VM now.
7597 System.exit(0);
7598 }
7599
7600 @UnsupportedAppUsage
7601 private void attach(boolean system, long startSeq) {
7602 sCurrentActivityThread = this;
7603 mConfigurationController = new ConfigurationController(this);
7604 mSystemThread = system;
7605 if (!system) {
7606 android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
7607 UserHandle.myUserId());
7608 RuntimeInit.setApplicationObject(mAppThread.asBinder());
7609 final IActivityManager mgr = ActivityManager.getService();
7610 try {
7611 mgr.attachApplication(mAppThread, startSeq);
7612 } catch (RemoteException ex) {
7613 throw ex.rethrowFromSystemServer();
7614 }
7615 // Watch for getting close to heap limit.
7616 BinderInternal.addGcWatcher(new Runnable() {
7617 @Override public void run() {
7618 if (!mSomeActivitiesChanged) {
7619 return;
7620 }
7621 Runtime runtime = Runtime.getRuntime();
7622 long dalvikMax = runtime.maxMemory();
7623 long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
7624 if (dalvikUsed > ((3*dalvikMax)/4)) {
7625 if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
7626 + " total=" + (runtime.totalMemory()/1024)
7627 + " used=" + (dalvikUsed/1024));
7628 mSomeActivitiesChanged = false;
7629 try {
7630 ActivityTaskManager.getService().releaseSomeActivities(mAppThread);
7631 } catch (RemoteException e) {
7632 throw e.rethrowFromSystemServer();
7633 }
7634 }
7635 }
7636 });
7637 } else {
7638 // Don't set application object here -- if the system crashes,
7639 // we can't display an alert, we just want to die die die.
7640 android.ddm.DdmHandleAppName.setAppName("system_process",
7641 UserHandle.myUserId());
7642 try {
7643 mInstrumentation = new Instrumentation();
7644 mInstrumentation.basicInit(this);
7645 ContextImpl context = ContextImpl.createAppContext(
7646 this, getSystemContext().mPackageInfo);
7647 mInitialApplication = context.mPackageInfo.makeApplicationInner(true, null);
7648 mInitialApplication.onCreate();
7649 } catch (Exception e) {
7650 throw new RuntimeException(
7651 "Unable to instantiate Application():" + e.toString(), e);
7652 }
7653 }
7654
7655 ViewRootImpl.ConfigChangedCallback configChangedCallback = (Configuration globalConfig) -> {
7656 synchronized (mResourcesManager) {
7657 // We need to apply this change to the resources immediately, because upon returning
7658 // the view hierarchy will be informed about it.
7659 if (mResourcesManager.applyConfigurationToResources(globalConfig,
7660 null /* compat */)) {
7661 mConfigurationController.updateLocaleListFromAppContext(
7662 mInitialApplication.getApplicationContext());
7663
7664 // This actually changed the resources! Tell everyone about it.
7665 final Configuration updatedConfig =
7666 mConfigurationController.updatePendingConfiguration(globalConfig);
7667 if (updatedConfig != null) {
7668 sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
7669 mPendingConfiguration = updatedConfig;
7670 }
7671 }
7672 }
7673 };
7674 ViewRootImpl.addConfigCallback(configChangedCallback);
7675 }
7676
7677 @UnsupportedAppUsage
7678 public static ActivityThread systemMain() {
7679 ThreadedRenderer.initForSystemProcess();
7680 ActivityThread thread = new ActivityThread();
7681 thread.attach(true, 0);
7682 return thread;
7683 }
7684
7685 public static void updateHttpProxy(@NonNull Context context) {
7686 final ConnectivityManager cm = context.getSystemService(ConnectivityManager.class);
7687 Proxy.setHttpProxyConfiguration(cm.getDefaultProxy());
7688 }
7689
7690 @UnsupportedAppUsage
7691 public final void installSystemProviders(List<ProviderInfo> providers) {
7692 if (providers != null) {
7693 installContentProviders(mInitialApplication, providers);
7694 }
7695 }
7696
7697 /**
7698 * Caller should NEVER mutate the Bundle returned from here
7699 */
7700 Bundle getCoreSettings() {
7701 synchronized (mCoreSettingsLock) {
7702 return mCoreSettings;
7703 }
7704 }
7705
7706 public int getIntCoreSetting(String key, int defaultValue) {
7707 synchronized (mCoreSettingsLock) {
7708 if (mCoreSettings != null) {
7709 return mCoreSettings.getInt(key, defaultValue);
7710 }
7711 return defaultValue;
7712 }
7713 }
7714
7715 /**
7716 * Get the string value of the given key from core settings.
7717 */
7718 public String getStringCoreSetting(String key, String defaultValue) {
7719 synchronized (mCoreSettingsLock) {
7720 if (mCoreSettings != null) {
7721 return mCoreSettings.getString(key, defaultValue);
7722 }
7723 return defaultValue;
7724 }
7725 }
7726
7727 float getFloatCoreSetting(String key, float defaultValue) {
7728 synchronized (mCoreSettingsLock) {
7729 if (mCoreSettings != null) {
7730 return mCoreSettings.getFloat(key, defaultValue);
7731 }
7732 return defaultValue;
7733 }
7734 }
7735
7736 private static class AndroidOs extends ForwardingOs {
7737 /**
7738 * Install selective syscall interception. For example, this is used to
7739 * implement special filesystem paths that will be redirected to
7740 * {@link ContentResolver#openFileDescriptor(Uri, String)}.
7741 */
7742 public static void install() {
7743 // If feature is disabled, we don't need to install
7744 if (!DEPRECATE_DATA_COLUMNS) return;
7745
7746 // Install interception and make sure it sticks!
7747 Os def = null;
7748 do {
7749 def = Os.getDefault();
7750 } while (!Os.compareAndSetDefault(def, new AndroidOs(def)));
7751 }
7752
7753 private AndroidOs(Os os) {
7754 super(os);
7755 }
7756
7757 private FileDescriptor openDeprecatedDataPath(String path, int mode) throws ErrnoException {
7758 final Uri uri = ContentResolver.translateDeprecatedDataPath(path);
7759 Log.v(TAG, "Redirecting " + path + " to " + uri);
7760
7761 final ContentResolver cr = currentActivityThread().getApplication()
7762 .getContentResolver();
7763 try {
7764 final FileDescriptor fd = new FileDescriptor();
7765 fd.setInt$(cr.openFileDescriptor(uri,
7766 FileUtils.translateModePosixToString(mode)).detachFd());
7767 return fd;
7768 } catch (SecurityException e) {
7769 throw new ErrnoException(e.getMessage(), OsConstants.EACCES);
7770 } catch (FileNotFoundException e) {
7771 throw new ErrnoException(e.getMessage(), OsConstants.ENOENT);
7772 }
7773 }
7774
7775 private void deleteDeprecatedDataPath(String path) throws ErrnoException {
7776 final Uri uri = ContentResolver.translateDeprecatedDataPath(path);
7777 Log.v(TAG, "Redirecting " + path + " to " + uri);
7778
7779 final ContentResolver cr = currentActivityThread().getApplication()
7780 .getContentResolver();
7781 try {
7782 if (cr.delete(uri, null, null) == 0) {
7783 throw new FileNotFoundException();
7784 }
7785 } catch (SecurityException e) {
7786 throw new ErrnoException(e.getMessage(), OsConstants.EACCES);
7787 } catch (FileNotFoundException e) {
7788 throw new ErrnoException(e.getMessage(), OsConstants.ENOENT);
7789 }
7790 }
7791
7792 @Override
7793 public boolean access(String path, int mode) throws ErrnoException {
7794 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7795 // If we opened it okay, then access check succeeded
7796 IoUtils.closeQuietly(
7797 openDeprecatedDataPath(path, FileUtils.translateModeAccessToPosix(mode)));
7798 return true;
7799 } else {
7800 return super.access(path, mode);
7801 }
7802 }
7803
7804 @Override
7805 public FileDescriptor open(String path, int flags, int mode) throws ErrnoException {
7806 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7807 return openDeprecatedDataPath(path, mode);
7808 } else {
7809 return super.open(path, flags, mode);
7810 }
7811 }
7812
7813 @Override
7814 public StructStat stat(String path) throws ErrnoException {
7815 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7816 final FileDescriptor fd = openDeprecatedDataPath(path, OsConstants.O_RDONLY);
7817 try {
7818 return android.system.Os.fstat(fd);
7819 } finally {
7820 IoUtils.closeQuietly(fd);
7821 }
7822 } else {
7823 return super.stat(path);
7824 }
7825 }
7826
7827 @Override
7828 public void unlink(String path) throws ErrnoException {
7829 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7830 deleteDeprecatedDataPath(path);
7831 } else {
7832 super.unlink(path);
7833 }
7834 }
7835
7836 @Override
7837 public void remove(String path) throws ErrnoException {
7838 if (path != null && path.startsWith(DEPRECATE_DATA_PREFIX)) {
7839 deleteDeprecatedDataPath(path);
7840 } else {
7841 super.remove(path);
7842 }
7843 }
7844
7845 @Override
7846 public void rename(String oldPath, String newPath) throws ErrnoException {
7847 try {
7848 super.rename(oldPath, newPath);
7849 } catch (ErrnoException e) {
7850 // On emulated volumes, we have bind mounts for /Android/data and
7851 // /Android/obb, which prevents move from working across those directories
7852 // and other directories on the filesystem. To work around that, try to
7853 // recover by doing a copy instead.
7854 // Note that we only do this for "/storage/emulated", because public volumes
7855 // don't have these bind mounts, neither do private volumes that are not
7856 // the primary storage.
7857 if (e.errno == OsConstants.EXDEV && oldPath.startsWith("/storage/emulated")
7858 && newPath.startsWith("/storage/emulated")) {
7859 Log.v(TAG, "Recovering failed rename " + oldPath + " to " + newPath);
7860 try {
7861 Files.move(new File(oldPath).toPath(), new File(newPath).toPath(),
7862 StandardCopyOption.REPLACE_EXISTING);
7863 } catch (IOException e2) {
7864 Log.e(TAG, "Rename recovery failed ", e2);
7865 throw e;
7866 }
7867 } else {
7868 throw e;
7869 }
7870 }
7871 }
7872 }
7873
7874 public static void main(String[] args) {
7875 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain");
7876
7877 // Install selective syscall interception
7878 AndroidOs.install();
7879
7880 // CloseGuard defaults to true and can be quite spammy. We
7881 // disable it here, but selectively enable it later (via
7882 // StrictMode) on debug builds, but using DropBox, not logs.
7883 CloseGuard.setEnabled(false);
7884
7885 Environment.initForCurrentUser();
7886
7887 // Make sure TrustedCertificateStore looks in the right place for CA certificates
7888 final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
7889 TrustedCertificateStore.setDefaultUserDirectory(configDir);
7890
7891 // Call per-process mainline module initialization.
7892 initializeMainlineModules();
7893
7894 Process.setArgV0("<pre-initialized>");
7895
7896 Looper.prepareMainLooper();
7897
7898 // Find the value for {@link #PROC_START_SEQ_IDENT} if provided on the command line.
7899 // It will be in the format "seq=114"
7900 long startSeq = 0;
7901 if (args != null) {
7902 for (int i = args.length - 1; i >= 0; --i) {
7903 if (args[i] != null && args[i].startsWith(PROC_START_SEQ_IDENT)) {
7904 startSeq = Long.parseLong(
7905 args[i].substring(PROC_START_SEQ_IDENT.length()));
7906 }
7907 }
7908 }
7909 ActivityThread thread = new ActivityThread();
7910 thread.attach(false, startSeq);
7911
7912 if (sMainThreadHandler == null) {
7913 sMainThreadHandler = thread.getHandler();
7914 }
7915
7916 if (false) {
7917 Looper.myLooper().setMessageLogging(new
7918 LogPrinter(Log.DEBUG, "ActivityThread"));
7919 }
7920
7921 // End of event ActivityThreadMain.
7922 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
7923 Looper.loop();
7924
7925 throw new RuntimeException("Main thread loop unexpectedly exited");
7926 }
7927
7928 /**
7929 * Call various initializer APIs in mainline modules that need to be called when each process
7930 * starts.
7931 */
7932 public static void initializeMainlineModules() {
7933 TelephonyFrameworkInitializer.setTelephonyServiceManager(new TelephonyServiceManager());
7934 StatsFrameworkInitializer.setStatsServiceManager(new StatsServiceManager());
7935 MediaFrameworkPlatformInitializer.setMediaServiceManager(new MediaServiceManager());
7936 MediaFrameworkInitializer.setMediaServiceManager(new MediaServiceManager());
7937 BluetoothFrameworkInitializer.setBluetoothServiceManager(new BluetoothServiceManager());
7938 BluetoothFrameworkInitializer.setBinderCallsStatsInitializer(context -> {
7939 BinderCallsStats.startForBluetooth(context); });
7940 NfcFrameworkInitializer.setNfcServiceManager(new NfcServiceManager());
7941 }
7942
7943 private void purgePendingResources() {
7944 Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "purgePendingResources");
7945 nPurgePendingResources();
7946 Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
7947 }
7948
7949 /**
7950 * Returns whether the provided {@link ActivityInfo} {@code ai} is a protected component.
7951 *
7952 * @see #isProtectedComponent(ComponentInfo, String)
7953 */
7954 public static boolean isProtectedComponent(@NonNull ActivityInfo ai) {
7955 return isProtectedComponent(ai, ai.permission);
7956 }
7957
7958 /**
7959 * Returns whether the provided {@link ServiceInfo} {@code si} is a protected component.
7960 *
7961 * @see #isProtectedComponent(ComponentInfo, String)
7962 */
7963 public static boolean isProtectedComponent(@NonNull ServiceInfo si) {
7964 return isProtectedComponent(si, si.permission);
7965 }
7966
7967 /**
7968 * Returns whether the provided {@link ComponentInfo} {@code ci} with the specified {@code
7969 * permission} is a protected component.
7970 *
7971 * <p>A component is protected if it is not exported, or if the specified {@code permission} is
7972 * a signature permission.
7973 */
7974 private static boolean isProtectedComponent(@NonNull ComponentInfo ci,
7975 @Nullable String permission) {
7976 // Bail early when this process isn't looking for violations
7977 if (!StrictMode.vmUnsafeIntentLaunchEnabled()) return false;
7978
7979 // TODO: consider optimizing by having AMS pre-calculate this value
7980 if (!ci.exported) {
7981 return true;
7982 }
7983 if (permission != null) {
7984 try {
7985 PermissionInfo pi = getPermissionManager().getPermissionInfo(permission,
7986 currentOpPackageName(), 0);
7987 return (pi != null) && pi.getProtection() == PermissionInfo.PROTECTION_SIGNATURE;
7988 } catch (RemoteException ignored) {
7989 }
7990 }
7991 return false;
7992 }
7993
7994 /**
7995 * Returns whether the action within the provided {@code intent} is a protected broadcast.
7996 */
7997 public static boolean isProtectedBroadcast(@NonNull Intent intent) {
7998 // Bail early when this process isn't looking for violations
7999 if (!StrictMode.vmUnsafeIntentLaunchEnabled()) return false;
8000
8001 // TODO: consider optimizing by having AMS pre-calculate this value
8002 try {
8003 return getPackageManager().isProtectedBroadcast(intent.getAction());
8004 } catch (RemoteException ignored) {
8005 }
8006 return false;
8007 }
8008
8009 @Override
8010 public boolean isInDensityCompatMode() {
8011 return mDensityCompatMode;
8012 }
8013
8014 // ------------------ Regular JNI ------------------------
8015 private native void nPurgePendingResources();
8016 private native void nInitZygoteChildHeapProfiling();
8017 }