1 /*
2  ** Copyright 2018, 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 #include "egl_layers.h"
18 
19 #include <EGL/egl.h>
20 #include <android-base/file.h>
21 #include <android-base/properties.h>
22 #include <android-base/strings.h>
23 #include <android/dlext.h>
24 #include <dlfcn.h>
25 #include <graphicsenv/GraphicsEnv.h>
26 #include <log/log.h>
27 #include <nativebridge/native_bridge.h>
28 #include <nativeloader/native_loader.h>
29 #include <sys/prctl.h>
30 
31 namespace android {
32 
33 // GLES Layers
34 //
35 // - Layer discovery -
36 // 1. Check for debug layer list from GraphicsEnv
37 // 2. If none enabled, check system properties
38 //
39 // - Layer initializing -
40 // - AndroidGLESLayer_Initialize (provided by layer, called by loader)
41 // - AndroidGLESLayer_GetProcAddress (provided by layer, called by loader)
42 // - getNextLayerProcAddress (provided by loader, called by layer)
43 //
44 // 1. Walk through defs for egl and each gl version
45 // 2. Call GetLayerProcAddress passing the name and the target hook entry point
46 //   - This tells the layer the next point in the chain it should call
47 // 3. Replace the hook with the layer's entry point
48 //    - All entryoints will be present, anything unsupported by the driver will
49 //      have gl_unimplemented
50 //
51 // - Extension layering -
52 //  Not all functions are known to Android, so libEGL handles extensions.
53 //  They are looked up by applications using eglGetProcAddress
54 //  Layers can look them up with getNextLayerProcAddress
55 
56 const int kFuncCount = sizeof(platform_impl_t) / sizeof(char*) + sizeof(egl_t) / sizeof(char*) +
57         sizeof(gl_hooks_t) / sizeof(char*);
58 
59 typedef struct FunctionTable {
60     EGLFuncPointer x[kFuncCount];
operator []android::FunctionTable61     EGLFuncPointer& operator[](int i) { return x[i]; }
62 } FunctionTable;
63 
64 // TODO: Move these to class
65 std::unordered_map<std::string, int> func_indices;
66 // func_indices.reserve(kFuncCount);
67 
68 std::unordered_map<int, std::string> func_names;
69 // func_names.reserve(kFuncCount);
70 
71 std::vector<FunctionTable> layer_functions;
72 
getNextLayerProcAddress(void * layer_id,const char * name)73 const void* getNextLayerProcAddress(void* layer_id, const char* name) {
74     // Use layer_id to find funcs for layer below current
75     // This is the same key provided in AndroidGLESLayer_Initialize
76     auto next_layer_funcs = reinterpret_cast<FunctionTable*>(layer_id);
77     EGLFuncPointer val;
78 
79     ALOGV("getNextLayerProcAddress servicing %s", name);
80 
81     if (func_indices.find(name) == func_indices.end()) {
82         // No entry for this function - it is an extension
83         // call down the GPA chain directly to the impl
84         ALOGV("getNextLayerProcAddress - name(%s) no func_indices entry found", name);
85 
86         // Look up which GPA we should use
87         int gpaIndex = func_indices["eglGetProcAddress"];
88         ALOGV("getNextLayerProcAddress - name(%s) gpaIndex(%i) <- using GPA from this index", name, gpaIndex);
89         EGLFuncPointer gpaNext = (*next_layer_funcs)[gpaIndex];
90         ALOGV("getNextLayerProcAddress - name(%s) gpaIndex(%i) gpaNext(%llu) <- using GPA at this address", name, gpaIndex, (unsigned long long)gpaNext);
91 
92 
93         // Call it for the requested function
94         typedef void* (*PFNEGLGETPROCADDRESSPROC)(const char*);
95         PFNEGLGETPROCADDRESSPROC next = reinterpret_cast<PFNEGLGETPROCADDRESSPROC>(gpaNext);
96 
97         val = reinterpret_cast<EGLFuncPointer>(next(name));
98         ALOGV("getNextLayerProcAddress - name(%s) gpaIndex(%i) gpaNext(%llu) Got back (%llu) from GPA", name, gpaIndex, (unsigned long long)gpaNext, (unsigned long long)val);
99 
100         // We should store it now, but to do that, we need to move func_idx to the class so we can
101         // increment it separately
102         // TODO: Move func_idx to class and store the result of GPA
103         return reinterpret_cast<void*>(val);
104     }
105 
106     int index = func_indices[name];
107     val = (*next_layer_funcs)[index];
108     ALOGV("getNextLayerProcAddress - name(%s) index(%i) entry(%llu) - Got a hit, returning known entry", name, index, (unsigned long long)val);
109     return reinterpret_cast<void*>(val);
110 }
111 
SetupFuncMaps(FunctionTable & functions,char const * const * entries,EGLFuncPointer * curr,int & func_idx)112 void SetupFuncMaps(FunctionTable& functions, char const* const* entries, EGLFuncPointer* curr,
113                    int& func_idx) {
114     while (*entries) {
115         const char* name = *entries;
116 
117         // Some names overlap, only fill with initial entry
118         // This does mean that some indices will not be used
119         if (func_indices.find(name) == func_indices.end()) {
120             ALOGV("SetupFuncMaps - name(%s), func_idx(%i), No entry for func_indices, assigning now", name, func_idx);
121             func_names[func_idx] = name;
122             func_indices[name] = func_idx;
123         } else {
124             ALOGV("SetupFuncMaps - name(%s), func_idx(%i), Found entry for func_indices", name, func_idx);
125         }
126 
127         // Populate layer_functions once with initial value
128         // These values will arrive in priority order, starting with platform entries
129         if (functions[func_idx] == nullptr) {
130             ALOGV("SetupFuncMaps - name(%s), func_idx(%i), No entry for functions, assigning (%llu)", name, func_idx, (unsigned long long) *curr);
131             functions[func_idx] = *curr;
132         } else {
133             ALOGV("SetupFuncMaps - name(%s), func_idx(%i), Found entry for functions (%llu)", name, func_idx, (unsigned long long) functions[func_idx]);
134         }
135 
136         entries++;
137         curr++;
138         func_idx++;
139     }
140 }
141 
getInstance()142 LayerLoader& LayerLoader::getInstance() {
143     // This function is mutex protected in egl_init_drivers_locked and eglGetProcAddressImpl
144     static LayerLoader layer_loader;
145 
146     if (!layer_loader.layers_loaded_) layer_loader.LoadLayers();
147 
148     return layer_loader;
149 }
150 
151 const char kSystemLayerLibraryDir[] = "/data/local/debug/gles";
152 
GetDebugLayers()153 std::string LayerLoader::GetDebugLayers() {
154     // Layers can be specified at the Java level in GraphicsEnvironment
155     // gpu_debug_layers_gles = layer1:layer2:layerN
156     std::string debug_layers = android::GraphicsEnv::getInstance().getDebugLayersGLES();
157 
158     if (debug_layers.empty()) {
159         // Only check system properties if Java settings are empty
160         debug_layers = base::GetProperty("debug.gles.layers", "");
161     }
162 
163     return debug_layers;
164 }
165 
ApplyLayer(layer_setup_func layer_setup,const char * name,EGLFuncPointer next)166 EGLFuncPointer LayerLoader::ApplyLayer(layer_setup_func layer_setup, const char* name,
167                                        EGLFuncPointer next) {
168     // Walk through our list of LayerSetup functions (they will already be in reverse order) to
169     // build up a call chain from the driver
170 
171     EGLFuncPointer layer_entry = next;
172 
173     layer_entry = layer_setup(name, layer_entry);
174 
175     if (next != layer_entry) {
176         ALOGV("We succeeded, replacing hook (%llu) with layer entry (%llu), for %s",
177               (unsigned long long)next, (unsigned long long)layer_entry, name);
178     }
179 
180     return layer_entry;
181 }
182 
ApplyLayers(const char * name,EGLFuncPointer next)183 EGLFuncPointer LayerLoader::ApplyLayers(const char* name, EGLFuncPointer next) {
184     if (!layers_loaded_ || layer_setup_.empty()) return next;
185 
186     ALOGV("ApplyLayers called for %s with next (%llu), current_layer_ (%i)", name,
187           (unsigned long long)next, current_layer_);
188 
189     EGLFuncPointer val = next;
190 
191     // Only ApplyLayers for layers that have been setup, not all layers yet
192     for (unsigned i = 0; i < current_layer_; i++) {
193         ALOGV("ApplyLayers: Calling ApplyLayer with i = %i for %s with next (%llu)", i, name,
194               (unsigned long long)next);
195         val = ApplyLayer(layer_setup_[i], name, val);
196     }
197 
198     ALOGV("ApplyLayers returning %llu for %s", (unsigned long long)val, name);
199 
200     return val;
201 }
202 
LayerPlatformEntries(layer_setup_func layer_setup,EGLFuncPointer * curr,char const * const * entries)203 void LayerLoader::LayerPlatformEntries(layer_setup_func layer_setup, EGLFuncPointer* curr,
204                                        char const* const* entries) {
205     while (*entries) {
206         char const* name = *entries;
207 
208         EGLFuncPointer prev = *curr;
209 
210         // Pass the existing entry point into the layer, replace the call with return value
211         *curr = ApplyLayer(layer_setup, name, *curr);
212 
213         if (prev != *curr) {
214             ALOGV("LayerPlatformEntries: Replaced (%llu) with platform entry (%llu), for %s",
215                   (unsigned long long)prev, (unsigned long long)*curr, name);
216         } else {
217             ALOGV("LayerPlatformEntries: No change(%llu) for %s, which means layer did not "
218                   "intercept",
219                   (unsigned long long)prev, name);
220         }
221 
222         curr++;
223         entries++;
224     }
225 }
226 
LayerDriverEntries(layer_setup_func layer_setup,EGLFuncPointer * curr,char const * const * entries)227 void LayerLoader::LayerDriverEntries(layer_setup_func layer_setup, EGLFuncPointer* curr,
228                                      char const* const* entries) {
229     while (*entries) {
230         char const* name = *entries;
231         EGLFuncPointer prev = *curr;
232 
233         // Only apply layers to driver entries if not handled by the platform
234         if (FindPlatformImplAddr(name) == nullptr) {
235             // Pass the existing entry point into the layer, replace the call with return value
236             *curr = ApplyLayer(layer_setup, name, *prev);
237 
238             if (prev != *curr) {
239                 ALOGV("LayerDriverEntries: Replaced (%llu) with platform entry (%llu), for %s",
240                       (unsigned long long)prev, (unsigned long long)*curr, name);
241             }
242 
243         } else {
244             ALOGV("LayerDriverEntries: Skipped (%llu) for %s", (unsigned long long)prev, name);
245         }
246 
247         curr++;
248         entries++;
249     }
250 }
251 
Initialized()252 bool LayerLoader::Initialized() {
253     return initialized_;
254 }
255 
InitLayers(egl_connection_t * cnx)256 void LayerLoader::InitLayers(egl_connection_t* cnx) {
257     if (!layers_loaded_) return;
258 
259     if (initialized_) return;
260 
261     if (layer_setup_.empty()) {
262         initialized_ = true;
263         return;
264     }
265 
266     // Include the driver in layer_functions
267     layer_functions.resize(layer_setup_.size() + 1);
268 
269     // Walk through the initial lists and create layer_functions[0]
270     int func_idx = 0;
271     char const* const* entries;
272     EGLFuncPointer* curr;
273 
274     entries = platform_names;
275     curr = reinterpret_cast<EGLFuncPointer*>(&cnx->platform);
276     SetupFuncMaps(layer_functions[0], entries, curr, func_idx);
277     ALOGV("InitLayers: func_idx after platform_names: %i", func_idx);
278 
279     entries = egl_names;
280     curr = reinterpret_cast<EGLFuncPointer*>(&cnx->egl);
281     SetupFuncMaps(layer_functions[0], entries, curr, func_idx);
282     ALOGV("InitLayers: func_idx after egl_names: %i", func_idx);
283 
284     entries = gl_names;
285     curr = reinterpret_cast<EGLFuncPointer*>(&cnx->hooks[egl_connection_t::GLESv2_INDEX]->gl);
286     SetupFuncMaps(layer_functions[0], entries, curr, func_idx);
287     ALOGV("InitLayers: func_idx after gl_names: %i", func_idx);
288 
289     // Walk through each layer's entry points per API, starting just above the driver
290     for (current_layer_ = 0; current_layer_ < layer_setup_.size(); current_layer_++) {
291         // Init the layer with a key that points to layer just below it
292         layer_init_[current_layer_](reinterpret_cast<void*>(&layer_functions[current_layer_]),
293                                     reinterpret_cast<PFNEGLGETNEXTLAYERPROCADDRESSPROC>(
294                                             getNextLayerProcAddress));
295 
296         // Check functions implemented by the platform
297         func_idx = 0;
298         entries = platform_names;
299         curr = reinterpret_cast<EGLFuncPointer*>(&cnx->platform);
300         LayerPlatformEntries(layer_setup_[current_layer_], curr, entries);
301 
302         // Populate next function table after layers have been applied
303         SetupFuncMaps(layer_functions[current_layer_ + 1], entries, curr, func_idx);
304 
305         // EGL
306         entries = egl_names;
307         curr = reinterpret_cast<EGLFuncPointer*>(&cnx->egl);
308         LayerDriverEntries(layer_setup_[current_layer_], curr, entries);
309 
310         // Populate next function table after layers have been applied
311         SetupFuncMaps(layer_functions[current_layer_ + 1], entries, curr, func_idx);
312 
313         // GLES 2+
314         // NOTE: We route calls to GLESv2 hooks, not GLESv1, so layering does not support GLES 1.x
315         // If it were added in the future, a different layer initialization model would be needed,
316         // that defers loading GLES entrypoints until after eglMakeCurrent, so two phase
317         // initialization.
318         entries = gl_names;
319         curr = reinterpret_cast<EGLFuncPointer*>(&cnx->hooks[egl_connection_t::GLESv2_INDEX]->gl);
320         LayerDriverEntries(layer_setup_[current_layer_], curr, entries);
321 
322         // Populate next function table after layers have been applied
323         SetupFuncMaps(layer_functions[current_layer_ + 1], entries, curr, func_idx);
324     }
325 
326     // We only want to apply layers once
327     initialized_ = true;
328 }
329 
LoadLayers()330 void LayerLoader::LoadLayers() {
331     std::string debug_layers = GetDebugLayers();
332 
333     // If no layers are specified, we're done
334     if (debug_layers.empty()) return;
335 
336     // Only enable the system search path for non-user builds
337     std::string system_path;
338     if (android::GraphicsEnv::getInstance().isDebuggable()) {
339         system_path = kSystemLayerLibraryDir;
340     }
341 
342     ALOGI("Debug layer list: %s", debug_layers.c_str());
343     std::vector<std::string> layers = android::base::Split(debug_layers, ":");
344 
345     // Load the layers in reverse order so we start with the driver's entrypoint and work our way up
346     for (int32_t i = layers.size() - 1; i >= 0; i--) {
347         // Check each layer path for the layer
348         std::vector<std::string> paths =
349                 android::base::Split(android::GraphicsEnv::getInstance().getLayerPaths().c_str(),
350                                      ":");
351 
352         if (!system_path.empty()) {
353             // Prepend the system paths so they override other layers
354             auto it = paths.begin();
355             paths.insert(it, system_path);
356         }
357 
358         bool layer_found = false;
359         for (uint32_t j = 0; j < paths.size() && !layer_found; j++) {
360             std::string layer;
361 
362             ALOGI("Searching %s for GLES layers", paths[j].c_str());
363 
364             // Realpath will return null for non-existent files
365             android::base::Realpath(paths[j] + "/" + layers[i], &layer);
366 
367             if (!layer.empty()) {
368                 layer_found = true;
369                 ALOGI("GLES layer found: %s", layer.c_str());
370 
371                 // Load the layer
372                 //
373                 // TODO: This code is common with Vulkan loader, refactor
374                 //
375                 // Libraries in the system layer library dir can't be loaded into
376                 // the application namespace. That causes compatibility problems, since
377                 // any symbol dependencies will be resolved by system libraries. They
378                 // can't safely use libc++_shared, for example. Which is one reason
379                 // (among several) we only allow them in non-user builds.
380                 auto app_namespace = android::GraphicsEnv::getInstance().getAppNamespace();
381                 if (app_namespace && !android::base::StartsWith(layer, kSystemLayerLibraryDir)) {
382                     char* error_message = nullptr;
383                     dlhandle_ = OpenNativeLibraryInNamespace(
384                         app_namespace, layer.c_str(), &native_bridge_, &error_message);
385                     if (!dlhandle_) {
386                         ALOGE("Failed to load layer %s with error: %s", layer.c_str(),
387                               error_message);
388                         android::NativeLoaderFreeErrorMessage(error_message);
389                         return;
390                     }
391 
392                 } else {
393                     dlhandle_ = dlopen(layer.c_str(), RTLD_NOW | RTLD_LOCAL);
394                 }
395 
396                 if (dlhandle_) {
397                     ALOGV("Loaded layer handle (%llu) for layer %s", (unsigned long long)dlhandle_,
398                           layers[i].c_str());
399                 } else {
400                     // If the layer is found but can't be loaded, try setenforce 0
401                     const char* dlsym_error = dlerror();
402                     ALOGE("Failed to load layer %s with error: %s", layer.c_str(), dlsym_error);
403                     return;
404                 }
405 
406                 // Find the layer's Initialize function
407                 std::string init_func = "AndroidGLESLayer_Initialize";
408                 ALOGV("Looking for entrypoint %s", init_func.c_str());
409 
410                 layer_init_func LayerInit = GetTrampoline<layer_init_func>(init_func.c_str());
411                 if (LayerInit) {
412                     ALOGV("Found %s for layer %s", init_func.c_str(), layer.c_str());
413                     layer_init_.push_back(LayerInit);
414                 } else {
415                     ALOGE("Failed to dlsym %s for layer %s", init_func.c_str(), layer.c_str());
416                     return;
417                 }
418 
419                 // Find the layer's setup function
420                 std::string setup_func = "AndroidGLESLayer_GetProcAddress";
421                 ALOGV("Looking for entrypoint %s", setup_func.c_str());
422 
423                 layer_setup_func LayerSetup = GetTrampoline<layer_setup_func>(setup_func.c_str());
424                 if (LayerSetup) {
425                     ALOGV("Found %s for layer %s", setup_func.c_str(), layer.c_str());
426                     layer_setup_.push_back(LayerSetup);
427                 } else {
428                     ALOGE("Failed to dlsym %s for layer %s", setup_func.c_str(), layer.c_str());
429                     return;
430                 }
431             }
432         }
433     }
434     // Track this so we only attempt to load these once
435     layers_loaded_ = true;
436 }
437 
438 } // namespace android
439