• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /**
2  * Copyright (c) 2021-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 #include "file_format_version.h"
17 #include "file-inl.h"
18 #include "os/file.h"
19 #include "os/mem.h"
20 #include "os/filesystem.h"
21 #include "mem/mem.h"
22 #include "panda_cache.h"
23 
24 #include "utils/hash.h"
25 #include "utils/logger.h"
26 #include "utils/utf.h"
27 #include "utils/span.h"
28 #include "zip_archive.h"
29 #include "trace/trace.h"
30 #include "securec.h"
31 
32 #include <cerrno>
33 #include <cstring>
34 
35 #include <algorithm>
36 #include <memory>
37 #include <string>
38 #include <variant>
39 #include <cstdio>
40 #include <map>
41 namespace ark::panda_file {
42 
43 // NOLINTNEXTLINE(readability-identifier-naming, modernize-avoid-c-arrays)
44 const char *ARCHIVE_FILENAME = "classes.abc";
45 // NOLINTNEXTLINE(readability-identifier-naming, modernize-avoid-c-arrays)
46 const char *ARCHIVE_SPLIT = "!/";
47 
48 const std::array<uint8_t, File::MAGIC_SIZE> File::MAGIC {'P', 'A', 'N', 'D', 'A', '\0', '\0', '\0'};
49 
50 // Name anonymous maps for perfing tools finding symbol file correctly.
51 // NOLINTNEXTLINE(readability-identifier-naming, modernize-avoid-c-arrays)
52 const char *ANONMAPNAME_PERFIX = "panda-";
53 
GetMode(panda_file::File::OpenMode openMode)54 os::file::Mode GetMode(panda_file::File::OpenMode openMode)
55 {
56     switch (openMode) {
57         case File::READ_ONLY: {
58             return os::file::Mode::READONLY;
59         }
60         case File::READ_WRITE: {
61 #ifdef PANDA_TARGET_WINDOWS
62             return os::file::Mode::READWRITE;
63 #else
64             return os::file::Mode::READONLY;
65 #endif
66         }
67         case File::WRITE_ONLY: {
68             return os::file::Mode::WRITEONLY;
69         }
70         default: {
71             break;
72         }
73     }
74 
75     UNREACHABLE();
76 }
77 
GetProt(panda_file::File::OpenMode mode)78 static uint32_t GetProt(panda_file::File::OpenMode mode)
79 {
80     uint32_t prot = os::mem::MMAP_PROT_READ;
81     if (mode == File::READ_WRITE) {
82         prot |= os::mem::MMAP_PROT_WRITE;
83     }
84     return prot;
85 }
86 
87 class AnonMemSet {
88 public:
89     using MemNameSet = std::map<std::string, std::string>;
90     using InsertResult = std::map<std::string, std::string>::iterator;
91 
GetInstance()92     static AnonMemSet &GetInstance()
93     {
94         static AnonMemSet anonMemSet;
95         return anonMemSet;
96     }
97 
Insert(const std::string & fileName,const std::string & anonMemName)98     InsertResult Insert(const std::string &fileName, const std::string &anonMemName)
99     {
100         return memNameSet_.emplace(fileName, anonMemName).first;
101     }
102 
Remove(const std::string & fileName)103     void Remove(const std::string &fileName)
104     {
105         auto it = memNameSet_.find(fileName);
106         if (it != memNameSet_.end()) {
107             memNameSet_.erase(it);
108         }
109     }
110 
111 private:
112     MemNameSet memNameSet_;
113 };
114 
OpenPandaFileOrZip(std::string_view location,panda_file::File::OpenMode openMode)115 std::unique_ptr<const File> OpenPandaFileOrZip(std::string_view location, panda_file::File::OpenMode openMode)
116 {
117     std::string_view archiveFilename = ARCHIVE_FILENAME;
118     std::size_t archiveSplitIndex = location.find(ARCHIVE_SPLIT);
119     if (archiveSplitIndex != std::string::npos) {
120         archiveFilename = location.substr(archiveSplitIndex + 2);  // 2 - archive split size
121         location = location.substr(0, archiveSplitIndex);
122     }
123 
124     return OpenPandaFile(location, archiveFilename, openMode);
125 }
126 
127 // NOLINTNEXTLINE(google-runtime-references)
OpenPandaFileFromZipErrorHandler(ZipArchiveHandle & handle)128 void OpenPandaFileFromZipErrorHandler(ZipArchiveHandle &handle)
129 {
130     if (handle != nullptr) {
131         if (ark::CloseArchiveFile(handle) != ZIPARCHIVE_OK) {
132             LOG(ERROR, PANDAFILE) << "CloseArchiveFile failed!";
133         }
134     }
135 }
136 
OpenPandaFileFromZipFile(ZipArchiveHandle & handle,std::string_view location,EntryFileStat & entry,std::string_view archiveName)137 std::unique_ptr<const panda_file::File> OpenPandaFileFromZipFile(ZipArchiveHandle &handle, std::string_view location,
138                                                                  EntryFileStat &entry, std::string_view archiveName)
139 {
140     uint32_t uncompressedLength = entry.GetUncompressedSize();
141     if (uncompressedLength == 0) {
142         LOG(ERROR, PANDAFILE) << "Panda file has zero length!";
143         return nullptr;
144     }
145 
146     size_t sizeToMmap = AlignUp(uncompressedLength, ark::os::mem::GetPageSize());
147     void *mem = os::mem::MapRWAnonymousRaw(sizeToMmap, false);
148     if (mem == nullptr) {
149         LOG(ERROR, PANDAFILE) << "Can't mmap anonymous!";
150         return nullptr;
151     }
152     os::mem::BytePtr ptr(reinterpret_cast<std::byte *>(mem), sizeToMmap, os::mem::MmapDeleter);
153     std::stringstream ss;
154     ss << ANONMAPNAME_PERFIX << archiveName << " extracted in memory from " << location;
155     auto it = AnonMemSet::GetInstance().Insert(std::string(location), ss.str());
156     auto ret = os::mem::TagAnonymousMemory(reinterpret_cast<void *>(ptr.Get()), sizeToMmap, it->second.c_str());
157     if (ret.has_value()) {
158         LOG(ERROR, PANDAFILE) << "Can't tag mmap anonymous!";
159         return nullptr;
160     }
161 
162     auto extractError = ExtractToMemory(handle, reinterpret_cast<uint8_t *>(ptr.Get()), sizeToMmap);
163     if (extractError != 0) {
164         LOG(ERROR, PANDAFILE) << "Can't extract!";
165         return nullptr;
166     }
167 
168     os::mem::ConstBytePtr constPtr = ptr.ToConst();
169     return panda_file::File::OpenFromMemory(std::move(constPtr), location);
170 }
171 
172 // NOLINTNEXTLINE(google-runtime-references)
HandleArchive(ZipArchiveHandle & handle,FILE * fp,std::string_view location,EntryFileStat & entry,std::string_view archiveFilename,panda_file::File::OpenMode openMode)173 std::unique_ptr<const panda_file::File> HandleArchive(ZipArchiveHandle &handle, FILE *fp, std::string_view location,
174                                                       EntryFileStat &entry, std::string_view archiveFilename,
175                                                       panda_file::File::OpenMode openMode)
176 {
177     std::unique_ptr<const panda_file::File> file;
178     // compressed or not 4 aligned, use anonymous memory
179     if (entry.IsCompressed() || (entry.GetOffset() & 0x3U) != 0) {
180         file = OpenPandaFileFromZipFile(handle, location, entry, archiveFilename);
181     } else {
182         LOG(INFO, PANDAFILE) << "Pandafile is uncompressed and 4 bytes aligned";
183         file = panda_file::File::OpenUncompressedArchive(fileno(fp), location, entry.GetUncompressedSize(),
184                                                          entry.GetOffset(), openMode);
185     }
186     return file;
187 }
188 
OpenZipPandaFile(FILE * fp,std::string_view location,std::string_view archiveFilename,panda_file::File::OpenMode openMode)189 static std::unique_ptr<const panda_file::File> OpenZipPandaFile(FILE *fp, std::string_view location,
190                                                                 std::string_view archiveFilename,
191                                                                 panda_file::File::OpenMode openMode)
192 {
193     // Open Zipfile and do the extraction.
194     ZipArchiveHandle zipfile = nullptr;
195     auto openError = OpenArchiveFile(zipfile, fp);
196     if (openError != ZIPARCHIVE_OK) {
197         LOG(ERROR, PANDAFILE) << "Can't open archive " << location;
198         return nullptr;
199     }
200     bool tryDefault = archiveFilename.empty();
201     if (!tryDefault) {
202         if (LocateFile(zipfile, archiveFilename.data()) != ZIPARCHIVE_OK) {
203             LOG(INFO, PANDAFILE) << "Can't find entry with name '" << archiveFilename << "', will try "
204                                  << ARCHIVE_FILENAME;
205             tryDefault = true;
206         }
207     }
208     if (tryDefault) {
209         if (LocateFile(zipfile, ARCHIVE_FILENAME) != ZIPARCHIVE_OK) {
210             OpenPandaFileFromZipErrorHandler(zipfile);
211             LOG(ERROR, PANDAFILE) << "Can't find entry with " << ARCHIVE_FILENAME;
212             fclose(fp);
213             return nullptr;
214         }
215     }
216 
217     EntryFileStat entry = EntryFileStat();
218     if (GetCurrentFileInfo(zipfile, &entry) != ZIPARCHIVE_OK) {
219         OpenPandaFileFromZipErrorHandler(zipfile);
220         LOG(ERROR, PANDAFILE) << "GetCurrentFileInfo error";
221         return nullptr;
222     }
223     // check that file is not empty, otherwise crash at CloseArchiveFile
224     if (entry.GetUncompressedSize() == 0) {
225         OpenPandaFileFromZipErrorHandler(zipfile);
226         LOG(ERROR, PANDAFILE) << "Invalid panda file '" << (tryDefault ? ARCHIVE_FILENAME : archiveFilename) << "'";
227         return nullptr;
228     }
229     if (OpenCurrentFile(zipfile) != ZIPARCHIVE_OK) {
230         CloseCurrentFile(zipfile);
231         OpenPandaFileFromZipErrorHandler(zipfile);
232         LOG(ERROR, PANDAFILE) << "Can't OpenCurrentFile!";
233         return nullptr;
234     }
235     GetCurrentFileOffset(zipfile, &entry);
236     auto file = HandleArchive(zipfile, fp, location, entry, archiveFilename, openMode);
237     CloseCurrentFile(zipfile);
238     OpenPandaFileFromZipErrorHandler(zipfile);
239     return file;
240 }
241 
OpenPandaFile(std::string_view location,std::string_view archiveFilename,panda_file::File::OpenMode openMode)242 std::unique_ptr<const panda_file::File> OpenPandaFile(std::string_view location, std::string_view archiveFilename,
243                                                       panda_file::File::OpenMode openMode)
244 {
245     trace::ScopedTrace scopedTrace("Open panda file " + std::string(location));
246     uint32_t magic;
247 
248 #ifdef PANDA_TARGET_WINDOWS
249     constexpr char const *MODE = "rb";
250 #else
251     constexpr char const *MODE = "rbe";
252 #endif
253 
254     FILE *fp = fopen(std::string(location).c_str(), MODE);
255     if (fp == nullptr) {
256         LOG(ERROR, PANDAFILE) << "Can't fopen location: " << location;
257         return nullptr;
258     }
259     fseek(fp, 0, SEEK_SET);
260     if (fread(&magic, sizeof(magic), 1, fp) != 1) {
261         fclose(fp);
262         LOG(ERROR, PANDAFILE) << "Can't read from file!(magic) " << location;
263         return nullptr;
264     }
265     fseek(fp, 0, SEEK_SET);
266     std::unique_ptr<const panda_file::File> file;
267     if (IsZipMagic(magic)) {
268         file = OpenZipPandaFile(fp, location, archiveFilename, openMode);
269     } else {
270         file = panda_file::File::Open(location, openMode);
271     }
272     fclose(fp);
273     return file;
274 }
275 
OpenPandaFileFromMemory(const void * buffer,size_t size,std::string tag)276 std::unique_ptr<const File> OpenPandaFileFromMemory(const void *buffer, size_t size, std::string tag)
277 {
278     size_t sizeToMmap = AlignUp(size, ark::os::mem::GetPageSize());
279     void *mem = os::mem::MapRWAnonymousRaw(sizeToMmap, false);
280     if (mem == nullptr) {
281         return nullptr;
282     }
283 
284     if (memcpy_s(mem, sizeToMmap, buffer, size) != 0) {
285         PLOG(ERROR, PANDAFILE) << "Failed to copy buffer into mem'";
286     }
287 
288     if (!tag.empty()) {
289         if (tag == "ArkTS Code") {
290             std::string memAddr = std::to_string(ToUintPtr(mem));
291             tag = tag + ":" + memAddr;
292         }
293         auto ret = os::mem::TagAnonymousMemory(mem, sizeToMmap, tag.c_str());
294         if (ret.has_value()) {
295             PLOG(ERROR, PANDAFILE) << "Can't tag mmap anonymous, errno: " << errno;
296         }
297     }
298 
299     os::mem::ConstBytePtr ptr(reinterpret_cast<std::byte *>(mem), sizeToMmap, os::mem::MmapDeleter);
300     if (ptr.Get() == nullptr) {
301         PLOG(ERROR, PANDAFILE) << "Failed to open panda file from memory'";
302         return nullptr;
303     }
304     std::hash<void *> hash;
305     return panda_file::File::OpenFromMemory(std::move(ptr), std::to_string(hash(mem)));
306 }
307 
308 class ClassIdxIterator {
309 public:
310     // NOLINTNEXTLINE(readability-identifier-naming)
311     using value_type = const uint8_t *;
312     // NOLINTNEXTLINE(readability-identifier-naming)
313     using difference_type = std::ptrdiff_t;
314     // NOLINTNEXTLINE(readability-identifier-naming)
315     using pointer = uint32_t *;
316     // NOLINTNEXTLINE(readability-identifier-naming)
317     using reference = uint32_t &;
318     // NOLINTNEXTLINE(readability-identifier-naming)
319     using iterator_category = std::random_access_iterator_tag;
320 
ClassIdxIterator(const File & file,const Span<const uint32_t> & span,size_t idx)321     ClassIdxIterator(const File &file, const Span<const uint32_t> &span, size_t idx)
322         : file_(file), span_(span), idx_(idx)
323     {
324     }
325 
326     ClassIdxIterator(const ClassIdxIterator &other) = default;
327     ClassIdxIterator(ClassIdxIterator &&other) = default;
328     ~ClassIdxIterator() = default;
329 
operator =(const ClassIdxIterator & other)330     ClassIdxIterator &operator=(const ClassIdxIterator &other)
331     {
332         if (&other != this) {
333             idx_ = other.idx_;
334         }
335 
336         return *this;
337     }
338 
operator =(ClassIdxIterator && other)339     ClassIdxIterator &operator=(ClassIdxIterator &&other) noexcept
340     {
341         idx_ = other.idx_;
342         return *this;
343     }
344 
operator +=(size_t n)345     ClassIdxIterator &operator+=(size_t n)
346     {
347         idx_ += n;
348         return *this;
349     }
350 
operator -=(size_t n)351     ClassIdxIterator &operator-=(size_t n)
352     {
353         idx_ -= n;
354         return *this;
355     }
356 
operator ++()357     ClassIdxIterator &operator++()
358     {
359         ++idx_;
360         return *this;
361     }
362 
operator --()363     ClassIdxIterator &operator--()
364     {
365         --idx_;
366         return *this;
367     }
368 
operator -(const ClassIdxIterator & other)369     difference_type operator-(const ClassIdxIterator &other)
370     {
371         return static_cast<difference_type>(idx_ - other.idx_);
372     }
373 
operator *() const374     value_type operator*() const
375     {
376         uint32_t id = span_[idx_];
377         return file_.GetStringData(File::EntityId(id)).data;
378     }
379 
IsValid() const380     bool IsValid() const
381     {
382         return idx_ < span_.Size();
383     }
384 
GetId() const385     uint32_t GetId() const
386     {
387         return span_[idx_];
388     }
389 
Begin(const File & file,const Span<const uint32_t> & span)390     static ClassIdxIterator Begin(const File &file, const Span<const uint32_t> &span)
391     {
392         return ClassIdxIterator(file, span, 0);
393     }
394 
End(const File & file,const Span<const uint32_t> & span)395     static ClassIdxIterator End(const File &file, const Span<const uint32_t> &span)
396     {
397         return ClassIdxIterator(file, span, span.Size());
398     }
399 
400 private:
401     const File &file_;
402     const Span<const uint32_t> &span_;
403     size_t idx_;
404 };
405 
File(std::string filename,os::mem::ConstBytePtr && base)406 File::File(std::string filename, os::mem::ConstBytePtr &&base)
407     : base_(std::forward<os::mem::ConstBytePtr>(base)),
408       filename_(std::move(filename)),
409       filenameHash_(CalcFilenameHash(filename_)),
410       fullFilename_(os::GetAbsolutePath(filename_)),
411       pandaCache_(std::make_unique<PandaCache>()),
412       uniqId_(MergeHashes(filenameHash_, GetHash32(reinterpret_cast<const uint8_t *>(GetHeader()), sizeof(Header))))
413 {
414 }
415 
~File()416 File::~File()
417 {
418     AnonMemSet::GetInstance().Remove(filename_);
419 }
420 
VersionToString(const std::array<uint8_t,File::VERSION_SIZE> & array)421 inline std::string VersionToString(const std::array<uint8_t, File::VERSION_SIZE> &array)
422 {
423     std::stringstream ss;
424 
425     for (size_t i = 0; i < File::VERSION_SIZE - 1; ++i) {
426         ss << static_cast<int>(array[i]);
427         ss << ".";
428     }
429     ss << static_cast<int>(array[File::VERSION_SIZE - 1]);
430 
431     return ss.str();
432 }
433 
434 // We can't use default std::array's comparision operators and need to implement
435 // own ones due to the bug in gcc: https://gcc.gnu.org/bugzilla/show_bug.cgi?id=95189
CompareVersions(const std::array<uint8_t,File::VERSION_SIZE> & lhs,const std::array<uint8_t,File::VERSION_SIZE> & rhs)436 inline int CompareVersions(const std::array<uint8_t, File::VERSION_SIZE> &lhs,
437                            const std::array<uint8_t, File::VERSION_SIZE> &rhs)
438 {
439     for (size_t i = 0; i < File::VERSION_SIZE; i++) {
440         if (lhs[i] == rhs[i]) {
441             continue;
442         }
443         return lhs[i] - rhs[i];
444     }
445     return 0;
446 }
447 
operator <(const std::array<uint8_t,File::VERSION_SIZE> & lhs,const std::array<uint8_t,File::VERSION_SIZE> & rhs)448 inline bool operator<(const std::array<uint8_t, File::VERSION_SIZE> &lhs,
449                       const std::array<uint8_t, File::VERSION_SIZE> &rhs)
450 {
451     return CompareVersions(lhs, rhs) < 0;
452 }
453 
operator >(const std::array<uint8_t,File::VERSION_SIZE> & lhs,const std::array<uint8_t,File::VERSION_SIZE> & rhs)454 inline bool operator>(const std::array<uint8_t, File::VERSION_SIZE> &lhs,
455                       const std::array<uint8_t, File::VERSION_SIZE> &rhs)
456 {
457     return CompareVersions(lhs, rhs) > 0;
458 }
459 
460 /* static */
Open(std::string_view filename,OpenMode openMode)461 std::unique_ptr<const File> File::Open(std::string_view filename, OpenMode openMode)
462 {
463     trace::ScopedTrace scopedTrace("Open panda file " + std::string(filename));
464     os::file::Mode mode = GetMode(openMode);
465     os::file::File file = os::file::Open(filename, mode);
466     if (!file.IsValid()) {
467         PLOG(ERROR, PANDAFILE) << "Failed to open panda file '" << filename << "'";
468         return nullptr;
469     }
470 
471     os::file::FileHolder fhHolder(file);
472 
473     auto res = file.GetFileSize();
474     if (!res) {
475         PLOG(ERROR, PANDAFILE) << "Failed to get size of panda file '" << filename << "'";
476         return nullptr;
477     }
478 
479     size_t size = res.Value();
480     if (size < sizeof(File::Header)) {
481         LOG(ERROR, PANDAFILE) << "Invalid panda file '" << filename << "' - has not header";
482         return nullptr;
483     }
484 
485     os::mem::ConstBytePtr ptr = os::mem::MapFile(file, GetProt(openMode), os::mem::MMAP_FLAG_PRIVATE, size).ToConst();
486     if (ptr.Get() == nullptr) {
487         PLOG(ERROR, PANDAFILE) << "Failed to map panda file '" << filename << "'";
488         return nullptr;
489     }
490 
491     if (!CheckHeader(ptr, filename)) {
492         return nullptr;
493     }
494 
495     return std::unique_ptr<File>(new File(filename.data(), std::move(ptr)));
496 }
497 
OpenUncompressedArchive(int fd,const std::string_view & filename,size_t size,uint32_t offset,OpenMode openMode)498 std::unique_ptr<const File> File::OpenUncompressedArchive(int fd, const std::string_view &filename, size_t size,
499                                                           uint32_t offset, OpenMode openMode)
500 {
501     trace::ScopedTrace scopedTrace("Open panda file " + std::string(filename));
502     auto file = os::file::File(fd);
503     if (!file.IsValid()) {
504         PLOG(ERROR, PANDAFILE) << "OpenUncompressedArchive: Failed to open panda file '" << filename << "'";
505         return nullptr;
506     }
507 
508     if (size < sizeof(File::Header)) {
509         LOG(ERROR, PANDAFILE) << "Invalid panda file size '" << filename << "'";
510         return nullptr;
511     }
512     LOG(DEBUG, PANDAFILE) << " size=" << size << " offset=" << offset << " " << filename;
513 
514     os::mem::ConstBytePtr ptr =
515         os::mem::MapFile(file, GetProt(openMode), os::mem::MMAP_FLAG_PRIVATE, size, offset).ToConst();
516     if (ptr.Get() == nullptr) {
517         PLOG(ERROR, PANDAFILE) << "Failed to map panda file '" << filename << "'";
518         return nullptr;
519     }
520     if (!CheckHeader(ptr, filename)) {
521         return nullptr;
522     }
523 
524     return std::unique_ptr<File>(new File(filename.data(), std::move(ptr)));
525 }
526 
CheckHeader(const os::mem::ConstBytePtr & ptr,const std::string_view & filename)527 bool CheckHeader(const os::mem::ConstBytePtr &ptr, const std::string_view &filename)
528 {
529     if (ptr.Get() == nullptr || ptr.GetSize() < sizeof(File::Header)) {
530         LOG(ERROR, PANDAFILE) << "Invalid panda file '" << filename << "'";
531         return false;
532     }
533     auto header = reinterpret_cast<const File::Header *>(reinterpret_cast<uintptr_t>(ptr.Get()));
534     if (header->magic != File::MAGIC) {
535         LOG(ERROR, PANDAFILE) << "Invalid magic number '";
536         return false;
537     }
538 
539     auto fileVersion = header->version;
540 
541     if (fileVersion < MIN_VERSION || fileVersion > VERSION) {
542         LOG(ERROR, PANDAFILE) << "Unable to open file '" << filename << "' with bytecode version "
543                               << VersionToString(fileVersion);
544         if (fileVersion < MIN_VERSION) {
545             LOG(ERROR, PANDAFILE) << "Minimum supported version is " << VersionToString(MIN_VERSION);
546         } else {
547             LOG(ERROR, PANDAFILE) << "Maximum supported version is " << VersionToString(VERSION);
548         }
549         return false;
550     }
551 
552     return true;
553 }
554 
555 /* static */
OpenFromMemory(os::mem::ConstBytePtr && ptr)556 std::unique_ptr<const File> File::OpenFromMemory(os::mem::ConstBytePtr &&ptr)
557 {
558     if (!CheckHeader(ptr, std::string_view())) {
559         return nullptr;
560     }
561 
562     return std::unique_ptr<File>(new File("", std::forward<os::mem::ConstBytePtr>(ptr)));
563 }
564 
565 /* static */
OpenFromMemory(os::mem::ConstBytePtr && ptr,std::string_view filename)566 std::unique_ptr<const File> File::OpenFromMemory(os::mem::ConstBytePtr &&ptr, std::string_view filename)
567 {
568     trace::ScopedTrace scopedTrace("Open panda file from RAM " + std::string(filename));
569 
570     if (!CheckHeader(ptr, filename)) {
571         return nullptr;
572     }
573 
574     return std::unique_ptr<File>(new File(filename.data(), std::forward<os::mem::ConstBytePtr>(ptr)));
575 }
576 
GetClassId(const uint8_t * mutf8Name) const577 File::EntityId File::GetClassId(const uint8_t *mutf8Name) const
578 {
579     auto classHashTable = GetClassHashTable();
580     if (!classHashTable.empty()) {
581         return GetClassIdFromClassHashTable(mutf8Name);
582     }
583 
584     auto classIdx = GetClasses();
585 
586     auto it = std::lower_bound(ClassIdxIterator::Begin(*this, classIdx), ClassIdxIterator::End(*this, classIdx),
587                                mutf8Name, utf::Mutf8Less());
588     if (!it.IsValid()) {
589         return EntityId();
590     }
591 
592     if (utf::CompareMUtf8ToMUtf8(mutf8Name, *it) == 0) {
593         return EntityId(it.GetId());
594     }
595 
596     return EntityId();
597 }
598 
CalcFilenameHash(const std::string & filename)599 uint32_t File::CalcFilenameHash(const std::string &filename)
600 {
601     return GetHash32String(reinterpret_cast<const uint8_t *>(filename.c_str()));
602 }
603 
GetLiteralArraysId() const604 File::EntityId File::GetLiteralArraysId() const
605 {
606     const Header *header = GetHeader();
607     return EntityId(header->literalarrayIdxOff);
608 }
609 
GetClassIdFromClassHashTable(const uint8_t * mutf8Name) const610 File::EntityId File::GetClassIdFromClassHashTable(const uint8_t *mutf8Name) const
611 {
612     auto classHashTable = GetClassHashTable();
613     auto hash = GetHash32String(mutf8Name);
614     auto pos = hash & (classHashTable.size() - 1);
615     auto entityPair = &classHashTable[pos];
616 
617     if (entityPair->descriptorHash % classHashTable.size() != pos) {
618         return File::EntityId();
619     }
620 
621     while (true) {
622         if (hash == entityPair->descriptorHash) {
623             auto entityId = File::EntityId(entityPair->entityIdOffset);
624             auto descriptor = GetStringData(entityId).data;
625             if (entityId.IsValid() && utf::CompareMUtf8ToMUtf8(descriptor, mutf8Name) == 0) {
626                 return entityId;
627             }
628         }
629         if (entityPair->nextPos == 0) {
630             break;
631         }
632         entityPair = &classHashTable[entityPair->nextPos - 1];
633     }
634 
635     return File::EntityId();
636 }
637 
638 }  // namespace ark::panda_file
639