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