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 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 dynamics = command("readelf", "--dynamic", self._f_safe) 57 res = [] 58 for line in dynamics: 59 pos = line.find("(NEEDED)") 60 if pos <= 0: 61 continue 62 line = line[pos + 8:] 63 line = line.strip() 64 if not line.startswith("Shared library:"): 65 continue 66 line = line[15:] 67 line = line.strip() 68 if line.startswith("["): 69 line = line[1:] 70 if line.endswith("]"): 71 line = line[:-1] 72 line = line.strip() 73 res.append(line) 74 return res 75 76 def __extract_soname(self): 77 soname_data = command("mklibs-readelf", "--print-soname", self._f_safe) 78 if soname_data: 79 return soname_data.pop() 80 return "" 81 82 def __extract_elf_size(self): 83 size_data = command("size", self._f_safe) 84 if not size_data or len(size_data) < 2: 85 self["text_size"] = 0 86 self["data_size"] = 0 87 self["bss_size"] = 0 88 return 0 89 90 vals = size_data[1].split() 91 self["text_size"] = int(vals[0]) 92 self["data_size"] = int(vals[1]) 93 self["bss_size"] = int(vals[2]) 94 return "" 95 96if __name__ == '__main__': 97 import elf_walker 98 99 cnt = 0 100 elfFiles = elf_walker.ELFWalker() 101 for f in elfFiles.get_elf_files(): 102 if f.find("libskia_ohos.z.so") < 0: 103 continue 104 elf = ElfFile(f, elfFiles.get_product_images_path()) 105 print(f) 106