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/compiler/aot_file/stub_file_info.h"
17#include "ecmascript/compiler/aot_file/elf_builder.h"
18#include "ecmascript/compiler/aot_file/elf_reader.h"
19
20#ifndef PANDA_TARGET_OHOS
21extern const uint8_t _binary_stub_an_start[];
22extern const uint32_t _binary_stub_an_length;
23#endif
24
25namespace panda::ecmascript {
26void StubFileInfo::Save(const std::string &filename, Triple triple)
27{
28    std::string realPath;
29    if (!RealPath(filename, realPath, false)) {
30        return;
31    }
32
33    std::ofstream file(realPath.c_str(), std::ofstream::binary);
34    ASSERT(GetCodeUnitsNum() == ASMSTUB_MODULE_NUM);
35    SetStubNum(entries_.size());
36    ModuleSectionDes &des = des_[0];
37    size_t lastModuleSectionIdx = ASMSTUB_MODULE_NUM - 1;
38    // add section
39    uint64_t funcEntryAddr = reinterpret_cast<uint64_t>(entries_.data());
40    uint32_t funcEntrySize = sizeof(FuncEntryDes) * entryNum_;
41    des.SetSecAddrAndSize(ElfSecName::ARK_FUNCENTRY, funcEntryAddr, funcEntrySize);
42    uint64_t asmStubAddr = GetAsmStubAddr();
43    uint32_t asmStubSize = GetAsmStubSize();
44    des.SetSecAddrAndSize(ElfSecName::ARK_ASMSTUB, asmStubAddr, asmStubSize);
45    std::vector<uint32_t> moduleInfo = {1};
46    uint64_t secSizeInfoAddr = reinterpret_cast<uint64_t>(moduleInfo.data());
47    des.SetSecAddrAndSize(ElfSecName::ARK_MODULEINFO, secSizeInfoAddr, sizeof(uint32_t));
48    des_[lastModuleSectionIdx].AddAsmStubELFInfo(asmStubELFInfo_);
49
50    ElfBuilder builder(des_, GetDumpSectionNames());
51    llvm::ELF::Elf64_Ehdr header;
52    builder.PackELFHeader(header, base::FileHeaderBase::ToVersionNumber(AOTFileVersion::AN_VERSION), triple);
53    file.write(reinterpret_cast<char *>(&header), sizeof(llvm::ELF::Elf64_Ehdr));
54    builder.PackELFSections(file);
55    builder.PackELFSegment(file);
56    file.close();
57}
58
59bool StubFileInfo::MmapLoad(const std::string &fileName)
60{
61    std::string filename = fileName.empty() ? STUB_AN_FILE : fileName;
62    std::string realPath;
63    if (!RealPath(filename, realPath, false)) {
64        LOG_COMPILER(ERROR) << "Can not load stub file from path [ " << filename << " ], "
65                            << "please execute ark_stub_compiler with options --stub-file.";
66        return false;
67    }
68
69    if (!FileExist(realPath.c_str())) {
70        LOG_ECMA(WARN) << "File not exist. file: " << realPath;
71        return false;
72    }
73
74    fileMapMem_ = FileMap(realPath.c_str(), FILE_RDONLY, PAGE_PROT_READ);
75    if (fileMapMem_.GetOriginAddr() == nullptr) {
76        LOG_ECMA(ERROR) << "File mmap failed";
77        return false;
78    }
79
80    ElfReader reader(fileMapMem_);
81    std::vector<ElfSecName> secs = GetDumpSectionNames();
82    reader.ParseELFSections(des_, secs);
83    moduleNum_ = des_.size();
84    ASSERT(moduleNum_ == ASMSTUB_MODULE_NUM);
85
86    if (!reader.ParseELFSegment()) {
87        LOG_ECMA(ERROR) << "modify mmap area permission failed";
88        return false;
89    }
90
91    ModuleSectionDes &des = des_[0];
92    uint64_t funcEntryAddr = des.GetSecAddr(ElfSecName::ARK_FUNCENTRY);
93    uint32_t funcEntrySize = des.GetSecSize(ElfSecName::ARK_FUNCENTRY);
94    FuncEntryDes *entryDes = reinterpret_cast<FuncEntryDes *>(funcEntryAddr);
95    entryNum_ = funcEntrySize / sizeof(FuncEntryDes);
96    entries_.assign(entryDes, entryDes + entryNum_);
97    uint64_t asmStubAddr = des.GetSecAddr(ElfSecName::ARK_ASMSTUB);
98    uint32_t asmStubSize = des.GetSecSize(ElfSecName::ARK_ASMSTUB);
99    SetAsmStubAddr(asmStubAddr);
100    SetAsmStubSize(asmStubSize);
101
102    for (auto &entry : entries_) {
103        if (entry.IsGeneralRTStub()) {
104            uint64_t begin = GetAsmStubAddr();
105            entry.codeAddr_ += begin;
106        } else {
107            auto moduleDes = des_[entry.moduleIndex_];
108            entry.codeAddr_ += moduleDes.GetSecAddr(ElfSecName::TEXT);
109        }
110    }
111    LOG_COMPILER(INFO) << "loaded stub file successfully";
112    return true;
113}
114#ifndef PANDA_TARGET_OHOS
115bool StubFileInfo::Load()
116{
117    if (_binary_stub_an_length <= 1) {
118        LOG_FULL(FATAL) << "stub.an length <= 1, is default and invalid.";
119        return false;
120    }
121
122    BinaryBufferParser binBufparser(const_cast<uint8_t *>(_binary_stub_an_start), _binary_stub_an_length);
123    moduleNum_ = ASMSTUB_MODULE_NUM;
124    des_.resize(moduleNum_);
125
126    ExecutedMemoryAllocator::AllocateBuf(_binary_stub_an_length, stubsMem_, PAGE_PROT_READWRITE);
127
128    ElfReader reader(stubsMem_);
129    std::vector<ElfSecName> secs = GetDumpSectionNames();
130    reader.ParseELFSections(binBufparser, des_, secs);
131
132    ModuleSectionDes &des = des_[0];
133    uint64_t funcEntryAddr = des.GetSecAddr(ElfSecName::ARK_FUNCENTRY);
134    uint32_t funcEntrySize = des.GetSecSize(ElfSecName::ARK_FUNCENTRY);
135    FuncEntryDes *entryDes = reinterpret_cast<FuncEntryDes *>(funcEntryAddr);
136    entryNum_ = funcEntrySize / sizeof(FuncEntryDes);
137    entries_.assign(entryDes, entryDes + entryNum_);
138    uint64_t asmStubAddr = des.GetSecAddr(ElfSecName::ARK_ASMSTUB);
139    uint32_t asmStubSize = des.GetSecSize(ElfSecName::ARK_ASMSTUB);
140    SetAsmStubAddr(asmStubAddr);
141    SetAsmStubSize(asmStubSize);
142
143    for (auto &entry : entries_) {
144        if (entry.IsGeneralRTStub()) {
145            uint64_t begin = GetAsmStubAddr();
146            entry.codeAddr_ += begin;
147        } else {
148            auto moduleDes = des_[entry.moduleIndex_];
149            entry.codeAddr_ += moduleDes.GetSecAddr(ElfSecName::TEXT);
150        }
151    }
152    LOG_COMPILER(INFO) << "loaded stub file successfully";
153    if (!PageProtect(stubsMem_.addr_, stubsMem_.size_, PAGE_PROT_EXEC_READ)) {
154        return false;
155    }
156    return true;
157}
158#endif
159const std::vector<ElfSecName> &StubFileInfo::GetDumpSectionNames()
160{
161    static const std::vector<ElfSecName> secNames = {
162        ElfSecName::TEXT,
163        ElfSecName::STRTAB,
164        ElfSecName::SYMTAB,
165        ElfSecName::SHSTRTAB,
166        ElfSecName::ARK_STACKMAP,
167        ElfSecName::ARK_FUNCENTRY,
168        ElfSecName::ARK_ASMSTUB,
169        ElfSecName::ARK_MODULEINFO
170    };
171    return secNames;
172}
173
174void StubFileInfo::Dump() const
175{
176    uint64_t asmAddr = GetAsmStubAddr();
177    uint64_t asmSize = GetAsmStubSize();
178
179    LOG_COMPILER(ERROR) << "Stub file loading: ";
180    LOG_COMPILER(ERROR) << " - asm stubs [0x" << std::hex << asmAddr << ", 0x" << std::hex << asmAddr + asmSize << "]";
181
182    for (const ModuleSectionDes &d : des_) {
183        for (const auto &s : d.GetSectionsInfo()) {
184            std::string name = d.GetSecName(s.first);
185            uint32_t size = d.GetSecSize(s.first);
186            uint64_t addr = d.GetSecAddr(s.first);
187            LOG_COMPILER(ERROR) << " - section = " << name << " [0x" << std::hex << addr << ", 0x" << std::hex
188                                << addr + size << "]";
189        }
190    }
191}
192}  // namespace panda::ecmascript
193