1 /*
2 * Copyright (c) 2021-2022 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 "disassembler.h"
17 #include "mangling.h"
18 #include "utils/logger.h"
19
20 #include <iomanip>
21
22 #include "get_language_specific_metadata.inc"
23
24 namespace panda::disasm {
25
Disassemble(const std::string & filename_in,const bool quiet,const bool skip_strings)26 void Disassembler::Disassemble(const std::string &filename_in, const bool quiet, const bool skip_strings)
27 {
28 auto file_new = panda_file::File::Open(filename_in);
29 file_.swap(file_new);
30
31 if (file_ != nullptr) {
32 prog_ = pandasm::Program {};
33
34 record_name_to_id_.clear();
35 method_name_to_id_.clear();
36
37 skip_strings_ = skip_strings;
38 quiet_ = quiet;
39
40 prog_info_ = ProgInfo {};
41
42 prog_ann_ = ProgAnnotations {};
43
44 GetRecords();
45 GetLiteralArrays();
46
47 GetLanguageSpecificMetadata();
48 } else {
49 LOG(ERROR, DISASSEMBLER) << "> unable to open specified pandafile: <" << filename_in << ">";
50 }
51 }
52
CollectInfo()53 void Disassembler::CollectInfo()
54 {
55 LOG(DEBUG, DISASSEMBLER) << "\n[getting program info]\n";
56
57 debug_info_extractor_ = std::make_unique<panda_file::DebugInfoExtractor>(file_.get());
58
59 for (const auto &pair : record_name_to_id_) {
60 GetRecordInfo(pair.second, &prog_info_.records_info[pair.first]);
61 }
62
63 for (const auto &pair : method_name_to_id_) {
64 GetMethodInfo(pair.second, &prog_info_.methods_info[pair.first]);
65 }
66 }
67
Serialize(std::ostream & os,bool add_separators,bool print_information) const68 void Disassembler::Serialize(std::ostream &os, bool add_separators, bool print_information) const
69 {
70 if (os.bad()) {
71 LOG(DEBUG, DISASSEMBLER) << "> serialization failed. os bad\n";
72
73 return;
74 }
75
76 if (file_ != nullptr) {
77 os << "# source binary: " << file_->GetFilename() << "\n\n";
78 }
79
80 SerializeLanguage(os);
81
82 if (add_separators) {
83 os << "# ====================\n"
84 "# LITERALS\n\n";
85 }
86
87 LOG(DEBUG, DISASSEMBLER) << "[serializing literals]";
88
89 for (const auto &[key, lit_arr] : prog_.literalarray_table) {
90 Serialize(key, lit_arr, os);
91 }
92
93 os << "\n";
94
95 if (add_separators) {
96 os << "# ====================\n"
97 "# RECORDS\n\n";
98 }
99
100 LOG(DEBUG, DISASSEMBLER) << "[serializing records]";
101
102 for (const auto &r : prog_.record_table) {
103 Serialize(r.second, os, print_information);
104 }
105
106 if (add_separators) {
107 os << "# ====================\n"
108 "# METHODS\n\n";
109 }
110
111 LOG(DEBUG, DISASSEMBLER) << "[serializing methods]";
112
113 for (const auto &m : prog_.function_table) {
114 Serialize(m.second, os, print_information);
115 }
116 }
117
IsSystemType(const std::string & type_name)118 inline bool Disassembler::IsSystemType(const std::string &type_name)
119 {
120 bool is_array_type = type_name.find('[') != std::string::npos;
121 bool is_global = type_name == "_GLOBAL";
122
123 return is_array_type || is_global;
124 }
125
GetRecord(pandasm::Record * record,const panda_file::File::EntityId & record_id)126 void Disassembler::GetRecord(pandasm::Record *record, const panda_file::File::EntityId &record_id)
127 {
128 LOG(DEBUG, DISASSEMBLER) << "\n[getting record]\nid: " << record_id << " (0x" << std::hex << record_id << ")";
129
130 if (record == nullptr) {
131 LOG(ERROR, DISASSEMBLER) << "> nullptr recieved, but record ptr expected!";
132
133 return;
134 }
135
136 record->name = GetFullRecordName(record_id);
137
138 LOG(DEBUG, DISASSEMBLER) << "name: " << record->name;
139
140 GetMetaData(record, record_id);
141
142 if (!file_->IsExternal(record_id)) {
143 GetMethods(record_id);
144 GetFields(record, record_id);
145 }
146 }
147
AddMethodToTables(const panda_file::File::EntityId & method_id)148 void Disassembler::AddMethodToTables(const panda_file::File::EntityId &method_id)
149 {
150 pandasm::Function new_method("", file_language_);
151 GetMethod(&new_method, method_id);
152
153 const auto signature = pandasm::GetFunctionSignatureFromName(new_method.name, new_method.params);
154 if (prog_.function_table.find(signature) != prog_.function_table.end()) {
155 return;
156 }
157
158 method_name_to_id_.emplace(signature, method_id);
159 prog_.function_synonyms[new_method.name].push_back(signature);
160 prog_.function_table.emplace(signature, std::move(new_method));
161 }
162
GetMethod(pandasm::Function * method,const panda_file::File::EntityId & method_id)163 void Disassembler::GetMethod(pandasm::Function *method, const panda_file::File::EntityId &method_id)
164 {
165 LOG(DEBUG, DISASSEMBLER) << "\n[getting method]\nid: " << method_id << " (0x" << std::hex << method_id << ")";
166
167 if (method == nullptr) {
168 LOG(ERROR, DISASSEMBLER) << "> nullptr recieved, but method ptr expected!";
169
170 return;
171 }
172
173 panda_file::MethodDataAccessor method_accessor(*file_, method_id);
174
175 method->name = GetFullMethodName(method_id);
176
177 LOG(DEBUG, DISASSEMBLER) << "name: " << method->name;
178
179 GetParams(method, method_accessor.GetProtoId());
180 GetMetaData(method, method_id);
181
182 if (method_accessor.GetCodeId().has_value()) {
183 const IdList id_list = GetInstructions(method, method_id, method_accessor.GetCodeId().value());
184
185 for (const auto &id : id_list) {
186 AddMethodToTables(id);
187 }
188 } else {
189 LOG(ERROR, DISASSEMBLER) << "> error encountered at " << method_id << " (0x" << std::hex << method_id
190 << "). implementation of method expected, but no \'CODE\' tag was found!";
191
192 return;
193 }
194 }
195
196 template <typename T>
FillLiteralArrayData(pandasm::LiteralArray * lit_array,const panda_file::LiteralTag & tag,const panda_file::LiteralDataAccessor::LiteralValue & value) const197 void Disassembler::FillLiteralArrayData(pandasm::LiteralArray *lit_array, const panda_file::LiteralTag &tag,
198 const panda_file::LiteralDataAccessor::LiteralValue &value) const
199 {
200 panda_file::File::EntityId id(std::get<uint32_t>(value));
201 auto sp = file_->GetSpanFromId(id);
202 auto len = panda_file::helpers::Read<sizeof(uint32_t)>(&sp);
203 if (tag != panda_file::LiteralTag::ARRAY_STRING) {
204 for (size_t i = 0; i < len; i++) {
205 pandasm::LiteralArray::Literal lit;
206 lit.tag_ = tag;
207 lit.value_ = bit_cast<T>(panda_file::helpers::Read<sizeof(T)>(&sp));
208 lit_array->literals_.push_back(lit);
209 }
210 return;
211 }
212 for (size_t i = 0; i < len; i++) {
213 auto str_id = panda_file::helpers::Read<sizeof(T)>(&sp);
214 pandasm::LiteralArray::Literal lit;
215 lit.tag_ = tag;
216 lit.value_ = StringDataToString(file_->GetStringData(panda_file::File::EntityId(str_id)));
217 lit_array->literals_.push_back(lit);
218 }
219 }
220
FillLiteralData(pandasm::LiteralArray * lit_array,const panda_file::LiteralDataAccessor::LiteralValue & value,const panda_file::LiteralTag & tag) const221 void Disassembler::FillLiteralData(pandasm::LiteralArray *lit_array,
222 const panda_file::LiteralDataAccessor::LiteralValue &value,
223 const panda_file::LiteralTag &tag) const
224 {
225 pandasm::LiteralArray::Literal lit;
226 lit.tag_ = tag;
227 switch (tag) {
228 case panda_file::LiteralTag::BOOL: {
229 lit.value_ = std::get<bool>(value);
230 break;
231 }
232 case panda_file::LiteralTag::ACCESSOR:
233 case panda_file::LiteralTag::NULLVALUE:
234 case panda_file::LiteralTag::BUILTINTYPEINDEX: {
235 lit.value_ = std::get<uint8_t>(value);
236 break;
237 }
238 case panda_file::LiteralTag::METHODAFFILIATE: {
239 lit.value_ = std::get<uint16_t>(value);
240 break;
241 }
242 case panda_file::LiteralTag::LITERALBUFFERINDEX:
243 case panda_file::LiteralTag::INTEGER: {
244 lit.value_ = std::get<uint32_t>(value);
245 break;
246 }
247 case panda_file::LiteralTag::DOUBLE: {
248 lit.value_ = std::get<double>(value);
249 break;
250 }
251 case panda_file::LiteralTag::STRING: {
252 auto str_data = file_->GetStringData(panda_file::File::EntityId(std::get<uint32_t>(value)));
253 lit.value_ = StringDataToString(str_data);
254 break;
255 }
256 case panda_file::LiteralTag::METHOD:
257 case panda_file::LiteralTag::GENERATORMETHOD: {
258 panda_file::MethodDataAccessor mda(*file_, panda_file::File::EntityId(std::get<uint32_t>(value)));
259 lit.value_ = StringDataToString(file_->GetStringData(mda.GetNameId()));
260 break;
261 }
262 case panda_file::LiteralTag::LITERALARRAY: {
263 std::stringstream ss;
264 ss << "0x" << std::hex << std::get<uint32_t>(value);
265 lit.value_ = ss.str();
266 break;
267 }
268 case panda_file::LiteralTag::TAGVALUE: {
269 return;
270 }
271 default: {
272 UNREACHABLE();
273 }
274 }
275 lit_array->literals_.push_back(lit);
276 }
277
GetLiteralArrayByOffset(pandasm::LiteralArray * lit_array,panda_file::File::EntityId offset) const278 void Disassembler::GetLiteralArrayByOffset(pandasm::LiteralArray *lit_array, panda_file::File::EntityId offset) const
279 {
280 panda_file::LiteralDataAccessor lit_array_accessor(*file_, file_->GetLiteralArraysId());
281 lit_array_accessor.EnumerateLiteralVals(
282 offset, [this, lit_array](const panda_file::LiteralDataAccessor::LiteralValue &value,
283 const panda_file::LiteralTag &tag) {
284 switch (tag) {
285 case panda_file::LiteralTag::ARRAY_U1: {
286 FillLiteralArrayData<bool>(lit_array, tag, value);
287 break;
288 }
289 case panda_file::LiteralTag::ARRAY_I8:
290 case panda_file::LiteralTag::ARRAY_U8: {
291 FillLiteralArrayData<uint8_t>(lit_array, tag, value);
292 break;
293 }
294 case panda_file::LiteralTag::ARRAY_I16:
295 case panda_file::LiteralTag::ARRAY_U16: {
296 FillLiteralArrayData<uint16_t>(lit_array, tag, value);
297 break;
298 }
299 case panda_file::LiteralTag::ARRAY_I32:
300 case panda_file::LiteralTag::ARRAY_U32: {
301 FillLiteralArrayData<uint32_t>(lit_array, tag, value);
302 break;
303 }
304 case panda_file::LiteralTag::ARRAY_I64:
305 case panda_file::LiteralTag::ARRAY_U64: {
306 FillLiteralArrayData<uint64_t>(lit_array, tag, value);
307 break;
308 }
309 case panda_file::LiteralTag::ARRAY_F32: {
310 FillLiteralArrayData<float>(lit_array, tag, value);
311 break;
312 }
313 case panda_file::LiteralTag::ARRAY_F64: {
314 FillLiteralArrayData<double>(lit_array, tag, value);
315 break;
316 }
317 case panda_file::LiteralTag::ARRAY_STRING: {
318 FillLiteralArrayData<uint32_t>(lit_array, tag, value);
319 break;
320 }
321 default: {
322 FillLiteralData(lit_array, value, tag);
323 break;
324 }
325 }
326 });
327 }
328
GetLiteralArray(pandasm::LiteralArray * lit_array,size_t index) const329 void Disassembler::GetLiteralArray(pandasm::LiteralArray *lit_array, size_t index) const
330 {
331 panda_file::LiteralDataAccessor lit_array_accessor(*file_, file_->GetLiteralArraysId());
332 GetLiteralArrayByOffset(lit_array, lit_array_accessor.GetLiteralArrayId(index));
333 }
334
IsModuleLiteralOffset(const panda_file::File::EntityId & id) const335 bool Disassembler::IsModuleLiteralOffset(const panda_file::File::EntityId &id) const
336 {
337 return module_literals_.find(id.GetOffset()) != module_literals_.end();
338 }
339
GetLiteralArrays()340 void Disassembler::GetLiteralArrays()
341 {
342 const auto lit_arrays_id = file_->GetLiteralArraysId();
343
344 LOG(DEBUG, DISASSEMBLER) << "\n[getting literal arrays]\nid: " << lit_arrays_id << " (0x" << std::hex
345 << lit_arrays_id << ")";
346
347 panda_file::LiteralDataAccessor lda(*file_, lit_arrays_id);
348 size_t num_litarrays = lda.GetLiteralNum();
349 for (size_t index = 0; index < num_litarrays; index++) {
350 auto id = lda.GetLiteralArrayId(index);
351 if (IsModuleLiteralOffset(id)) {
352 continue; // exclude module literals as they do not obey encoding rules of normal literals
353 }
354 std::stringstream ss;
355 ss << index << " 0x" << std::hex << id.GetOffset();
356 panda::pandasm::LiteralArray lit_arr;
357 GetLiteralArray(&lit_arr, index);
358 prog_.literalarray_table.emplace(ss.str(), lit_arr);
359 }
360 }
361
GetRecords()362 void Disassembler::GetRecords()
363 {
364 LOG(DEBUG, DISASSEMBLER) << "\n[getting records]\n";
365
366 const auto class_idx = file_->GetClasses();
367
368 for (size_t i = 0; i < class_idx.size(); i++) {
369 uint32_t class_id = class_idx[i];
370 auto class_off = file_->GetHeader()->class_idx_off + sizeof(uint32_t) * i;
371
372 if (class_id > file_->GetHeader()->file_size) {
373 LOG(ERROR, DISASSEMBLER) << "> error encountered in record at " << class_off << " (0x" << std::hex
374 << class_off << "). binary file corrupted. record offset (0x" << class_id
375 << ") out of bounds (0x" << file_->GetHeader()->file_size << ")!";
376 break;
377 }
378
379 const panda_file::File::EntityId record_id {class_id};
380 auto language = GetRecordLanguage(record_id);
381 if (language != file_language_) {
382 if (file_language_ == panda_file::SourceLang::PANDA_ASSEMBLY) {
383 file_language_ = language;
384 } else if (language != panda_file::SourceLang::PANDA_ASSEMBLY) {
385 LOG(ERROR, DISASSEMBLER) << "> possible error encountered in record at" << class_off << " (0x"
386 << std::hex << class_off << "). record's language ("
387 << panda_file::LanguageToString(language)
388 << ") differs from file's language ("
389 << panda_file::LanguageToString(file_language_) << ")!";
390 }
391 }
392
393 pandasm::Record record("", file_language_);
394 GetRecord(&record, record_id);
395
396 if (prog_.record_table.find(record.name) == prog_.record_table.end()) {
397 record_name_to_id_.emplace(record.name, record_id);
398 prog_.record_table.emplace(record.name, std::move(record));
399 }
400 }
401 }
402
GetFields(pandasm::Record * record,const panda_file::File::EntityId & record_id)403 void Disassembler::GetFields(pandasm::Record *record, const panda_file::File::EntityId &record_id)
404 {
405 panda_file::ClassDataAccessor class_accessor {*file_, record_id};
406
407 class_accessor.EnumerateFields([&](panda_file::FieldDataAccessor &field_accessor) -> void {
408 pandasm::Field field(file_language_);
409
410 panda_file::File::EntityId field_name_id = field_accessor.GetNameId();
411 field.name = StringDataToString(file_->GetStringData(field_name_id));
412
413 uint32_t field_type = field_accessor.GetType();
414 field.type = FieldTypeToPandasmType(field_type);
415
416 GetMetaData(&field, field_accessor.GetFieldId());
417
418 record->field_list.push_back(std::move(field));
419 });
420 }
421
GetMethods(const panda_file::File::EntityId & record_id)422 void Disassembler::GetMethods(const panda_file::File::EntityId &record_id)
423 {
424 panda_file::ClassDataAccessor class_accessor {*file_, record_id};
425
426 class_accessor.EnumerateMethods([&](panda_file::MethodDataAccessor &method_accessor) -> void {
427 AddMethodToTables(method_accessor.GetMethodId());
428 });
429 }
430
GetParams(pandasm::Function * method,const panda_file::File::EntityId & proto_id) const431 void Disassembler::GetParams(pandasm::Function *method, const panda_file::File::EntityId &proto_id) const
432 {
433 /**
434 * frame size - 2^16 - 1
435 */
436 static const uint32_t MAX_ARG_NUM = 0xFFFF;
437
438 LOG(DEBUG, DISASSEMBLER) << "[getting params]\nproto id: " << proto_id << " (0x" << std::hex << proto_id << ")";
439
440 if (method == nullptr) {
441 LOG(ERROR, DISASSEMBLER) << "> nullptr recieved, but method ptr expected!";
442
443 return;
444 }
445
446 panda_file::ProtoDataAccessor proto_accessor(*file_, proto_id);
447
448 auto params_num = proto_accessor.GetNumArgs();
449 if (params_num > MAX_ARG_NUM) {
450 LOG(ERROR, DISASSEMBLER) << "> error encountered at " << proto_id << " (0x" << std::hex << proto_id
451 << "). number of function's arguments (" << std::dec << params_num
452 << ") exceeds MAX_ARG_NUM (" << MAX_ARG_NUM << ") !";
453
454 return;
455 }
456
457 size_t ref_idx = 0;
458 method->return_type = PFTypeToPandasmType(proto_accessor.GetReturnType(), proto_accessor, ref_idx);
459
460 for (uint8_t i = 0; i < params_num; i++) {
461 auto arg_type = PFTypeToPandasmType(proto_accessor.GetArgType(i), proto_accessor, ref_idx);
462 method->params.push_back(pandasm::Function::Parameter(arg_type, file_language_));
463 }
464 }
465
GetExceptions(pandasm::Function * method,panda_file::File::EntityId method_id,panda_file::File::EntityId code_id) const466 LabelTable Disassembler::GetExceptions(pandasm::Function *method, panda_file::File::EntityId method_id,
467 panda_file::File::EntityId code_id) const
468 {
469 LOG(DEBUG, DISASSEMBLER) << "[getting exceptions]\ncode id: " << code_id << " (0x" << std::hex << code_id << ")";
470
471 if (method == nullptr) {
472 LOG(ERROR, DISASSEMBLER) << "> nullptr recieved, but method ptr expected!\n";
473 return LabelTable {};
474 }
475
476 panda_file::CodeDataAccessor code_accessor(*file_, code_id);
477
478 const auto bc_ins = BytecodeInstruction(code_accessor.GetInstructions());
479 const auto bc_ins_last = bc_ins.JumpTo(code_accessor.GetCodeSize());
480
481 size_t try_idx = 0;
482 LabelTable label_table {};
483 code_accessor.EnumerateTryBlocks([&](panda_file::CodeDataAccessor::TryBlock &try_block) {
484 pandasm::Function::CatchBlock catch_block_pa {};
485 if (!LocateTryBlock(bc_ins, bc_ins_last, try_block, &catch_block_pa, &label_table, try_idx)) {
486 return false;
487 }
488 size_t catch_idx = 0;
489 try_block.EnumerateCatchBlocks([&](panda_file::CodeDataAccessor::CatchBlock &catch_block) {
490 auto class_idx = catch_block.GetTypeIdx();
491 if (class_idx == panda_file::INVALID_INDEX) {
492 catch_block_pa.exception_record = "";
493 } else {
494 const auto class_id = file_->ResolveClassIndex(method_id, class_idx);
495 catch_block_pa.exception_record = GetFullRecordName(class_id);
496 }
497 if (!LocateCatchBlock(bc_ins, bc_ins_last, catch_block, &catch_block_pa, &label_table, try_idx,
498 catch_idx)) {
499 return false;
500 }
501
502 method->catch_blocks.push_back(catch_block_pa);
503 catch_block_pa.catch_begin_label = "";
504 catch_block_pa.catch_end_label = "";
505 catch_idx++;
506
507 return true;
508 });
509 try_idx++;
510
511 return true;
512 });
513
514 return label_table;
515 }
516
getBytecodeInstructionNumber(BytecodeInstruction bc_ins_first,BytecodeInstruction bc_ins_cur)517 static size_t getBytecodeInstructionNumber(BytecodeInstruction bc_ins_first, BytecodeInstruction bc_ins_cur)
518 {
519 size_t count = 0;
520
521 while (bc_ins_first.GetAddress() != bc_ins_cur.GetAddress()) {
522 count++;
523 bc_ins_first = bc_ins_first.GetNext();
524 if (bc_ins_first.GetAddress() > bc_ins_cur.GetAddress()) {
525 return std::numeric_limits<size_t>::max();
526 }
527 }
528
529 return count;
530 }
531
LocateTryBlock(const BytecodeInstruction & bc_ins,const BytecodeInstruction & bc_ins_last,const panda_file::CodeDataAccessor::TryBlock & try_block,pandasm::Function::CatchBlock * catch_block_pa,LabelTable * label_table,size_t try_idx) const532 bool Disassembler::LocateTryBlock(const BytecodeInstruction &bc_ins, const BytecodeInstruction &bc_ins_last,
533 const panda_file::CodeDataAccessor::TryBlock &try_block,
534 pandasm::Function::CatchBlock *catch_block_pa, LabelTable *label_table,
535 size_t try_idx) const
536 {
537 const auto try_begin_bc_ins = bc_ins.JumpTo(try_block.GetStartPc());
538 const auto try_end_bc_ins = bc_ins.JumpTo(try_block.GetStartPc() + try_block.GetLength());
539
540 const size_t try_begin_idx = getBytecodeInstructionNumber(bc_ins, try_begin_bc_ins);
541 const size_t try_end_idx = getBytecodeInstructionNumber(bc_ins, try_end_bc_ins);
542
543 const bool try_begin_offset_in_range = bc_ins_last.GetAddress() > try_begin_bc_ins.GetAddress();
544 const bool try_end_offset_in_range = bc_ins_last.GetAddress() >= try_end_bc_ins.GetAddress();
545 const bool try_begin_offset_valid = try_begin_idx != std::numeric_limits<size_t>::max();
546 const bool try_end_offset_valid = try_end_idx != std::numeric_limits<size_t>::max();
547
548 if (!try_begin_offset_in_range || !try_begin_offset_valid) {
549 LOG(ERROR, DISASSEMBLER) << "> invalid try block begin offset! address is: 0x" << std::hex
550 << try_begin_bc_ins.GetAddress();
551 return false;
552 } else {
553 std::stringstream ss {};
554 ss << "try_begin_label_" << try_idx;
555
556 LabelTable::iterator it = label_table->find(try_begin_idx);
557 if (it == label_table->end()) {
558 catch_block_pa->try_begin_label = ss.str();
559 label_table->insert(std::pair<size_t, std::string>(try_begin_idx, ss.str()));
560 } else {
561 catch_block_pa->try_begin_label = it->second;
562 }
563 }
564
565 if (!try_end_offset_in_range || !try_end_offset_valid) {
566 LOG(ERROR, DISASSEMBLER) << "> invalid try block end offset! address is: 0x" << std::hex
567 << try_end_bc_ins.GetAddress();
568 return false;
569 } else {
570 std::stringstream ss {};
571 ss << "try_end_label_" << try_idx;
572
573 LabelTable::iterator it = label_table->find(try_end_idx);
574 if (it == label_table->end()) {
575 catch_block_pa->try_end_label = ss.str();
576 label_table->insert(std::pair<size_t, std::string>(try_end_idx, ss.str()));
577 } else {
578 catch_block_pa->try_end_label = it->second;
579 }
580 }
581
582 return true;
583 }
584
LocateCatchBlock(const BytecodeInstruction & bc_ins,const BytecodeInstruction & bc_ins_last,const panda_file::CodeDataAccessor::CatchBlock & catch_block,pandasm::Function::CatchBlock * catch_block_pa,LabelTable * label_table,size_t try_idx,size_t catch_idx) const585 bool Disassembler::LocateCatchBlock(const BytecodeInstruction &bc_ins, const BytecodeInstruction &bc_ins_last,
586 const panda_file::CodeDataAccessor::CatchBlock &catch_block,
587 pandasm::Function::CatchBlock *catch_block_pa, LabelTable *label_table,
588 size_t try_idx, size_t catch_idx) const
589 {
590 const auto handler_begin_offset = catch_block.GetHandlerPc();
591 const auto handler_end_offset = handler_begin_offset + catch_block.GetCodeSize();
592
593 const auto handler_begin_bc_ins = bc_ins.JumpTo(handler_begin_offset);
594 const auto handler_end_bc_ins = bc_ins.JumpTo(handler_end_offset);
595
596 const size_t handler_begin_idx = getBytecodeInstructionNumber(bc_ins, handler_begin_bc_ins);
597 const size_t handler_end_idx = getBytecodeInstructionNumber(bc_ins, handler_end_bc_ins);
598
599 const bool handler_begin_offset_in_range = bc_ins_last.GetAddress() > handler_begin_bc_ins.GetAddress();
600 const bool handler_end_offset_in_range = bc_ins_last.GetAddress() > handler_end_bc_ins.GetAddress();
601 const bool handler_end_present = catch_block.GetCodeSize() != 0;
602 const bool handler_begin_offset_valid = handler_begin_idx != std::numeric_limits<size_t>::max();
603 const bool handler_end_offset_valid = handler_end_idx != std::numeric_limits<size_t>::max();
604
605 if (!handler_begin_offset_in_range || !handler_begin_offset_valid) {
606 LOG(ERROR, DISASSEMBLER) << "> invalid catch block begin offset! address is: 0x" << std::hex
607 << handler_begin_bc_ins.GetAddress();
608 return false;
609 } else {
610 std::stringstream ss {};
611 ss << "handler_begin_label_" << try_idx << "_" << catch_idx;
612
613 LabelTable::iterator it = label_table->find(handler_begin_idx);
614 if (it == label_table->end()) {
615 catch_block_pa->catch_begin_label = ss.str();
616 label_table->insert(std::pair<size_t, std::string>(handler_begin_idx, ss.str()));
617 } else {
618 catch_block_pa->catch_begin_label = it->second;
619 }
620 }
621
622 if (!handler_end_offset_in_range || !handler_end_offset_valid) {
623 LOG(ERROR, DISASSEMBLER) << "> invalid catch block end offset! address is: 0x" << std::hex
624 << handler_end_bc_ins.GetAddress();
625 return false;
626 } else if (handler_end_present) {
627 std::stringstream ss {};
628 ss << "handler_end_label_" << try_idx << "_" << catch_idx;
629
630 LabelTable::iterator it = label_table->find(handler_end_idx);
631 if (it == label_table->end()) {
632 catch_block_pa->catch_end_label = ss.str();
633 label_table->insert(std::pair<size_t, std::string>(handler_end_idx, ss.str()));
634 } else {
635 catch_block_pa->catch_end_label = it->second;
636 }
637 }
638
639 return true;
640 }
641
GetMetaData(pandasm::Function * method,const panda_file::File::EntityId & method_id) const642 void Disassembler::GetMetaData(pandasm::Function *method, const panda_file::File::EntityId &method_id) const
643 {
644 LOG(DEBUG, DISASSEMBLER) << "[getting metadata]\nmethod id: " << method_id << " (0x" << std::hex << method_id
645 << ")";
646
647 if (method == nullptr) {
648 LOG(ERROR, DISASSEMBLER) << "> nullptr recieved, but method ptr expected!";
649
650 return;
651 }
652
653 panda_file::MethodDataAccessor method_accessor(*file_, method_id);
654
655 const auto method_name_raw = StringDataToString(file_->GetStringData(method_accessor.GetNameId()));
656
657 if (!method_accessor.IsStatic()) {
658 const auto class_name = StringDataToString(file_->GetStringData(method_accessor.GetClassId()));
659 auto this_type = pandasm::Type::FromDescriptor(class_name);
660
661 LOG(DEBUG, DISASSEMBLER) << "method (raw: \'" << method_name_raw
662 << "\') is not static. emplacing self-argument of type " << this_type.GetName();
663
664 method->params.insert(method->params.begin(), pandasm::Function::Parameter(this_type, file_language_));
665 } else {
666 method->metadata->SetAttribute("static");
667 }
668
669 if (file_->IsExternal(method_accessor.GetMethodId())) {
670 method->metadata->SetAttribute("external");
671 }
672
673 std::string ctor_name = panda::panda_file::GetCtorName(file_language_);
674 std::string cctor_name = panda::panda_file::GetCctorName(file_language_);
675
676 const bool is_ctor = (method_name_raw == ctor_name);
677 const bool is_cctor = (method_name_raw == cctor_name);
678
679 if (is_ctor) {
680 method->metadata->SetAttribute("ctor");
681 method->name.replace(method->name.find(ctor_name), ctor_name.length(), "_ctor_");
682 } else if (is_cctor) {
683 method->metadata->SetAttribute("cctor");
684 method->name.replace(method->name.find(cctor_name), cctor_name.length(), "_cctor_");
685 }
686 }
687
GetMetaData(pandasm::Record * record,const panda_file::File::EntityId & record_id) const688 void Disassembler::GetMetaData(pandasm::Record *record, const panda_file::File::EntityId &record_id) const
689 {
690 LOG(DEBUG, DISASSEMBLER) << "[getting metadata]\nrecord id: " << record_id << " (0x" << std::hex << record_id
691 << ")";
692
693 if (record == nullptr) {
694 LOG(ERROR, DISASSEMBLER) << "> nullptr recieved, but record ptr expected!";
695
696 return;
697 }
698
699 if (file_->IsExternal(record_id)) {
700 record->metadata->SetAttribute("external");
701 }
702 }
703
GetMetaData(pandasm::Field * field,const panda_file::File::EntityId & field_id)704 void Disassembler::GetMetaData(pandasm::Field *field, const panda_file::File::EntityId &field_id)
705 {
706 LOG(DEBUG, DISASSEMBLER) << "[getting metadata]\nfield id: " << field_id << " (0x" << std::hex << field_id << ")";
707
708 if (field == nullptr) {
709 LOG(ERROR, DISASSEMBLER) << "> nullptr recieved, but method ptr expected!";
710
711 return;
712 }
713
714 panda_file::FieldDataAccessor field_accessor(*file_, field_id);
715
716 if (field_accessor.IsExternal()) {
717 field->metadata->SetAttribute("external");
718 }
719
720 if (field_accessor.IsStatic()) {
721 field->metadata->SetAttribute("static");
722 }
723
724 if (field->type.GetId() == panda_file::Type::TypeId::U32) {
725 const auto offset = field_accessor.GetValue<uint32_t>().value();
726 static const std::string TYPE_SUMMARY_FIELD_NAME = "typeSummaryOffset";
727 if (field->name != TYPE_SUMMARY_FIELD_NAME) {
728 LOG(DEBUG, DISASSEMBLER) << "Module literalarray " << field->name << " at offset 0x" << std::hex << offset
729 << " is excluded";
730 module_literals_.insert(offset);
731 }
732 field->metadata->SetValue(pandasm::ScalarValue::Create<pandasm::Value::Type::U32>(offset));
733 }
734 if (field->type.GetId() == panda_file::Type::TypeId::U8) {
735 const auto val = field_accessor.GetValue<uint8_t>().value();
736 field->metadata->SetValue(pandasm::ScalarValue::Create<pandasm::Value::Type::U8>(val));
737 }
738 }
739
AnnotationTagToString(const char tag) const740 std::string Disassembler::AnnotationTagToString(const char tag) const
741 {
742 switch (tag) {
743 case '1':
744 return "u1";
745 case '2':
746 return "i8";
747 case '3':
748 return "u8";
749 case '4':
750 return "i16";
751 case '5':
752 return "u16";
753 case '6':
754 return "i32";
755 case '7':
756 return "u32";
757 case '8':
758 return "i64";
759 case '9':
760 return "u64";
761 case 'A':
762 return "f32";
763 case 'B':
764 return "f64";
765 case 'C':
766 return "string";
767 case 'D':
768 return "record";
769 case 'E':
770 return "method";
771 case 'F':
772 return "enum";
773 case 'G':
774 return "annotation";
775 case 'I':
776 return "void";
777 case 'J':
778 return "method_handle";
779 case 'K':
780 return "u1[]";
781 case 'L':
782 return "i8[]";
783 case 'M':
784 return "u8[]";
785 case 'N':
786 return "i16[]";
787 case 'O':
788 return "u16[]";
789 case 'P':
790 return "i32[]";
791 case 'Q':
792 return "u32[]";
793 case 'R':
794 return "i64[]";
795 case 'S':
796 return "u64[]";
797 case 'T':
798 return "f32[]";
799 case 'U':
800 return "f64[]";
801 case 'V':
802 return "string[]";
803 case 'W':
804 return "record[]";
805 case 'X':
806 return "method[]";
807 case 'Y':
808 return "enum[]";
809 case 'Z':
810 return "annotation[]";
811 case '@':
812 return "method_handle[]";
813 case '*':
814 return "nullptr string";
815 default:
816 return std::string();
817 }
818 }
819
ScalarValueToString(const panda_file::ScalarValue & value,const std::string & type)820 std::string Disassembler::ScalarValueToString(const panda_file::ScalarValue &value, const std::string &type)
821 {
822 std::stringstream ss;
823
824 if (type == "i8") {
825 int8_t res = value.Get<int8_t>();
826 ss << static_cast<int>(res);
827 } else if (type == "u1" || type == "u8") {
828 uint8_t res = value.Get<uint8_t>();
829 ss << static_cast<unsigned int>(res);
830 } else if (type == "i16") {
831 ss << value.Get<int16_t>();
832 } else if (type == "u16") {
833 ss << value.Get<uint16_t>();
834 } else if (type == "i32") {
835 ss << value.Get<int32_t>();
836 } else if (type == "u32") {
837 ss << value.Get<uint32_t>();
838 } else if (type == "i64") {
839 ss << value.Get<int64_t>();
840 } else if (type == "u64") {
841 ss << value.Get<uint64_t>();
842 } else if (type == "f32") {
843 ss << value.Get<float>();
844 } else if (type == "f64") {
845 ss << value.Get<double>();
846 } else if (type == "string") {
847 const auto id = value.Get<panda_file::File::EntityId>();
848 ss << "\"" << StringDataToString(file_->GetStringData(id)) << "\"";
849 } else if (type == "record") {
850 const auto id = value.Get<panda_file::File::EntityId>();
851 ss << GetFullRecordName(id);
852 } else if (type == "method") {
853 const auto id = value.Get<panda_file::File::EntityId>();
854 AddMethodToTables(id);
855 ss << GetMethodSignature(id);
856 } else if (type == "enum") {
857 const auto id = value.Get<panda_file::File::EntityId>();
858 panda_file::FieldDataAccessor field_accessor(*file_, id);
859 ss << GetFullRecordName(field_accessor.GetClassId()) << "."
860 << StringDataToString(file_->GetStringData(field_accessor.GetNameId()));
861 } else if (type == "annotation") {
862 const auto id = value.Get<panda_file::File::EntityId>();
863 ss << "id_" << id;
864 } else if (type == "void") {
865 return std::string();
866 } else if (type == "method_handle") {
867 }
868
869 return ss.str();
870 }
871
ArrayValueToString(const panda_file::ArrayValue & value,const std::string & type,const size_t idx)872 std::string Disassembler::ArrayValueToString(const panda_file::ArrayValue &value, const std::string &type,
873 const size_t idx)
874 {
875 std::stringstream ss;
876
877 if (type == "i8") {
878 int8_t res = value.Get<int8_t>(idx);
879 ss << static_cast<int>(res);
880 } else if (type == "u1" || type == "u8") {
881 uint8_t res = value.Get<uint8_t>(idx);
882 ss << static_cast<unsigned int>(res);
883 } else if (type == "i16") {
884 ss << value.Get<int16_t>(idx);
885 } else if (type == "u16") {
886 ss << value.Get<uint16_t>(idx);
887 } else if (type == "i32") {
888 ss << value.Get<int32_t>(idx);
889 } else if (type == "u32") {
890 ss << value.Get<uint32_t>(idx);
891 } else if (type == "i64") {
892 ss << value.Get<int64_t>(idx);
893 } else if (type == "u64") {
894 ss << value.Get<uint64_t>(idx);
895 } else if (type == "f32") {
896 ss << value.Get<float>(idx);
897 } else if (type == "f64") {
898 ss << value.Get<double>(idx);
899 } else if (type == "string") {
900 const auto id = value.Get<panda_file::File::EntityId>(idx);
901 ss << '\"' << StringDataToString(file_->GetStringData(id)) << '\"';
902 } else if (type == "record") {
903 const auto id = value.Get<panda_file::File::EntityId>(idx);
904 ss << GetFullRecordName(id);
905 } else if (type == "method") {
906 const auto id = value.Get<panda_file::File::EntityId>(idx);
907 AddMethodToTables(id);
908 ss << GetMethodSignature(id);
909 } else if (type == "enum") {
910 const auto id = value.Get<panda_file::File::EntityId>(idx);
911 panda_file::FieldDataAccessor field_accessor(*file_, id);
912 ss << GetFullRecordName(field_accessor.GetClassId()) << "."
913 << StringDataToString(file_->GetStringData(field_accessor.GetNameId()));
914 } else if (type == "annotation") {
915 const auto id = value.Get<panda_file::File::EntityId>(idx);
916 ss << "id_" << id;
917 } else if (type == "method_handle") {
918 } else if (type == "nullptr string") {
919 }
920
921 return ss.str();
922 }
923
GetFullMethodName(const panda_file::File::EntityId & method_id) const924 std::string Disassembler::GetFullMethodName(const panda_file::File::EntityId &method_id) const
925 {
926 panda::panda_file::MethodDataAccessor method_accessor(*file_, method_id);
927
928 const auto method_name_raw = StringDataToString(file_->GetStringData(method_accessor.GetNameId()));
929
930 std::string class_name = GetFullRecordName(method_accessor.GetClassId());
931 if (IsSystemType(class_name)) {
932 class_name = "";
933 } else {
934 class_name += ".";
935 }
936
937 return class_name + method_name_raw;
938 }
939
GetMethodSignature(const panda_file::File::EntityId & method_id) const940 std::string Disassembler::GetMethodSignature(const panda_file::File::EntityId &method_id) const
941 {
942 panda::panda_file::MethodDataAccessor method_accessor(*file_, method_id);
943
944 pandasm::Function method(GetFullMethodName(method_id), file_language_);
945 GetParams(&method, method_accessor.GetProtoId());
946 GetMetaData(&method, method_id);
947
948 return pandasm::GetFunctionSignatureFromName(method.name, method.params);
949 }
950
GetFullRecordName(const panda_file::File::EntityId & class_id) const951 std::string Disassembler::GetFullRecordName(const panda_file::File::EntityId &class_id) const
952 {
953 std::string name = StringDataToString(file_->GetStringData(class_id));
954
955 auto type = pandasm::Type::FromDescriptor(name);
956 type = pandasm::Type(type.GetComponentName(), type.GetRank());
957
958 return type.GetPandasmName();
959 }
960
GetRecordInfo(const panda_file::File::EntityId & record_id,RecordInfo * record_info) const961 void Disassembler::GetRecordInfo(const panda_file::File::EntityId &record_id, RecordInfo *record_info) const
962 {
963 constexpr size_t DEFAULT_OFFSET_WIDTH = 4;
964
965 if (file_->IsExternal(record_id)) {
966 return;
967 }
968
969 panda_file::ClassDataAccessor class_accessor {*file_, record_id};
970 std::stringstream ss;
971
972 ss << "offset: 0x" << std::setfill('0') << std::setw(DEFAULT_OFFSET_WIDTH) << std::hex
973 << class_accessor.GetClassId() << ", size: 0x" << std::setfill('0') << std::setw(DEFAULT_OFFSET_WIDTH)
974 << class_accessor.GetSize() << " (" << std::dec << class_accessor.GetSize() << ")";
975
976 record_info->record_info = ss.str();
977 ss.str(std::string());
978
979 class_accessor.EnumerateFields([&](panda_file::FieldDataAccessor &field_accessor) -> void {
980 ss << "offset: 0x" << std::setfill('0') << std::setw(DEFAULT_OFFSET_WIDTH) << std::hex
981 << field_accessor.GetFieldId();
982
983 record_info->fields_info.push_back(ss.str());
984
985 ss.str(std::string());
986 });
987 }
988
GetMethodInfo(const panda_file::File::EntityId & method_id,MethodInfo * method_info) const989 void Disassembler::GetMethodInfo(const panda_file::File::EntityId &method_id, MethodInfo *method_info) const
990 {
991 constexpr size_t DEFAULT_OFFSET_WIDTH = 4;
992
993 panda_file::MethodDataAccessor method_accessor {*file_, method_id};
994 std::stringstream ss;
995
996 ss << "offset: 0x" << std::setfill('0') << std::setw(DEFAULT_OFFSET_WIDTH) << std::hex
997 << method_accessor.GetMethodId();
998
999 if (method_accessor.GetCodeId().has_value()) {
1000 ss << ", code offset: 0x" << std::setfill('0') << std::setw(DEFAULT_OFFSET_WIDTH) << std::hex
1001 << method_accessor.GetCodeId().value();
1002
1003 GetInsInfo(method_accessor.GetCodeId().value(), method_info);
1004 } else {
1005 ss << ", <no code>";
1006 }
1007
1008 method_info->method_info = ss.str();
1009
1010 if (method_accessor.GetCodeId()) {
1011 ASSERT(debug_info_extractor_ != nullptr);
1012 method_info->line_number_table = debug_info_extractor_->GetLineNumberTable(method_id);
1013 method_info->local_variable_table = debug_info_extractor_->GetLocalVariableTable(method_id);
1014
1015 // Add information about parameters into the table
1016 panda_file::CodeDataAccessor codeda(*file_, method_accessor.GetCodeId().value());
1017 auto arg_idx = static_cast<int32_t>(codeda.GetNumVregs());
1018 uint32_t code_size = codeda.GetCodeSize();
1019 for (auto info : debug_info_extractor_->GetParameterInfo(method_id)) {
1020 panda_file::LocalVariableInfo arg_info {info.name, info.signature, "", arg_idx++, 0, code_size};
1021 method_info->local_variable_table.emplace_back(arg_info);
1022 }
1023 }
1024 }
1025
IsArray(const panda_file::LiteralTag & tag)1026 static bool IsArray(const panda_file::LiteralTag &tag)
1027 {
1028 switch (tag) {
1029 case panda_file::LiteralTag::ARRAY_U1:
1030 case panda_file::LiteralTag::ARRAY_U8:
1031 case panda_file::LiteralTag::ARRAY_I8:
1032 case panda_file::LiteralTag::ARRAY_U16:
1033 case panda_file::LiteralTag::ARRAY_I16:
1034 case panda_file::LiteralTag::ARRAY_U32:
1035 case panda_file::LiteralTag::ARRAY_I32:
1036 case panda_file::LiteralTag::ARRAY_U64:
1037 case panda_file::LiteralTag::ARRAY_I64:
1038 case panda_file::LiteralTag::ARRAY_F32:
1039 case panda_file::LiteralTag::ARRAY_F64:
1040 case panda_file::LiteralTag::ARRAY_STRING:
1041 return true;
1042 default:
1043 return false;
1044 }
1045 }
1046
SerializeLiteralArray(const pandasm::LiteralArray & lit_array) const1047 std::string Disassembler::SerializeLiteralArray(const pandasm::LiteralArray &lit_array) const
1048 {
1049 std::stringstream ret;
1050 if (lit_array.literals_.empty()) {
1051 return "";
1052 }
1053
1054 std::stringstream ss;
1055 ss << "{ ";
1056 const auto &tag = lit_array.literals_[0].tag_;
1057 if (IsArray(tag)) {
1058 ss << LiteralTagToString(tag);
1059 }
1060 ss << lit_array.literals_.size();
1061 ss << " [ ";
1062 SerializeValues(lit_array, ss);
1063 ss << "]}";
1064 return ss.str();
1065 }
1066
Serialize(const std::string & key,const pandasm::LiteralArray & lit_array,std::ostream & os) const1067 void Disassembler::Serialize(const std::string &key, const pandasm::LiteralArray &lit_array, std::ostream &os) const
1068 {
1069 os << key << " ";
1070 os << SerializeLiteralArray(lit_array);
1071 os << "\n";
1072 }
1073
LiteralTagToString(const panda_file::LiteralTag & tag) const1074 std::string Disassembler::LiteralTagToString(const panda_file::LiteralTag &tag) const
1075 {
1076 switch (tag) {
1077 case panda_file::LiteralTag::BOOL:
1078 case panda_file::LiteralTag::ARRAY_U1:
1079 return "u1";
1080 case panda_file::LiteralTag::ARRAY_U8:
1081 return "u8";
1082 case panda_file::LiteralTag::ARRAY_I8:
1083 return "i8";
1084 case panda_file::LiteralTag::ARRAY_U16:
1085 return "u16";
1086 case panda_file::LiteralTag::ARRAY_I16:
1087 return "i16";
1088 case panda_file::LiteralTag::ARRAY_U32:
1089 return "u32";
1090 case panda_file::LiteralTag::INTEGER:
1091 case panda_file::LiteralTag::ARRAY_I32:
1092 return "i32";
1093 case panda_file::LiteralTag::ARRAY_U64:
1094 return "u64";
1095 case panda_file::LiteralTag::ARRAY_I64:
1096 return "i64";
1097 case panda_file::LiteralTag::ARRAY_F32:
1098 return "f32";
1099 case panda_file::LiteralTag::DOUBLE:
1100 case panda_file::LiteralTag::ARRAY_F64:
1101 return "f64";
1102 case panda_file::LiteralTag::STRING:
1103 case panda_file::LiteralTag::ARRAY_STRING:
1104 return "string";
1105 case panda_file::LiteralTag::METHOD:
1106 return "method";
1107 case panda_file::LiteralTag::GENERATORMETHOD:
1108 return "generator_method";
1109 case panda_file::LiteralTag::ACCESSOR:
1110 return "accessor";
1111 case panda_file::LiteralTag::METHODAFFILIATE:
1112 return "method_affiliate";
1113 case panda_file::LiteralTag::NULLVALUE:
1114 return "null_value";
1115 case panda_file::LiteralTag::TAGVALUE:
1116 return "tagvalue";
1117 case panda_file::LiteralTag::LITERALBUFFERINDEX:
1118 return "lit_index";
1119 case panda_file::LiteralTag::LITERALARRAY:
1120 return "lit_offset";
1121 case panda_file::LiteralTag::BUILTINTYPEINDEX:
1122 return "builtin_type";
1123 default:
1124 UNREACHABLE();
1125 }
1126 }
1127
1128 template <typename T>
SerializeValues(const pandasm::LiteralArray & lit_array,T & os) const1129 void Disassembler::SerializeValues(const pandasm::LiteralArray &lit_array, T &os) const
1130 {
1131 switch (lit_array.literals_[0].tag_) {
1132 case panda_file::LiteralTag::ARRAY_U1: {
1133 for (size_t i = 0; i < lit_array.literals_.size(); i++) {
1134 os << std::get<bool>(lit_array.literals_[i].value_) << " ";
1135 }
1136 break;
1137 }
1138 case panda_file::LiteralTag::ARRAY_U8: {
1139 for (size_t i = 0; i < lit_array.literals_.size(); i++) {
1140 os << static_cast<uint16_t>(std::get<uint8_t>(lit_array.literals_[i].value_)) << " ";
1141 }
1142 break;
1143 }
1144 case panda_file::LiteralTag::ARRAY_I8: {
1145 for (size_t i = 0; i < lit_array.literals_.size(); i++) {
1146 os << static_cast<int16_t>(bit_cast<int8_t>(std::get<uint8_t>(lit_array.literals_[i].value_))) << " ";
1147 }
1148 break;
1149 }
1150 case panda_file::LiteralTag::ARRAY_U16: {
1151 for (size_t i = 0; i < lit_array.literals_.size(); i++) {
1152 os << std::get<uint16_t>(lit_array.literals_[i].value_) << " ";
1153 }
1154 break;
1155 }
1156 case panda_file::LiteralTag::ARRAY_I16: {
1157 for (size_t i = 0; i < lit_array.literals_.size(); i++) {
1158 os << bit_cast<int16_t>(std::get<uint16_t>(lit_array.literals_[i].value_)) << " ";
1159 }
1160 break;
1161 }
1162 case panda_file::LiteralTag::ARRAY_U32: {
1163 for (size_t i = 0; i < lit_array.literals_.size(); i++) {
1164 os << std::get<uint32_t>(lit_array.literals_[i].value_) << " ";
1165 }
1166 break;
1167 }
1168 case panda_file::LiteralTag::ARRAY_I32: {
1169 for (size_t i = 0; i < lit_array.literals_.size(); i++) {
1170 os << bit_cast<int32_t>(std::get<uint32_t>(lit_array.literals_[i].value_)) << " ";
1171 }
1172 break;
1173 }
1174 case panda_file::LiteralTag::ARRAY_U64: {
1175 for (size_t i = 0; i < lit_array.literals_.size(); i++) {
1176 os << std::get<uint64_t>(lit_array.literals_[i].value_) << " ";
1177 }
1178 break;
1179 }
1180 case panda_file::LiteralTag::ARRAY_I64: {
1181 for (size_t i = 0; i < lit_array.literals_.size(); i++) {
1182 os << bit_cast<int64_t>(std::get<uint64_t>(lit_array.literals_[i].value_)) << " ";
1183 }
1184 break;
1185 }
1186 case panda_file::LiteralTag::ARRAY_F32: {
1187 for (size_t i = 0; i < lit_array.literals_.size(); i++) {
1188 os << std::get<float>(lit_array.literals_[i].value_) << " ";
1189 }
1190 break;
1191 }
1192 case panda_file::LiteralTag::ARRAY_F64: {
1193 for (size_t i = 0; i < lit_array.literals_.size(); i++) {
1194 os << std::get<double>(lit_array.literals_[i].value_) << " ";
1195 }
1196 break;
1197 }
1198 case panda_file::LiteralTag::ARRAY_STRING: {
1199 for (size_t i = 0; i < lit_array.literals_.size(); i++) {
1200 os << "\"" << std::get<std::string>(lit_array.literals_[i].value_) << "\" ";
1201 }
1202 break;
1203 }
1204 default:
1205 SerializeLiterals(lit_array, os);
1206 }
1207 }
1208
1209 template <typename T>
SerializeLiterals(const pandasm::LiteralArray & lit_array,T & os) const1210 void Disassembler::SerializeLiterals(const pandasm::LiteralArray &lit_array, T &os) const
1211 {
1212 for (size_t i = 0; i < lit_array.literals_.size(); i++) {
1213 const auto &tag = lit_array.literals_[i].tag_;
1214 os << LiteralTagToString(tag) << ":";
1215 const auto &val = lit_array.literals_[i].value_;
1216 switch (lit_array.literals_[i].tag_) {
1217 case panda_file::LiteralTag::BOOL: {
1218 os << std::get<bool>(val);
1219 break;
1220 }
1221 case panda_file::LiteralTag::LITERALBUFFERINDEX:
1222 case panda_file::LiteralTag::INTEGER: {
1223 os << bit_cast<int32_t>(std::get<uint32_t>(val));
1224 break;
1225 }
1226 case panda_file::LiteralTag::DOUBLE: {
1227 os << std::get<double>(val);
1228 break;
1229 }
1230 case panda_file::LiteralTag::STRING: {
1231 os << "\"" << std::get<std::string>(val) << "\"";
1232 break;
1233 }
1234 case panda_file::LiteralTag::METHOD:
1235 case panda_file::LiteralTag::GENERATORMETHOD: {
1236 os << std::get<std::string>(val);
1237 break;
1238 }
1239 case panda_file::LiteralTag::NULLVALUE:
1240 case panda_file::LiteralTag::ACCESSOR: {
1241 os << static_cast<int16_t>(bit_cast<int8_t>(std::get<uint8_t>(val)));
1242 break;
1243 }
1244 case panda_file::LiteralTag::METHODAFFILIATE: {
1245 os << std::get<uint16_t>(val);
1246 break;
1247 }
1248 case panda_file::LiteralTag::LITERALARRAY: {
1249 os << std::get<std::string>(val);
1250 break;
1251 }
1252 case panda_file::LiteralTag::BUILTINTYPEINDEX: {
1253 os << static_cast<int16_t>(std::get<uint8_t>(val));
1254 break;
1255 }
1256 default:
1257 UNREACHABLE();
1258 }
1259 os << ", ";
1260 }
1261 }
1262
Serialize(const pandasm::Record & record,std::ostream & os,bool print_information) const1263 void Disassembler::Serialize(const pandasm::Record &record, std::ostream &os, bool print_information) const
1264 {
1265 if (IsSystemType(record.name)) {
1266 return;
1267 }
1268
1269 os << ".record " << record.name;
1270
1271 const auto record_iter = prog_ann_.record_annotations.find(record.name);
1272 const bool record_in_table = record_iter != prog_ann_.record_annotations.end();
1273 if (record_in_table) {
1274 Serialize(*record.metadata, record_iter->second.ann_list, os);
1275 } else {
1276 Serialize(*record.metadata, {}, os);
1277 }
1278
1279 if (record.metadata->IsForeign()) {
1280 os << "\n\n";
1281 return;
1282 }
1283
1284 os << " {";
1285
1286 if (print_information && prog_info_.records_info.find(record.name) != prog_info_.records_info.end()) {
1287 os << " # " << prog_info_.records_info.at(record.name).record_info << "\n";
1288 SerializeFields(record, os, true);
1289 } else {
1290 os << "\n";
1291 SerializeFields(record, os, false);
1292 }
1293
1294 os << "}\n\n";
1295 }
1296
SerializeFields(const pandasm::Record & record,std::ostream & os,bool print_information) const1297 void Disassembler::SerializeFields(const pandasm::Record &record, std::ostream &os, bool print_information) const
1298 {
1299 constexpr size_t INFO_OFFSET = 80;
1300
1301 const auto record_iter = prog_ann_.record_annotations.find(record.name);
1302 const bool record_in_table = record_iter != prog_ann_.record_annotations.end();
1303
1304 const auto rec_inf = (print_information) ? (prog_info_.records_info.at(record.name)) : (RecordInfo {});
1305
1306 size_t field_idx = 0;
1307
1308 std::stringstream ss;
1309 for (const auto &f : record.field_list) {
1310 ss << "\t" << f.type.GetPandasmName() << " " << f.name;
1311 if (f.metadata->GetValue().has_value()) {
1312 if (f.type.GetId() == panda_file::Type::TypeId::U32) {
1313 ss << " = 0x" << std::hex << f.metadata->GetValue().value().GetValue<uint32_t>();
1314 }
1315 if (f.type.GetId() == panda_file::Type::TypeId::U8) {
1316 ss << " = 0x" << std::hex << static_cast<uint32_t>(f.metadata->GetValue().value().GetValue<uint8_t>());
1317 }
1318 }
1319 if (record_in_table) {
1320 const auto field_iter = record_iter->second.field_annotations.find(f.name);
1321 if (field_iter != record_iter->second.field_annotations.end()) {
1322 Serialize(*f.metadata, field_iter->second, ss);
1323 } else {
1324 Serialize(*f.metadata, {}, ss);
1325 }
1326 } else {
1327 Serialize(*f.metadata, {}, ss);
1328 }
1329
1330 if (print_information) {
1331 os << std::setw(INFO_OFFSET) << std::left << ss.str() << " # " << rec_inf.fields_info.at(field_idx) << "\n";
1332 } else {
1333 os << ss.str() << "\n";
1334 }
1335
1336 ss.str(std::string());
1337 ss.clear();
1338
1339 field_idx++;
1340 }
1341 }
1342
Serialize(const pandasm::Function & method,std::ostream & os,bool print_information) const1343 void Disassembler::Serialize(const pandasm::Function &method, std::ostream &os, bool print_information) const
1344 {
1345 os << ".function " << method.return_type.GetPandasmName() << " " << method.name << "(";
1346
1347 if (method.params.size() > 0) {
1348 os << method.params[0].type.GetPandasmName() << " a0";
1349
1350 for (uint8_t i = 1; i < method.params.size(); i++) {
1351 os << ", " << method.params[i].type.GetPandasmName() << " a" << (size_t)i;
1352 }
1353 }
1354 os << ")";
1355
1356 const std::string signature = pandasm::GetFunctionSignatureFromName(method.name, method.params);
1357
1358 const auto method_iter = prog_ann_.method_annotations.find(signature);
1359 if (method_iter != prog_ann_.method_annotations.end()) {
1360 Serialize(*method.metadata, method_iter->second, os);
1361 } else {
1362 Serialize(*method.metadata, {}, os);
1363 }
1364
1365 auto method_info_it = prog_info_.methods_info.find(signature);
1366 bool print_method_info = print_information && method_info_it != prog_info_.methods_info.end();
1367 if (print_method_info) {
1368 const MethodInfo &method_info = method_info_it->second;
1369
1370 size_t width = 0;
1371 for (const auto &i : method.ins) {
1372 if (i.ToString().size() > width) {
1373 width = i.ToString().size();
1374 }
1375 }
1376
1377 os << " { # " << method_info.method_info << "\n# CODE:\n";
1378
1379 for (size_t i = 0; i < method.ins.size(); i++) {
1380 os << "\t" << std::setw(width) << std::left << method.ins.at(i).ToString("", true, method.regs_num) << " # "
1381 << method_info.instructions_info.at(i) << "\n";
1382 }
1383 } else {
1384 os << " {\n";
1385
1386 for (const auto &i : method.ins) {
1387 if (i.set_label) {
1388 std::string ins = i.ToString("", true, method.regs_num);
1389 std::string delim = ": ";
1390 size_t pos = ins.find(delim);
1391 std::string label = ins.substr(0, pos);
1392 ins.erase(0, pos + delim.length());
1393 os << label << ":\n\t" << ins << "\n";
1394 } else {
1395 os << "\t" << i.ToString("", true, method.regs_num) << "\n";
1396 }
1397 }
1398 }
1399
1400 if (method.catch_blocks.size() != 0) {
1401 os << "\n";
1402
1403 for (const auto &catch_block : method.catch_blocks) {
1404 Serialize(catch_block, os);
1405
1406 os << "\n";
1407 }
1408 }
1409
1410 if (print_method_info) {
1411 const MethodInfo &method_info = method_info_it->second;
1412 SerializeLineNumberTable(method_info.line_number_table, os);
1413 SerializeLocalVariableTable(method_info.local_variable_table, method, os);
1414 }
1415
1416 os << "}\n\n";
1417 }
1418
Serialize(const pandasm::Function::CatchBlock & catch_block,std::ostream & os) const1419 void Disassembler::Serialize(const pandasm::Function::CatchBlock &catch_block, std::ostream &os) const
1420 {
1421 if (catch_block.exception_record == "") {
1422 os << ".catchall ";
1423 } else {
1424 os << ".catch " << catch_block.exception_record << ", ";
1425 }
1426
1427 os << catch_block.try_begin_label << ", " << catch_block.try_end_label << ", " << catch_block.catch_begin_label;
1428
1429 if (catch_block.catch_end_label != "") {
1430 os << ", " << catch_block.catch_end_label;
1431 }
1432 }
1433
Serialize(const pandasm::ItemMetadata & meta,const AnnotationList & ann_list,std::ostream & os) const1434 void Disassembler::Serialize(const pandasm::ItemMetadata &meta, const AnnotationList &ann_list, std::ostream &os) const
1435 {
1436 auto bool_attributes = meta.GetBoolAttributes();
1437 auto attributes = meta.GetAttributes();
1438 if (bool_attributes.empty() && attributes.empty() && ann_list.empty()) {
1439 return;
1440 }
1441
1442 os << " <";
1443
1444 size_t size = bool_attributes.size();
1445 size_t idx = 0;
1446 for (const auto &attr : bool_attributes) {
1447 os << attr;
1448 ++idx;
1449
1450 if (!attributes.empty() || !ann_list.empty() || idx < size) {
1451 os << ", ";
1452 }
1453 }
1454
1455 size = attributes.size();
1456 idx = 0;
1457 for (const auto &[key, values] : attributes) {
1458 for (size_t i = 0; i < values.size(); i++) {
1459 os << key << "=" << values[i];
1460
1461 if (i < values.size() - 1) {
1462 os << ", ";
1463 }
1464 }
1465
1466 ++idx;
1467
1468 if (!ann_list.empty() || idx < size) {
1469 os << ", ";
1470 }
1471 }
1472
1473 size = ann_list.size();
1474 idx = 0;
1475 for (const auto &[key, value] : ann_list) {
1476 os << key << "=" << value;
1477
1478 ++idx;
1479
1480 if (idx < size) {
1481 os << ", ";
1482 }
1483 }
1484
1485 os << ">";
1486 }
1487
SerializeLineNumberTable(const panda_file::LineNumberTable & line_number_table,std::ostream & os) const1488 void Disassembler::SerializeLineNumberTable(const panda_file::LineNumberTable &line_number_table,
1489 std::ostream &os) const
1490 {
1491 if (line_number_table.empty()) {
1492 return;
1493 }
1494
1495 os << "\n# LINE_NUMBER_TABLE:\n";
1496 for (const auto &line_info : line_number_table) {
1497 os << "#\tline " << line_info.line << ": " << line_info.offset << "\n";
1498 }
1499 }
1500
SerializeLocalVariableTable(const panda_file::LocalVariableTable & local_variable_table,const pandasm::Function & method,std::ostream & os) const1501 void Disassembler::SerializeLocalVariableTable(const panda_file::LocalVariableTable &local_variable_table,
1502 const pandasm::Function &method, std::ostream &os) const
1503 {
1504 if (local_variable_table.empty()) {
1505 return;
1506 }
1507
1508 os << "\n# LOCAL_VARIABLE_TABLE:\n";
1509 os << "#\t Start End Register Name Signature\n";
1510 const int START_WIDTH = 5;
1511 const int END_WIDTH = 4;
1512 const int REG_WIDTH = 8;
1513 const int NAME_WIDTH = 14;
1514 for (const auto &variable_info : local_variable_table) {
1515 std::ostringstream reg_stream;
1516 reg_stream << variable_info.reg_number << '(';
1517 if (variable_info.reg_number < 0) {
1518 reg_stream << "acc";
1519 } else {
1520 uint32_t vreg = variable_info.reg_number;
1521 uint32_t first_arg_reg = method.GetTotalRegs();
1522 if (vreg < first_arg_reg) {
1523 reg_stream << 'v' << vreg;
1524 } else {
1525 reg_stream << 'a' << vreg - first_arg_reg;
1526 }
1527 }
1528 reg_stream << ')';
1529
1530 os << "#\t " << std::setw(START_WIDTH) << std::right << variable_info.start_offset << " ";
1531 os << std::setw(END_WIDTH) << std::right << variable_info.end_offset << " ";
1532 os << std::setw(REG_WIDTH) << std::right << reg_stream.str() << " ";
1533 os << std::setw(NAME_WIDTH) << std::right << variable_info.name << " " << variable_info.type;
1534 if (!variable_info.type_signature.empty() && variable_info.type_signature != variable_info.type) {
1535 os << " (" << variable_info.type_signature << ")";
1536 }
1537 os << "\n";
1538 }
1539 }
1540
BytecodeOpcodeToPandasmOpcode(uint8_t o) const1541 pandasm::Opcode Disassembler::BytecodeOpcodeToPandasmOpcode(uint8_t o) const
1542 {
1543 return BytecodeOpcodeToPandasmOpcode(BytecodeInstruction::Opcode(o));
1544 }
1545
IDToString(BytecodeInstruction bc_ins,panda_file::File::EntityId method_id,size_t idx) const1546 std::string Disassembler::IDToString(BytecodeInstruction bc_ins, panda_file::File::EntityId method_id,
1547 size_t idx) const
1548 {
1549 std::stringstream name;
1550 const auto offset = file_->ResolveOffsetByIndex(method_id, bc_ins.GetId(idx).AsIndex());
1551
1552 if (bc_ins.IsIdMatchFlag(idx, BytecodeInstruction::Flags::METHOD_ID)) {
1553 name << GetMethodSignature(offset);
1554 } else if (bc_ins.IsIdMatchFlag(idx, BytecodeInstruction::Flags::STRING_ID)) {
1555 name << '\"';
1556 name << StringDataToString(file_->GetStringData(offset));
1557 name << '\"';
1558 } else {
1559 ASSERT(bc_ins.IsIdMatchFlag(idx, BytecodeInstruction::Flags::LITERALARRAY_ID));
1560 pandasm::LiteralArray lit_array;
1561 GetLiteralArrayByOffset(&lit_array, panda_file::File::EntityId(offset));
1562 name << SerializeLiteralArray(lit_array);
1563 }
1564
1565 return name.str();
1566 }
1567
GetRecordLanguage(panda_file::File::EntityId class_id) const1568 panda::panda_file::SourceLang Disassembler::GetRecordLanguage(panda_file::File::EntityId class_id) const
1569 {
1570 if (file_->IsExternal(class_id)) {
1571 return panda::panda_file::SourceLang::PANDA_ASSEMBLY;
1572 }
1573
1574 panda_file::ClassDataAccessor cda(*file_, class_id);
1575 return cda.GetSourceLang().value_or(panda_file::SourceLang::PANDA_ASSEMBLY);
1576 }
1577
translateImmToLabel(pandasm::Ins * pa_ins,LabelTable * label_table,const uint8_t * ins_arr,BytecodeInstruction bc_ins,BytecodeInstruction bc_ins_last,panda_file::File::EntityId code_id)1578 static void translateImmToLabel(pandasm::Ins *pa_ins, LabelTable *label_table, const uint8_t *ins_arr,
1579 BytecodeInstruction bc_ins, BytecodeInstruction bc_ins_last,
1580 panda_file::File::EntityId code_id)
1581 {
1582 const int32_t jmp_offset = std::get<int64_t>(pa_ins->imms.at(0));
1583 const auto bc_ins_dest = bc_ins.JumpTo(jmp_offset);
1584 if (bc_ins_last.GetAddress() > bc_ins_dest.GetAddress()) {
1585 size_t idx = getBytecodeInstructionNumber(BytecodeInstruction(ins_arr), bc_ins_dest);
1586 if (idx != std::numeric_limits<size_t>::max()) {
1587 if (label_table->find(idx) == label_table->end()) {
1588 std::stringstream ss {};
1589 ss << "jump_label_" << label_table->size();
1590 (*label_table)[idx] = ss.str();
1591 }
1592
1593 pa_ins->imms.clear();
1594 pa_ins->ids.push_back(label_table->at(idx));
1595 } else {
1596 LOG(ERROR, DISASSEMBLER) << "> error encountered at " << code_id << " (0x" << std::hex << code_id
1597 << "). incorrect instruction at offset: 0x" << (bc_ins.GetAddress() - ins_arr)
1598 << ": invalid jump offset 0x" << jmp_offset
1599 << " - jumping in the middle of another instruction!";
1600 }
1601 } else {
1602 LOG(ERROR, DISASSEMBLER) << "> error encountered at " << code_id << " (0x" << std::hex << code_id
1603 << "). incorrect instruction at offset: 0x" << (bc_ins.GetAddress() - ins_arr)
1604 << ": invalid jump offset 0x" << jmp_offset << " - jumping out of bounds!";
1605 }
1606 }
1607
GetInstructions(pandasm::Function * method,panda_file::File::EntityId method_id,panda_file::File::EntityId code_id) const1608 IdList Disassembler::GetInstructions(pandasm::Function *method, panda_file::File::EntityId method_id,
1609 panda_file::File::EntityId code_id) const
1610 {
1611 panda_file::CodeDataAccessor code_accessor(*file_, code_id);
1612
1613 const auto ins_sz = code_accessor.GetCodeSize();
1614 const auto ins_arr = code_accessor.GetInstructions();
1615
1616 method->regs_num = code_accessor.GetNumVregs();
1617
1618 auto bc_ins = BytecodeInstruction(ins_arr);
1619 const auto bc_ins_last = bc_ins.JumpTo(ins_sz);
1620
1621 LabelTable label_table = GetExceptions(method, method_id, code_id);
1622
1623 IdList unknown_external_methods {};
1624
1625 while (bc_ins.GetAddress() != bc_ins_last.GetAddress()) {
1626 if (bc_ins.GetAddress() > bc_ins_last.GetAddress()) {
1627 LOG(ERROR, DISASSEMBLER) << "> error encountered at " << code_id << " (0x" << std::hex << code_id
1628 << "). bytecode instructions sequence corrupted for method " << method->name
1629 << "! went out of bounds";
1630
1631 break;
1632 }
1633
1634 auto pa_ins = BytecodeInstructionToPandasmInstruction(bc_ins, method_id);
1635 if (pa_ins.IsJump()) {
1636 translateImmToLabel(&pa_ins, &label_table, ins_arr, bc_ins, bc_ins_last, code_id);
1637 }
1638
1639 // check if method id is unknown external method. if so, emplace it in table
1640 if (bc_ins.HasFlag(BytecodeInstruction::Flags::METHOD_ID)) {
1641 const auto arg_method_idx = bc_ins.GetId().AsIndex();
1642 const auto arg_method_id = file_->ResolveMethodIndex(method_id, arg_method_idx);
1643
1644 const auto arg_method_signature = GetMethodSignature(arg_method_id);
1645
1646 const bool is_present = prog_.function_table.find(arg_method_signature) != prog_.function_table.cend();
1647 const bool is_external = file_->IsExternal(arg_method_id);
1648 if (is_external && !is_present) {
1649 unknown_external_methods.push_back(arg_method_id);
1650 }
1651 }
1652
1653 method->ins.push_back(pa_ins);
1654 bc_ins = bc_ins.GetNext();
1655 }
1656
1657 for (const auto &pair : label_table) {
1658 method->ins[pair.first].label = pair.second;
1659 method->ins[pair.first].set_label = true;
1660 }
1661
1662 return unknown_external_methods;
1663 }
1664
1665 } // namespace panda::disasm
1666