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/an_file_info.h"
17
18 #include "ecmascript/compiler/aot_file/aot_checksum_helper.h"
19 #include "ecmascript/compiler/aot_file/elf_builder.h"
20 #include "ecmascript/compiler/aot_file/elf_reader.h"
21 #include "ecmascript/log_wrapper.h"
22
23 namespace panda::ecmascript {
Save(const std::string & filename,Triple triple,size_t anFileMaxByteSize,const std::unordered_map<CString,uint32_t> & fileNameToChecksumMap)24 bool AnFileInfo::Save(const std::string &filename, Triple triple, size_t anFileMaxByteSize,
25 const std::unordered_map<CString, uint32_t> &fileNameToChecksumMap)
26 {
27 std::string realPath;
28 if (!RealPath(filename, realPath, false)) {
29 return false;
30 }
31 const char *rawPath = realPath.c_str();
32 if (!TryRemoveAnFile(rawPath)) {
33 LOG_COMPILER(ERROR) << "unlink an file fail";
34 return false;
35 };
36
37 SetStubNum(entries_.size());
38 AddFuncEntrySec();
39 AddFileNameToChecksumSec(fileNameToChecksumMap);
40
41 ElfBuilder builder(des_, GetDumpSectionNames(), false, triple);
42 size_t anFileSize = builder.CalculateTotalFileSize();
43 if (anFileMaxByteSize != 0) {
44 if (anFileSize > anFileMaxByteSize) {
45 LOG_COMPILER(ERROR) << "Expected AN file size " << anFileSize << " bytes ("
46 << (static_cast<double>(anFileSize) / 1_MB) << "MB) "
47 << "exceeds maximum allowed size of " << (static_cast<double>(anFileMaxByteSize) / 1_MB)
48 << "MB";
49 return false;
50 }
51 }
52 std::fstream file(rawPath, std::fstream::binary | std::fstream::out | std::fstream::trunc);
53 llvm::ELF::Elf64_Ehdr header;
54 builder.PackELFHeader(header, base::FileHeaderBase::ToVersionNumber(AOTFileVersion::AN_VERSION), triple);
55 file.write(reinterpret_cast<char *>(&header), sizeof(llvm::ELF::Elf64_Ehdr));
56 builder.PackELFSections(file);
57 builder.PackELFSegment(file);
58 if (static_cast<size_t>(file.tellp()) != anFileSize) {
59 LOG_COMPILER(ERROR) << "Error to save an file: file size " << file.tellp()
60 << " not equal calculated size: " << anFileSize;
61 file.close();
62 TryRemoveAnFile(rawPath);
63 return false;
64 }
65 file.close();
66 return true;
67 }
68
LoadInternal(const std::string & filename)69 bool AnFileInfo::LoadInternal(const std::string &filename)
70 {
71 if (fileMapMem_.GetOriginAddr() == nullptr) {
72 LOG_ECMA(ERROR) << "File mmap failed";
73 return false;
74 }
75
76 moduleNum_ = 1;
77 des_.resize(moduleNum_);
78 ModuleSectionDes &des = des_[0];
79
80 ElfReader reader(fileMapMem_);
81 std::vector<ElfSecName> secs = GetDumpSectionNames();
82 if (!reader.VerifyELFHeader(base::FileHeaderBase::ToVersionNumber(AOTFileVersion::AN_VERSION),
83 AOTFileVersion::AN_STRICT_MATCH)) {
84 return false;
85 }
86 reader.ParseELFSections(des, secs);
87 if (!reader.ParseELFSegment()) {
88 LOG_ECMA(ERROR) << "modify mmap area permission failed";
89 return false;
90 }
91 if (!ParseChecksumInfo(des)) {
92 LOG_ECMA(ERROR) << "Parse checksum info failed, stop load aot";
93 return false;
94 }
95 ParseFunctionEntrySection(des);
96
97 UpdateFuncEntries();
98
99 LOG_COMPILER(INFO) << "loaded an file: " << filename.c_str();
100 isLoad_ = true;
101 return true;
102 }
103
Load(const std::string & filename)104 bool AnFileInfo::Load(const std::string &filename)
105 {
106 std::string realPath;
107 if (!RealPath(filename, realPath, false)) {
108 LOG_COMPILER(ERROR) << "Can not load aot file from path [ " << filename << " ], "
109 << "please execute ark_aot_compiler with options --aot-file.";
110 return false;
111 }
112 if (!FileExist(realPath.c_str())) {
113 LOG_ECMA(WARN) << "File not exist. file: " << realPath;
114 return false;
115 }
116
117 fileMapMem_ = FileMap(realPath.c_str(), FILE_RDONLY, PAGE_PROT_READ);
118 return LoadInternal(filename);
119 }
120
121 #if defined(CROSS_PLATFORM) && defined(ANDROID_PLATFORM)
Load(const std::string & filename,std::function<bool (std::string fileName,uint8_t ** buff,size_t * buffSize)> ReadAOTCallBack)122 bool AnFileInfo::Load(const std::string &filename, [[maybe_unused]] std::function<bool
123 (std::string fileName, uint8_t **buff, size_t *buffSize)> ReadAOTCallBack)
124 {
125 std::string fileName = filename;
126 uint8_t *buff = nullptr;
127 size_t buffSize = 0;
128 size_t found = filename.find_last_of("/");
129 if (found != std::string::npos) {
130 fileName = filename.substr(found + 1);
131 }
132
133 LOG_ECMA(INFO) << "Call JsAotReader to load: " << fileName;
134 if (ReadAOTCallBack(fileName, &buff, &buffSize)) {
135 void* newBuff = nullptr;
136 if (posix_memalign(&newBuff, sysconf(_SC_PAGESIZE), buffSize) != 0) {
137 LOG_ECMA(ERROR) << "posix_memalign failed!";
138 return false;
139 }
140 std::copy(reinterpret_cast<char*>(buff), reinterpret_cast<char*>(buff) + buffSize,
141 reinterpret_cast<char*>(newBuff));
142 fileMapMem_ = MemMap(newBuff, buffSize);
143 }
144
145 return LoadInternal(filename);
146 }
147 #endif
148
TryRemoveAnFile(const char * filename)149 bool AnFileInfo::TryRemoveAnFile(const char *filename)
150 {
151 if (!FileExist(filename)) {
152 return true;
153 }
154 if (Unlink(filename) == -1) {
155 LOG_COMPILER(ERROR) << "remove " << filename << " failed and errno is " << errno;
156 return false;
157 }
158 return true;
159 }
160
ParseFunctionEntrySection(ModuleSectionDes & des)161 void AnFileInfo::ParseFunctionEntrySection(ModuleSectionDes &des)
162 {
163 uint64_t secAddr = des.GetSecAddr(ElfSecName::ARK_FUNCENTRY);
164 uint32_t secSize = des.GetSecSize(ElfSecName::ARK_FUNCENTRY);
165 FuncEntryDes *entryDes = reinterpret_cast<FuncEntryDes *>(secAddr);
166 entryNum_ = secSize / sizeof(FuncEntryDes);
167 entries_.assign(entryDes, entryDes + entryNum_);
168 des.SetStartIndex(0);
169 des.SetFuncCount(entryNum_);
170 }
171
ParseChecksumInfo(ModuleSectionDes & des)172 bool AnFileInfo::ParseChecksumInfo(ModuleSectionDes &des)
173 {
174 uint64_t secAddr = des.GetSecAddr(ElfSecName::ARK_CHECKSUMINFO);
175 uint32_t secSize = des.GetSecSize(ElfSecName::ARK_CHECKSUMINFO);
176 const char *data = reinterpret_cast<const char *>(secAddr);
177 std::unordered_map<CString, uint32_t> checksumInfoMap;
178 if (!AOTChecksumHelper::DeserializeChecksumMapFromChar(data, secSize, checksumInfoMap)) {
179 LOG_COMPILER(ERROR) << "Deserialize checksum info from .an file failed!";
180 return false;
181 }
182
183 AnFileDataManager::GetInstance()->UnsafeMergeChecksumInfo(checksumInfoMap);
184 return true;
185 }
186
UpdateFuncEntries()187 void AnFileInfo::UpdateFuncEntries()
188 {
189 ModuleSectionDes &des = des_[0];
190 size_t len = entries_.size();
191 for (size_t i = 0; i < len; i++) {
192 FuncEntryDes &funcDes = entries_[i];
193 funcDes.codeAddr_ += des.GetSecAddr(ElfSecName::TEXT);
194 if (funcDes.isMainFunc_) {
195 EntryKey key = std::make_pair(funcDes.abcIndexInAi_, funcDes.indexInKindOrMethodId_);
196 mainEntryMap_[key] = MainFuncEntry { funcDes.codeAddr_, funcDes.fpDeltaPrevFrameSp_, funcDes.isFastCall_ };
197 #ifndef NDEBUG
198 LOG_COMPILER(INFO) << "AnFileInfo Load main method id: " << funcDes.indexInKindOrMethodId_
199 << " code addr: " << reinterpret_cast<void *>(funcDes.codeAddr_);
200 #endif
201 }
202 }
203 }
204
GetDumpSectionNames()205 const std::vector<ElfSecName> &AnFileInfo::GetDumpSectionNames()
206 {
207 static const std::vector<ElfSecName> secNames = {
208 ElfSecName::TEXT,
209 ElfSecName::STRTAB,
210 ElfSecName::SYMTAB,
211 ElfSecName::SHSTRTAB,
212 ElfSecName::ARK_STACKMAP,
213 ElfSecName::ARK_FUNCENTRY,
214 ElfSecName::ARK_CHECKSUMINFO
215 };
216 return secNames;
217 }
218
Destroy()219 void AnFileInfo::Destroy()
220 {
221 mainEntryMap_.clear();
222 isLoad_ = false;
223 curTextSecOffset_ = 0;
224 AOTFileInfo::Destroy();
225 }
226
Dump() const227 void AnFileInfo::Dump() const
228 {
229 LOG_COMPILER(INFO) << "An file loading: ";
230 int i = 0;
231 for (const ModuleSectionDes &d : des_) {
232 i++;
233 for (const auto &s : d.GetSectionsInfo()) {
234 std::string name = d.GetSecName(s.first);
235 uint32_t size = d.GetSecSize(s.first);
236 uint64_t addr = d.GetSecAddr(s.first);
237 LOG_COMPILER(INFO) << " - module-" << i << " <" << name << "> [0x" << std::hex << addr << ", 0x"
238 << std::hex << addr + size << "]";
239 }
240 }
241 }
242
IsLoadMain(uint32_t fileIndex,const JSPandaFile * jsPandaFile,const CString & entry) const243 bool AnFileInfo::IsLoadMain(uint32_t fileIndex, const JSPandaFile *jsPandaFile, const CString &entry) const
244 {
245 auto methodId = jsPandaFile->GetMainMethodIndex(entry);
246 #ifndef NDEBUG
247 LOG_COMPILER(INFO) << "AnFileInfo IsLoadMain method id: " << methodId << " entry: " << entry;
248 #endif
249 auto it = mainEntryMap_.find(std::make_pair(fileIndex, methodId));
250 return it != mainEntryMap_.end();
251 }
252
AddFuncEntrySec()253 void AnFileInfo::AddFuncEntrySec()
254 {
255 ModuleSectionDes &des = des_[ElfBuilder::FuncEntryModuleDesIndex];
256 // add section
257 uint64_t funcEntryAddr = reinterpret_cast<uint64_t>(entries_.data());
258 uint32_t funcEntrySize = sizeof(FuncEntryDes) * entryNum_;
259 des.SetSecAddrAndSize(ElfSecName::ARK_FUNCENTRY, funcEntryAddr, funcEntrySize);
260 }
261
AddFileNameToChecksumSec(const std::unordered_map<CString,uint32_t> & fileNameToChecksumMap)262 void AnFileInfo::AddFileNameToChecksumSec(const std::unordered_map<CString, uint32_t> &fileNameToChecksumMap)
263 {
264 AOTChecksumHelper::SerializeChecksumMapToVector(fileNameToChecksumMap, checksumDataVector_);
265 ModuleSectionDes &des = des_[ElfBuilder::FuncEntryModuleDesIndex];
266 uint64_t checksumInfoAddr = reinterpret_cast<uint64_t>(checksumDataVector_.data());
267 uint32_t checksumInfoSize = checksumDataVector_.size();
268 des.SetSecAddrAndSize(ElfSecName::ARK_CHECKSUMINFO, checksumInfoAddr, checksumInfoSize);
269 }
270
GenerateMethodToEntryIndexMap()271 void AnFileInfo::GenerateMethodToEntryIndexMap()
272 {
273 const std::vector<AOTFileInfo::FuncEntryDes> &entries = GetStubs();
274 uint32_t entriesSize = entries.size();
275 for (uint32_t i = 0; i < entriesSize; ++i) {
276 const AOTFileInfo::FuncEntryDes &entry = entries[i];
277 std::string &fileName = entryIdxToFileNameMap_.at(i);
278 auto key = std::make_pair(fileName, entry.indexInKindOrMethodId_);
279 methodToEntryIndexMap_[key] = i;
280 }
281 }
282 } // namespace panda::ecmascript
283