• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023 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 #include "ecmascript/platform/elf.h"
17 
18 #include "ecmascript/base/file_header.h"
19 #include "ecmascript/ecma_macros.h"
20 #include "securec.h"
21 
22 namespace panda::ecmascript {
PackELFHeader(Elf64_Ehdr & header,uint32_t version,kungfu::Triple triple)23 void PackELFHeader(Elf64_Ehdr &header, uint32_t version, kungfu::Triple triple)
24 {
25     if (memset_s(reinterpret_cast<void *>(&header), sizeof(Elf64_Ehdr), 0, sizeof(Elf64_Ehdr)) != EOK) {
26         UNREACHABLE();
27     }
28     header.e_ident[EI_MAG0] = ELFMAG0;
29     header.e_ident[EI_MAG1] = ELFMAG1;
30     header.e_ident[EI_MAG2] = ELFMAG2;
31     header.e_ident[EI_MAG3] = ELFMAG3;
32     header.e_ident[EI_CLASS] = ELFCLASS64;
33     header.e_ident[EI_DATA] = ELFDATA2LSB;
34     header.e_ident[EI_VERSION] = 1;
35 
36     header.e_type = ET_DYN;
37     switch (triple) {
38         case kungfu::Triple::TRIPLE_AMD64:
39             header.e_machine = EM_X86_64;
40             break;
41         case kungfu::Triple::TRIPLE_ARM32:
42             header.e_machine = EM_ARM;
43             break;
44         case kungfu::Triple::TRIPLE_AARCH64:
45             header.e_machine = EM_AARCH64;
46             break;
47         default:
48             UNREACHABLE();
49             break;
50     }
51     header.e_version = version;
52 }
53 
VerifyELFHeader(const Elf64_Ehdr & header,uint32_t version,bool silent)54 bool VerifyELFHeader(const Elf64_Ehdr &header, uint32_t version, bool silent)
55 {
56     if (header.e_ident[EI_MAG0] != ELFMAG0 || header.e_ident[EI_MAG1] != ELFMAG1 ||
57         header.e_ident[EI_MAG2] != ELFMAG2 || header.e_ident[EI_MAG3] != ELFMAG3) {
58         if (!silent) {
59             LOG_ECMA(ERROR) << "ELF format error, expected magic is " << ELFMAG << ", but got "
60                             << header.e_ident[EI_MAG0] << header.e_ident[EI_MAG1] << header.e_ident[EI_MAG2]
61                             << header.e_ident[EI_MAG3];
62         }
63         return false;
64     }
65     if (!base::FileHeader::VerifyVersion("Elf ", header.e_version, version, silent)) {
66         return false;
67     }
68     return true;
69 }
70 }  // namespace panda::ecmascript
71