Skip to content

Commit 2d981ae

Browse files
committed
+ tests
1 parent 8aa3af6 commit 2d981ae

File tree

3 files changed

+80
-0
lines changed

3 files changed

+80
-0
lines changed

classpy-wasm/src/main/java/com/github/zxh/classpy/wasm/WasmBinReader.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44

55
import java.nio.ByteOrder;
66

7+
// https://en.wikipedia.org/wiki/LEB128
78
public class WasmBinReader extends BytesReader {
89

910
public WasmBinReader(byte[] data) {
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
package com.github.zxh.classpy.wasm;
2+
3+
import com.github.zxh.classpy.common.FileComponent;
4+
import com.github.zxh.classpy.wasm.instructions.Expr;
5+
import com.github.zxh.classpy.wasm.instructions.Instr;
6+
import com.github.zxh.classpy.wasm.sections.Code;
7+
import org.junit.Test;
8+
9+
import java.util.Base64;
10+
11+
public class FuncTest {
12+
13+
@Test
14+
public void read() {
15+
String base64 = "AQJ/IAIEfwNAIAAsAAAiAyABLAAAIgRGBEAgAEEBaiEAIAFBAWohAUEAIAJBf2oiAkUNAxoMAQsLIANB/wFxIARB/wFxawVBAAsPCw==";
16+
byte[] code = Base64.getDecoder().decode(base64);
17+
Code.Func func = new Code.Func();
18+
try {
19+
func.read(new WasmBinReader(code));
20+
} catch (Exception e) {
21+
new ExprPrinter().printExpr((Expr) func.getComponents().get(1));
22+
throw e;
23+
}
24+
}
25+
26+
27+
private static class ExprPrinter {
28+
29+
private int indentation;
30+
31+
private void printExpr(Expr expr) {
32+
for (FileComponent fc : expr.getComponents()) {
33+
printInstr((Instr) fc);
34+
}
35+
}
36+
37+
private void printInstr(Instr instr) {
38+
if (instr.getOpcode() == 0x0B
39+
|| instr.getOpcode() == 0x05) {
40+
indentation -= 1;
41+
}
42+
for (int i = 0; i < indentation; i++) {
43+
System.out.print("\t");
44+
}
45+
System.out.println(instr.getName());
46+
if (instr.getOpcode() == 0x02
47+
|| instr.getOpcode() == 0x03
48+
|| instr.getOpcode() == 0x04) {
49+
indentation += 1;
50+
}
51+
for (FileComponent fc : instr.getComponents()) {
52+
if (fc instanceof Instr) {
53+
printInstr((Instr) fc);
54+
}
55+
}
56+
}
57+
}
58+
59+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
package com.github.zxh.classpy.wasm;
2+
3+
import org.junit.Assert;
4+
import org.junit.Test;
5+
6+
public class LEB128Test {
7+
8+
@Test
9+
public void readU32() {
10+
Assert.assertEquals(624485,
11+
new WasmBinReader(new byte[] {(byte) 0xE5, (byte) 0x8E, 0x26}).readU32());
12+
}
13+
14+
@Test
15+
public void readS32() {
16+
Assert.assertEquals(-624485,
17+
new WasmBinReader(new byte[] {(byte) 0x9B, (byte) 0xF1, 0x59}).readS32());
18+
}
19+
20+
}

0 commit comments

Comments
 (0)