1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436
|
// Copyright 2022 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <fstream>
#include <iomanip>
#include <iostream>
#include <optional>
#include <vector>
#include "include/libplatform/libplatform.h"
#include "include/v8-initialization.h"
#include "src/wasm/module-decoder-impl.h"
#include "src/wasm/names-provider.h"
#include "src/wasm/string-builder-multiline.h"
#include "src/wasm/wasm-disassembler-impl.h"
#include "src/wasm/wasm-opcodes-inl.h"
#include "tools/wasm/mjsunit-module-disassembler-impl.h"
#if V8_OS_POSIX
#include <unistd.h>
#endif
int PrintHelp(char** argv) {
std::cerr
<< "Usage: Specify an action and a module in any order.\n"
<< "The action can be any of:\n"
<< " --help\n"
<< " Print this help and exit.\n"
<< " --list-functions\n"
<< " List functions in the given module\n"
<< " --list-signatures\n"
<< " List signatures with their use counts in the given module\n"
<< " --section-stats\n"
<< " Show information about sections in the given module\n"
<< " --instruction-stats\n"
<< " Show information about instructions in the given module\n"
<< " --function-stats [bucket_size] [bucket_count]\n"
<< " Show distribution of function sizes in the given module.\n"
<< " An optional bucket size and bucket count can be passed.\n"
<< " --single-wat FUNC_INDEX\n"
<< " Print function FUNC_INDEX in .wat format\n"
<< " --full-wat\n"
<< " Print full module in .wat format\n"
<< " --single-hexdump FUNC_INDEX\n"
<< " Print function FUNC_INDEX in annotated hex format\n"
<< " --full-hexdump\n"
<< " Print full module in annotated hex format\n"
<< " --mjsunit\n"
<< " Print full module in mjsunit/wasm-module-builder.js syntax\n"
<< " --strip\n"
<< " Dump the module, in binary format, without its Name"
<< " section (requires using -o as well)\n"
<< "\n"
<< "Options:\n"
<< " --offsets\n"
<< " Include module-relative offsets in output\n"
<< " -o OUTFILE or --output OUTFILE\n"
<< " Send output to OUTFILE instead of <stdout>\n";
return 1;
}
namespace v8::internal::wasm {
enum class OutputMode { kWat, kHexDump };
char* PrintHexBytesCore(char* ptr, uint32_t num_bytes, const uint8_t* start) {
for (uint32_t i = 0; i < num_bytes; i++) {
uint8_t b = *(start + i);
*(ptr++) = '0';
*(ptr++) = 'x';
*(ptr++) = kHexChars[b >> 4];
*(ptr++) = kHexChars[b & 0xF];
*(ptr++) = ',';
*(ptr++) = ' ';
}
return ptr;
}
class InstructionStatistics {
public:
void Record(WasmOpcode opcode, uint32_t size) {
Entry& entry = entries[opcode];
entry.opcode = opcode;
entry.count++;
entry.total_size += size;
}
void RecordImmediate(WasmOpcode opcode, int imm_value) {
OpcodeImmediates& map = immediates[opcode];
map[imm_value]++;
}
void RecordCodeSize(size_t chunk) { total_code_size_ += chunk; }
void RecordLocals(uint32_t count, uint32_t size) {
locals_count_ += count;
locals_size_ += size;
}
void WriteTo(std::ostream& out) {
// Sort by number of occurrences.
std::vector<Entry> sorted;
sorted.reserve(entries.size());
for (const auto& e : entries) sorted.push_back(e.second);
std::sort(sorted.begin(), sorted.end(),
[](const Entry& a, const Entry& b) { return a.count > b.count; });
// Prepare column widths.
int longest_mnemo = 0;
for (const Entry& e : sorted) {
int s = static_cast<int>(strlen(WasmOpcodes::OpcodeName(e.opcode)));
if (s > longest_mnemo) longest_mnemo = s;
}
constexpr int kSpacing = 2;
longest_mnemo =
std::max(longest_mnemo, static_cast<int>(strlen("Instruction"))) +
kSpacing;
uint32_t highest_count = sorted[0].count;
int count_digits = GetNumDigits(highest_count);
count_digits = std::max(count_digits, static_cast<int>(strlen("count")));
// Print headline.
out << std::setw(longest_mnemo) << std::left << "Instruction";
out << std::setw(count_digits) << std::right << "count";
out << std::setw(kSpacing) << " ";
out << std::setw(8) << "tot.size";
out << std::setw(kSpacing) << " ";
out << std::setw(8) << "avg.size";
out << std::setw(kSpacing) << " ";
out << std::setw(8) << "% of code\n";
// Print instruction counts.
auto PrintLine = [&](const char* name, uint32_t count,
uint32_t total_size) {
out << std::setw(longest_mnemo) << std::left << name;
out << std::setw(count_digits) << std::right << count;
out << std::setw(kSpacing) << " ";
out << std::setw(8) << total_size;
out << std::setw(kSpacing) << " ";
out << std::fixed << std::setprecision(2) << std::setw(8)
<< static_cast<double>(total_size) / count;
out << std::setw(kSpacing) << " ";
out << std::fixed << std::setprecision(1) << std::setw(8)
<< 100.0 * total_size / total_code_size_ << "%\n";
};
for (const Entry& e : sorted) {
PrintLine(WasmOpcodes::OpcodeName(e.opcode), e.count, e.total_size);
}
out << "\n";
PrintLine("locals", locals_count_, locals_size_);
// Print most common immediate values.
for (const auto& imm : immediates) {
WasmOpcode opcode = imm.first;
out << "\nMost common immediates for " << WasmOpcodes::OpcodeName(opcode)
<< ":\n";
std::vector<std::pair<int, int>> counts;
counts.reserve(imm.second.size());
for (const auto& pair : imm.second) {
counts.push_back(std::make_pair(pair.first, pair.second));
}
std::sort(counts.begin(), counts.end(),
[](const std::pair<int, uint32_t>& a,
const std::pair<int, uint32_t>& b) {
return a.second > b.second;
});
constexpr int kImmLen = 9; // Length of "Immediate".
int count_len = std::max(GetNumDigits(counts[0].second),
static_cast<int>(strlen("count")));
// How many most-common values to show.
size_t print_top = std::min(size_t{10}, counts.size());
out << std::setw(kImmLen) << "Immediate";
out << std::setw(kSpacing) << " ";
out << std::setw(count_len) << "count"
<< "\n";
for (size_t i = 0; i < print_top; i++) {
out << std::setw(kImmLen) << counts[i].first;
out << std::setw(kSpacing) << " ";
out << std::setw(count_len) << counts[i].second << "\n";
}
}
}
private:
struct Entry {
WasmOpcode opcode;
uint32_t count = 0;
uint32_t total_size = 0;
};
// First: immediate value, second: count.
using OpcodeImmediates = std::map<int, uint32_t>;
std::unordered_map<WasmOpcode, Entry> entries;
std::map<WasmOpcode, OpcodeImmediates> immediates;
size_t total_code_size_ = 0;
uint32_t locals_count_ = 0;
uint32_t locals_size_ = 0;
};
// A variant of FunctionBodyDisassembler that can produce "annotated hex dump"
// format, e.g.:
// 0xfb, 0x07, 0x01, // struct.new $type1
class ExtendedFunctionDis : public FunctionBodyDisassembler {
public:
ExtendedFunctionDis(Zone* zone, const WasmModule* module, uint32_t func_index,
bool shared, WasmDetectedFeatures* detected,
const FunctionSig* sig, const uint8_t* start,
const uint8_t* end, uint32_t offset,
const ModuleWireBytes wire_bytes, NamesProvider* names)
: FunctionBodyDisassembler(zone, module, func_index, shared, detected,
sig, start, end, offset, wire_bytes, names) {}
void HexDump(MultiLineStringBuilder& out, FunctionHeader include_header) {
out_ = &out;
if (!more()) return; // Fuzzers...
// Print header.
if (include_header == kPrintHeader) {
out << " // func ";
names_->PrintFunctionName(out, func_index_, NamesProvider::kDevTools);
PrintSignatureOneLine(out, sig_, func_index_, names_, true,
NamesProvider::kIndexAsComment);
out.NextLine(pc_offset());
}
// Decode and print locals.
DecodeLocals(pc_);
if (failed()) {
// TODO(jkummerow): Better error handling.
out << "Failed to decode locals";
return;
}
auto [entries, length] = read_u32v<ValidationTag>(pc_);
PrintHexBytes(out, length, pc_, 4);
out << " // " << entries << " entries in locals list";
pc_ += length;
out.NextLine(pc_offset());
while (entries-- > 0) {
auto [count, count_length] = read_u32v<ValidationTag>(pc_);
auto [type, type_length] =
value_type_reader::read_value_type<ValidationTag>(
this, pc_ + count_length, WasmEnabledFeatures::All(),
this->detected_);
value_type_reader::Populate(&type, module_);
PrintHexBytes(out, count_length + type_length, pc_, 4);
out << " // " << count << (count != 1 ? " locals" : " local")
<< " of type ";
names_->PrintValueType(out, type);
pc_ += count_length + type_length;
out.NextLine(pc_offset());
}
// Main loop.
while (pc_ < end_ && ok()) {
WasmOpcode opcode = GetOpcode();
current_opcode_ = opcode; // Some immediates need to know this.
StringBuilder immediates;
uint32_t opcode_length = PrintImmediatesAndGetLength(immediates);
PrintHexBytes(out, opcode_length, pc_, 4);
if (opcode == kExprEnd) {
out << " // end";
if (label_stack_.size() > 0) {
const LabelInfo& label = label_stack_.back();
if (label.start != nullptr) {
out << " ";
out.write(label.start, label.length);
}
label_stack_.pop_back();
}
} else {
out << " // " << WasmOpcodes::OpcodeName(opcode);
}
out.write(immediates.start(), immediates.length());
if (opcode == kExprBlock || opcode == kExprIf || opcode == kExprLoop ||
opcode == kExprTry) {
label_stack_.emplace_back(out.line_number(), out.length(),
label_occurrence_index_++);
}
pc_ += opcode_length;
out.NextLine(pc_offset());
}
if (pc_ != end_) {
// TODO(jkummerow): Better error handling.
out << "Beyond end of code\n";
}
}
void HexdumpConstantExpression(MultiLineStringBuilder& out) {
while (pc_ < end_ && ok()) {
WasmOpcode opcode = GetOpcode();
current_opcode_ = opcode; // Some immediates need to know this.
StringBuilder immediates;
uint32_t length = PrintImmediatesAndGetLength(immediates);
// Don't print the final "end" separately.
if (pc_ + length + 1 == end_ && *(pc_ + length) == kExprEnd) {
length++;
}
PrintHexBytes(out, length, pc_, 4);
out << " // " << WasmOpcodes::OpcodeName(opcode);
out.write(immediates.start(), immediates.length());
pc_ += length;
out.NextLine(pc_offset());
}
}
void PrintHexBytes(StringBuilder& out, uint32_t num_bytes,
const uint8_t* start, uint32_t fill_to_minimum = 0) {
constexpr int kCharsPerByte = 6; // Length of "0xFF, ".
uint32_t max = std::max(num_bytes, fill_to_minimum) * kCharsPerByte + 2;
char* ptr = out.allocate(max);
*(ptr++) = ' ';
*(ptr++) = ' ';
ptr = PrintHexBytesCore(ptr, num_bytes, start);
if (fill_to_minimum > num_bytes) {
memset(ptr, ' ', (fill_to_minimum - num_bytes) * kCharsPerByte);
}
}
void CollectInstructionStats(InstructionStatistics& stats) {
uint32_t locals_length = DecodeLocals(pc_);
if (failed()) return;
stats.RecordLocals(num_locals(), locals_length);
consume_bytes(locals_length);
while (pc_ < end_ && ok()) {
WasmOpcode opcode = GetOpcode();
if (opcode == kExprI32Const) {
ImmI32Immediate imm(this, pc_ + 1, Decoder::kNoValidation);
stats.RecordImmediate(opcode, imm.value);
} else if (opcode == kExprLocalGet || opcode == kExprGlobalGet) {
IndexImmediate imm(this, pc_ + 1, "", Decoder::kNoValidation);
stats.RecordImmediate(opcode, static_cast<int>(imm.index));
}
uint32_t length = WasmDecoder::OpcodeLength(this, pc_);
stats.Record(opcode, length);
pc_ += length;
}
}
};
// A variant of ModuleDisassembler that produces "annotated hex dump" format,
// e.g.:
// 0x01, 0x70, 0x00, // table count 1: funcref no maximum
class HexDumpModuleDis;
class DumpingModuleDecoder : public ModuleDecoderImpl {
public:
DumpingModuleDecoder(ModuleWireBytes wire_bytes,
HexDumpModuleDis* module_dis);
private:
void onFirstError() override {
// Pretend we've reached the end of the section, but contrary to the
// superclass implementation do so without moving {pc_}, so whatever
// bytes caused the failure can still be dumped correctly.
end_ = pc_;
}
WasmDetectedFeatures unused_detected_features_;
};
class HexDumpModuleDis : public ITracer {
public:
HexDumpModuleDis(MultiLineStringBuilder& out, const WasmModule* module,
NamesProvider* names, const ModuleWireBytes wire_bytes,
AccountingAllocator* allocator)
: out_(out),
module_(module),
names_(names),
wire_bytes_(wire_bytes),
zone_(allocator, "disassembler") {}
// Public entrypoint.
void PrintModule() {
DumpingModuleDecoder decoder{wire_bytes_, this};
decoder_ = &decoder;
// If the module failed validation, create fakes to allow us to print
// what we can.
std::unique_ptr<WasmModule> fake_module;
std::unique_ptr<NamesProvider> names_provider;
if (!names_) {
fake_module.reset(new WasmModule(kWasmOrigin));
names_provider.reset(
new NamesProvider(fake_module.get(), wire_bytes_.module_bytes()));
names_ = names_provider.get();
}
out_ << "[";
out_.NextLine(0);
constexpr bool kNoVerifyFunctions = false;
decoder.DecodeModule(kNoVerifyFunctions);
NextLine();
out_ << "]";
if (total_bytes_ != wire_bytes_.length()) {
std::cerr << "WARNING: OUTPUT INCOMPLETE. Disassembled " << total_bytes_
<< " out of " << wire_bytes_.length() << " bytes.\n";
}
// For cleanliness, reset {names_} if it's pointing at a fake.
if (names_ == names_provider.get()) {
names_ = nullptr;
}
}
// Tracer hooks.
void Bytes(const uint8_t* start, uint32_t count) override {
if (count > kMaxBytesPerLine) {
DCHECK_EQ(queue_, nullptr);
queue_ = start;
queue_length_ = count;
total_bytes_ += count;
return;
}
if (line_bytes_ == 0 && count > 0) out_ << " ";
PrintHexBytes(out_, count, start);
line_bytes_ += count;
total_bytes_ += count;
}
void Description(const char* desc) override { description_ << desc; }
void Description(const char* desc, size_t length) override {
description_.write(desc, length);
}
void Description(uint32_t number) override {
if (description_.length() != 0) description_ << " ";
description_ << number;
}
void Description(uint64_t number) override {
if (description_.length() != 0) description_ << " ";
description_ << number;
}
void Description(ValueType type) override {
if (description_.length() != 0) description_ << " ";
names_->PrintValueType(description_, type);
}
void Description(HeapType type) override {
if (description_.length() != 0) description_ << " ";
names_->PrintHeapType(description_, type);
}
void Description(const FunctionSig* sig) override {
PrintSignatureOneLine(description_, sig, 0 /* ignored */, names_, false);
}
void FunctionName(uint32_t func_index) override {
description_ << func_index << " ";
names_->PrintFunctionName(description_, func_index,
NamesProvider::kDevTools);
}
void NextLineIfFull() override {
if (queue_ || line_bytes_ >= kPadBytes) NextLine();
}
void NextLineIfNonEmpty() override {
if (queue_ || line_bytes_ > 0) NextLine();
}
void NextLine() override {
if (queue_) {
// Print queued hex bytes first, unless there have also been unqueued
// bytes.
if (line_bytes_ > 0) {
// Keep the queued bytes together on the next line.
for (; line_bytes_ < kPadBytes; line_bytes_++) {
out_ << " ";
}
out_ << " // ";
out_.write(description_.start(), description_.length());
out_.NextLine(pc_offset(queue_));
}
while (queue_length_ > kMaxBytesPerLine) {
out_ << " ";
PrintHexBytes(out_, kMaxBytesPerLine, queue_);
queue_length_ -= kMaxBytesPerLine;
queue_ += kMaxBytesPerLine;
out_.NextLine(pc_offset(queue_));
}
if (queue_length_ > 0) {
out_ << " ";
PrintHexBytes(out_, queue_length_, queue_);
}
if (line_bytes_ == 0) {
if (queue_length_ > kPadBytes) {
out_.NextLine(pc_offset(queue_ + queue_length_));
out_ << " // ";
} else {
for (uint32_t i = queue_length_; i < kPadBytes; i++) {
out_ << " ";
}
out_ << " // ";
}
out_.write(description_.start(), description_.length());
}
queue_ = nullptr;
} else {
// No queued bytes; just write the accumulated description.
if (description_.length() != 0) {
if (line_bytes_ == 0) out_ << " ";
for (; line_bytes_ < kPadBytes; line_bytes_++) {
out_ << " ";
}
out_ << " // ";
out_.write(description_.start(), description_.length());
}
}
out_.NextLine(pc_offset());
line_bytes_ = 0;
description_.rewind_to_start();
}
// We don't care about offsets, but we can use these hooks to provide
// helpful indexing comments in long lists.
void TypeOffset(uint32_t offset) override {
if (!module_ || module_->types.size() > 3) {
description_ << "type #" << next_type_index_ << " ";
names_->PrintTypeName(description_, next_type_index_);
next_type_index_++;
}
}
void ImportOffset(uint32_t offset) override {
description_ << "import #" << next_import_index_++;
NextLine();
}
void ImportsDone(const WasmModule* module) override {
next_table_index_ = static_cast<uint32_t>(module->tables.size());
next_global_index_ = static_cast<uint32_t>(module->globals.size());
next_tag_index_ = static_cast<uint32_t>(module->tags.size());
}
void TableOffset(uint32_t offset) override {
if (!module_ || module_->tables.size() > 3) {
description_ << "table #" << next_table_index_++;
}
}
void MemoryOffset(uint32_t offset) override {}
void TagOffset(uint32_t offset) override {
if (!module_ || module_->tags.size() > 3) {
description_ << "tag #" << next_tag_index_++ << ":";
}
}
void GlobalOffset(uint32_t offset) override {
description_ << "global #" << next_global_index_++ << ":";
}
void StartOffset(uint32_t offset) override {}
void ElementOffset(uint32_t offset) override {
if (!module_ || module_->elem_segments.size() > 3) {
description_ << "segment #" << next_segment_index_++;
NextLine();
}
}
void DataOffset(uint32_t offset) override {
if (!module_ || module_->data_segments.size() > 3) {
description_ << "data segment #" << next_data_segment_index_++;
NextLine();
}
}
void StringOffset(uint32_t offset) override {
if (!module_ || module_->stringref_literals.size() > 3) {
description_ << "string literal #" << next_string_index_++;
NextLine();
}
}
// We handle recgroups via {Description()} hooks.
void RecGroupOffset(uint32_t offset, uint32_t group_size) override {}
// The following two hooks give us an opportunity to call the hex-dumping
// function body disassembler for initializers and functions.
void InitializerExpression(const uint8_t* start, const uint8_t* end,
ValueType expected_type) override {
WasmDetectedFeatures detected;
auto sig = FixedSizeSignature<ValueType>::Returns(expected_type);
uint32_t offset = decoder_->pc_offset();
const WasmModule* module = module_;
if (!module) module = decoder_->shared_module().get();
ExtendedFunctionDis d(&zone_, module, 0, false, &detected, &sig, start, end,
offset, wire_bytes_, names_);
d.HexdumpConstantExpression(out_);
total_bytes_ += static_cast<size_t>(end - start);
}
void FunctionBody(const WasmFunction* func, const uint8_t* start) override {
const uint8_t* end = start + func->code.length();
WasmDetectedFeatures detected;
DCHECK_EQ(start - wire_bytes_.start(), pc_offset());
uint32_t offset = pc_offset();
const WasmModule* module = module_;
if (!module) module = decoder_->shared_module().get();
bool shared = module->type(func->sig_index).is_shared;
ExtendedFunctionDis d(&zone_, module, func->func_index, shared, &detected,
func->sig, start, end, offset, wire_bytes_, names_);
d.HexDump(out_, FunctionBodyDisassembler::kSkipHeader);
total_bytes_ += func->code.length();
}
// We have to do extra work for the name section here, because the regular
// decoder mostly just skips over it.
void NameSection(const uint8_t* start, const uint8_t* end,
uint32_t offset) override {
Decoder decoder(start, end, offset);
while (decoder.ok() && decoder.more()) {
uint8_t name_type = decoder.consume_u8("name type: ", this);
Description(NameTypeName(name_type));
NextLine();
uint32_t payload_length = decoder.consume_u32v("payload length:", this);
Description(payload_length);
NextLine();
if (!decoder.checkAvailable(payload_length)) break;
switch (name_type) {
case kModuleCode:
consume_string(&decoder, unibrow::Utf8Variant::kLossyUtf8,
"module name", this);
break;
case kFunctionCode:
case kTypeCode:
case kTableCode:
case kMemoryCode:
case kGlobalCode:
case kElementSegmentCode:
case kDataSegmentCode:
case kTagCode:
DumpNameMap(decoder);
break;
case kLocalCode:
case kLabelCode:
case kFieldCode:
DumpIndirectNameMap(decoder);
break;
default:
Bytes(decoder.pc(), payload_length);
NextLine();
decoder.consume_bytes(payload_length);
break;
}
}
}
private:
static constexpr uint32_t kMaxBytesPerLine = 8;
static constexpr uint32_t kPadBytes = 4;
void PrintHexBytes(StringBuilder& out, uint32_t num_bytes,
const uint8_t* start) {
char* ptr = out.allocate(num_bytes * 6);
PrintHexBytesCore(ptr, num_bytes, start);
}
void DumpNameMap(Decoder& decoder) {
uint32_t count = decoder.consume_u32v("names count", this);
Description(count);
NextLine();
for (uint32_t i = 0; i < count; i++) {
uint32_t index = decoder.consume_u32v("index", this);
Description(index);
Description(" ");
consume_string(&decoder, unibrow::Utf8Variant::kLossyUtf8, "name", this);
if (!decoder.ok()) break;
}
}
void DumpIndirectNameMap(Decoder& decoder) {
uint32_t outer_count = decoder.consume_u32v("outer count", this);
Description(outer_count);
NextLine();
for (uint32_t i = 0; i < outer_count; i++) {
uint32_t outer_index = decoder.consume_u32v("outer index", this);
Description(outer_index);
uint32_t inner_count = decoder.consume_u32v(" inner count", this);
Description(inner_count);
NextLine();
for (uint32_t j = 0; j < inner_count; j++) {
uint32_t inner_index = decoder.consume_u32v("inner index", this);
Description(inner_index);
Description(" ");
consume_string(&decoder, unibrow::Utf8Variant::kLossyUtf8, "name",
this);
if (!decoder.ok()) break;
}
if (!decoder.ok()) break;
}
}
static constexpr const char* NameTypeName(uint8_t name_type) {
switch (name_type) {
// clang-format off
case kModuleCode: return "module";
case kFunctionCode: return "function";
case kTypeCode: return "type";
case kTableCode: return "table";
case kMemoryCode: return "memory";
case kGlobalCode: return "global";
case kElementSegmentCode: return "element segment";
case kDataSegmentCode: return "data segment";
case kTagCode: return "tag";
case kLocalCode: return "local";
case kLabelCode: return "label";
case kFieldCode: return "field";
default: return "unknown";
// clang-format on
}
}
uint32_t pc_offset() { return static_cast<uint32_t>(total_bytes_); }
uint32_t pc_offset(const uint8_t* pc) {
return static_cast<uint32_t>(pc - wire_bytes_.start());
}
MultiLineStringBuilder& out_;
const WasmModule* module_;
NamesProvider* names_;
const ModuleWireBytes wire_bytes_;
Zone zone_;
StringBuilder description_;
const uint8_t* queue_{nullptr};
uint32_t queue_length_{0};
uint32_t line_bytes_{0};
size_t total_bytes_{0};
DumpingModuleDecoder* decoder_{nullptr};
uint32_t next_type_index_{0};
uint32_t next_import_index_{0};
uint32_t next_table_index_{0};
uint32_t next_global_index_{0};
uint32_t next_tag_index_{0};
uint32_t next_segment_index_{0};
uint32_t next_data_segment_index_{0};
uint32_t next_string_index_{0};
};
class FunctionStatistics {
public:
explicit FunctionStatistics(size_t bucket_size, size_t bucket_count)
: bucket_size_(bucket_size), buckets_(bucket_count) {}
void addFunction(size_t size) {
size_t index = size / bucket_size_;
index = std::min(buckets_.size() - 1, index);
buckets_[index] += 1;
total_bytes_ += size;
}
void WriteTo(std::ostream& out) {
size_t fct_count = std::accumulate(buckets_.begin(), buckets_.end(), 0ull);
if (fct_count == 0) {
out << "No functions found in module.\n";
return;
}
int max_w = log10(bucket_size_ * buckets_.size() - 1) + 1;
out << "Function distribution:\n";
for (size_t i = 0; i < buckets_.size(); ++i) {
size_t lower = i * bucket_size_;
size_t upper = (i + 1) * bucket_size_ - 1;
bool last = i + 1 == buckets_.size();
out << std::setw(max_w) << lower << " - ";
out << std::setw(max_w) << upper << (last ? '+' : ' ') << " bytes: ";
size_t count = buckets_[i];
out << std::setw(6) << count;
double percent = 100.0 * count / fct_count;
out << " (" << std::fixed << std::setw(4) << std::setprecision(1)
<< percent << "%)\n";
}
out << "Total function count: " << fct_count << '\n';
out << "Average size per function: " << total_bytes_ / fct_count
<< " bytes\n";
}
private:
size_t bucket_size_;
std::vector<size_t> buckets_;
size_t total_bytes_ = 0;
};
////////////////////////////////////////////////////////////////////////////////
class FormatConverter {
public:
enum Status { kNotReady, kIoInitialized, kModuleReady };
explicit FormatConverter(const char* input, const char* output,
bool print_offsets)
: output_(output), out_(output_.get()), print_offsets_(print_offsets) {
if (!output_.ok()) return;
if (!LoadFile(input)) return;
wire_bytes_ = ModuleWireBytes(raw_bytes());
status_ = kIoInitialized;
offsets_provider_ = AllocateOffsetsProvider();
ModuleResult result =
DecodeWasmModuleForDisassembler(raw_bytes(), offsets_provider_.get());
if (result.failed()) {
const WasmError& error = result.error();
std::cerr << "Decoding error: " << error.message() << " at offset "
<< error.offset() << "\n";
return;
}
status_ = kModuleReady;
module_ = result.value();
names_provider_ =
std::make_unique<NamesProvider>(module_.get(), raw_bytes());
}
Status status() const { return status_; }
void ListFunctions() {
DCHECK_EQ(status_, kModuleReady);
const WasmModule* m = module();
uint32_t num_functions = static_cast<uint32_t>(m->functions.size());
double small_function_percentage =
module_->num_small_functions * 100.0 / module_->num_declared_functions;
out_ << "There are " << num_functions << " functions ("
<< m->num_imported_functions << " imported, "
<< m->num_declared_functions << " locally defined; "
<< small_function_percentage
<< "% of them \"small\"); the following have names:\n";
for (uint32_t i = 0; i < num_functions; i++) {
StringBuilder sb;
names()->PrintFunctionName(sb, i);
if (sb.length() == 0) continue;
std::string name(sb.start(), sb.length());
out_ << i << " " << name << "\n";
}
}
static bool sig_uses_vector_comparison(std::pair<uint32_t, uint32_t> left,
std::pair<uint32_t, uint32_t> right) {
return left.second > right.second;
}
void SortAndPrintSigUses(std::map<uint32_t, uint32_t> uses,
const WasmModule* module, const char* kind) {
std::vector<std::pair<uint32_t, uint32_t>> sig_uses_vector{uses.begin(),
uses.end()};
std::sort(sig_uses_vector.begin(), sig_uses_vector.end(),
sig_uses_vector_comparison);
out_ << sig_uses_vector.size() << " different signatures get used by "
<< kind << std::endl;
for (auto sig_use : sig_uses_vector) {
uint32_t sig_index = sig_use.first;
uint32_t use_count = sig_use.second;
const FunctionSig* sig = module->signature(ModuleTypeIndex{sig_index});
out_ << use_count << " " << kind << " use the signature " << *sig
<< std::endl;
}
}
void ListSignatures() {
DCHECK_EQ(status_, kModuleReady);
const WasmModule* m = module();
uint32_t num_functions = static_cast<uint32_t>(m->functions.size());
std::map<uint32_t, uint32_t> sig_uses;
std::map<uint32_t, uint32_t> export_sig_uses;
for (uint32_t i = 0; i < num_functions; i++) {
const WasmFunction& f = m->functions[i];
sig_uses[f.sig_index.index]++;
if (f.exported) {
export_sig_uses[f.sig_index.index]++;
}
}
SortAndPrintSigUses(sig_uses, m, "functions");
out_ << std::endl;
SortAndPrintSigUses(export_sig_uses, m, "exported functions");
}
void SectionStats() {
DCHECK_EQ(status_, kModuleReady);
Decoder decoder(raw_bytes());
decoder.consume_bytes(kModuleHeaderSize, "module header");
uint32_t module_size = static_cast<uint32_t>(raw_bytes().size());
int digits = GetNumDigits(module_size);
size_t kMinNameLength = 8;
// 18 = kMinNameLength + strlen(" section: ").
out_ << std::setw(18) << std::left << "Module size: ";
out_ << std::setw(digits) << std::right << module_size << " bytes\n";
for (WasmSectionIterator it(&decoder, ITracer::NoTrace); it.more();
it.advance(true)) {
const char* name = SectionName(it.section_code());
size_t name_len = strlen(name);
out_ << SectionName(it.section_code()) << " section: ";
for (; name_len < kMinNameLength; name_len++) out_ << " ";
uint32_t length = it.section_length();
out_ << std::setw(name_len > kMinNameLength ? 0 : digits) << length
<< " bytes / ";
out_ << std::fixed << std::setprecision(1) << std::setw(4)
<< 100.0 * length / module_size;
out_ << "% of total\n";
}
}
void Strip() {
DCHECK_EQ(status_, kModuleReady);
Decoder decoder(raw_bytes());
out_.write(reinterpret_cast<const char*>(decoder.pc()), kModuleHeaderSize);
decoder.consume_bytes(kModuleHeaderSize);
for (WasmSectionIterator it(&decoder, ITracer::NoTrace); it.more();
it.advance(true)) {
if (it.section_code() == kNameSectionCode) continue;
out_.write(reinterpret_cast<const char*>(it.section_start()),
it.section_length());
}
}
void InstructionStats() {
DCHECK_EQ(status_, kModuleReady);
Zone zone(&allocator_, "disassembler");
InstructionStatistics stats;
for (uint32_t i = module()->num_imported_functions;
i < module()->functions.size(); i++) {
const WasmFunction* func = &module()->functions[i];
bool shared = module()->type(func->sig_index).is_shared;
WasmDetectedFeatures detected;
base::Vector<const uint8_t> code = wire_bytes_.GetFunctionBytes(func);
ExtendedFunctionDis d(&zone, module(), i, shared, &detected, func->sig,
code.begin(), code.end(), func->code.offset(),
wire_bytes_, names());
d.CollectInstructionStats(stats);
stats.RecordCodeSize(code.size());
}
stats.WriteTo(out_);
}
void FunctionStats(size_t bucket_size, size_t bucket_count) {
DCHECK_EQ(status_, kModuleReady);
FunctionStatistics stats(bucket_size, bucket_count);
for (uint32_t i = module()->num_imported_functions;
i < module()->functions.size(); ++i) {
const WasmFunction* func = &module()->functions[i];
stats.addFunction(wire_bytes_.GetFunctionBytes(func).size());
}
stats.WriteTo(out_);
}
void DisassembleFunction(uint32_t func_index, OutputMode mode) {
DCHECK_EQ(status_, kModuleReady);
MultiLineStringBuilder sb;
if (func_index >= module()->functions.size()) {
sb << "Invalid function index!\n";
return;
}
if (func_index < module()->num_imported_functions) {
sb << "Can't disassemble imported functions!\n";
return;
}
const WasmFunction* func = &module()->functions[func_index];
Zone zone(&allocator_, "disassembler");
bool shared = module()->type(func->sig_index).is_shared;
WasmDetectedFeatures detected;
base::Vector<const uint8_t> code = wire_bytes_.GetFunctionBytes(func);
ExtendedFunctionDis d(&zone, module(), func_index, shared, &detected,
func->sig, code.begin(), code.end(),
func->code.offset(), wire_bytes_, names());
sb.set_current_line_bytecode_offset(func->code.offset());
if (mode == OutputMode::kWat) {
d.DecodeAsWat(sb, {0, 1});
} else if (mode == OutputMode::kHexDump) {
d.HexDump(sb, FunctionBodyDisassembler::kPrintHeader);
}
// Print any types that were used by the function.
sb.NextLine(0);
// If we ever want to support disassembling more than one function, we
// should find a way to reuse the {offsets_provider_} (which is currently
// consumed and released by the {ModuleDisassembler}).
ModuleDisassembler md(sb, module(), names(), wire_bytes_, &allocator_,
std::move(offsets_provider_));
for (uint32_t type_index : d.used_types()) {
md.PrintTypeDefinition(type_index, {0, 1},
NamesProvider::kIndexAsComment);
}
sb.WriteTo(out_, print_offsets_);
}
void WatForModule() {
DCHECK_EQ(status_, kModuleReady);
MultiLineStringBuilder sb;
ModuleDisassembler md(sb, module(), names(), wire_bytes_, &allocator_,
std::move(offsets_provider_));
// 100 GB is an approximation of "unlimited".
size_t max_mb = 100'000;
md.PrintModule({0, 2}, max_mb);
sb.WriteTo(out_, print_offsets_);
}
void HexdumpForModule() {
DCHECK_NE(status_, kNotReady);
DCHECK_IMPLIES(status_ == kIoInitialized,
module() == nullptr && names() == nullptr);
MultiLineStringBuilder sb;
HexDumpModuleDis md(sb, module(), names(), wire_bytes_, &allocator_);
md.PrintModule();
sb.WriteTo(out_, print_offsets_);
}
void Mjsunit() {
DCHECK_NE(status_, kNotReady);
DCHECK_IMPLIES(status_ == kIoInitialized,
module() == nullptr && names() == nullptr);
MultiLineStringBuilder sb;
MjsunitModuleDis md(sb, module(), names(), wire_bytes_, &allocator_);
md.PrintModule();
// Printing offsets into mjsunit test cases is not (yet?) supported:
// the MultiLineStringBuilder doesn't know how to emit them in a
// JS-compatible way, so the MjsunitModuleDis doesn't even collect them.
bool offsets = false;
sb.WriteTo(out_, offsets);
}
private:
static constexpr int kModuleHeaderSize = 8;
enum class ParseLiteralResult { kSuccess, kTryNext, kEOF };
class Output {
public:
explicit Output(const char* filename) {
if (strcmp(filename, "-") == 0) {
mode_ = kStdout;
} else {
mode_ = kFile;
filestream_.emplace(filename, std::ios::out | std::ios::binary);
if (!filestream_->is_open()) {
std::cerr << "Failed to open " << filename << " for writing!\n";
mode_ = kError;
}
}
}
~Output() {
if (mode_ == kFile) filestream_->close();
}
bool ok() { return mode_ != kError; }
std::ostream& get() {
return mode_ == kFile ? filestream_.value() : std::cout;
}
private:
enum Mode { kFile, kStdout, kError };
std::optional<std::ofstream> filestream_;
Mode mode_;
};
bool LoadFile(std::string path) {
if (path == "-") return LoadFileFromStream(std::cin);
std::ifstream input(path, std::ios::binary);
if (!input.is_open()) {
std::cerr << "Failed to open " << path << "!\n";
return false;
}
return LoadFileFromStream(input);
}
bool LoadFileFromStream(std::istream& input) {
int c0 = input.get();
int c1 = input.get();
int c2 = input.get();
int c3 = input.peek();
input.putback(c2);
input.putback(c1);
input.putback(c0);
if (c0 == 0 && c1 == 'a' && c2 == 's' && c3 == 'm') {
// Wasm binary module.
raw_bytes_ =
std::vector<uint8_t>(std::istreambuf_iterator<char>(input), {});
return true;
}
do {
ParseLiteralResult result = TryParseLiteral(input, raw_bytes_);
if (result == ParseLiteralResult::kSuccess) return true;
if (result == ParseLiteralResult::kEOF) break;
DCHECK_EQ(result, ParseLiteralResult::kTryNext);
raw_bytes_.clear();
} while (true);
std::cerr << "That's not a Wasm module!\n";
return false;
}
bool IsWhitespace(int c) {
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\v';
}
// Attempts to read a module in "array literal" syntax:
// - Bytes must be separated by ',', may be specified in decimal or hex.
// - The whole module must be enclosed in '[]', anything outside these
// braces is ignored.
// - Whitespace, line comments, and block comments are ignored.
// So in particular, this can consume what --full-hexdump produces.
ParseLiteralResult TryParseLiteral(std::istream& input,
std::vector<uint8_t>& output_bytes) {
int c = input.get();
// Skip anything before the first opening '['.
while (c != '[' && c != EOF) c = input.get();
enum State { kBeforeValue = 0, kAfterValue = 1, kDecimal = 10, kHex = 16 };
State state = kBeforeValue;
int value = 0;
while (true) {
c = input.get();
// Skip whitespace, except inside values.
if (state < kDecimal) {
while (IsWhitespace(c)) c = input.get();
}
// End of file before ']' is unexpected = invalid.
if (c == EOF) return ParseLiteralResult::kEOF;
// Skip comments.
if (c == '/' && input.peek() == '/') {
// Line comment. Skip until '\n'.
do {
c = input.get();
} while (c != '\n' && c != EOF);
continue;
}
if (c == '/' && input.peek() == '*') {
// Block comment. Skip until "*/".
input.get(); // Consume '*' of opening "/*".
do {
c = input.get();
if (c == '*' && input.peek() == '/') {
input.get(); // Consume '/'.
break;
}
} while (c != EOF);
continue;
}
if (state == kBeforeValue) {
if (c == '0' && (input.peek() == 'x' || input.peek() == 'X')) {
input.get(); // Consume the 'x'.
state = kHex;
continue;
}
if (c >= '0' && c <= '9') {
state = kDecimal;
// Fall through to handling kDecimal below.
} else if (c == ']') {
return output_bytes.size() > 8 ? ParseLiteralResult::kSuccess
: ParseLiteralResult::kTryNext;
} else {
return c == EOF ? ParseLiteralResult::kEOF
: ParseLiteralResult::kTryNext;
}
}
DCHECK(state == kDecimal || state == kHex || state == kAfterValue);
if (c == ',') {
DCHECK_LT(value, 256);
output_bytes.push_back(static_cast<uint8_t>(value));
state = kBeforeValue;
value = 0;
continue;
}
if (c == ']') {
DCHECK_LT(value, 256);
output_bytes.push_back(static_cast<uint8_t>(value));
return output_bytes.size() > 8 ? ParseLiteralResult::kSuccess
: ParseLiteralResult::kTryNext;
}
if (state == kAfterValue) {
// Didn't take the ',' or ']' paths above, anything else is invalid.
DCHECK(c != ',' && c != ']');
return c == EOF ? ParseLiteralResult::kEOF
: ParseLiteralResult::kTryNext;
}
DCHECK(state == kDecimal || state == kHex);
if (IsWhitespace(c)) {
state = kAfterValue;
continue;
}
int v;
if (c >= '0' && c <= '9') {
v = c - '0';
} else if (state == kHex && (c | 0x20) >= 'a' && (c | 0x20) <= 'f') {
// Setting the "0x20" bit maps uppercase onto lowercase letters.
v = (c | 0x20) - 'a' + 10;
} else {
return c == EOF ? ParseLiteralResult::kEOF
: ParseLiteralResult::kTryNext;
}
value = value * state + v;
if (value > 0xFF) return ParseLiteralResult::kTryNext;
}
}
base::Vector<const uint8_t> raw_bytes() const {
return base::VectorOf(raw_bytes_);
}
const WasmModule* module() { return module_.get(); }
NamesProvider* names() { return names_provider_.get(); }
AccountingAllocator allocator_;
Output output_;
std::ostream& out_;
Status status_{kNotReady};
bool print_offsets_;
std::vector<uint8_t> raw_bytes_;
ModuleWireBytes wire_bytes_{{}};
std::shared_ptr<WasmModule> module_;
std::unique_ptr<OffsetsProvider> offsets_provider_;
std::unique_ptr<NamesProvider> names_provider_;
};
DumpingModuleDecoder::DumpingModuleDecoder(ModuleWireBytes wire_bytes,
HexDumpModuleDis* module_dis)
: ModuleDecoderImpl(WasmEnabledFeatures::All(), wire_bytes.module_bytes(),
kWasmOrigin, &unused_detected_features_, module_dis) {}
} // namespace v8::internal::wasm
using FormatConverter = v8::internal::wasm::FormatConverter;
using OutputMode = v8::internal::wasm::OutputMode;
using MultiLineStringBuilder = v8::internal::wasm::MultiLineStringBuilder;
enum class Action {
kUnset,
kHelp,
kListFunctions,
kListSignatures,
kSectionStats,
kInstructionStats,
kFunctionStats,
kFullWat,
kFullHexdump,
kMjsunit,
kSingleWat,
kSingleHexdump,
kStrip,
};
struct Options {
const char* input = nullptr;
const char* output = nullptr;
Action action = Action::kUnset;
int func_index = -1;
bool offsets = false;
int fct_bucket_size = 100;
int fct_bucket_count = 20;
};
bool ParseInt(char* s, int* out) {
char* end;
if (s[0] == '\0') return false;
errno = 0;
long l = strtol(s, &end, 10);
if (errno != 0 || *end != '\0' || l > std::numeric_limits<int>::max() ||
l < std::numeric_limits<int>::min()) {
return false;
}
*out = static_cast<int>(l);
return true;
}
int ParseOptions(int argc, char** argv, Options* options) {
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-h") == 0 ||
strcmp(argv[i], "help") == 0) {
options->action = Action::kHelp;
} else if (strcmp(argv[i], "--list-functions") == 0) {
options->action = Action::kListFunctions;
} else if (strcmp(argv[i], "--list-signatures") == 0) {
options->action = Action::kListSignatures;
} else if (strcmp(argv[i], "--section-stats") == 0) {
options->action = Action::kSectionStats;
} else if (strcmp(argv[i], "--instruction-stats") == 0) {
options->action = Action::kInstructionStats;
} else if (strcmp(argv[i], "--function-stats") == 0) {
options->action = Action::kFunctionStats;
if (i < argc - 1 && ParseInt(argv[i + 1], &options->fct_bucket_size)) {
++i;
if (options->fct_bucket_size <= 0) {
std::cerr << "invalid argument for --function-stats: bucket size may "
"not be negative\n";
return PrintHelp(argv);
}
}
if (i < argc - 1 && ParseInt(argv[i + 1], &options->fct_bucket_count)) {
++i;
if (options->fct_bucket_count <= 0) {
std::cerr << "invalid argument for --function-stats: bucket count "
"may not be negative\n";
return PrintHelp(argv);
}
}
} else if (strcmp(argv[i], "--full-wat") == 0) {
options->action = Action::kFullWat;
} else if (strcmp(argv[i], "--full-hexdump") == 0) {
options->action = Action::kFullHexdump;
} else if (strcmp(argv[i], "--mjsunit") == 0) {
options->action = Action::kMjsunit;
} else if (strcmp(argv[i], "--single-wat") == 0) {
options->action = Action::kSingleWat;
if (i == argc - 1 || !ParseInt(argv[++i], &options->func_index)) {
return PrintHelp(argv);
}
} else if (strncmp(argv[i], "--single-wat=", 13) == 0) {
options->action = Action::kSingleWat;
if (!ParseInt(argv[i] + 13, &options->func_index)) return PrintHelp(argv);
} else if (strcmp(argv[i], "--single-hexdump") == 0) {
options->action = Action::kSingleHexdump;
if (i == argc - 1 || !ParseInt(argv[++i], &options->func_index)) {
return PrintHelp(argv);
}
} else if (strncmp(argv[i], "--single-hexdump=", 17) == 0) {
if (!ParseInt(argv[i] + 17, &options->func_index)) return PrintHelp(argv);
} else if (strcmp(argv[i], "--strip") == 0) {
options->action = Action::kStrip;
} else if (strcmp(argv[i], "-o") == 0) {
if (i == argc - 1) return PrintHelp(argv);
options->output = argv[++i];
} else if (strncmp(argv[i], "-o=", 3) == 0) {
options->output = argv[i] + 3;
} else if (strcmp(argv[i], "--output") == 0) {
if (i == argc - 1) return PrintHelp(argv);
options->output = argv[++i];
} else if (strncmp(argv[i], "--output=", 9) == 0) {
options->output = argv[i] + 9;
} else if (strcmp(argv[i], "--offsets") == 0) {
options->offsets = true;
} else if (options->input != nullptr) {
return PrintHelp(argv);
} else {
options->input = argv[i];
}
}
#if V8_OS_POSIX
// When piping data into wami, specifying the input as "-" is optional.
if (options->input == nullptr && !isatty(STDIN_FILENO)) {
options->input = "-";
}
#endif
if (options->output == nullptr) {
// Refuse to send binary data to the terminal.
if (options->action == Action::kStrip) {
#if V8_OS_POSIX
// Piping binary output to another command is okay.
if (isatty(STDOUT_FILENO)) return PrintHelp(argv);
#else
return PrintHelp(argv);
#endif
}
options->output = "-"; // Default output: stdout.
}
if (options->action == Action::kUnset || options->input == nullptr) {
return PrintHelp(argv);
}
return 0;
}
int main(int argc, char** argv) {
Options options;
if (ParseOptions(argc, argv, &options) != 0) return 1;
if (options.action == Action::kHelp) {
PrintHelp(argv);
return 0;
}
// Bootstrap the basics.
v8::V8::InitializeICUDefaultLocation(argv[0]);
v8::V8::InitializeExternalStartupData(argv[0]);
std::unique_ptr<v8::Platform> platform = v8::platform::NewDefaultPlatform();
v8::V8::InitializePlatform(platform.get());
v8::V8::Initialize();
FormatConverter fc(options.input, options.output, options.offsets);
if (fc.status() == FormatConverter::kNotReady) return 1;
// Allow hex dumping invalid modules.
if (fc.status() != FormatConverter::kModuleReady &&
options.action != Action::kFullHexdump) {
std::cerr << "Consider using --full-hexdump to learn more.\n";
return 1;
}
switch (options.action) {
case Action::kListFunctions:
fc.ListFunctions();
break;
case Action::kListSignatures:
fc.ListSignatures();
break;
case Action::kSectionStats:
fc.SectionStats();
break;
case Action::kInstructionStats:
fc.InstructionStats();
break;
case Action::kFunctionStats:
fc.FunctionStats(options.fct_bucket_size, options.fct_bucket_count);
break;
case Action::kSingleWat:
fc.DisassembleFunction(options.func_index, OutputMode::kWat);
break;
case Action::kSingleHexdump:
fc.DisassembleFunction(options.func_index, OutputMode::kHexDump);
break;
case Action::kFullWat:
fc.WatForModule();
break;
case Action::kFullHexdump:
fc.HexdumpForModule();
break;
case Action::kMjsunit:
fc.Mjsunit();
break;
case Action::kStrip:
fc.Strip();
break;
case Action::kHelp:
case Action::kUnset:
UNREACHABLE();
}
v8::V8::Dispose();
v8::V8::DisposePlatform();
return 0;
}
|