Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
wasmbinary.cpp
Go to the documentation of this file.
1// Copyright (C) 2025 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0
3
4#include "wasmbinary.h"
5
6#include <QFile>
7
8#include <iostream>
9
10WasmBinary::WasmBinary(QString filepath)
11{
12 QFile file(filepath);
13 if (!file.open(QIODevice::ReadOnly)) {
14 std::cout << "ERROR: Cannot open the file " << filepath.toStdString() << std::endl;
15 std::cout << file.errorString().toStdString() << std::endl;
17 return;
18 }
19 auto bytes = file.readAll();
20 if (!parsePreambule(bytes)) {
22 }
23}
24
25bool WasmBinary::parsePreambule(QByteArrayView data)
26{
27 const auto preambuleSize = 24;
28 if (data.size() < preambuleSize) {
29 std::cout << "ERROR: Preambule of binary shorter than expected!" << std::endl;
30 return false;
31 }
32 uint32_t int32View[6];
33 std::memcpy(int32View, data.data(), sizeof(int32View));
34 if (int32View[0] != 0x6d736100) {
35 std::cout << "ERROR: Magic WASM number not found in binary. Binary corrupted?" << std::endl;
36 return false;
37 }
38 if (data[8] != 0) {
40 return true;
41 } else {
43 }
44 const auto sectionStart = 9;
45 size_t offset = sectionStart;
46 auto sectionSize = getLeb(data, offset);
47 auto sectionEnd = sectionStart + sectionSize;
48 auto name = getString(data, offset);
49 if (name != "dylink.0") {
51 std::cout << "ERROR: dylink.0 was not found in supposedly dynamically linked module"
52 << std::endl;
53 return false;
54 }
55
56 const auto WASM_DYLINK_NEEDED = 0x2;
57 while (offset < sectionEnd) {
58 auto subsectionType = data[offset++];
59 auto subsectionSize = getLeb(data, offset);
60 if (subsectionType == WASM_DYLINK_NEEDED) {
61 auto neededDynlibsCount = getLeb(data, offset);
62 while (neededDynlibsCount--) {
63 dependencies.append(getString(data, offset));
64 }
65 } else {
66 offset += subsectionSize;
67 }
68 }
69 return true;
70}
71
72size_t WasmBinary::getLeb(QByteArrayView data, size_t &offset)
73{
74 auto ret = 0;
75 auto mul = 1;
76 while (true) {
77 auto byte = data[offset++];
78 ret += (byte & 0x7f) * mul;
79 mul *= 0x80;
80 if (!(byte & 0x80))
81 break;
82 }
83 return ret;
84}
85
86QString WasmBinary::getString(QByteArrayView data, size_t &offset)
87{
88 auto length = getLeb(data, offset);
89 offset += length;
90 return QString::fromUtf8(data.sliced(offset - length, length));
91}
WasmBinary(QString filepath)