1 /* 2 * Copyright (c) 2024-2024 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 package com.ohos.hapsigntool.codesigning.elf; 17 18 import com.ohos.hapsigntool.codesigning.exception.ElfFormatException; 19 20 import java.io.IOException; 21 import java.io.InputStream; 22 import java.util.ArrayList; 23 import java.util.List; 24 import java.util.stream.Collectors; 25 26 /** 27 * ELF file 28 * 29 * @since 2024/07/01 30 */ 31 public class ElfFile { 32 private ElfHeader elfHeader; 33 34 private final List<ElfProgramHeader> programHeaderList = new ArrayList<>(); 35 36 /** 37 * Constructor for ElfFile 38 * 39 * @param is InputStream 40 * @throws IOException io error 41 * @throws ElfFormatException elf file format error 42 */ ElfFile(InputStream is)43 public ElfFile(InputStream is) throws IOException, ElfFormatException { 44 elfHeader = new ElfHeader(is); 45 if (!isElfFile()) { 46 return; 47 } 48 byte eiClass = elfHeader.getEiClass(); 49 byte eiData = elfHeader.getEiData(); 50 int ePhnum = elfHeader.getEPhnum(); 51 long ePhOff = elfHeader.getEPhOff(); 52 if (eiClass == ElfDefine.ELF_32_CLASS) { 53 is.skip(ePhOff - ElfDefine.ELF_HEADER_32_LEN); 54 } else if (eiClass == ElfDefine.ELF_64_CLASS) { 55 is.skip(ePhOff - ElfDefine.ELF_HEADER_64_LEN); 56 } 57 for (int i = 0; i < ePhnum; i++) { 58 ElfProgramHeader pHeader = new ElfProgramHeader(is, eiClass, eiData); 59 programHeaderList.add(pHeader); 60 } 61 } 62 63 /** 64 * filter executable program segment headers 65 * 66 * @return executable program segment headers 67 */ filterExecPHeaders()68 public List<ElfProgramHeader> filterExecPHeaders() { 69 return programHeaderList.stream().filter(phdr -> (phdr.getPFlags() & 1) == 1).collect(Collectors.toList()); 70 } 71 72 /** 73 * return true if magic number is correct 74 * 75 * @return true if magic number is correct 76 */ isElfFile()77 public final boolean isElfFile() { 78 return elfHeader.isElfFile(); 79 } 80 } 81