Debian Codegraph @

core/java/android/os/GraphicsEnvironment.java

raw symbols SCIP
1 /*
2 * Copyright 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 package android.os;
18
19 import android.app.Activity;
20 import android.app.GameManager;
21 import android.content.BroadcastReceiver;
22 import android.content.ContentResolver;
23 import android.content.Context;
24 import android.content.Intent;
25 import android.content.pm.ApplicationInfo;
26 import android.content.pm.IPackageManager;
27 import android.content.pm.PackageInfo;
28 import android.content.pm.PackageManager;
29 import android.content.pm.ResolveInfo;
30 import android.provider.Settings;
31 import android.text.TextUtils;
32 import android.util.Log;
33 import android.widget.Toast;
34
35 import dalvik.system.VMRuntime;
36
37 import java.io.BufferedReader;
38 import java.io.File;
39 import java.io.IOException;
40 import java.io.InputStreamReader;
41 import java.util.ArrayList;
42 import java.util.Arrays;
43 import java.util.List;
44
45 /**
46 * GraphicsEnvironment sets up necessary properties for the graphics environment of the
47 * application process.
48 * GraphicsEnvironment uses a bunch of settings global variables to determine the setup,
49 * the change of settings global variables will only take effect before setup() is called,
50 * and any subsequent change will not impact the current running processes.
51 *
52 * @hide
53 */
54 public class GraphicsEnvironment {
55
56 private static final GraphicsEnvironment sInstance = new GraphicsEnvironment();
57
58 /**
59 * Returns the shared {@link GraphicsEnvironment} instance.
60 */
61 public static GraphicsEnvironment getInstance() {
62 return sInstance;
63 }
64
65 private static final boolean DEBUG = false;
66 private static final String TAG = "GraphicsEnvironment";
67 private static final String SYSTEM_DRIVER_NAME = "system";
68 private static final String SYSTEM_DRIVER_VERSION_NAME = "";
69 private static final long SYSTEM_DRIVER_VERSION_CODE = 0;
70 private static final String ANGLE_DRIVER_NAME = "angle";
71 private static final String ANGLE_DRIVER_VERSION_NAME = "";
72 private static final long ANGLE_DRIVER_VERSION_CODE = 0;
73
74 // System properties related to updatable graphics drivers.
75 private static final String PROPERTY_GFX_DRIVER_PRODUCTION = "ro.gfx.driver.0";
76 private static final String PROPERTY_GFX_DRIVER_PRERELEASE = "ro.gfx.driver.1";
77 private static final String PROPERTY_GFX_DRIVER_BUILD_TIME = "ro.gfx.driver_build_time";
78
79 // Metadata flags within the <application> tag in the AndroidManifest.xml file.
80 private static final String METADATA_DRIVER_BUILD_TIME =
81 "com.android.graphics.driver.build_time";
82 private static final String METADATA_DEVELOPER_DRIVER_ENABLE =
83 "com.android.graphics.developerdriver.enable";
84 private static final String METADATA_INJECT_LAYERS_ENABLE =
85 "com.android.graphics.injectLayers.enable";
86
87 private static final String UPDATABLE_DRIVER_ALLOWLIST_ALL = "*";
88 private static final String UPDATABLE_DRIVER_SPHAL_LIBRARIES_FILENAME = "sphal_libraries.txt";
89
90 private static final String ACTION_ANGLE_FOR_ANDROID = "android.app.action.ANGLE_FOR_ANDROID";
91 private static final String ACTION_ANGLE_FOR_ANDROID_TOAST_MESSAGE =
92 "android.app.action.ANGLE_FOR_ANDROID_TOAST_MESSAGE";
93 private static final String INTENT_KEY_A4A_TOAST_MESSAGE = "A4A Toast Message";
94
95 private static final int VULKAN_1_0 = 0x00400000;
96 private static final int VULKAN_1_1 = 0x00401000;
97 private static final int VULKAN_1_2 = 0x00402000;
98 private static final int VULKAN_1_3 = 0x00403000;
99
100 // Values for UPDATABLE_DRIVER_ALL_APPS
101 // 0: Default (Invalid values fallback to default as well)
102 // 1: All apps use updatable production driver
103 // 2: All apps use updatable prerelease driver
104 // 3: All apps use system graphics driver
105 private static final int UPDATABLE_DRIVER_GLOBAL_OPT_IN_DEFAULT = 0;
106 private static final int UPDATABLE_DRIVER_GLOBAL_OPT_IN_PRODUCTION_DRIVER = 1;
107 private static final int UPDATABLE_DRIVER_GLOBAL_OPT_IN_PRERELEASE_DRIVER = 2;
108 private static final int UPDATABLE_DRIVER_GLOBAL_OPT_IN_OFF = 3;
109
110 // System properties related to ANGLE and legacy GLES graphics drivers.
111 private static final String PROPERTY_EGL_SYSTEM_DRIVER = "ro.hardware.egl";
112 // TODO (b/224558229): Properly add this to the list of system properties for a device:
113 private static final String PROPERTY_EGL_LEGACY_DRIVER = "ro.hardware.egl_legacy";
114
115 // Values for ANGLE_GL_DRIVER_ALL_ANGLE
116 private static final int ANGLE_GL_DRIVER_ALL_ANGLE_ON = 1;
117 private static final int ANGLE_GL_DRIVER_ALL_ANGLE_OFF = 0;
118 private static final int ANGLE_GL_DRIVER_ALL_LEGACY = -1;
119
120 // Values for ANGLE_GL_DRIVER_SELECTION_VALUES
121 private static final String ANGLE_GL_DRIVER_CHOICE_DEFAULT = "default";
122 private static final String ANGLE_GL_DRIVER_CHOICE_ANGLE = "angle";
123 private static final String ANGLE_GL_DRIVER_CHOICE_LEGACY = "legacy";
124 // The following value is a deprecated choice for "legacy"
125 private static final String ANGLE_GL_DRIVER_CHOICE_NATIVE = "native";
126
127 // Values returned by getDriverForPackage() and getDefaultDriverToUse() (avoid returning
128 // strings for performance reasons)
129 private static final int ANGLE_GL_DRIVER_TO_USE_LEGACY = 0;
130 private static final int ANGLE_GL_DRIVER_TO_USE_ANGLE = 1;
131
132 private ClassLoader mClassLoader;
133 private String mLibrarySearchPaths;
134 private String mLibraryPermittedPaths;
135 private GameManager mGameManager;
136
137 private boolean mAngleIsSystemDriver = false;
138 private boolean mNoLegacyDriver = false;
139 // When ANGLE is the system driver, this is the name of the legacy driver.
140 //
141 // IMPORTANT: When ANGLE is the system driver, and if there is a fallback "legacy" GLES driver
142 // (e.g. from the GPU provider), the name of that driver must be set here, unles and until
143 // PROPERTY_EGL_LEGACY_DRIVER has been properly plumbed and this becomes broadly available.
144 private String mEglLegacyDriver = "";
145
146 private int mAngleOptInIndex = -1;
147
148 /**
149 * Set up GraphicsEnvironment
150 */
151 public void setup(Context context, Bundle coreSettings) {
152 final PackageManager pm = context.getPackageManager();
153 final String packageName = context.getPackageName();
154 final ApplicationInfo appInfoWithMetaData =
155 getAppInfoWithMetadata(context, pm, packageName);
156
157 mGameManager = context.getSystemService(GameManager.class);
158
159 Trace.traceBegin(Trace.TRACE_TAG_GRAPHICS, "setupGpuLayers");
160 setupGpuLayers(context, coreSettings, pm, packageName, appInfoWithMetaData);
161 Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS);
162
163 // Determine if ANGLE is the system driver, as this will determine other logic
164 final String eglSystemDriver = SystemProperties.get(PROPERTY_EGL_SYSTEM_DRIVER);
165 Log.v(TAG, "GLES system driver is '" + eglSystemDriver + "'");
166 mAngleIsSystemDriver = eglSystemDriver.equals(ANGLE_DRIVER_NAME);
167 if (mAngleIsSystemDriver) {
168 // Lookup the legacy driver, to send down to the EGL loader
169 final String eglLegacyDriver = SystemProperties.get(PROPERTY_EGL_LEGACY_DRIVER);
170 if (eglLegacyDriver.isEmpty()) {
171 mNoLegacyDriver = true;
172 mEglLegacyDriver = eglSystemDriver;
173 }
174 } else {
175 mEglLegacyDriver = eglSystemDriver;
176 }
177 Log.v(TAG, "Legacy GLES driver is '" + mEglLegacyDriver + "'");
178
179 // Setup ANGLE and pass down ANGLE details to the C++ code
180 Trace.traceBegin(Trace.TRACE_TAG_GRAPHICS, "setupAngle");
181 boolean useAngle = false;
182 if (setupAngle(context, coreSettings, pm, packageName)) {
183 if (shouldUseAngle(context, coreSettings, packageName)) {
184 useAngle = true;
185 setGpuStats(ANGLE_DRIVER_NAME, ANGLE_DRIVER_VERSION_NAME, ANGLE_DRIVER_VERSION_CODE,
186 0, packageName, getVulkanVersion(pm));
187 } else if (mNoLegacyDriver) {
188 Log.e(TAG, "Unexpected problem with the ANGLE for use with: '" + packageName + "'");
189 useAngle = true;
190 }
191 }
192 Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS);
193
194 Trace.traceBegin(Trace.TRACE_TAG_GRAPHICS, "chooseDriver");
195 if (!chooseDriver(context, coreSettings, pm, packageName, appInfoWithMetaData)) {
196 if (!useAngle) {
197 setGpuStats(SYSTEM_DRIVER_NAME, SYSTEM_DRIVER_VERSION_NAME,
198 SYSTEM_DRIVER_VERSION_CODE,
199 SystemProperties.getLong(PROPERTY_GFX_DRIVER_BUILD_TIME, 0),
200 packageName, getVulkanVersion(pm));
201 }
202 }
203 Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS);
204
205 Trace.traceBegin(Trace.TRACE_TAG_GRAPHICS, "notifyGraphicsEnvironmentSetup");
206 if (mGameManager != null
207 && appInfoWithMetaData.category == ApplicationInfo.CATEGORY_GAME) {
208 mGameManager.notifyGraphicsEnvironmentSetup();
209 }
210 Trace.traceEnd(Trace.TRACE_TAG_GRAPHICS);
211 }
212
213 /**
214 * Query to determine if the Game Mode has enabled ANGLE.
215 */
216 private boolean isAngleEnabledByGameMode(Context context, String packageName) {
217 try {
218 final boolean gameModeEnabledAngle =
219 (mGameManager != null) && mGameManager.isAngleEnabled(packageName);
220 Log.v(TAG, "ANGLE GameManagerService for " + packageName + ": " + gameModeEnabledAngle);
221 return gameModeEnabledAngle;
222 } catch (SecurityException e) {
223 Log.e(TAG, "Caught exception while querying GameManagerService if ANGLE is enabled "
224 + "for package: " + packageName);
225 }
226
227 return false;
228 }
229
230 /**
231 * Query to determine if ANGLE should be used
232 */
233 private boolean shouldUseAngle(Context context, Bundle coreSettings, String packageName) {
234 if (TextUtils.isEmpty(packageName)) {
235 Log.v(TAG, "No package name specified; use the system driver");
236 return mAngleIsSystemDriver ? true : false;
237 }
238
239 final int driverToUse = getDriverForPackage(context, coreSettings, packageName);
240 boolean yesOrNo = driverToUse == ANGLE_GL_DRIVER_TO_USE_ANGLE;
241 return yesOrNo;
242 }
243
244 private int getVulkanVersion(PackageManager pm) {
245 // PackageManager doesn't have an API to retrieve the version of a specific feature, and we
246 // need to avoid retrieving all system features here and looping through them.
247 if (pm.hasSystemFeature(PackageManager.FEATURE_VULKAN_HARDWARE_VERSION, VULKAN_1_3)) {
248 return VULKAN_1_3;
249 }
250
251 if (pm.hasSystemFeature(PackageManager.FEATURE_VULKAN_HARDWARE_VERSION, VULKAN_1_2)) {
252 return VULKAN_1_2;
253 }
254
255 if (pm.hasSystemFeature(PackageManager.FEATURE_VULKAN_HARDWARE_VERSION, VULKAN_1_1)) {
256 return VULKAN_1_1;
257 }
258
259 if (pm.hasSystemFeature(PackageManager.FEATURE_VULKAN_HARDWARE_VERSION, VULKAN_1_0)) {
260 return VULKAN_1_0;
261 }
262
263 return 0;
264 }
265
266 /**
267 * Check whether application is has set the manifest metadata for layer injection.
268 */
269 private boolean canInjectLayers(ApplicationInfo ai) {
270 return (ai.metaData != null && ai.metaData.getBoolean(METADATA_INJECT_LAYERS_ENABLE)
271 && setInjectLayersPrSetDumpable());
272 }
273
274 /**
275 * Store the class loader for namespace lookup later.
276 */
277 public void setLayerPaths(ClassLoader classLoader,
278 String searchPaths,
279 String permittedPaths) {
280 // We have to store these in the class because they are set up before we
281 // have access to the Context to properly set up GraphicsEnvironment
282 mClassLoader = classLoader;
283 mLibrarySearchPaths = searchPaths;
284 mLibraryPermittedPaths = permittedPaths;
285 }
286
287 /**
288 * Returns the debug layer paths from settings.
289 * Returns null if:
290 * 1) The application process is not debuggable or layer injection metadata flag is not
291 * true; Or
292 * 2) ENABLE_GPU_DEBUG_LAYERS is not true; Or
293 * 3) Package name is not equal to GPU_DEBUG_APP.
294 */
295 public String getDebugLayerPathsFromSettings(
296 Bundle coreSettings, IPackageManager pm, String packageName,
297 ApplicationInfo ai) {
298 if (!debugLayerEnabled(coreSettings, packageName, ai)) {
299 return null;
300 }
301 Log.i(TAG, "GPU debug layers enabled for " + packageName);
302 String debugLayerPaths = "";
303
304 // Grab all debug layer apps and add to paths.
305 final String gpuDebugLayerApps =
306 coreSettings.getString(Settings.Global.GPU_DEBUG_LAYER_APP, "");
307 if (!gpuDebugLayerApps.isEmpty()) {
308 Log.i(TAG, "GPU debug layer apps: " + gpuDebugLayerApps);
309 // If a colon is present, treat this as multiple apps, so Vulkan and GLES
310 // layer apps can be provided at the same time.
311 final String[] layerApps = gpuDebugLayerApps.split(":");
312 for (int i = 0; i < layerApps.length; i++) {
313 String paths = getDebugLayerAppPaths(pm, layerApps[i]);
314 if (!paths.isEmpty()) {
315 // Append the path so files placed in the app's base directory will
316 // override the external path
317 debugLayerPaths += paths + File.pathSeparator;
318 }
319 }
320 }
321 return debugLayerPaths;
322 }
323
324 /**
325 * Return the debug layer app's on-disk and in-APK lib directories
326 */
327 private String getDebugLayerAppPaths(IPackageManager pm, String packageName) {
328 final ApplicationInfo appInfo;
329 try {
330 appInfo = pm.getApplicationInfo(packageName, PackageManager.MATCH_ALL,
331 UserHandle.myUserId());
332 } catch (RemoteException e) {
333 return "";
334 }
335 if (appInfo == null) {
336 Log.w(TAG, "Debug layer app '" + packageName + "' not installed");
337 return "";
338 }
339
340 final String abi = chooseAbi(appInfo);
341 final StringBuilder sb = new StringBuilder();
342 sb.append(appInfo.nativeLibraryDir)
343 .append(File.pathSeparator)
344 .append(appInfo.sourceDir)
345 .append("!/lib/")
346 .append(abi);
347 final String paths = sb.toString();
348 if (DEBUG) Log.v(TAG, "Debug layer app libs: " + paths);
349
350 return paths;
351 }
352
353 private boolean debugLayerEnabled(Bundle coreSettings, String packageName, ApplicationInfo ai) {
354 // Only enable additional debug functionality if the following conditions are met:
355 // 1. App is debuggable or device is rooted or layer injection metadata flag is true
356 // 2. ENABLE_GPU_DEBUG_LAYERS is true
357 // 3. Package name is equal to GPU_DEBUG_APP
358 if (!isDebuggable() && !canInjectLayers(ai)) {
359 return false;
360 }
361 final int enable = coreSettings.getInt(Settings.Global.ENABLE_GPU_DEBUG_LAYERS, 0);
362 if (enable == 0) {
363 return false;
364 }
365 final String gpuDebugApp = coreSettings.getString(Settings.Global.GPU_DEBUG_APP, "");
366 if (packageName == null
367 || (gpuDebugApp.isEmpty() || packageName.isEmpty())
368 || !gpuDebugApp.equals(packageName)) {
369 return false;
370 }
371 return true;
372 }
373
374 /**
375 * Set up layer search paths for all apps
376 */
377 private void setupGpuLayers(
378 Context context, Bundle coreSettings, PackageManager pm, String packageName,
379 ApplicationInfo ai) {
380 final boolean enabled = debugLayerEnabled(coreSettings, packageName, ai);
381 String layerPaths = "";
382 if (enabled) {
383 layerPaths = mLibraryPermittedPaths;
384
385 final String layers = coreSettings.getString(Settings.Global.GPU_DEBUG_LAYERS);
386 Log.i(TAG, "Vulkan debug layer list: " + layers);
387 if (layers != null && !layers.isEmpty()) {
388 setDebugLayers(layers);
389 }
390
391 final String layersGLES =
392 coreSettings.getString(Settings.Global.GPU_DEBUG_LAYERS_GLES);
393 Log.i(TAG, "GLES debug layer list: " + layersGLES);
394 if (layersGLES != null && !layersGLES.isEmpty()) {
395 setDebugLayersGLES(layersGLES);
396 }
397 }
398
399 // Include the app's lib directory in all cases
400 layerPaths += mLibrarySearchPaths;
401 setLayerPaths(mClassLoader, layerPaths);
402 }
403
404 private static List<String> getGlobalSettingsString(ContentResolver contentResolver,
405 Bundle bundle,
406 String globalSetting) {
407 final List<String> valueList;
408 final String settingsValue;
409
410 if (bundle != null) {
411 settingsValue = bundle.getString(globalSetting);
412 } else {
413 settingsValue = Settings.Global.getString(contentResolver, globalSetting);
414 }
415
416 if (settingsValue != null) {
417 valueList = new ArrayList<>(Arrays.asList(settingsValue.split(",")));
418 } else {
419 valueList = new ArrayList<>();
420 }
421
422 return valueList;
423 }
424
425 private static int getPackageIndex(String packageName, List<String> packages) {
426 for (int idx = 0; idx < packages.size(); idx++) {
427 if (packages.get(idx).equals(packageName)) {
428 return idx;
429 }
430 }
431
432 return -1;
433 }
434
435 private static ApplicationInfo getAppInfoWithMetadata(Context context,
436 PackageManager pm, String packageName) {
437 ApplicationInfo ai;
438 try {
439 // Get the ApplicationInfo from PackageManager so that metadata fields present.
440 ai = pm.getApplicationInfo(packageName, PackageManager.GET_META_DATA);
441 } catch (PackageManager.NameNotFoundException e) {
442 // Unlikely to fail for applications, but in case of failure, fall back to use the
443 // ApplicationInfo from context directly.
444 ai = context.getApplicationInfo();
445 }
446 return ai;
447 }
448
449 /**
450 * Return the appropriate "default" driver, unless overridden by isAngleEnabledByGameMode().
451 */
452 private int getDefaultDriverToUse(Context context, String packageName) {
453 if (mAngleIsSystemDriver || isAngleEnabledByGameMode(context, packageName)) {
454 return ANGLE_GL_DRIVER_TO_USE_ANGLE;
455 } else {
456 return ANGLE_GL_DRIVER_TO_USE_LEGACY;
457 }
458 }
459
460 /*
461 * Determine which GLES "driver" should be used for the package, taking into account the
462 * following factors (in priority order):
463 *
464 * 1) The semi-global switch (i.e. Settings.Global.ANGLE_GL_DRIVER_ALL_ANGLE; which is set by
465 * the "angle_gl_driver_all_angle" setting; which forces a driver for all processes that
466 * start after the Java run time is up), if it forces a choice; otherwise ...
467 * 2) The per-application switch (i.e. Settings.Global.ANGLE_GL_DRIVER_SELECTION_PKGS and
468 * Settings.Global.ANGLE_GL_DRIVER_SELECTION_VALUES; which corresponds to the
469 * “angle_gl_driver_selection_pkgs” and “angle_gl_driver_selection_values” settings); if it
470 * forces a choice; otherwise ...
471 * 3) Use ANGLE if isAngleEnabledByGameMode() returns true; otherwise ...
472 * 4) The global switch (i.e. use the system driver, whether ANGLE or legacy;
473 * a.k.a. mAngleIsSystemDriver, which is set by the device’s “ro.hardware.egl” property)
474 *
475 * Factors 1 and 2 are decided by this method. Factors 3 and 4 are decided by
476 * getDefaultDriverToUse().
477 */
478 private int getDriverForPackage(Context context, Bundle bundle, String packageName) {
479 // Check the semi-global switch (i.e. once system has booted enough) for whether ANGLE
480 // should be forced on or off for "all appplications"
481 final int allUseAngle;
482 if (bundle != null) {
483 allUseAngle = bundle.getInt(Settings.Global.ANGLE_GL_DRIVER_ALL_ANGLE);
484 } else {
485 ContentResolver contentResolver = context.getContentResolver();
486 allUseAngle = Settings.Global.getInt(contentResolver,
487 Settings.Global.ANGLE_GL_DRIVER_ALL_ANGLE, ANGLE_GL_DRIVER_ALL_ANGLE_OFF);
488 }
489 if (allUseAngle == ANGLE_GL_DRIVER_ALL_ANGLE_ON) {
490 Log.v(TAG, "Turn on ANGLE for all applications.");
491 return ANGLE_GL_DRIVER_TO_USE_ANGLE;
492 }
493 if (allUseAngle == ANGLE_GL_DRIVER_ALL_LEGACY) {
494 Log.v(TAG, "Disable ANGLE for all applications.");
495 return ANGLE_GL_DRIVER_TO_USE_LEGACY;
496 }
497
498 // Make sure we have a good package name
499 if (TextUtils.isEmpty(packageName)) {
500 return getDefaultDriverToUse(context, packageName);
501 }
502
503 // Get the per-application settings lists
504 final ContentResolver contentResolver = context.getContentResolver();
505 final List<String> optInPackages = getGlobalSettingsString(
506 contentResolver, bundle, Settings.Global.ANGLE_GL_DRIVER_SELECTION_PKGS);
507 final List<String> optInValues = getGlobalSettingsString(
508 contentResolver, bundle, Settings.Global.ANGLE_GL_DRIVER_SELECTION_VALUES);
509 Log.v(TAG, "Currently set values for:");
510 Log.v(TAG, " angle_gl_driver_selection_pkgs = " + optInPackages);
511 Log.v(TAG, " angle_gl_driver_selection_values =" + optInValues);
512
513 // Make sure we have good settings to use
514 if (optInPackages.size() != optInValues.size()) {
515 Log.w(TAG,
516 "Global.Settings values are invalid: "
517 + "number of packages: "
518 + optInPackages.size() + ", "
519 + "number of values: "
520 + optInValues.size());
521 return getDefaultDriverToUse(context, packageName);
522 }
523
524 // See if this application is listed in the per-application settings lists
525 final int pkgIndex = getPackageIndex(packageName, optInPackages);
526
527 if (pkgIndex < 0) {
528 // The application is NOT listed in the per-application settings lists; and so use the
529 // system driver (i.e. either ANGLE or the Legacy driver)
530 Log.v(TAG, "getDriverForPackage(): No per-application setting");
531 return getDefaultDriverToUse(context, packageName);
532 }
533 mAngleOptInIndex = pkgIndex;
534
535 Log.v(TAG,
536 "getDriverForPackage(): using per-application switch: "
537 + optInValues.get(pkgIndex));
538 // The application IS listed in the per-application settings lists; and so use the
539 // setting--choosing the current system driver if the setting is "default" (i.e. either
540 // ANGLE or the Legacy driver)
541 String rtnValue = optInValues.get(pkgIndex);
542 Log.v(TAG,
543 "ANGLE Developer option for '" + packageName + "' "
544 + "set to: '" + rtnValue + "'");
545 if (rtnValue.equals(ANGLE_GL_DRIVER_CHOICE_ANGLE)) {
546 return ANGLE_GL_DRIVER_TO_USE_ANGLE;
547 } else if (rtnValue.equals(ANGLE_GL_DRIVER_CHOICE_NATIVE)
548 || rtnValue.equals(ANGLE_GL_DRIVER_CHOICE_LEGACY)) {
549 return ANGLE_GL_DRIVER_TO_USE_LEGACY;
550 } else {
551 // The user either chose default or an invalid value; go with the default driver or what
552 // the game dashboard indicates
553 return getDefaultDriverToUse(context, packageName);
554 }
555 }
556
557 /**
558 * Get the ANGLE package name.
559 */
560 private String getAnglePackageName(PackageManager pm) {
561 final Intent intent = new Intent(ACTION_ANGLE_FOR_ANDROID);
562
563 final List<ResolveInfo> resolveInfos =
564 pm.queryIntentActivities(intent, PackageManager.MATCH_SYSTEM_ONLY);
565 if (resolveInfos.size() != 1) {
566 Log.e(TAG, "Invalid number of ANGLE packages. Required: 1, Found: "
567 + resolveInfos.size());
568 for (ResolveInfo resolveInfo : resolveInfos) {
569 Log.e(TAG, "Found ANGLE package: " + resolveInfo.activityInfo.packageName);
570 }
571 return "";
572 }
573
574 // Must be exactly 1 ANGLE PKG found to get here.
575 return resolveInfos.get(0).activityInfo.packageName;
576 }
577
578 /**
579 * Check for ANGLE debug package, but only for apps that can load them.
580 * An application can load ANGLE debug package if it is a debuggable application, or
581 * the device is debuggable.
582 */
583 private String getAngleDebugPackage(Context context, Bundle coreSettings) {
584 if (!isDebuggable()) {
585 return "";
586 }
587 final String debugPackage;
588
589 if (coreSettings != null) {
590 debugPackage =
591 coreSettings.getString(Settings.Global.ANGLE_DEBUG_PACKAGE);
592 } else {
593 ContentResolver contentResolver = context.getContentResolver();
594 debugPackage = Settings.Global.getString(contentResolver,
595 Settings.Global.ANGLE_DEBUG_PACKAGE);
596 }
597 if (TextUtils.isEmpty(debugPackage)) {
598 return "";
599 }
600 return debugPackage;
601 }
602
603 /**
604 * Determine whether ANGLE should be used, set it up if so, and pass ANGLE details down to
605 * the C++ GraphicsEnv class.
606 *
607 * If ANGLE will be used, GraphicsEnv::setAngleInfo() will be called to enable ANGLE to be
608 * properly used. Otherwise, GraphicsEnv::setLegacyDriverInfo() will be called to
609 * enable the legacy GLES driver (e.g. when ANGLE is the system driver) to be identified and
610 * used.
611 *
612 * @param context
613 * @param bundle
614 * @param pm
615 * @param packageName - package name of the application.
616 * @return true: ANGLE setup successfully
617 * false: ANGLE not setup (not on allowlist, ANGLE not present, etc.)
618 */
619 private boolean setupAngle(Context context, Bundle bundle, PackageManager pm,
620 String packageName) {
621
622 if (!shouldUseAngle(context, bundle, packageName)) {
623 setLegacyDriverInfo(packageName, mAngleIsSystemDriver, mEglLegacyDriver);
624 return false;
625 }
626
627 ApplicationInfo angleInfo = null;
628
629 // If the developer has specified a debug package over ADB, attempt to find it
630 String anglePkgName = getAngleDebugPackage(context, bundle);
631 if (!anglePkgName.isEmpty()) {
632 Log.i(TAG, "ANGLE debug package enabled: " + anglePkgName);
633 try {
634 // Note the debug package does not have to be pre-installed
635 angleInfo = pm.getApplicationInfo(anglePkgName, 0);
636 } catch (PackageManager.NameNotFoundException e) {
637 Log.w(TAG, "ANGLE debug package '" + anglePkgName + "' not installed");
638 setLegacyDriverInfo(packageName, mAngleIsSystemDriver, mEglLegacyDriver);
639 return false;
640 }
641 }
642
643 // Otherwise, check to see if ANGLE is properly installed
644 if (angleInfo == null) {
645 anglePkgName = getAnglePackageName(pm);
646 if (TextUtils.isEmpty(anglePkgName)) {
647 Log.w(TAG, "Failed to find ANGLE package.");
648 setLegacyDriverInfo(packageName, mAngleIsSystemDriver, mEglLegacyDriver);
649 return false;
650 }
651
652 Log.v(TAG, "ANGLE package enabled: " + anglePkgName);
653 try {
654 // Production ANGLE libraries must be pre-installed as a system app
655 angleInfo = pm.getApplicationInfo(anglePkgName,
656 PackageManager.MATCH_SYSTEM_ONLY);
657 } catch (PackageManager.NameNotFoundException e) {
658 Log.w(TAG, "ANGLE package '" + anglePkgName + "' not installed");
659 setLegacyDriverInfo(packageName, mAngleIsSystemDriver, mEglLegacyDriver);
660 return false;
661 }
662 }
663
664 final String abi = chooseAbi(angleInfo);
665
666 // Build a path that includes installed native libs and APK
667 final String paths = angleInfo.nativeLibraryDir
668 + File.pathSeparator
669 + angleInfo.sourceDir
670 + "!/lib/"
671 + abi;
672
673 if (DEBUG) {
674 Log.v(TAG, "ANGLE package libs: " + paths);
675 }
676
677 // If we make it to here, ANGLE will be used. Call setAngleInfo() with the package name,
678 // and features to use.
679 final String[] features = getAngleEglFeatures(context, bundle);
680 setAngleInfo(
681 paths, packageName, mAngleIsSystemDriver, ANGLE_GL_DRIVER_CHOICE_ANGLE, features);
682
683 return true;
684 }
685
686 /**
687 * Determine if the "ANGLE In Use" dialog box should be shown.
688 */
689 private boolean shouldShowAngleInUseDialogBox(Context context) {
690 try {
691 ContentResolver contentResolver = context.getContentResolver();
692 final int showDialogBox = Settings.Global.getInt(contentResolver,
693 Settings.Global.SHOW_ANGLE_IN_USE_DIALOG_BOX);
694
695 return (showDialogBox == 1);
696 } catch (Settings.SettingNotFoundException | SecurityException e) {
697 // Do nothing and move on
698 }
699
700 // No setting, so assume false
701 return false;
702 }
703
704 /**
705 * Determine if ANGLE will be used and setup the environment
706 */
707 private boolean setupAndUseAngle(Context context, String packageName) {
708 // Need to make sure we are evaluating ANGLE usage for the correct circumstances
709 if (!setupAngle(context, null, context.getPackageManager(), packageName)) {
710 Log.v(TAG, "Package '" + packageName + "' should not use ANGLE");
711 return false;
712 }
713
714 final boolean useAngle = getShouldUseAngle(packageName);
715 Log.v(TAG, "Package '" + packageName + "' should use ANGLE = '" + useAngle + "'");
716
717 return useAngle;
718 }
719
720 /**
721 * Show the ANGLE in Use Dialog Box
722 * @param context
723 */
724 public void showAngleInUseDialogBox(Context context) {
725 final String packageName = context.getPackageName();
726
727 if (shouldShowAngleInUseDialogBox(context) && setupAndUseAngle(context, packageName)) {
728 final Intent intent = new Intent(ACTION_ANGLE_FOR_ANDROID_TOAST_MESSAGE);
729 String anglePkg = getAnglePackageName(context.getPackageManager());
730 intent.setPackage(anglePkg);
731
732 context.sendOrderedBroadcast(intent, null, new BroadcastReceiver() {
733 @Override
734 public void onReceive(Context context, Intent intent) {
735 Bundle results = getResultExtras(true);
736
737 String toastMsg = results.getString(INTENT_KEY_A4A_TOAST_MESSAGE);
738 final Toast toast = Toast.makeText(context, toastMsg, Toast.LENGTH_LONG);
739 toast.show();
740 }
741 }, null, Activity.RESULT_OK, null, null);
742 }
743 }
744
745 private String[] getAngleEglFeatures(Context context, Bundle coreSettings) {
746 if (mAngleOptInIndex < 0) {
747 return null;
748 }
749
750 final List<String> featuresLists = getGlobalSettingsString(
751 context.getContentResolver(), coreSettings, Settings.Global.ANGLE_EGL_FEATURES);
752 if (featuresLists.size() <= mAngleOptInIndex) {
753 return null;
754 }
755 return featuresLists.get(mAngleOptInIndex).split(":");
756 }
757
758 /**
759 * Return the driver package name to use. Return null for system driver.
760 */
761 private String chooseDriverInternal(Bundle coreSettings, ApplicationInfo ai) {
762 final String productionDriver = SystemProperties.get(PROPERTY_GFX_DRIVER_PRODUCTION);
763 final boolean hasProductionDriver = productionDriver != null && !productionDriver.isEmpty();
764
765 final String prereleaseDriver = SystemProperties.get(PROPERTY_GFX_DRIVER_PRERELEASE);
766 final boolean hasPrereleaseDriver = prereleaseDriver != null && !prereleaseDriver.isEmpty();
767
768 if (!hasProductionDriver && !hasPrereleaseDriver) {
769 Log.v(TAG, "Neither updatable production driver nor prerelease driver is supported.");
770 return null;
771 }
772
773 // To minimize risk of driver updates crippling the device beyond user repair, never use the
774 // updatable drivers for privileged or non-updated system apps. Presumably pre-installed
775 // apps were tested thoroughly with the system driver.
776 if (ai.isPrivilegedApp() || (ai.isSystemApp() && !ai.isUpdatedSystemApp())) {
777 if (DEBUG) {
778 Log.v(TAG,
779 "Ignore updatable driver package for privileged/non-updated system app.");
780 }
781 return null;
782 }
783
784 final boolean enablePrereleaseDriver =
785 (ai.metaData != null && ai.metaData.getBoolean(METADATA_DEVELOPER_DRIVER_ENABLE))
786 || isDebuggable();
787
788 // Priority of updatable driver settings on confliction (Higher priority comes first):
789 // 1. UPDATABLE_DRIVER_ALL_APPS
790 // 2. UPDATABLE_DRIVER_PRODUCTION_OPT_OUT_APPS
791 // 3. UPDATABLE_DRIVER_PRERELEASE_OPT_IN_APPS
792 // 4. UPDATABLE_DRIVER_PRODUCTION_OPT_IN_APPS
793 // 5. UPDATABLE_DRIVER_PRODUCTION_DENYLIST
794 // 6. UPDATABLE_DRIVER_PRODUCTION_ALLOWLIST
795 switch (coreSettings.getInt(Settings.Global.UPDATABLE_DRIVER_ALL_APPS, 0)) {
796 case UPDATABLE_DRIVER_GLOBAL_OPT_IN_OFF:
797 Log.v(TAG, "The updatable driver is turned off on this device.");
798 return null;
799 case UPDATABLE_DRIVER_GLOBAL_OPT_IN_PRODUCTION_DRIVER:
800 Log.v(TAG, "All apps opt in to use updatable production driver.");
801 return hasProductionDriver ? productionDriver : null;
802 case UPDATABLE_DRIVER_GLOBAL_OPT_IN_PRERELEASE_DRIVER:
803 Log.v(TAG, "All apps opt in to use updatable prerelease driver.");
804 return hasPrereleaseDriver && enablePrereleaseDriver ? prereleaseDriver : null;
805 case UPDATABLE_DRIVER_GLOBAL_OPT_IN_DEFAULT:
806 default:
807 break;
808 }
809
810 final String appPackageName = ai.packageName;
811 if (getGlobalSettingsString(null, coreSettings,
812 Settings.Global.UPDATABLE_DRIVER_PRODUCTION_OPT_OUT_APPS)
813 .contains(appPackageName)) {
814 Log.v(TAG, "App opts out for updatable production driver.");
815 return null;
816 }
817
818 if (getGlobalSettingsString(
819 null, coreSettings, Settings.Global.UPDATABLE_DRIVER_PRERELEASE_OPT_IN_APPS)
820 .contains(appPackageName)) {
821 Log.v(TAG, "App opts in for updatable prerelease driver.");
822 return hasPrereleaseDriver && enablePrereleaseDriver ? prereleaseDriver : null;
823 }
824
825 // Early return here since the rest logic is only for updatable production Driver.
826 if (!hasProductionDriver) {
827 Log.v(TAG, "Updatable production driver is not supported on the device.");
828 return null;
829 }
830
831 final boolean isOptIn =
832 getGlobalSettingsString(null, coreSettings,
833 Settings.Global.UPDATABLE_DRIVER_PRODUCTION_OPT_IN_APPS)
834 .contains(appPackageName);
835 final List<String> allowlist =
836 getGlobalSettingsString(null, coreSettings,
837 Settings.Global.UPDATABLE_DRIVER_PRODUCTION_ALLOWLIST);
838 if (!isOptIn && allowlist.indexOf(UPDATABLE_DRIVER_ALLOWLIST_ALL) != 0
839 && !allowlist.contains(appPackageName)) {
840 Log.v(TAG, "App is not on the allowlist for updatable production driver.");
841 return null;
842 }
843
844 // If the application is not opted-in, then check whether it's on the denylist,
845 // terminate early if it's on the denylist and fallback to system driver.
846 if (!isOptIn
847 && getGlobalSettingsString(
848 null, coreSettings, Settings.Global.UPDATABLE_DRIVER_PRODUCTION_DENYLIST)
849 .contains(appPackageName)) {
850 Log.v(TAG, "App is on the denylist for updatable production driver.");
851 return null;
852 }
853
854 return productionDriver;
855 }
856
857 /**
858 * Choose whether the current process should use the builtin or an updated driver.
859 */
860 private boolean chooseDriver(
861 Context context, Bundle coreSettings, PackageManager pm, String packageName,
862 ApplicationInfo ai) {
863 final String driverPackageName = chooseDriverInternal(coreSettings, ai);
864 if (driverPackageName == null) {
865 return false;
866 }
867
868 final PackageInfo driverPackageInfo;
869 try {
870 driverPackageInfo = pm.getPackageInfo(driverPackageName,
871 PackageManager.MATCH_SYSTEM_ONLY | PackageManager.GET_META_DATA);
872 } catch (PackageManager.NameNotFoundException e) {
873 Log.w(TAG, "updatable driver package '" + driverPackageName + "' not installed");
874 return false;
875 }
876
877 // O drivers are restricted to the sphal linker namespace, so don't try to use
878 // packages unless they declare they're compatible with that restriction.
879 final ApplicationInfo driverAppInfo = driverPackageInfo.applicationInfo;
880 if (driverAppInfo.targetSdkVersion < Build.VERSION_CODES.O) {
881 if (DEBUG) {
882 Log.w(TAG, "updatable driver package is not compatible with O");
883 }
884 return false;
885 }
886
887 final String abi = chooseAbi(driverAppInfo);
888 if (abi == null) {
889 if (DEBUG) {
890 // This is the normal case for the pre-installed empty driver package, don't spam
891 if (driverAppInfo.isUpdatedSystemApp()) {
892 Log.w(TAG, "Updatable driver package has no compatible native libraries");
893 }
894 }
895 return false;
896 }
897
898 final StringBuilder sb = new StringBuilder();
899 sb.append(driverAppInfo.nativeLibraryDir)
900 .append(File.pathSeparator);
901 sb.append(driverAppInfo.sourceDir)
902 .append("!/lib/")
903 .append(abi);
904 final String paths = sb.toString();
905 final String sphalLibraries = getSphalLibraries(context, driverPackageName);
906 Log.v(TAG, "Updatable driver package search path: " + paths
907 + ", required sphal libraries: " + sphalLibraries);
908 setDriverPathAndSphalLibraries(paths, sphalLibraries);
909
910 if (driverAppInfo.metaData == null) {
911 throw new NullPointerException("apk's meta-data cannot be null");
912 }
913
914 String driverBuildTime = driverAppInfo.metaData.getString(METADATA_DRIVER_BUILD_TIME);
915 if (driverBuildTime == null || driverBuildTime.length() <= 1) {
916 Log.w(TAG, "com.android.graphics.driver.build_time is not set");
917 driverBuildTime = "L0";
918 }
919 // driver_build_time in the meta-data is in "L<Unix epoch timestamp>" format. e.g. L123456.
920 // Long.parseLong will throw if the meta-data "driver_build_time" is not set properly.
921 setGpuStats(driverPackageName, driverPackageInfo.versionName, driverAppInfo.longVersionCode,
922 Long.parseLong(driverBuildTime.substring(1)), packageName, 0);
923
924 return true;
925 }
926
927 private static String chooseAbi(ApplicationInfo ai) {
928 final String isa = VMRuntime.getCurrentInstructionSet();
929 if (ai.primaryCpuAbi != null &&
930 isa.equals(VMRuntime.getInstructionSet(ai.primaryCpuAbi))) {
931 return ai.primaryCpuAbi;
932 }
933 if (ai.secondaryCpuAbi != null &&
934 isa.equals(VMRuntime.getInstructionSet(ai.secondaryCpuAbi))) {
935 return ai.secondaryCpuAbi;
936 }
937 return null;
938 }
939
940 private String getSphalLibraries(Context context, String driverPackageName) {
941 try {
942 final Context driverContext =
943 context.createPackageContext(driverPackageName, Context.CONTEXT_RESTRICTED);
944 final BufferedReader reader = new BufferedReader(new InputStreamReader(
945 driverContext.getAssets().open(UPDATABLE_DRIVER_SPHAL_LIBRARIES_FILENAME)));
946 final ArrayList<String> assetStrings = new ArrayList<>();
947 for (String assetString; (assetString = reader.readLine()) != null;) {
948 assetStrings.add(assetString);
949 }
950 return String.join(":", assetStrings);
951 } catch (PackageManager.NameNotFoundException e) {
952 if (DEBUG) {
953 Log.w(TAG, "Driver package '" + driverPackageName + "' not installed");
954 }
955 } catch (IOException e) {
956 if (DEBUG) {
957 Log.w(TAG, "Failed to load '" + UPDATABLE_DRIVER_SPHAL_LIBRARIES_FILENAME + "'");
958 }
959 }
960 return "";
961 }
962
963 private static native boolean isDebuggable();
964 private static native void setLayerPaths(ClassLoader classLoader, String layerPaths);
965 private static native void setDebugLayers(String layers);
966 private static native void setDebugLayersGLES(String layers);
967 private static native void setDriverPathAndSphalLibraries(String path, String sphalLibraries);
968 private static native void setGpuStats(String driverPackageName, String driverVersionName,
969 long driverVersionCode, long driverBuildTime, String appPackageName, int vulkanVersion);
970 private static native void setAngleInfo(String path, String appPackage,
971 boolean angleIsSystemDriver, String devOptIn, String[] features);
972 private static native void setLegacyDriverInfo(
973 String appPackage, boolean angleIsSystemDriver, String legacyDriverName);
974 private static native boolean getShouldUseAngle(String packageName);
975 private static native boolean setInjectLayersPrSetDumpable();
976
977 /**
978 * Hint for GraphicsEnvironment that an activity is launching on the process.
979 * Then the app process is allowed to send stats to GpuStats module.
980 */
981 public static native void hintActivityLaunch();
982 }