1 /*
2 * Copyright 2017 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 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
18
19 //#define LOG_NDEBUG 1
20 #define LOG_TAG "GraphicsEnv"
21
22 #include <graphicsenv/GraphicsEnv.h>
23
24 #include <dlfcn.h>
25 #include <unistd.h>
26
27 #include <android-base/file.h>
28 #include <android-base/properties.h>
29 #include <android-base/strings.h>
30 #include <android/dlext.h>
31 #include <binder/IServiceManager.h>
32 #include <graphicsenv/IGpuService.h>
33 #include <log/log.h>
34 #include <nativeloader/dlext_namespaces.h>
35 #include <sys/prctl.h>
36 #include <utils/Trace.h>
37
38 #include <memory>
39 #include <string>
40 #include <thread>
41
42 // TODO(b/159240322): Extend this to x86 ABI.
43 #if defined(__LP64__)
44 #define UPDATABLE_DRIVER_ABI "arm64-v8a"
45 #else
46 #define UPDATABLE_DRIVER_ABI "armeabi-v7a"
47 #endif // defined(__LP64__)
48
49 // TODO(ianelliott@): Get the following from an ANGLE header:
50 #define CURRENT_ANGLE_API_VERSION 2 // Current API verion we are targetting
51 // Version-2 API:
52 typedef bool (*fpANGLEGetFeatureSupportUtilAPIVersion)(unsigned int* versionToUse);
53 typedef bool (*fpANGLEAndroidParseRulesString)(const char* rulesString, void** rulesHandle,
54 int* rulesVersion);
55 typedef bool (*fpANGLEGetSystemInfo)(void** handle);
56 typedef bool (*fpANGLEAddDeviceInfoToSystemInfo)(const char* deviceMfr, const char* deviceModel,
57 void* handle);
58 typedef bool (*fpANGLEShouldBeUsedForApplication)(void* rulesHandle, int rulesVersion,
59 void* systemInfoHandle, const char* appName);
60 typedef bool (*fpANGLEFreeRulesHandle)(void* handle);
61 typedef bool (*fpANGLEFreeSystemInfoHandle)(void* handle);
62
63 namespace {
isVndkEnabled()64 static bool isVndkEnabled() {
65 #ifdef __BIONIC__
66 static bool isVndkEnabled = android::base::GetProperty("ro.vndk.version", "") != "";
67 return isVndkEnabled;
68 #endif
69 return false;
70 }
71 } // namespace
72
73 namespace android {
74
75 enum NativeLibrary {
76 LLNDK = 0,
77 VNDKSP = 1,
78 };
79
80 static constexpr const char* kNativeLibrariesSystemConfigPath[] =
81 {"/apex/com.android.vndk.v{}/etc/llndk.libraries.{}.txt",
82 "/apex/com.android.vndk.v{}/etc/vndksp.libraries.{}.txt"};
83
84 static const char* kLlndkLibrariesTxtPath = "/system/etc/llndk.libraries.txt";
85
vndkVersionStr()86 static std::string vndkVersionStr() {
87 #ifdef __BIONIC__
88 return base::GetProperty("ro.vndk.version", "");
89 #endif
90 return "";
91 }
92
insertVndkVersionStr(std::string * fileName)93 static void insertVndkVersionStr(std::string* fileName) {
94 LOG_ALWAYS_FATAL_IF(!fileName, "fileName should never be nullptr");
95 std::string version = vndkVersionStr();
96 size_t pos = fileName->find("{}");
97 while (pos != std::string::npos) {
98 fileName->replace(pos, 2, version);
99 pos = fileName->find("{}", pos + version.size());
100 }
101 }
102
readConfig(const std::string & configFile,std::vector<std::string> * soNames)103 static bool readConfig(const std::string& configFile, std::vector<std::string>* soNames) {
104 // Read list of public native libraries from the config file.
105 std::string fileContent;
106 if (!base::ReadFileToString(configFile, &fileContent)) {
107 return false;
108 }
109
110 std::vector<std::string> lines = base::Split(fileContent, "\n");
111
112 for (auto& line : lines) {
113 auto trimmedLine = base::Trim(line);
114 if (!trimmedLine.empty()) {
115 soNames->push_back(trimmedLine);
116 }
117 }
118
119 return true;
120 }
121
getSystemNativeLibraries(NativeLibrary type)122 static const std::string getSystemNativeLibraries(NativeLibrary type) {
123 std::string nativeLibrariesSystemConfig = "";
124
125 if (!isVndkEnabled() && type == NativeLibrary::LLNDK) {
126 nativeLibrariesSystemConfig = kLlndkLibrariesTxtPath;
127 } else {
128 nativeLibrariesSystemConfig = kNativeLibrariesSystemConfigPath[type];
129 insertVndkVersionStr(&nativeLibrariesSystemConfig);
130 }
131
132 std::vector<std::string> soNames;
133 if (!readConfig(nativeLibrariesSystemConfig, &soNames)) {
134 ALOGE("Failed to retrieve library names from %s", nativeLibrariesSystemConfig.c_str());
135 return "";
136 }
137
138 return base::Join(soNames, ':');
139 }
140
getGpuService()141 static sp<IGpuService> getGpuService() {
142 static const sp<IBinder> binder = defaultServiceManager()->checkService(String16("gpu"));
143 if (!binder) {
144 ALOGE("Failed to get gpu service");
145 return nullptr;
146 }
147
148 return interface_cast<IGpuService>(binder);
149 }
150
getInstance()151 /*static*/ GraphicsEnv& GraphicsEnv::getInstance() {
152 static GraphicsEnv env;
153 return env;
154 }
155
isDebuggable()156 bool GraphicsEnv::isDebuggable() {
157 // This flag determines if the application is marked debuggable
158 bool appDebuggable = prctl(PR_GET_DUMPABLE, 0, 0, 0, 0) > 0;
159
160 // This flag is set only in `debuggable` builds of the platform
161 #if defined(ANDROID_DEBUGGABLE)
162 bool platformDebuggable = true;
163 #else
164 bool platformDebuggable = false;
165 #endif
166
167 ALOGV("GraphicsEnv::isDebuggable returning appDebuggable=%s || platformDebuggable=%s",
168 appDebuggable ? "true" : "false", platformDebuggable ? "true" : "false");
169
170 return appDebuggable || platformDebuggable;
171 }
172
173 /**
174 * APIs for updatable graphics drivers
175 */
176
setDriverPathAndSphalLibraries(const std::string & path,const std::string & sphalLibraries)177 void GraphicsEnv::setDriverPathAndSphalLibraries(const std::string& path,
178 const std::string& sphalLibraries) {
179 if (!mDriverPath.empty() || !mSphalLibraries.empty()) {
180 ALOGV("ignoring attempt to change driver path from '%s' to '%s' or change sphal libraries "
181 "from '%s' to '%s'",
182 mDriverPath.c_str(), path.c_str(), mSphalLibraries.c_str(), sphalLibraries.c_str());
183 return;
184 }
185 ALOGV("setting driver path to '%s' and sphal libraries to '%s'", path.c_str(),
186 sphalLibraries.c_str());
187 mDriverPath = path;
188 mSphalLibraries = sphalLibraries;
189 }
190
191 // Return true if all the required libraries from vndk and sphal namespace are
192 // linked to the driver namespace correctly.
linkDriverNamespaceLocked(android_namespace_t * destNamespace,android_namespace_t * vndkNamespace,const std::string & sharedSphalLibraries)193 bool GraphicsEnv::linkDriverNamespaceLocked(android_namespace_t* destNamespace,
194 android_namespace_t* vndkNamespace,
195 const std::string& sharedSphalLibraries) {
196 const std::string llndkLibraries = getSystemNativeLibraries(NativeLibrary::LLNDK);
197 if (llndkLibraries.empty()) {
198 return false;
199 }
200 if (!android_link_namespaces(destNamespace, nullptr, llndkLibraries.c_str())) {
201 ALOGE("Failed to link default namespace[%s]", dlerror());
202 return false;
203 }
204
205 const std::string vndkspLibraries = getSystemNativeLibraries(NativeLibrary::VNDKSP);
206 if (vndkspLibraries.empty()) {
207 return false;
208 }
209 if (!android_link_namespaces(destNamespace, vndkNamespace, vndkspLibraries.c_str())) {
210 ALOGE("Failed to link vndk namespace[%s]", dlerror());
211 return false;
212 }
213
214 if (sharedSphalLibraries.empty()) {
215 return true;
216 }
217
218 // Make additional libraries in sphal to be accessible
219 auto sphalNamespace = android_get_exported_namespace("sphal");
220 if (!sphalNamespace) {
221 ALOGE("Depend on these libraries[%s] in sphal, but failed to get sphal namespace",
222 sharedSphalLibraries.c_str());
223 return false;
224 }
225
226 if (!android_link_namespaces(destNamespace, sphalNamespace, sharedSphalLibraries.c_str())) {
227 ALOGE("Failed to link sphal namespace[%s]", dlerror());
228 return false;
229 }
230
231 return true;
232 }
233
getDriverNamespace()234 android_namespace_t* GraphicsEnv::getDriverNamespace() {
235 std::lock_guard<std::mutex> lock(mNamespaceMutex);
236
237 if (mDriverNamespace) {
238 return mDriverNamespace;
239 }
240
241 if (mDriverPath.empty()) {
242 // For an application process, driver path is empty means this application is not opted in
243 // to use updatable driver. Application process doesn't have the ability to set up
244 // environment variables and hence before `getenv` call will return.
245 // For a process that is not an application process, if it's run from an environment,
246 // for example shell, where environment variables can be set, then it can opt into using
247 // udpatable driver by setting UPDATABLE_GFX_DRIVER to 1. By setting to 1 the developer
248 // driver will be used currently.
249 // TODO(b/159240322) Support the production updatable driver.
250 const char* id = getenv("UPDATABLE_GFX_DRIVER");
251 if (id == nullptr || std::strcmp(id, "1") != 0) {
252 return nullptr;
253 }
254 const sp<IGpuService> gpuService = getGpuService();
255 if (!gpuService) {
256 return nullptr;
257 }
258 mDriverPath = gpuService->getUpdatableDriverPath();
259 if (mDriverPath.empty()) {
260 return nullptr;
261 }
262 mDriverPath.append(UPDATABLE_DRIVER_ABI);
263 ALOGI("Driver path is setup via UPDATABLE_GFX_DRIVER: %s", mDriverPath.c_str());
264 }
265
266 auto vndkNamespace = android_get_exported_namespace("vndk");
267 if (!vndkNamespace) {
268 mDriverNamespace = nullptr;
269 return mDriverNamespace;
270 }
271
272 mDriverNamespace = android_create_namespace("updatable gfx driver",
273 mDriverPath.c_str(), // ld_library_path
274 mDriverPath.c_str(), // default_library_path
275 ANDROID_NAMESPACE_TYPE_ISOLATED,
276 nullptr, // permitted_when_isolated_path
277 nullptr);
278
279 if (!linkDriverNamespaceLocked(mDriverNamespace, vndkNamespace, mSphalLibraries)) {
280 mDriverNamespace = nullptr;
281 }
282
283 return mDriverNamespace;
284 }
285
getDriverPath() const286 std::string GraphicsEnv::getDriverPath() const {
287 return mDriverPath;
288 }
289
290 /**
291 * APIs for GpuStats
292 */
293
hintActivityLaunch()294 void GraphicsEnv::hintActivityLaunch() {
295 ATRACE_CALL();
296
297 {
298 std::lock_guard<std::mutex> lock(mStatsLock);
299 if (mActivityLaunched) return;
300 mActivityLaunched = true;
301 }
302
303 std::thread trySendGpuStatsThread([this]() {
304 // If there's already graphics driver preloaded in the process, just send
305 // the stats info to GpuStats directly through async binder.
306 std::lock_guard<std::mutex> lock(mStatsLock);
307 if (mGpuStats.glDriverToSend) {
308 mGpuStats.glDriverToSend = false;
309 sendGpuStatsLocked(GpuStatsInfo::Api::API_GL, true, mGpuStats.glDriverLoadingTime);
310 }
311 if (mGpuStats.vkDriverToSend) {
312 mGpuStats.vkDriverToSend = false;
313 sendGpuStatsLocked(GpuStatsInfo::Api::API_VK, true, mGpuStats.vkDriverLoadingTime);
314 }
315 });
316 trySendGpuStatsThread.detach();
317 }
318
setGpuStats(const std::string & driverPackageName,const std::string & driverVersionName,uint64_t driverVersionCode,int64_t driverBuildTime,const std::string & appPackageName,const int vulkanVersion)319 void GraphicsEnv::setGpuStats(const std::string& driverPackageName,
320 const std::string& driverVersionName, uint64_t driverVersionCode,
321 int64_t driverBuildTime, const std::string& appPackageName,
322 const int vulkanVersion) {
323 ATRACE_CALL();
324
325 std::lock_guard<std::mutex> lock(mStatsLock);
326 ALOGV("setGpuStats:\n"
327 "\tdriverPackageName[%s]\n"
328 "\tdriverVersionName[%s]\n"
329 "\tdriverVersionCode[%" PRIu64 "]\n"
330 "\tdriverBuildTime[%" PRId64 "]\n"
331 "\tappPackageName[%s]\n"
332 "\tvulkanVersion[%d]\n",
333 driverPackageName.c_str(), driverVersionName.c_str(), driverVersionCode, driverBuildTime,
334 appPackageName.c_str(), vulkanVersion);
335
336 mGpuStats.driverPackageName = driverPackageName;
337 mGpuStats.driverVersionName = driverVersionName;
338 mGpuStats.driverVersionCode = driverVersionCode;
339 mGpuStats.driverBuildTime = driverBuildTime;
340 mGpuStats.appPackageName = appPackageName;
341 mGpuStats.vulkanVersion = vulkanVersion;
342 }
343
setDriverToLoad(GpuStatsInfo::Driver driver)344 void GraphicsEnv::setDriverToLoad(GpuStatsInfo::Driver driver) {
345 ATRACE_CALL();
346
347 std::lock_guard<std::mutex> lock(mStatsLock);
348 switch (driver) {
349 case GpuStatsInfo::Driver::GL:
350 case GpuStatsInfo::Driver::GL_UPDATED:
351 case GpuStatsInfo::Driver::ANGLE: {
352 if (mGpuStats.glDriverToLoad == GpuStatsInfo::Driver::NONE ||
353 mGpuStats.glDriverToLoad == GpuStatsInfo::Driver::GL) {
354 mGpuStats.glDriverToLoad = driver;
355 break;
356 }
357
358 if (mGpuStats.glDriverFallback == GpuStatsInfo::Driver::NONE) {
359 mGpuStats.glDriverFallback = driver;
360 }
361 break;
362 }
363 case GpuStatsInfo::Driver::VULKAN:
364 case GpuStatsInfo::Driver::VULKAN_UPDATED: {
365 if (mGpuStats.vkDriverToLoad == GpuStatsInfo::Driver::NONE ||
366 mGpuStats.vkDriverToLoad == GpuStatsInfo::Driver::VULKAN) {
367 mGpuStats.vkDriverToLoad = driver;
368 break;
369 }
370
371 if (mGpuStats.vkDriverFallback == GpuStatsInfo::Driver::NONE) {
372 mGpuStats.vkDriverFallback = driver;
373 }
374 break;
375 }
376 default:
377 break;
378 }
379 }
380
setDriverLoaded(GpuStatsInfo::Api api,bool isDriverLoaded,int64_t driverLoadingTime)381 void GraphicsEnv::setDriverLoaded(GpuStatsInfo::Api api, bool isDriverLoaded,
382 int64_t driverLoadingTime) {
383 ATRACE_CALL();
384
385 std::lock_guard<std::mutex> lock(mStatsLock);
386 if (api == GpuStatsInfo::Api::API_GL) {
387 mGpuStats.glDriverToSend = true;
388 mGpuStats.glDriverLoadingTime = driverLoadingTime;
389 } else {
390 mGpuStats.vkDriverToSend = true;
391 mGpuStats.vkDriverLoadingTime = driverLoadingTime;
392 }
393
394 sendGpuStatsLocked(api, isDriverLoaded, driverLoadingTime);
395 }
396
397 // Hash function to calculate hash for null-terminated Vulkan extension names
398 // We store hash values of the extensions, rather than the actual names or
399 // indices to be able to support new extensions easily, avoid creating
400 // a table of 'known' extensions inside Android and reduce the runtime overhead.
calculateExtensionHash(const char * word)401 static uint64_t calculateExtensionHash(const char* word) {
402 if (!word) {
403 return 0;
404 }
405 const size_t wordLen = strlen(word);
406 const uint32_t seed = 167;
407 uint64_t hash = 0;
408 for (size_t i = 0; i < wordLen; i++) {
409 hash = (hash * seed) + word[i];
410 }
411 return hash;
412 }
413
setVulkanInstanceExtensions(uint32_t enabledExtensionCount,const char * const * ppEnabledExtensionNames)414 void GraphicsEnv::setVulkanInstanceExtensions(uint32_t enabledExtensionCount,
415 const char* const* ppEnabledExtensionNames) {
416 ATRACE_CALL();
417 if (enabledExtensionCount == 0 || ppEnabledExtensionNames == nullptr) {
418 return;
419 }
420
421 const uint32_t maxNumStats = android::GpuStatsAppInfo::MAX_NUM_EXTENSIONS;
422 uint64_t extensionHashes[maxNumStats];
423 const uint32_t numStats = std::min(enabledExtensionCount, maxNumStats);
424 for(uint32_t i = 0; i < numStats; i++) {
425 extensionHashes[i] = calculateExtensionHash(ppEnabledExtensionNames[i]);
426 }
427 setTargetStatsArray(android::GpuStatsInfo::Stats::VULKAN_INSTANCE_EXTENSION,
428 extensionHashes, numStats);
429 }
430
setVulkanDeviceExtensions(uint32_t enabledExtensionCount,const char * const * ppEnabledExtensionNames)431 void GraphicsEnv::setVulkanDeviceExtensions(uint32_t enabledExtensionCount,
432 const char* const* ppEnabledExtensionNames) {
433 ATRACE_CALL();
434 if (enabledExtensionCount == 0 || ppEnabledExtensionNames == nullptr) {
435 return;
436 }
437
438 const uint32_t maxNumStats = android::GpuStatsAppInfo::MAX_NUM_EXTENSIONS;
439 uint64_t extensionHashes[maxNumStats];
440 const uint32_t numStats = std::min(enabledExtensionCount, maxNumStats);
441 for(uint32_t i = 0; i < numStats; i++) {
442 extensionHashes[i] = calculateExtensionHash(ppEnabledExtensionNames[i]);
443 }
444 setTargetStatsArray(android::GpuStatsInfo::Stats::VULKAN_DEVICE_EXTENSION,
445 extensionHashes, numStats);
446 }
447
addVulkanEngineName(const char * engineName)448 void GraphicsEnv::addVulkanEngineName(const char* engineName) {
449 ATRACE_CALL();
450 if (engineName == nullptr) {
451 return;
452 }
453 std::lock_guard<std::mutex> lock(mStatsLock);
454 if (!readyToSendGpuStatsLocked()) return;
455
456 const sp<IGpuService> gpuService = getGpuService();
457 if (gpuService) {
458 gpuService->addVulkanEngineName(mGpuStats.appPackageName, mGpuStats.driverVersionCode,
459 engineName);
460 }
461 }
462
readyToSendGpuStatsLocked()463 bool GraphicsEnv::readyToSendGpuStatsLocked() {
464 // Only send stats for processes having at least one activity launched and that process doesn't
465 // skip the GraphicsEnvironment setup.
466 return mActivityLaunched && !mGpuStats.appPackageName.empty();
467 }
468
setTargetStats(const GpuStatsInfo::Stats stats,const uint64_t value)469 void GraphicsEnv::setTargetStats(const GpuStatsInfo::Stats stats, const uint64_t value) {
470 return setTargetStatsArray(stats, &value, 1);
471 }
472
setTargetStatsArray(const GpuStatsInfo::Stats stats,const uint64_t * values,const uint32_t valueCount)473 void GraphicsEnv::setTargetStatsArray(const GpuStatsInfo::Stats stats, const uint64_t* values,
474 const uint32_t valueCount) {
475 ATRACE_CALL();
476
477 std::lock_guard<std::mutex> lock(mStatsLock);
478 if (!readyToSendGpuStatsLocked()) return;
479
480 const sp<IGpuService> gpuService = getGpuService();
481 if (gpuService) {
482 gpuService->setTargetStatsArray(mGpuStats.appPackageName, mGpuStats.driverVersionCode,
483 stats, values, valueCount);
484 }
485 }
486
sendGpuStatsLocked(GpuStatsInfo::Api api,bool isDriverLoaded,int64_t driverLoadingTime)487 void GraphicsEnv::sendGpuStatsLocked(GpuStatsInfo::Api api, bool isDriverLoaded,
488 int64_t driverLoadingTime) {
489 ATRACE_CALL();
490
491 if (!readyToSendGpuStatsLocked()) return;
492
493 ALOGV("sendGpuStats:\n"
494 "\tdriverPackageName[%s]\n"
495 "\tdriverVersionName[%s]\n"
496 "\tdriverVersionCode[%" PRIu64 "]\n"
497 "\tdriverBuildTime[%" PRId64 "]\n"
498 "\tappPackageName[%s]\n"
499 "\tvulkanVersion[%d]\n"
500 "\tapi[%d]\n"
501 "\tisDriverLoaded[%d]\n"
502 "\tdriverLoadingTime[%" PRId64 "]",
503 mGpuStats.driverPackageName.c_str(), mGpuStats.driverVersionName.c_str(),
504 mGpuStats.driverVersionCode, mGpuStats.driverBuildTime, mGpuStats.appPackageName.c_str(),
505 mGpuStats.vulkanVersion, static_cast<int32_t>(api), isDriverLoaded, driverLoadingTime);
506
507 GpuStatsInfo::Driver driver = GpuStatsInfo::Driver::NONE;
508 bool isIntendedDriverLoaded = false;
509 if (api == GpuStatsInfo::Api::API_GL) {
510 driver = mGpuStats.glDriverToLoad;
511 isIntendedDriverLoaded =
512 isDriverLoaded && (mGpuStats.glDriverFallback == GpuStatsInfo::Driver::NONE);
513 } else {
514 driver = mGpuStats.vkDriverToLoad;
515 isIntendedDriverLoaded =
516 isDriverLoaded && (mGpuStats.vkDriverFallback == GpuStatsInfo::Driver::NONE);
517 }
518
519 const sp<IGpuService> gpuService = getGpuService();
520 if (gpuService) {
521 gpuService->setGpuStats(mGpuStats.driverPackageName, mGpuStats.driverVersionName,
522 mGpuStats.driverVersionCode, mGpuStats.driverBuildTime,
523 mGpuStats.appPackageName, mGpuStats.vulkanVersion, driver,
524 isIntendedDriverLoaded, driverLoadingTime);
525 }
526 }
527
setInjectLayersPrSetDumpable()528 bool GraphicsEnv::setInjectLayersPrSetDumpable() {
529 if (prctl(PR_SET_DUMPABLE, 1, 0, 0, 0) == -1) {
530 return false;
531 }
532 return true;
533 }
534
535 /**
536 * APIs for ANGLE
537 */
538
shouldUseAngle()539 bool GraphicsEnv::shouldUseAngle() {
540 // Make sure we are init'ed
541 if (mPackageName.empty()) {
542 ALOGV("Package name is empty. setAngleInfo() has not been called to enable ANGLE.");
543 return false;
544 }
545
546 return mShouldUseAngle;
547 }
548
549 // Set ANGLE information.
550 // If path is "system", it means system ANGLE must be used for the process.
551 // If shouldUseNativeDriver is true, it means native GLES drivers must be used for the process.
552 // If path is set to nonempty and shouldUseNativeDriver is true, ANGLE will be used regardless.
setAngleInfo(const std::string & path,const bool shouldUseNativeDriver,const std::string & packageName,const std::vector<std::string> eglFeatures)553 void GraphicsEnv::setAngleInfo(const std::string& path, const bool shouldUseNativeDriver,
554 const std::string& packageName,
555 const std::vector<std::string> eglFeatures) {
556 if (mShouldUseAngle) {
557 // ANGLE is already set up for this application process, even if the application
558 // needs to switch from apk to system or vice versa, the application process must
559 // be killed and relaunch so that the loader can properly load ANGLE again.
560 // The architecture does not support runtime switch between drivers, so just return.
561 ALOGE("ANGLE is already set for %s", packageName.c_str());
562 return;
563 }
564
565 mAngleEglFeatures = std::move(eglFeatures);
566 ALOGV("setting ANGLE path to '%s'", path.c_str());
567 mAnglePath = std::move(path);
568 ALOGV("setting app package name to '%s'", packageName.c_str());
569 mPackageName = std::move(packageName);
570 if (mAnglePath == "system") {
571 mShouldUseSystemAngle = true;
572 }
573 if (!mAnglePath.empty()) {
574 mShouldUseAngle = true;
575 }
576 mShouldUseNativeDriver = shouldUseNativeDriver;
577 }
578
getPackageName()579 std::string& GraphicsEnv::getPackageName() {
580 return mPackageName;
581 }
582
getAngleEglFeatures()583 const std::vector<std::string>& GraphicsEnv::getAngleEglFeatures() {
584 return mAngleEglFeatures;
585 }
586
getAngleNamespace()587 android_namespace_t* GraphicsEnv::getAngleNamespace() {
588 std::lock_guard<std::mutex> lock(mNamespaceMutex);
589
590 if (mAngleNamespace) {
591 return mAngleNamespace;
592 }
593
594 // If ANGLE path is not set, it means ANGLE should not be used for this process;
595 // or if ANGLE path is set and set to use system ANGLE, then a namespace is not needed
596 // because:
597 // 1) if the default OpenGL ES driver is already ANGLE, then the loader will skip;
598 // 2) if the default OpenGL ES driver is native, then there's no symbol conflict;
599 // 3) if there's no OpenGL ES driver is preloaded, then there's no symbol conflict.
600 if (mAnglePath.empty() || mShouldUseSystemAngle) {
601 ALOGV("mAnglePath is empty or use system ANGLE, abort creating ANGLE namespace");
602 return nullptr;
603 }
604
605 // Construct the search paths for system ANGLE.
606 const char* const defaultLibraryPaths =
607 #if defined(__LP64__)
608 "/vendor/lib64/egl:/system/lib64";
609 #else
610 "/vendor/lib/egl:/system/lib";
611 #endif
612
613 // If the application process will run on top of system ANGLE, construct the namespace
614 // with sphal namespace being the parent namespace so that search paths and libraries
615 // are properly inherited.
616 mAngleNamespace =
617 android_create_namespace("ANGLE",
618 mShouldUseSystemAngle ? defaultLibraryPaths
619 : mAnglePath.c_str(), // ld_library_path
620 mShouldUseSystemAngle
621 ? defaultLibraryPaths
622 : mAnglePath.c_str(), // default_library_path
623 ANDROID_NAMESPACE_TYPE_SHARED_ISOLATED,
624 nullptr, // permitted_when_isolated_path
625 mShouldUseSystemAngle ? android_get_exported_namespace("sphal")
626 : nullptr); // parent
627
628 ALOGD_IF(!mAngleNamespace, "Could not create ANGLE namespace from default");
629
630 if (!mShouldUseSystemAngle) {
631 return mAngleNamespace;
632 }
633
634 auto vndkNamespace = android_get_exported_namespace("vndk");
635 if (!vndkNamespace) {
636 mAngleNamespace = nullptr;
637 return mAngleNamespace;
638 }
639
640 if (!linkDriverNamespaceLocked(mAngleNamespace, vndkNamespace, "")) {
641 mAngleNamespace = nullptr;
642 }
643
644 return mAngleNamespace;
645 }
646
nativeToggleAngleAsSystemDriver(bool enabled)647 void GraphicsEnv::nativeToggleAngleAsSystemDriver(bool enabled) {
648 const sp<IGpuService> gpuService = getGpuService();
649 if (!gpuService) {
650 ALOGE("No GPU service");
651 return;
652 }
653 gpuService->toggleAngleAsSystemDriver(enabled);
654 }
655
shouldUseSystemAngle()656 bool GraphicsEnv::shouldUseSystemAngle() {
657 return mShouldUseSystemAngle;
658 }
659
shouldUseNativeDriver()660 bool GraphicsEnv::shouldUseNativeDriver() {
661 return mShouldUseNativeDriver;
662 }
663
664 /**
665 * APIs for debuggable layers
666 */
667
setLayerPaths(NativeLoaderNamespace * appNamespace,const std::string & layerPaths)668 void GraphicsEnv::setLayerPaths(NativeLoaderNamespace* appNamespace,
669 const std::string& layerPaths) {
670 if (mLayerPaths.empty()) {
671 mLayerPaths = layerPaths;
672 mAppNamespace = appNamespace;
673 } else {
674 ALOGV("Vulkan layer search path already set, not clobbering with '%s' for namespace %p'",
675 layerPaths.c_str(), appNamespace);
676 }
677 }
678
getAppNamespace()679 NativeLoaderNamespace* GraphicsEnv::getAppNamespace() {
680 return mAppNamespace;
681 }
682
getLayerPaths()683 const std::string& GraphicsEnv::getLayerPaths() {
684 return mLayerPaths;
685 }
686
getDebugLayers()687 const std::string& GraphicsEnv::getDebugLayers() {
688 return mDebugLayers;
689 }
690
getDebugLayersGLES()691 const std::string& GraphicsEnv::getDebugLayersGLES() {
692 return mDebugLayersGLES;
693 }
694
setDebugLayers(const std::string & layers)695 void GraphicsEnv::setDebugLayers(const std::string& layers) {
696 mDebugLayers = layers;
697 }
698
setDebugLayersGLES(const std::string & layers)699 void GraphicsEnv::setDebugLayersGLES(const std::string& layers) {
700 mDebugLayersGLES = layers;
701 }
702
703 } // namespace android
704