1 /*
2  * Copyright (C) 2015 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 com.android.car;
18 
19 import static android.car.Car.CAR_DISPLAY_COMPAT_SERVICE;
20 import static android.car.builtin.content.pm.PackageManagerHelper.PROPERTY_CAR_SERVICE_PACKAGE_NAME;
21 
22 import static com.android.car.CarServiceImpl.CAR_SERVICE_INIT_TIMING_MIN_DURATION_MS;
23 import static com.android.car.CarServiceImpl.CAR_SERVICE_INIT_TIMING_TAG;
24 import static com.android.car.internal.ExcludeFromCodeCoverageGeneratedReport.DEPRECATED_CODE;
25 import static com.android.car.internal.ExcludeFromCodeCoverageGeneratedReport.DUMP_INFO;
26 import static com.android.car.internal.SystemConstants.ICAR_SYSTEM_SERVER_CLIENT;
27 
28 import android.annotation.MainThread;
29 import android.annotation.NonNull;
30 import android.annotation.Nullable;
31 import android.app.ActivityManager;
32 import android.car.Car;
33 import android.car.CarFeatures;
34 import android.car.ICar;
35 import android.car.ICarResultReceiver;
36 import android.car.builtin.CarBuiltin;
37 import android.car.builtin.os.BinderHelper;
38 import android.car.builtin.os.BuildHelper;
39 import android.car.builtin.os.TraceHelper;
40 import android.car.builtin.os.UserManagerHelper;
41 import android.car.builtin.util.EventLogHelper;
42 import android.car.builtin.util.Slogf;
43 import android.car.builtin.util.TimingsTraceLog;
44 import android.car.feature.FeatureFlags;
45 import android.car.feature.FeatureFlagsImpl;
46 import android.car.user.CarUserManager;
47 import android.content.Context;
48 import android.content.om.OverlayInfo;
49 import android.content.om.OverlayManager;
50 import android.content.pm.PackageManager;
51 import android.os.Build;
52 import android.os.Bundle;
53 import android.os.IBinder;
54 import android.os.IInterface;
55 import android.os.Parcel;
56 import android.os.ParcelFileDescriptor;
57 import android.os.Process;
58 import android.os.RemoteException;
59 import android.os.SystemProperties;
60 import android.os.UserHandle;
61 import android.os.UserManager;
62 import android.util.ArrayMap;
63 import android.util.Log;
64 import android.util.proto.ProtoOutputStream;
65 
66 import com.android.car.admin.CarDevicePolicyService;
67 import com.android.car.am.CarActivityService;
68 import com.android.car.am.FixedActivityService;
69 import com.android.car.audio.CarAudioService;
70 import com.android.car.bluetooth.CarBluetoothService;
71 import com.android.car.cluster.ClusterHomeService;
72 import com.android.car.cluster.ClusterNavigationService;
73 import com.android.car.cluster.InstrumentClusterService;
74 import com.android.car.evs.CarEvsService;
75 import com.android.car.garagemode.GarageModeService;
76 import com.android.car.hal.PowerHalService;
77 import com.android.car.hal.VehicleHal;
78 import com.android.car.internal.ExcludeFromCodeCoverageGeneratedReport;
79 import com.android.car.internal.ICarServiceHelper;
80 import com.android.car.internal.ICarSystemServerClient;
81 import com.android.car.internal.StaticBinderInterface;
82 import com.android.car.internal.SystemStaticBinder;
83 import com.android.car.internal.util.IndentingPrintWriter;
84 import com.android.car.occupantconnection.CarOccupantConnectionService;
85 import com.android.car.occupantconnection.CarRemoteDeviceService;
86 import com.android.car.oem.CarOemProxyService;
87 import com.android.car.os.CarPerformanceService;
88 import com.android.car.pm.CarPackageManagerService;
89 import com.android.car.power.CarPowerManagementService;
90 import com.android.car.remoteaccess.CarRemoteAccessService;
91 import com.android.car.stats.CarStatsService;
92 import com.android.car.systeminterface.SystemInterface;
93 import com.android.car.systemui.keyguard.ExperimentalCarKeyguardService;
94 import com.android.car.telemetry.CarTelemetryService;
95 import com.android.car.user.CarUserNoticeService;
96 import com.android.car.user.CarUserService;
97 import com.android.car.user.ExperimentalCarUserService;
98 import com.android.car.vms.VmsBrokerService;
99 import com.android.car.watchdog.CarWatchdogService;
100 import com.android.car.wifi.CarWifiService;
101 import com.android.internal.annotations.GuardedBy;
102 import com.android.internal.annotations.VisibleForTesting;
103 
104 import java.io.File;
105 import java.io.FileDescriptor;
106 import java.io.FileOutputStream;
107 import java.io.PrintWriter;
108 import java.util.ArrayList;
109 import java.util.Arrays;
110 import java.util.List;
111 import java.util.Map;
112 import java.util.Objects;
113 import java.util.concurrent.Callable;
114 
115 public class ICarImpl extends ICar.Stub {
116 
117     public static final String INTERNAL_INPUT_SERVICE = "internal_input";
118     public static final String INTERNAL_SYSTEM_ACTIVITY_MONITORING_SERVICE =
119             "system_activity_monitoring";
120 
121     @VisibleForTesting
122     static final String TAG = CarLog.tagFor(ICarImpl.class);
123 
124     private final Context mContext;
125     private final Context mCarServiceBuiltinPackageContext;
126     private final VehicleHal mHal;
127 
128     private final CarServiceHelperWrapper mCarServiceHelperWrapper;
129 
130     private final CarFeatureController mFeatureController;
131 
132     private final SystemInterface mSystemInterface;
133 
134     private final FeatureFlags mFeatureFlags;
135 
136     private final CarOemProxyService mCarOemService;
137     private final SystemActivityMonitoringService mSystemActivityMonitoringService;
138     private final CarPowerManagementService mCarPowerManagementService;
139     private final CarPackageManagerService mCarPackageManagerService;
140     private final CarInputService mCarInputService;
141     private final CarDrivingStateService mCarDrivingStateService;
142     private final CarUxRestrictionsManagerService mCarUXRestrictionsService;
143     private final OccupantAwarenessService mOccupantAwarenessService;
144     private final CarAudioService mCarAudioService;
145     private final CarProjectionService mCarProjectionService;
146     private final CarPropertyService mCarPropertyService;
147     private final CarNightService mCarNightService;
148     private final AppFocusService mAppFocusService;
149     private final FixedActivityService mFixedActivityService;
150     private final GarageModeService mGarageModeService;
151     private final ClusterNavigationService mClusterNavigationService;
152     private final InstrumentClusterService mInstrumentClusterService;
153     private final CarLocationService mCarLocationService;
154     private final CarBluetoothService mCarBluetoothService;
155     private final CarPerUserServiceHelper mCarPerUserServiceHelper;
156     private final CarDiagnosticService mCarDiagnosticService;
157     private final CarStorageMonitoringService mCarStorageMonitoringService;
158     private final CarMediaService mCarMediaService;
159     private final CarUserService mCarUserService;
160     @Nullable
161     private final ExperimentalCarUserService mExperimentalCarUserService;
162     @Nullable
163     private final ExperimentalCarKeyguardService mExperimentalCarKeyguardService;
164     private final CarOccupantZoneService mCarOccupantZoneService;
165     private final CarUserNoticeService mCarUserNoticeService;
166     private final VmsBrokerService mVmsBrokerService;
167     private final CarBugreportManagerService mCarBugreportManagerService;
168     private final CarStatsService mCarStatsService;
169     private final CarExperimentalFeatureServiceController mCarExperimentalFeatureServiceController;
170     private final CarWatchdogService mCarWatchdogService;
171     private final CarPerformanceService mCarPerformanceService;
172     private final CarDevicePolicyService mCarDevicePolicyService;
173     private final ClusterHomeService mClusterHomeService;
174     private final CarEvsService mCarEvsService;
175     private final CarTelemetryService mCarTelemetryService;
176     private final CarActivityService mCarActivityService;
177     private final CarOccupantConnectionService mCarOccupantConnectionService;
178     private final CarRemoteDeviceService mCarRemoteDeviceService;
179     private final CarWifiService mCarWifiService;
180     @Nullable
181     private final CarRemoteAccessService mCarRemoteAccessService;
182 
183     // Storing all the car services in the order of their init.
184     private final CarSystemService[] mAllServicesInInitOrder;
185 
186     private static final boolean DBG = Slogf.isLoggable(TAG, Log.DEBUG);
187 
188     private final Object mLock = new Object();
189 
190     // This flag indicates whether priorityInit() should be called in the constructor or
191     // will be deferred to CarImpl.init(). With the new boot user code flow, the boot user is set
192     // in initialUserSetter as early as possible. The earliest it can be done is in the ICarImpl
193     // constructor. In priorityInit() HAL and UserService are initialized which sets boot user.
194     private final boolean mDoPriorityInitInConstruction;
195 
196     /** Test only service. Populate it only when necessary. */
197     @GuardedBy("mLock")
198     private CarTestService mCarTestService;
199 
200     private final String mVehicleInterfaceName;
201 
202     private final ICarSystemServerClientImpl mICarSystemServerClientImpl;
203 
204     private final BinderHelper.ShellCommandListener mCmdListener =
205             (FileDescriptor in, FileDescriptor out, FileDescriptor err, String[] args) ->
206                     newCarShellCommand().exec(ICarImpl.this, in, out, err, args);
207 
208     // A static Binder class implementation. Faked during unit tests.
209     private final StaticBinderInterface mStaticBinder;
210 
ICarImpl(Builder builder)211     private ICarImpl(Builder builder) {
212         TimingsTraceLog t = new TimingsTraceLog(
213                 CAR_SERVICE_INIT_TIMING_TAG, TraceHelper.TRACE_TAG_CAR_SERVICE,
214                 CAR_SERVICE_INIT_TIMING_MIN_DURATION_MS);
215         t.traceBegin("ICarImpl.constructor");
216 
217         mStaticBinder = Objects.requireNonNullElseGet(builder.mStaticBinder,
218                 () -> new SystemStaticBinder());
219         mFeatureFlags = Objects.requireNonNullElseGet(builder.mFeatureFlags,
220                 () -> new FeatureFlagsImpl());
221         mDoPriorityInitInConstruction = builder.mDoPriorityInitInConstruction;
222 
223         mContext = builder.mContext;
224         if (builder.mCarServiceBuiltinPackageContext == null) {
225             mCarServiceBuiltinPackageContext = mContext;
226         } else {
227             mCarServiceBuiltinPackageContext = builder.mCarServiceBuiltinPackageContext;
228         }
229 
230         mCarServiceHelperWrapper = CarServiceHelperWrapper.create();
231 
232         // Currently there are ~36 services, hence using 40 as the initial capacity.
233         List<CarSystemService> allServices = new ArrayList<>(40);
234         mCarOemService = constructWithTrace(t, CarOemProxyService.class,
235                 () -> new CarOemProxyService(mContext), allServices);
236 
237         mSystemInterface = builder.mSystemInterface;
238         CarLocalServices.addService(SystemInterface.class, mSystemInterface);
239 
240         mHal = constructWithTrace(t, VehicleHal.class,
241                 () -> new VehicleHal(mContext, builder.mVehicle), allServices);
242 
243         mFeatureController = constructWithTrace(t, CarFeatureController.class,
244                 () -> new CarFeatureController(
245                         mContext, mSystemInterface.getSystemCarDir(), mHal), allServices);
246         mVehicleInterfaceName = builder.mVehicleInterfaceName;
247         mCarPropertyService = constructWithTrace(
248                 t, CarPropertyService.class,
249                 () -> new CarPropertyService.Builder()
250                         .setContext(mContext)
251                         .setPropertyHalService(mHal.getPropertyHal())
252                         .build(), allServices);
253         mCarDrivingStateService = constructWithTrace(
254                 t, CarDrivingStateService.class,
255                 () -> new CarDrivingStateService(mContext, mCarPropertyService), allServices);
256         mCarOccupantZoneService = constructWithTrace(t, CarOccupantZoneService.class,
257                 () -> new CarOccupantZoneService(mContext), allServices);
258         mCarUXRestrictionsService = constructWithTrace(t, CarUxRestrictionsManagerService.class,
259                 () -> new CarUxRestrictionsManagerService(mContext, mCarDrivingStateService,
260                         mCarPropertyService, mCarOccupantZoneService), allServices);
261         mCarActivityService = constructWithTrace(t, CarActivityService.class,
262                 () -> new CarActivityService(mContext), allServices);
263         mCarPackageManagerService = constructWithTrace(t, CarPackageManagerService.class,
264                 () -> new CarPackageManagerService(mContext, mCarUXRestrictionsService,
265                         mCarActivityService, mCarOccupantZoneService), allServices);
266         UserManager userManager = mContext.getSystemService(UserManager.class);
267         mCarUserService = getFromBuilderOrConstruct(t, CarUserService.class,
268                 builder.mCarUserService,
269                 () -> {
270                     int maxRunningUsers = UserManagerHelper.getMaxRunningUsers(mContext);
271                     return new CarUserService(mContext, mHal.getUserHal(), userManager,
272                         maxRunningUsers, mCarUXRestrictionsService, mCarPackageManagerService,
273                         mCarOccupantZoneService);
274                 },
275                 allServices);
276         if (mDoPriorityInitInConstruction) {
277             Slogf.i(TAG, "VHAL Priority Init Enabled");
278             Slogf.i(TAG, "Car User Service Priority Init Enabled");
279             priorityInit();
280         }
281 
282         if (mFeatureController.isFeatureEnabled(Car.EXPERIMENTAL_CAR_USER_SERVICE)) {
283             mExperimentalCarUserService = constructWithTrace(t, ExperimentalCarUserService.class,
284                     () -> new ExperimentalCarUserService(mContext, mCarUserService,
285                             userManager), allServices);
286         } else {
287             mExperimentalCarUserService = null;
288         }
289         if (mFeatureController.isFeatureEnabled(Car.EXPERIMENTAL_CAR_KEYGUARD_SERVICE)) {
290             mExperimentalCarKeyguardService = constructWithTrace(t,
291                         ExperimentalCarKeyguardService.class,
292                     () -> new ExperimentalCarKeyguardService(mContext, mCarUserService,
293                             mCarOccupantZoneService), allServices);
294         } else {
295             mExperimentalCarKeyguardService = null;
296         }
297         mSystemActivityMonitoringService = constructWithTrace(
298                 t, SystemActivityMonitoringService.class,
299                 () -> new SystemActivityMonitoringService(mContext), allServices);
300 
301         mCarPowerManagementService = constructWithTrace(
302                 t, CarPowerManagementService.class,
303                 () -> new CarPowerManagementService.Builder()
304                         .setContext(mContext)
305                         .setPowerHalService(mHal.getPowerHal())
306                         .setSystemInterface(mSystemInterface)
307                         .setCarUserService(mCarUserService)
308                         .setPowerPolicyDaemon(builder.mPowerPolicyDaemon)
309                         .setFeatureFlags(mFeatureFlags)
310                         .build(),
311                 allServices);
312         if (mFeatureController.isFeatureEnabled(CarFeatures.FEATURE_CAR_USER_NOTICE_SERVICE)) {
313             mCarUserNoticeService = constructWithTrace(
314                     t, CarUserNoticeService.class, () -> new CarUserNoticeService(mContext),
315                     allServices);
316         } else {
317             mCarUserNoticeService = null;
318         }
319         if (mFeatureController.isFeatureEnabled(Car.OCCUPANT_AWARENESS_SERVICE)) {
320             mOccupantAwarenessService = constructWithTrace(t, OccupantAwarenessService.class,
321                     () -> new OccupantAwarenessService(mContext), allServices);
322         } else {
323             mOccupantAwarenessService = null;
324         }
325         mCarPerUserServiceHelper = constructWithTrace(
326                 t, CarPerUserServiceHelper.class,
327                 () -> new CarPerUserServiceHelper(mContext, mCarUserService), allServices);
328         mCarBluetoothService = constructWithTrace(t, CarBluetoothService.class,
329                 () -> new CarBluetoothService(mContext, mCarPerUserServiceHelper),
330                 allServices);
331         mCarInputService = constructWithTrace(t, CarInputService.class,
332                 () -> new CarInputService(mContext, mHal.getInputHal(), mCarUserService,
333                         mCarOccupantZoneService, mCarBluetoothService, mCarPowerManagementService,
334                         mSystemInterface), allServices);
335         mCarProjectionService = constructWithTrace(t, CarProjectionService.class,
336                 () -> new CarProjectionService(mContext, null /* handler */, mCarInputService,
337                         mCarBluetoothService), allServices);
338         mGarageModeService = getFromBuilderOrConstruct(t, GarageModeService.class,
339                 builder.mGarageModeService, () -> new GarageModeService(mContext),
340                 allServices);
341         mAppFocusService = getFromBuilderOrConstruct(t, AppFocusService.class,
342                 builder.mAppFocusService,
343                 () -> new AppFocusService(mContext, mSystemActivityMonitoringService),
344                 allServices);
345         mCarAudioService = constructWithTrace(t, CarAudioService.class,
346                 () -> new CarAudioService(mContext), allServices);
347         mCarNightService = constructWithTrace(t, CarNightService.class,
348                 () -> new CarNightService(mContext, mCarPropertyService), allServices);
349         mFixedActivityService = constructWithTrace(t, FixedActivityService.class,
350                 () -> new FixedActivityService(mContext, mCarActivityService), allServices);
351         mClusterNavigationService = constructWithTrace(
352                 t, ClusterNavigationService.class,
353                 () -> new ClusterNavigationService(mContext, mAppFocusService), allServices);
354         if (mFeatureController.isFeatureEnabled(Car.CAR_INSTRUMENT_CLUSTER_SERVICE)) {
355             mInstrumentClusterService = constructWithTrace(t, InstrumentClusterService.class,
356                     () -> new InstrumentClusterService(mContext, mClusterNavigationService,
357                             mCarInputService), allServices);
358         } else {
359             mInstrumentClusterService = null;
360         }
361 
362         mCarStatsService = constructWithTrace(t, CarStatsService.class,
363                 () -> new CarStatsService(mContext), allServices);
364 
365         if (mFeatureController.isFeatureEnabled(Car.VEHICLE_MAP_SERVICE)) {
366             mVmsBrokerService = constructWithTrace(t, VmsBrokerService.class,
367                     () -> new VmsBrokerService(mContext, mCarStatsService), allServices);
368         } else {
369             mVmsBrokerService = null;
370         }
371         if (mFeatureController.isFeatureEnabled(Car.DIAGNOSTIC_SERVICE)) {
372             mCarDiagnosticService = constructWithTrace(t, CarDiagnosticService.class,
373                     () -> new CarDiagnosticService(mContext, mHal.getDiagnosticHal()), allServices);
374         } else {
375             mCarDiagnosticService = null;
376         }
377         if (mFeatureController.isFeatureEnabled(Car.STORAGE_MONITORING_SERVICE)) {
378             mCarStorageMonitoringService = constructWithTrace(
379                     t, CarStorageMonitoringService.class,
380                     () -> new CarStorageMonitoringService(mContext, mSystemInterface), allServices);
381         } else {
382             mCarStorageMonitoringService = null;
383         }
384         mCarLocationService = constructWithTrace(t, CarLocationService.class,
385                 () -> new CarLocationService(mContext), allServices);
386         mCarMediaService = constructWithTrace(t, CarMediaService.class,
387                 () -> new CarMediaService(mContext, mCarOccupantZoneService, mCarUserService,
388                         mCarPowerManagementService),
389                 allServices);
390         mCarBugreportManagerService = constructWithTrace(t, CarBugreportManagerService.class,
391                 () -> new CarBugreportManagerService(mContext), allServices);
392         mCarWatchdogService = getFromBuilderOrConstruct(t, CarWatchdogService.class,
393                 builder.mCarWatchdogService,
394                 () -> new CarWatchdogService(mContext, mCarServiceBuiltinPackageContext),
395                 allServices);
396         mCarPerformanceService = getFromBuilderOrConstruct(t, CarPerformanceService.class,
397                 builder.mCarPerformanceService, () -> new CarPerformanceService(mContext),
398                 allServices);
399         mCarDevicePolicyService = constructWithTrace(
400                 t, CarDevicePolicyService.class, () -> new CarDevicePolicyService(mContext,
401                         mCarServiceBuiltinPackageContext, mCarUserService), allServices);
402         if (mFeatureController.isFeatureEnabled(Car.CLUSTER_HOME_SERVICE)) {
403             if (!mFeatureController.isFeatureEnabled(Car.CAR_INSTRUMENT_CLUSTER_SERVICE)) {
404                 mClusterHomeService = constructWithTrace(
405                         t, ClusterHomeService.class,
406                         () -> new ClusterHomeService(mContext, mHal.getClusterHal(),
407                                 mClusterNavigationService, mCarOccupantZoneService,
408                                 mFixedActivityService), allServices);
409             } else {
410                 Slogf.w(TAG, "Can't init ClusterHomeService, since Old cluster service is running");
411                 mClusterHomeService = null;
412             }
413         } else {
414             mClusterHomeService = null;
415         }
416 
417         if (mFeatureController.isFeatureEnabled(Car.CAR_EVS_SERVICE)) {
418             mCarEvsService = constructWithTrace(t, CarEvsService.class,
419                     () -> new CarEvsService(mContext, mCarServiceBuiltinPackageContext,
420                             mHal.getEvsHal(), mCarPropertyService), allServices);
421         } else {
422             mCarEvsService = null;
423         }
424 
425         if (mFeatureController.isFeatureEnabled(Car.CAR_TELEMETRY_SERVICE)) {
426             mCarTelemetryService = getFromBuilderOrConstruct(t, CarTelemetryService.class,
427                     builder.mCarTelemetryService,
428                     () -> new CarTelemetryService(mContext, mCarPowerManagementService,
429                             mCarPropertyService),
430                     allServices);
431         } else {
432             mCarTelemetryService = null;
433         }
434 
435         if (mFeatureController.isFeatureEnabled((Car.CAR_REMOTE_ACCESS_SERVICE))) {
436             if (builder.mCarRemoteAccessServiceConstructor == null) {
437                 mCarRemoteAccessService = constructWithTrace(t, CarRemoteAccessService.class,
438                         () -> new CarRemoteAccessService(
439                                 mContext, mSystemInterface, mHal.getPowerHal()), allServices);
440             } else {
441                 mCarRemoteAccessService = builder.mCarRemoteAccessServiceConstructor.construct(
442                         mContext, mSystemInterface, mHal.getPowerHal());
443                 allServices.add(mCarRemoteAccessService);
444             }
445         } else {
446             mCarRemoteAccessService = null;
447         }
448 
449         mCarWifiService = constructWithTrace(t, CarWifiService.class,
450                 () -> new CarWifiService(mContext), allServices);
451 
452         // Always put mCarExperimentalFeatureServiceController in last.
453         if (!BuildHelper.isUserBuild()) {
454             mCarExperimentalFeatureServiceController = constructWithTrace(
455                     t, CarExperimentalFeatureServiceController.class,
456                     () -> new CarExperimentalFeatureServiceController(mContext),
457                     allServices);
458         } else {
459             mCarExperimentalFeatureServiceController = null;
460         }
461 
462         if (mFeatureController.isFeatureEnabled(Car.CAR_OCCUPANT_CONNECTION_SERVICE)
463                 || mFeatureController.isFeatureEnabled(Car.CAR_REMOTE_DEVICE_SERVICE)) {
464             mCarRemoteDeviceService = constructWithTrace(
465                     t, CarRemoteDeviceService.class,
466                     () -> new CarRemoteDeviceService(mContext, mCarOccupantZoneService,
467                             mCarPowerManagementService, mSystemActivityMonitoringService),
468                     allServices);
469             mCarOccupantConnectionService = constructWithTrace(
470                     t, CarOccupantConnectionService.class,
471                     () -> new CarOccupantConnectionService(mContext, mCarOccupantZoneService,
472                             mCarRemoteDeviceService),
473                     allServices);
474 
475         } else {
476             mCarOccupantConnectionService = null;
477             mCarRemoteDeviceService = null;
478         }
479 
480         mAllServicesInInitOrder = allServices.toArray(new CarSystemService[allServices.size()]);
481         mICarSystemServerClientImpl = new ICarSystemServerClientImpl();
482 
483         t.traceEnd(); // "ICarImpl.constructor"
484     }
485 
486     @MainThread
init()487     void init() {
488         TimingsTraceLog t = new TimingsTraceLog(CAR_SERVICE_INIT_TIMING_TAG,
489                 TraceHelper.TRACE_TAG_CAR_SERVICE, CAR_SERVICE_INIT_TIMING_MIN_DURATION_MS);
490 
491         t.traceBegin("ICarImpl.init");
492         if (!mDoPriorityInitInConstruction) {
493             priorityInit();
494         }
495 
496         t.traceBegin("CarService.initAllServices");
497         for (CarSystemService service : mAllServicesInInitOrder) {
498             t.traceBegin(service.getClass().getSimpleName());
499             service.init();
500             t.traceEnd();
501         }
502         t.traceEnd(); // "CarService.initAllServices"
503 
504         t.traceBegin("CarService.onInitComplete");
505         for (CarSystemService service : mAllServicesInInitOrder) {
506             if (service == mCarPowerManagementService) {
507                 // Must make sure mCarPowerManagementService.onInitComplete runs at last since
508                 // it might shutdown the device.
509                 continue;
510             }
511             t.traceBegin("onInitComplete:" + service.getClass().getSimpleName());
512             service.onInitComplete();
513             t.traceEnd();
514         }
515         mCarPowerManagementService.onInitComplete();
516         t.traceEnd(); // "CarService.onInitComplete"
517 
518         t.traceEnd(); // "ICarImpl.init"
519     }
520 
release()521     void release() {
522         // release done in opposite order from init
523         for (int i = mAllServicesInInitOrder.length - 1; i >= 0; i--) {
524             mAllServicesInInitOrder[i].release();
525         }
526     }
527 
528     @Override
setSystemServerConnections(ICarServiceHelper carServiceHelper, ICarResultReceiver resultReceiver)529     public void setSystemServerConnections(ICarServiceHelper carServiceHelper,
530             ICarResultReceiver resultReceiver) {
531         Bundle bundle;
532         try {
533             EventLogHelper.writeCarServiceSetCarServiceHelper(mStaticBinder.getCallingPid());
534             assertCallingFromSystemProcess();
535 
536             mCarServiceHelperWrapper.setCarServiceHelper(carServiceHelper);
537 
538             bundle = new Bundle();
539             bundle.putBinder(ICAR_SYSTEM_SERVER_CLIENT, mICarSystemServerClientImpl.asBinder());
540         } catch (Exception e) {
541             // send back a null response
542             Slogf.w(TAG, "Exception in setSystemServerConnections", e);
543             bundle = null;
544         }
545 
546         try {
547             resultReceiver.send(/* unused */ 0, bundle);
548         } catch (RemoteException e) {
549             Slogf.w(TAG, "RemoteException from CarServiceHelperService", e);
550         }
551     }
552 
553     @Override
isFeatureEnabled(String featureName)554     public boolean isFeatureEnabled(String featureName) {
555         return mFeatureController.isFeatureEnabled(featureName);
556     }
557 
558     @Override
enableFeature(String featureName)559     public int enableFeature(String featureName) {
560         // permission check inside the controller
561         return mFeatureController.enableFeature(featureName);
562     }
563 
564     @Override
disableFeature(String featureName)565     public int disableFeature(String featureName) {
566         // permission check inside the controller
567         return mFeatureController.disableFeature(featureName);
568     }
569 
570     @Override
getAllEnabledFeatures()571     public List<String> getAllEnabledFeatures() {
572         // permission check inside the controller
573         return mFeatureController.getAllEnabledFeatures();
574     }
575 
576     @Override
getAllPendingDisabledFeatures()577     public List<String> getAllPendingDisabledFeatures() {
578         // permission check inside the controller
579         return mFeatureController.getAllPendingDisabledFeatures();
580     }
581 
582     @Override
getAllPendingEnabledFeatures()583     public List<String> getAllPendingEnabledFeatures() {
584         // permission check inside the controller
585         return mFeatureController.getAllPendingEnabledFeatures();
586     }
587 
588     @Override
589     @Nullable
getCarManagerClassForFeature(String featureName)590     public String getCarManagerClassForFeature(String featureName) {
591         if (mCarExperimentalFeatureServiceController == null) {
592             return null;
593         }
594         return mCarExperimentalFeatureServiceController.getCarManagerClassForFeature(featureName);
595     }
596 
597 
assertCallingFromSystemProcess()598     private void assertCallingFromSystemProcess() {
599         int uid = mStaticBinder.getCallingUid();
600         if (uid != Process.SYSTEM_UID) {
601             throw new SecurityException("Only allowed from system");
602         }
603     }
604 
605     @Override
606     @Nullable
getCarService(String serviceName)607     public IBinder getCarService(String serviceName) {
608         if (!mFeatureController.isFeatureEnabled(serviceName)) {
609             Slogf.w(CarLog.TAG_SERVICE, "getCarService for disabled service:" + serviceName);
610             return null;
611         }
612         switch (serviceName) {
613             case Car.AUDIO_SERVICE:
614                 return mCarAudioService;
615             case Car.APP_FOCUS_SERVICE:
616                 return mAppFocusService;
617             case Car.PACKAGE_SERVICE:
618                 return mCarPackageManagerService;
619             case Car.DIAGNOSTIC_SERVICE:
620                 CarServiceUtils.assertAnyDiagnosticPermission(mContext);
621                 return mCarDiagnosticService;
622             case Car.POWER_SERVICE:
623                 return mCarPowerManagementService;
624             case Car.CABIN_SERVICE:
625             case Car.HVAC_SERVICE:
626             case Car.INFO_SERVICE:
627             case Car.PROPERTY_SERVICE:
628             case Car.SENSOR_SERVICE:
629             case Car.VENDOR_EXTENSION_SERVICE:
630                 return mCarPropertyService;
631             case Car.CAR_NAVIGATION_SERVICE:
632                 CarServiceUtils.assertNavigationManagerPermission(mContext);
633                 return mClusterNavigationService;
634             case Car.CAR_INSTRUMENT_CLUSTER_SERVICE:
635                 CarServiceUtils.assertClusterManagerPermission(mContext);
636                 return mInstrumentClusterService.getManagerService();
637             case Car.PROJECTION_SERVICE:
638                 return mCarProjectionService;
639             case Car.VEHICLE_MAP_SERVICE:
640                 CarServiceUtils.assertAnyVmsPermission(mContext);
641                 return mVmsBrokerService;
642             case Car.VMS_SUBSCRIBER_SERVICE:
643                 CarServiceUtils.assertVmsSubscriberPermission(mContext);
644                 return mVmsBrokerService;
645             case Car.TEST_SERVICE: {
646                 CarServiceUtils.assertPermission(mContext, Car.PERMISSION_CAR_TEST_SERVICE);
647                 synchronized (mLock) {
648                     if (mCarTestService == null) {
649                         mCarTestService = new CarTestService(mContext, this);
650                     }
651                     return mCarTestService;
652                 }
653             }
654             case Car.STORAGE_MONITORING_SERVICE:
655                 CarServiceUtils.assertPermission(mContext, Car.PERMISSION_STORAGE_MONITORING);
656                 return mCarStorageMonitoringService;
657             case Car.CAR_DRIVING_STATE_SERVICE:
658                 CarServiceUtils.assertDrivingStatePermission(mContext);
659                 return mCarDrivingStateService;
660             case Car.CAR_UX_RESTRICTION_SERVICE:
661                 return mCarUXRestrictionsService;
662             case Car.OCCUPANT_AWARENESS_SERVICE:
663                 return mOccupantAwarenessService;
664             case Car.CAR_MEDIA_SERVICE:
665                 return mCarMediaService;
666             case Car.CAR_OCCUPANT_ZONE_SERVICE:
667                 return mCarOccupantZoneService;
668             case Car.CAR_BUGREPORT_SERVICE:
669                 return mCarBugreportManagerService;
670             case Car.CAR_USER_SERVICE:
671                 return mCarUserService;
672             case Car.EXPERIMENTAL_CAR_USER_SERVICE:
673                 return mExperimentalCarUserService;
674             case Car.EXPERIMENTAL_CAR_KEYGUARD_SERVICE:
675                 return mExperimentalCarKeyguardService;
676             case Car.CAR_WATCHDOG_SERVICE:
677                 return mCarWatchdogService;
678             case Car.CAR_PERFORMANCE_SERVICE:
679                 return mCarPerformanceService;
680             case Car.CAR_INPUT_SERVICE:
681                 return mCarInputService;
682             case Car.CAR_DEVICE_POLICY_SERVICE:
683                 return mCarDevicePolicyService;
684             case Car.CLUSTER_HOME_SERVICE:
685                 return mClusterHomeService;
686             case Car.CAR_EVS_SERVICE:
687                 return mCarEvsService;
688             case Car.CAR_TELEMETRY_SERVICE:
689                 return mCarTelemetryService;
690             case Car.CAR_ACTIVITY_SERVICE:
691                 return mCarActivityService;
692             case Car.CAR_OCCUPANT_CONNECTION_SERVICE:
693                 return mCarOccupantConnectionService;
694             case Car.CAR_REMOTE_DEVICE_SERVICE:
695                 return mCarRemoteDeviceService;
696             case Car.CAR_REMOTE_ACCESS_SERVICE:
697                 return mCarRemoteAccessService;
698             default:
699                 // CarDisplayCompatManager does not need a new service but the Car class
700                 // doesn't allow a new Manager class without a service.
701                 if (mFeatureFlags.displayCompatibility()) {
702                     if (serviceName.equals(CAR_DISPLAY_COMPAT_SERVICE)) {
703                         return mCarActivityService;
704                     }
705                 }
706                 if (mFeatureFlags.persistApSettings()) {
707                     if (serviceName.equals(Car.CAR_WIFI_SERVICE)) {
708                         return mCarWifiService;
709                     }
710                 }
711                 IBinder service = null;
712                 if (mCarExperimentalFeatureServiceController != null) {
713                     service = mCarExperimentalFeatureServiceController.getCarService(serviceName);
714                 }
715                 if (service == null) {
716                     Slogf.w(CarLog.TAG_SERVICE, "getCarService for unknown service:"
717                             + serviceName);
718                 }
719                 return service;
720         }
721     }
722 
723     @Override
724     @ExcludeFromCodeCoverageGeneratedReport(reason = DEPRECATED_CODE)
getCarConnectionType()725     public int getCarConnectionType() {
726         return Car.CONNECTION_TYPE_EMBEDDED;
727     }
728 
729     @Override
730     @ExcludeFromCodeCoverageGeneratedReport(reason = DUMP_INFO)
dump(FileDescriptor fd, PrintWriter writer, String[] args)731     protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
732         if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
733                 != PackageManager.PERMISSION_GRANTED) {
734             writer.println("Permission Denial: can't dump CarService from from pid="
735                     + mStaticBinder.getCallingPid() + ", uid=" + mStaticBinder.getCallingUid()
736                     + " without permission " + android.Manifest.permission.DUMP);
737             return;
738         }
739 
740         try (IndentingPrintWriter pw = new IndentingPrintWriter(writer)) {
741             dumpIndenting(fd, pw, args);
742         }
743     }
744 
745     @ExcludeFromCodeCoverageGeneratedReport(reason = DUMP_INFO)
dumpIndenting(FileDescriptor fd, IndentingPrintWriter writer, String[] args)746     private void dumpIndenting(FileDescriptor fd, IndentingPrintWriter writer, String[] args) {
747         if (args == null || args.length == 0) {
748             dumpAll(writer);
749             return;
750         }
751         switch (args[0]) {
752             case "-a":
753                 dumpAll(writer);
754                 return;
755             case "--list":
756                 dumpListOfServices(writer);
757                 return;
758             case "--version":
759                 dumpVersions(writer);
760                 return;
761             case "--services": {
762                 int length = args.length;
763                 boolean dumpToProto = false;
764                 if (length < 2) {
765                     writer.println("Must pass services to dump when using --services");
766                     return;
767                 }
768                 if (Objects.equals(args[length - 1], "--proto")) {
769                     length -= 2;
770                     dumpToProto = true;
771                     if (length > 1) {
772                         writer.println("Cannot dump multiple services to proto");
773                         return;
774                     }
775                 } else {
776                     length -= 1;
777                 }
778                 String[] services = new String[length];
779                 System.arraycopy(args, 1, services, 0, length);
780                 if (dumpToProto) {
781                     if (!mFeatureFlags.carDumpToProto()) {
782                         writer.println("Cannot dump " + services[0]
783                                 + " to proto since FLAG_CAR_DUMP_TO_PROTO is disabled");
784                         return;
785                     }
786                     dumpServiceProto(writer, fd, services[0]);
787                 } else {
788                     dumpIndividualServices(writer, services);
789                 }
790                 return;
791             }
792             case "--metrics":
793                 // Strip the --metrics flag when passing dumpsys arguments to CarStatsService
794                 // allowing for nested flag selection.
795                 if (args.length == 1 || Arrays.asList(args).contains("--vms-client")) {
796                     mCarStatsService.dump(writer);
797                 }
798                 return;
799             case "--vms-hal":
800                 mHal.getVmsHal().dumpMetrics(fd);
801                 return;
802             case "--hal": {
803                 if (args.length == 1) {
804                     dumpAllHals(writer);
805                     return;
806                 }
807                 int length = args.length - 1;
808                 String[] halNames = new String[length];
809                 System.arraycopy(args, 1, halNames, 0, length);
810                 mHal.dumpSpecificHals(writer, halNames);
811                 return;
812             }
813             case "--list-hals":
814                 mHal.dumpListHals(writer);
815                 return;
816             case "--data-dir":
817                 dumpDataDir(writer);
818                 return;
819             case "--help":
820                 showDumpHelp(writer);
821                 return;
822             case "--rro":
823                 dumpRROs(writer);
824                 return;
825             case "--oem-service":
826                 if (args.length > 1 && args[1].equalsIgnoreCase("--name-only")) {
827                     writer.println(getOemServiceName());
828                 } else {
829                     dumpOemService(writer);
830                 }
831                 return;
832             default:
833                 execShellCmd(args, writer);
834         }
835     }
836 
dumpOemService(IndentingPrintWriter writer)837     private void dumpOemService(IndentingPrintWriter writer) {
838         mCarOemService.dump(writer);
839     }
840 
getOemServiceName()841     public String getOemServiceName() {
842         return mCarOemService.getOemServiceName();
843     }
844 
dumpAll(IndentingPrintWriter writer)845     private void dumpAll(IndentingPrintWriter writer) {
846         writer.println("*Dump car service*");
847         dumpVersions(writer);
848         dumpAllServices(writer);
849         dumpAllHals(writer);
850         dumpRROs(writer);
851     }
852 
dumpRROs(IndentingPrintWriter writer)853     private void dumpRROs(IndentingPrintWriter writer) {
854         writer.println("*Dump Car Service RROs*");
855 
856         String packageName = SystemProperties.get(
857                 PROPERTY_CAR_SERVICE_PACKAGE_NAME, /*def= */null);
858         if (packageName == null) {
859             writer.println("Car Service updatable package name is null.");
860             return;
861         }
862 
863         OverlayManager manager = mContext.getSystemService(OverlayManager.class);
864 
865         List<OverlayInfo> installedOverlaysForSystem = manager.getOverlayInfosForTarget(packageName,
866                 UserHandle.SYSTEM);
867         writer.println("RROs for System User");
868         for (int i = 0; i < installedOverlaysForSystem.size(); i++) {
869             OverlayInfo overlayInfo = installedOverlaysForSystem.get(i);
870             writer.printf("Overlay: %s, Enabled: %b \n", overlayInfo.getPackageName(),
871                     overlayInfo.isEnabled());
872         }
873 
874         int currentUser = ActivityManager.getCurrentUser();
875         writer.printf("RROs for Current User: %d\n", currentUser);
876         List<OverlayInfo> installedOverlaysForCurrentUser = manager.getOverlayInfosForTarget(
877                 packageName, UserHandle.of(currentUser));
878         for (int i = 0; i < installedOverlaysForCurrentUser.size(); i++) {
879             OverlayInfo overlayInfo = installedOverlaysForCurrentUser.get(i);
880             writer.printf("Overlay: %s, Enabled: %b \n", overlayInfo.getPackageName(),
881                     overlayInfo.isEnabled());
882         }
883     }
884 
885     @ExcludeFromCodeCoverageGeneratedReport(reason = DUMP_INFO)
dumpVersions(IndentingPrintWriter writer)886     private void dumpVersions(IndentingPrintWriter writer) {
887         writer.println("*Dump versions*");
888         writer.println("Android SDK_INT: " + Build.VERSION.SDK_INT);
889         writer.println("Car Version: " + Car.getCarVersion());
890         writer.println("Platform Version: " + Car.getPlatformVersion());
891         writer.println("CarBuiltin Platform minor: " + CarBuiltin.PLATFORM_VERSION_MINOR_INT);
892         writer.println("Legacy versions (might differ from above as they can't be emulated)");
893         writer.increaseIndent();
894         writer.println("Car API major: " + Car.getCarVersion().getMajorVersion());
895         writer.println("Car API minor: " + Car.getCarVersion().getMinorVersion());
896         writer.println("Car Platform minor: " + Car.PLATFORM_VERSION_MINOR_INT);
897         writer.println("VHAL and Car User Service Priority Init: " + mDoPriorityInitInConstruction);
898         writer.decreaseIndent();
899     }
900 
901     @ExcludeFromCodeCoverageGeneratedReport(reason = DUMP_INFO)
dumpAllHals(IndentingPrintWriter writer)902     private void dumpAllHals(IndentingPrintWriter writer) {
903         writer.println("*Dump Vehicle HAL*");
904         writer.println("Vehicle HAL Interface: " + mVehicleInterfaceName);
905         try {
906             // TODO dump all feature flags by creating a dumpable interface
907             mHal.dump(writer);
908         } catch (Exception e) {
909             writer.println("Failed dumping: " + mHal.getClass().getName());
910             e.printStackTrace(writer);
911         }
912     }
913 
914     @ExcludeFromCodeCoverageGeneratedReport(reason = DUMP_INFO)
showDumpHelp(IndentingPrintWriter writer)915     private void showDumpHelp(IndentingPrintWriter writer) {
916         writer.println("Car service dump usage:");
917         writer.println("[NO ARG]");
918         writer.println("\t  dumps everything (all services and HALs)");
919         writer.println("--help");
920         writer.println("\t  shows this help");
921         writer.println("--version");
922         writer.println("\t  shows the version of all car components");
923         writer.println("--list");
924         writer.println("\t  lists the name of all services");
925         writer.println("--list-hals");
926         writer.println("\t  lists the name of all HALs");
927         writer.println("--services <SVC1> [SVC2] [SVCN]");
928         writer.println("\t  dumps just the specific services, where SVC is just the service class");
929         writer.println("\t  name (like CarUserService)");
930         writer.println("--vms-hal");
931         writer.println("\t  dumps the VMS HAL metrics");
932         writer.println("--hal [HAL1] [HAL2] [HALN]");
933         writer.println("\t  dumps just the specified HALs (or all of them if none specified),");
934         writer.println("\t  where HAL is just the class name (like UserHalService)");
935         writer.println("--user-metrics");
936         writer.println("\t  dumps user switching and stopping metrics");
937         writer.println("--first-user-metrics");
938         writer.println("\t  dumps how long it took to unlock first user since Android started\n");
939         writer.println("\t  (or -1 if not unlocked)");
940         writer.println("--data-dir");
941         writer.println("\t  dumps CarService data dir (and whether it exists)");
942         writer.println("--rro");
943         writer.println("\t  dumps only the RROs");
944         writer.println("-h");
945         writer.println("\t  shows commands usage (NOTE: commands are not available on USER builds");
946         writer.println("[ANYTHING ELSE]");
947         writer.println("\t  runs the given command (use --h to see the available commands)");
948     }
949 
950     @ExcludeFromCodeCoverageGeneratedReport(reason = DUMP_INFO)
dumpDataDir(IndentingPrintWriter writer)951     private void dumpDataDir(IndentingPrintWriter writer) {
952         File dataDir = mContext.getDataDir();
953         writer.printf("Data dir: %s Exists: %b\n", dataDir.getAbsolutePath(), dataDir.exists());
954     }
955 
956     @Override
onTransact(int code, @NonNull Parcel data, @Nullable Parcel reply, int flags)957     public boolean onTransact(int code, @NonNull Parcel data, @Nullable Parcel reply,
958             int flags) throws RemoteException {
959         // Shell cmd is handled specially.
960         if (BinderHelper.onTransactForCmd(code, data, reply, flags, mCmdListener)) {
961             return true;
962         }
963         return super.onTransact(code, data, reply, flags);
964     }
965 
newCarShellCommand()966     private CarShellCommand newCarShellCommand() {
967         Map<Class, CarSystemService> allServicesByClazz = new ArrayMap<>();
968         for (CarSystemService service : mAllServicesInInitOrder) {
969             allServicesByClazz.put(service.getClass(), service);
970         }
971 
972         return new CarShellCommand(mContext, mHal, mFeatureController, mSystemInterface,
973                 allServicesByClazz);
974     }
975 
976     @ExcludeFromCodeCoverageGeneratedReport(reason = DUMP_INFO)
dumpListOfServices(IndentingPrintWriter writer)977     private void dumpListOfServices(IndentingPrintWriter writer) {
978         for (CarSystemService service : mAllServicesInInitOrder) {
979             writer.println(service.getClass().getName());
980         }
981     }
982 
983     @ExcludeFromCodeCoverageGeneratedReport(reason = DUMP_INFO)
dumpAllServices(IndentingPrintWriter writer)984     private void dumpAllServices(IndentingPrintWriter writer) {
985         writer.println("*Dump all services*");
986         for (CarSystemService service : mAllServicesInInitOrder) {
987             if (service instanceof CarServiceBase) {
988                 dumpService(service, writer);
989             }
990         }
991         synchronized (mLock) {
992             if (mCarTestService != null) {
993                 dumpService(mCarTestService, writer);
994             }
995         }
996     }
997 
998     @ExcludeFromCodeCoverageGeneratedReport(reason = DUMP_INFO)
dumpIndividualServices(IndentingPrintWriter writer, String... serviceNames)999     private void dumpIndividualServices(IndentingPrintWriter writer, String... serviceNames) {
1000         for (String serviceName : serviceNames) {
1001             writer.printf("** Dumping %s\n\n", serviceName);
1002             CarSystemService service = getCarServiceBySubstring(serviceName);
1003             if (service == null) {
1004                 writer.println("No such service!");
1005             } else {
1006                 dumpService(service, writer);
1007             }
1008             writer.println();
1009         }
1010     }
1011 
1012     @ExcludeFromCodeCoverageGeneratedReport(reason = DUMP_INFO)
dumpServiceProto(IndentingPrintWriter writer, FileDescriptor fd, String serviceName)1013     private void dumpServiceProto(IndentingPrintWriter writer, FileDescriptor fd,
1014             String serviceName) {
1015         CarSystemService service = getCarServiceBySubstring(serviceName);
1016         if (service == null) {
1017             writer.println("No such service!");
1018         } else {
1019             if (service instanceof CarServiceBase) {
1020                 CarServiceBase carService = (CarServiceBase) service;
1021                 try (FileOutputStream fileStream = new FileOutputStream(fd)) {
1022                     ProtoOutputStream proto = new ProtoOutputStream(fileStream);
1023                     carService.dumpProto(proto);
1024                     proto.flush();
1025                 } catch (Exception e) {
1026                     writer.println("Failed dumping: " + carService.getClass().getName());
1027                     e.printStackTrace(writer);
1028                 }
1029             } else {
1030                 writer.println("Only services that extend CarServiceBase can dump to proto");
1031             }
1032         }
1033     }
1034 
1035     @Nullable
getCarServiceBySubstring(String className)1036     private CarSystemService getCarServiceBySubstring(String className) {
1037         for (int i = 0; i < mAllServicesInInitOrder.length; i++) {
1038             if (Objects.equals(mAllServicesInInitOrder[i].getClass().getSimpleName(), className)) {
1039                 return mAllServicesInInitOrder[i];
1040             }
1041         }
1042         return null;
1043     }
1044 
1045     @ExcludeFromCodeCoverageGeneratedReport(reason = DUMP_INFO)
dumpService(CarSystemService service, IndentingPrintWriter writer)1046     private void dumpService(CarSystemService service, IndentingPrintWriter writer) {
1047         try {
1048             service.dump(writer);
1049         } catch (Exception e) {
1050             writer.println("Failed dumping: " + service.getClass().getName());
1051             e.printStackTrace(writer);
1052         }
1053     }
1054 
execShellCmd(String[] args, IndentingPrintWriter writer)1055     void execShellCmd(String[] args, IndentingPrintWriter writer) {
1056         newCarShellCommand().exec(args, writer);
1057     }
1058 
getFromBuilderOrConstruct(TimingsTraceLog t, Class<T> cls, T serviceFromBuilder, Callable<T> callable, List<CarSystemService> allServices)1059     private static <T extends CarSystemService> T getFromBuilderOrConstruct(TimingsTraceLog t,
1060             Class<T> cls, T serviceFromBuilder, Callable<T> callable,
1061             List<CarSystemService> allServices) {
1062         if (serviceFromBuilder != null) {
1063             allServices.add(serviceFromBuilder);
1064             CarLocalServices.addService(cls, serviceFromBuilder);
1065             return serviceFromBuilder;
1066         }
1067         return constructWithTrace(t, cls, callable, allServices);
1068     }
1069 
constructWithTrace(TimingsTraceLog t, Class<T> cls, Callable<T> callable, List<CarSystemService> allServices)1070     private static <T extends CarSystemService> T constructWithTrace(TimingsTraceLog t,
1071             Class<T> cls, Callable<T> callable, List<CarSystemService> allServices) {
1072         t.traceBegin(cls.getSimpleName());
1073         T constructed;
1074         try {
1075             constructed = callable.call();
1076             CarLocalServices.addService(cls, constructed);
1077         } catch (Exception e) {
1078             throw new RuntimeException("Crash while constructing:" + cls.getSimpleName(), e);
1079         } finally {
1080             t.traceEnd();
1081         }
1082         allServices.add(constructed);
1083         return constructed;
1084     }
1085 
1086     private final class ICarSystemServerClientImpl extends ICarSystemServerClient.Stub {
1087         @Override
onUserLifecycleEvent(int eventType, int fromUserId, int toUserId)1088         public void onUserLifecycleEvent(int eventType, int fromUserId, int toUserId)
1089                 throws RemoteException {
1090             assertCallingFromSystemProcess();
1091             EventLogHelper.writeCarServiceOnUserLifecycle(eventType, fromUserId, toUserId);
1092             if (DBG) {
1093                 Slogf.d(TAG,
1094                         "onUserLifecycleEvent("
1095                                 + CarUserManager.lifecycleEventTypeToString(eventType) + ", "
1096                                 + toUserId + ")");
1097             }
1098             mCarUserService.onUserLifecycleEvent(eventType, fromUserId, toUserId);
1099         }
1100 
1101         @Override
onFactoryReset(ICarResultReceiver callback)1102         public void onFactoryReset(ICarResultReceiver callback) {
1103             assertCallingFromSystemProcess();
1104 
1105             mCarPowerManagementService.setFactoryResetCallback(callback);
1106             BuiltinPackageDependency.createNotificationHelper(mCarServiceBuiltinPackageContext)
1107                     .showFactoryResetNotification(callback);
1108         }
1109 
1110         @Override
setInitialUser(UserHandle user)1111         public void setInitialUser(UserHandle user) {
1112             assertCallingFromSystemProcess();
1113             mCarUserService.setInitialUserFromSystemServer(user);
1114         }
1115 
1116         @Override
notifyFocusChanged(int pid, int uid)1117         public void notifyFocusChanged(int pid, int uid) {
1118             assertCallingFromSystemProcess();
1119             mSystemActivityMonitoringService.handleFocusChanged(pid, uid);
1120         }
1121     }
1122 
dumpVhal(ParcelFileDescriptor fd, List<String> options)1123     /* package */ void dumpVhal(ParcelFileDescriptor fd, List<String> options)
1124             throws RemoteException {
1125         mHal.dumpVhal(fd, options);
1126     }
1127 
hasAidlVhal()1128     /* package */ boolean hasAidlVhal() {
1129         return mHal.isAidlVhal();
1130     }
1131 
priorityInit()1132     /* package */ void priorityInit() {
1133         mHal.priorityInit();
1134         mCarUserService.priorityInit();
1135     }
1136 
1137     public static final class Builder {
1138         Context mContext;
1139         Context mCarServiceBuiltinPackageContext;
1140         VehicleStub mVehicle;
1141         SystemInterface mSystemInterface;
1142         String mVehicleInterfaceName;
1143         CarUserService mCarUserService;
1144         CarWatchdogService mCarWatchdogService;
1145         CarPerformanceService mCarPerformanceService;
1146         GarageModeService mGarageModeService;
1147         AppFocusService mAppFocusService;
1148         IInterface mPowerPolicyDaemon;
1149         CarTelemetryService mCarTelemetryService;
1150         CarRemoteAccessServiceConstructor mCarRemoteAccessServiceConstructor;
1151         boolean mDoPriorityInitInConstruction;
1152         StaticBinderInterface mStaticBinder;
1153         FeatureFlags mFeatureFlags;
1154 
1155         /**
1156          * Builds the ICarImpl object represented by this builder object
1157          * @return ICarImpl object
1158          */
build()1159         public ICarImpl build() {
1160             return new ICarImpl(this);
1161         }
1162 
1163         /**
1164          * Sets ICarImpl builder service context
1165          * @param serviceContext The service context
1166          * @return Current builder object
1167          */
setServiceContext(Context serviceContext)1168         public Builder setServiceContext(Context serviceContext) {
1169             mContext = serviceContext;
1170             return this;
1171         }
1172 
1173         /**
1174          * Sets ICarImpl builder built in context
1175          * @param builtInContext The car service built in package context
1176          * @return Current builder object
1177          */
setBuiltInContext(Context builtInContext)1178         public Builder setBuiltInContext(Context builtInContext) {
1179             mCarServiceBuiltinPackageContext = builtInContext;
1180             return this;
1181         }
1182 
1183         /**
1184          * Sets ICarImpl builder vehicle
1185          * @param vehicle The vehicle stub object to use
1186          * @return Current builder object
1187          */
setVehicle(VehicleStub vehicle)1188         public Builder setVehicle(VehicleStub vehicle) {
1189             mVehicle = vehicle;
1190             return this;
1191         }
1192 
1193         /**
1194          * Sets ICarImpl builder system interface
1195          * @param systemInterface The system interface object
1196          * @return Current builder object
1197          */
setSystemInterface(SystemInterface systemInterface)1198         public Builder setSystemInterface(SystemInterface systemInterface) {
1199             mSystemInterface = systemInterface;
1200             return this;
1201         }
1202 
1203         /**
1204          * Sets ICarImpl builder vehicle interface name
1205          * @param vehicleInterfaceName The vehicle interface name
1206          * @return Current builder object
1207          */
setVehicleInterfaceName(String vehicleInterfaceName)1208         public Builder setVehicleInterfaceName(String vehicleInterfaceName) {
1209             mVehicleInterfaceName = vehicleInterfaceName;
1210             return this;
1211         }
1212 
1213         /**
1214          * Sets ICarImpl builder car user service
1215          * @param carUserService The car user service
1216          * @return Current builder object
1217          */
setCarUserService(CarUserService carUserService)1218         public Builder setCarUserService(CarUserService carUserService) {
1219             mCarUserService = carUserService;
1220             return this;
1221         }
1222 
1223         /**
1224          * Sets ICarImpl builder car watchdog service
1225          * @param carWatchdogService The car watchdog service
1226          * @return Current builder object
1227          */
setCarWatchdogService(CarWatchdogService carWatchdogService)1228         public Builder setCarWatchdogService(CarWatchdogService carWatchdogService) {
1229             mCarWatchdogService = carWatchdogService;
1230             return this;
1231         }
1232 
1233         /**
1234          * Sets ICarImpl builder car performance service
1235          * @param carPerformanceService The car performance service
1236          * @return Current builder object
1237          */
setCarPerformanceService(CarPerformanceService carPerformanceService)1238         public Builder setCarPerformanceService(CarPerformanceService carPerformanceService) {
1239             mCarPerformanceService = carPerformanceService;
1240             return this;
1241         }
1242 
1243         /**
1244          * Sets ICarImpl builder garage mode service
1245          * @param garageModeService The garage mode service
1246          * @return Current builder object
1247          */
setGarageModeService(GarageModeService garageModeService)1248         public Builder setGarageModeService(GarageModeService garageModeService) {
1249             mGarageModeService = garageModeService;
1250             return this;
1251         }
1252 
1253         /**
1254          * Sets ICarImpl builder app focus service
1255          * @param appFocusService The app focus service
1256          * @return Current builder object
1257          */
setAppFocusService(AppFocusService appFocusService)1258         public Builder setAppFocusService(AppFocusService appFocusService) {
1259             mAppFocusService = appFocusService;
1260             return this;
1261         }
1262 
1263         /**
1264          * Sets ICarImpl power policy daemon
1265          * @param powerPolicyDaemon The power policy daemon interface
1266          * @return Current builder object
1267          */
setPowerPolicyDaemon(IInterface powerPolicyDaemon)1268         public Builder setPowerPolicyDaemon(IInterface powerPolicyDaemon) {
1269             mPowerPolicyDaemon = powerPolicyDaemon;
1270             return this;
1271         }
1272 
1273         /**
1274          * Sets ICarImpl car telemetry service
1275          * @param carTelemetryService The car telemetry service
1276          * @return Current builder object
1277          */
setCarTelemetryService(CarTelemetryService carTelemetryService)1278         public Builder setCarTelemetryService(CarTelemetryService carTelemetryService) {
1279             mCarTelemetryService = carTelemetryService;
1280             return this;
1281         }
1282 
1283         /**
1284          * The constructor interface to create a CarRemoteAccessService.
1285          *
1286          * Used for creating a fake CarRemoteAccessService during car service test.
1287          */
1288         @VisibleForTesting
1289         public interface CarRemoteAccessServiceConstructor {
1290             /**
1291              * Creates the {@link CarRemoteAccessService} object.
1292              */
construct(Context context, SystemInterface systemInterface, PowerHalService powerHalService)1293             CarRemoteAccessService construct(Context context, SystemInterface systemInterface,
1294                     PowerHalService powerHalService);
1295         }
1296 
1297         /**
1298          * Set a fake car remote access service constructor to be used for ICarImpl.
1299          * @param constructor The car remote access service constructor.
1300          * @return Current builder object
1301          */
1302         @VisibleForTesting
setCarRemoteAccessServiceConstructor( CarRemoteAccessServiceConstructor constructor)1303         public Builder setCarRemoteAccessServiceConstructor(
1304                 CarRemoteAccessServiceConstructor constructor) {
1305             mCarRemoteAccessServiceConstructor = constructor;
1306             return this;
1307         }
1308 
1309         /**
1310          * Sets whether ICarImpl builder will make an ICarImpl object that does priority
1311          * initialization in construction
1312          * @param doPriorityInitInConstruction Whether to do priority initialization in construction
1313          *                                     of the ICarImpl object this builder represents
1314          * @return Current builder object
1315          */
setDoPriorityInitInConstruction(boolean doPriorityInitInConstruction)1316         public Builder setDoPriorityInitInConstruction(boolean doPriorityInitInConstruction) {
1317             mDoPriorityInitInConstruction = doPriorityInitInConstruction;
1318             return this;
1319         }
1320 
1321         /**
1322          * Sets the calling Uid, only used for testing.
1323          */
1324         @VisibleForTesting
setTestStaticBinder(StaticBinderInterface testStaticBinder)1325         public Builder setTestStaticBinder(StaticBinderInterface testStaticBinder) {
1326             mStaticBinder = testStaticBinder;
1327             return this;
1328         }
1329 
1330         /**
1331          * Sets the feature flags.
1332          */
setFeatureFlags(FeatureFlags featureFlags)1333         public Builder setFeatureFlags(FeatureFlags featureFlags) {
1334             mFeatureFlags = featureFlags;
1335             return this;
1336         }
1337     }
1338 }
1339