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