1 /*
2  * Copyright (C) 2024 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 "binary_loader.h"
18 
19 // If dlopen is unnecessary (eg. for shared libs), absoluteBinPath should be empty.
BinaryLoader(const std::string absoluteBinPath)20 BinaryLoader::BinaryLoader(const std::string absoluteBinPath) {
21     if (!absoluteBinPath.empty()) {
22         binPath = absoluteBinPath.c_str();
23         binHandle = dlopen(binPath, RTLD_NOW);
24         if (!binHandle) {
25             printf("Error opening binary: %s. Error: %s\n", binPath, dlerror());
26         }
27     }
28 }
29 
~BinaryLoader()30 BinaryLoader::~BinaryLoader() {
31     if (binHandle) {
32         dlclose(binHandle);
33         binHandle = nullptr;
34     }
35     binPath = nullptr;
36     baseAddress = 0;
37 }
38 
39 // When functionOffset is 0, return the base address
getFunctionAddress(uintptr_t functionOffset)40 uintptr_t BinaryLoader::getFunctionAddress(uintptr_t functionOffset) {
41     if (!baseAddress) {
42         if (!dl_iterate_phdr(callback, (void*)this) || !baseAddress) {
43             return 0;
44         }
45     }
46     return baseAddress + functionOffset;
47 }
48 
49 // Callback function to iterate loaded binaries
callback(struct dl_phdr_info * info,size_t,void * data)50 int BinaryLoader::callback(struct dl_phdr_info* info, size_t /* size */, void* data) {
51     BinaryLoader* binLoader = (BinaryLoader*)data;
52 
53     // Check if the library name matches the binPath and p_type is PT_LOAD
54     if (strcmp(info->dlpi_name, binLoader->binPath) == 0) {
55         for (size_t j = 0; j < info->dlpi_phnum; ++j) {
56             if (info->dlpi_phdr[j].p_type == PT_LOAD) {
57                 binLoader->baseAddress = (uintptr_t)(info->dlpi_addr + info->dlpi_phdr[j].p_vaddr);
58                 return 1;
59             }
60         }
61     }
62     return 0;
63 }
64