1#!/usr/bin/env python 2#coding=utf-8 3 4# 5# Copyright (c) 2022 Huawei Device Co., Ltd. 6# Licensed under the Apache License, Version 2.0 (the "License"); 7# you may not use this file except in compliance with the License. 8# You may obtain a copy of the License at 9# 10# http://www.apache.org/licenses/LICENSE-2.0 11# 12# Unless required by applicable law or agreed to in writing, software 13# distributed under the License is distributed on an "AS IS" BASIS, 14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15# See the License for the specific language governing permissions and 16# limitations under the License. 17# 18 19import os 20from stat import ST_SIZE 21 22from .utils import command, command_without_error 23 24 25class ElfFile(dict): 26 def __init__(self, file, prefix): 27 self._f = file 28 self._f_safe = "'%s'" % file 29 30 self["name"] = os.path.basename(file) 31 self["size"] = os.stat(self._f)[ST_SIZE] 32 if self["name"].find(".so") > 0: 33 self["type"] = "lib" 34 else: 35 self["type"] = "bin" 36 self["path"] = file[len(prefix):] 37 38 def __eq__(self, other): 39 if not isinstance(other, ElfFile): 40 return NotImplemented 41 42 return self["path"] == other["path"] 43 44 def is_library(self): 45 if self["name"].find(".so") > 0: 46 return True 47 return False 48 49 def get_file(self): 50 return self._f 51 52 # Return a set of libraries the passed objects depend on. 53 def library_depends(self): 54 if not os.access(self._f, os.F_OK): 55 raise Exception("Cannot find lib: " + self._f) 56 file_name = self._f_safe.split("/")[-1].strip("'") 57 dynamics = command_without_error("strings", self._f_safe, f"|grep -E lib_.so|grep -v {file_name}") 58 res = [] 59 if dynamics: 60 for line in dynamics: 61 if line.startswith("lib") and line.endswith(".so"): 62 res.append(line) 63 64 return res 65 66 def __extract_soname(self): 67 soname_data = command("mklibs-readelf", "--print-soname", self._f_safe) 68 if soname_data: 69 return soname_data.pop() 70 return "" 71 72 def __extract_elf_size(self): 73 size_data = command("size", self._f_safe) 74 if not size_data or len(size_data) < 2: 75 self["text_size"] = 0 76 self["data_size"] = 0 77 self["bss_size"] = 0 78 return 0 79 80 vals = size_data[1].split() 81 self["text_size"] = int(vals[0]) 82 self["data_size"] = int(vals[1]) 83 self["bss_size"] = int(vals[2]) 84 return "" 85 86if __name__ == '__main__': 87 import elf_walker 88 89 cnt = 0 90 elfFiles = elf_walker.ELFWalker() 91 for f in elfFiles.get_elf_files(): 92 if f.find("libskia_ohos.z.so") < 0: 93 continue 94 elf = ElfFile(f, elfFiles.get_product_images_path()) 95 print(f) 96