-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNativeExports.java
More file actions
288 lines (250 loc) · 9.64 KB
/
Copy pathNativeExports.java
File metadata and controls
288 lines (250 loc) · 9.64 KB
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
package unluac;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import org.graalvm.nativeimage.IsolateThread;
import org.graalvm.nativeimage.UnmanagedMemory;
import org.graalvm.nativeimage.c.function.CEntryPoint;
import org.graalvm.nativeimage.c.type.CCharPointer;
import org.graalvm.nativeimage.c.type.CCharPointerPointer;
import org.graalvm.nativeimage.c.type.CIntPointer;
import org.graalvm.nativeimage.c.type.CTypeConversion;
import org.graalvm.word.WordFactory;
import unluac.assemble.Tokenizer;
import unluac.decompile.*;
import unluac.parse.BHeader;
public final class NativeExports {
private enum ResultCode {
OK(0),
ERROR(1),
PARTIAL_DECOMPILE(2),
CORRUPTED_OPCODE_MAP(3);
private final int value;
ResultCode(int value) {
this.value = value;
}
private int value() {
return value;
}
}
private static final int FLAG_RAWSTRING = 1 << 0;
private static final int FLAG_LUAJ = 1 << 1;
private static final int FLAG_NODEBUG = 1 << 2;
private static final int FLAG_OpCodeMap = 1 << 16;
private static final int FLAG_OpCodeMapPatch = 1 << 17;
private static final int FLAG_DECOMPILE = 1 << 24;
private static final int FLAG_DISASSEMBLE = 1 << 25;
private static final int OPMAP_PATCH_FORMAT_VERSION = 0;
private static final class ErrorBuffer {
private ErrorBuffer() {}
private static void clear(StringBuilder errorBuffer) {
if(errorBuffer != null) {
errorBuffer.setLength(0);
}
}
private static void print(StringBuilder errorBuffer, String message) {
if(message == null || message.isEmpty()) {
return;
}
if(!errorBuffer.isEmpty()) {
errorBuffer.append('\n');
}
errorBuffer.append(message);
System.err.println(message);
}
private static void print(StringBuilder errorBuffer, Throwable t) {
if(t == null) {
return;
}
StringWriter stackTrace = new StringWriter();
PrintWriter writer = new PrintWriter(stackTrace);
t.printStackTrace(writer);
writer.flush();
print(errorBuffer, stackTrace.toString().trim());
}
private static String get(StringBuilder errorBuffer) {
return errorBuffer == null ? "" : errorBuffer.toString();
}
}
private static Configuration configFromFlags(int flags) {
Configuration cfg = new Configuration();
if ((flags & FLAG_RAWSTRING) != 0) cfg.rawstring = true;
if ((flags & FLAG_LUAJ) != 0) cfg.luaj = true;
if ((flags & FLAG_NODEBUG) != 0) cfg.variable = Configuration.VariableMode.NODEBUG;
return cfg;
}
private static InputStream toInputStream(CCharPointer ptr, int len) {
if (ptr.isNull() || len <= 0) return InputStream.nullInputStream();
ByteBuffer bb = CTypeConversion.asByteBuffer(ptr, len);
byte[] bytes = new byte[bb.remaining()];
bb.get(bytes);
return new ByteArrayInputStream(bytes);
}
private static void readOpCodeMapBuffer(CCharPointer opMapData, int opMapLen, BHeader header) {
try (InputStream in = toInputStream(opMapData, opMapLen)) {
Tokenizer t = new Tokenizer(in);
String tok;
Map<Integer, Op> useropmap = new HashMap<>();
while ((tok = t.next()) != null) {
if (tok.equals(".op")) {
tok = t.next();
if (tok == null) throw new RuntimeException("Unexpected end of opmap file.");
int opcode;
try {
opcode = Integer.parseInt(tok);
} catch (NumberFormatException e) {
throw new RuntimeException("Excepted number in opmap file, got \"" + tok + "\".");
}
tok = t.next();
if (tok == null) throw new RuntimeException("Unexpected end of opmap file.");
Op op = header.opmap.get(tok);
if (op == null) throw new RuntimeException("Unknown op name \"" + tok + "\" in opmap file.");
useropmap.put(opcode, op);
} else {
throw new RuntimeException("Unexpected token \"" + tok + "\" + in opmap file.");
}
}
header.opmap = new OpcodeMap(useropmap);
} catch (IOException e) {
throw new RuntimeException(e.getMessage());
}
}
/**
* Binary patch format:
* u16 formatVersion
* u16 reserved
* u32 remapCount
* remapCount * (u8 dstOpcodeIndex, u8 srcDefaultOpcodeIndex)
* u32 explicitCount
* explicitCount * (u8 dstOpcodeIndex, u8 opId [Op enum ordinal])
*/
private static void patchOpCodeMapFromBuffer(CCharPointer opMapData, int opMapLen, BHeader header) {
if(opMapLen < 12)
throw new IllegalArgumentException("Invalid opcode map patch data.");
ByteBuffer patchBuffer = CTypeConversion.asByteBuffer(opMapData, opMapLen).order(ByteOrder.LITTLE_ENDIAN);
int formatVersion = patchBuffer.getShort();
if(formatVersion != OPMAP_PATCH_FORMAT_VERSION) {
throw new IllegalArgumentException("Unsupported opcode map patch format version: " + formatVersion);
}
patchBuffer.getShort(); // padding
OpcodeMap defaultMap = header.version.getOpcodeMap();
Map<Integer, Op> userMap = new HashMap<>(defaultMap.size());
for(int i = 0; i < defaultMap.size(); i++) {
userMap.put(i, defaultMap.get(i));
}
int remapCount = patchBuffer.getInt();
for(int i = 0; i < remapCount; i++) {
int dst = patchBuffer.get();
int src = patchBuffer.get();
userMap.put(dst, defaultMap.get(src));
}
int explicitCount = patchBuffer.getInt();
if (explicitCount > 0) {
Op[] ops = Op.values();
for(int i = 0; i < explicitCount; i++) {
int dst = patchBuffer.get();
int opId = patchBuffer.get();
if (opId < 0 || opId >= ops.length) userMap.put(dst, null);
else userMap.put(dst, ops[opId]);
}
}
header.opmap = new OpcodeMap(userMap);
}
private static ResultCode tryUpdateOpcodeMap(int flags, CCharPointer opMapData, int opMapLen, BHeader header, StringBuilder errorBuffer ) {
try {
if ((flags & FLAG_OpCodeMapPatch) != 0) {
patchOpCodeMapFromBuffer(opMapData, opMapLen, header);
} else if ((flags & FLAG_OpCodeMap) != 0) {
readOpCodeMapBuffer(opMapData, opMapLen, header);
}
} catch (Throwable t){
ErrorBuffer.print(errorBuffer, t);
return ResultCode.CORRUPTED_OPCODE_MAP;
}
return ResultCode.OK;
}
private record ResultWithCode(ResultCode code, byte[] data) {}
private static ResultWithCode getResult(int flags, BHeader header, StringBuilder errorBuffer) {
ResultCode code = ResultCode.OK;
MemoryOutputProvider memProvider = new MemoryOutputProvider();
Output out = new Output(memProvider);
try {
if ((flags & FLAG_DECOMPILE) != 0) {
Decompiler d = new Decompiler(header.main);
Decompiler.State state = d.decompile();
d.print(state, out);
} else {
Disassembler d = new Disassembler(header.main);
d.disassemble(out);
}
} catch (Throwable t) {
code = ResultCode.PARTIAL_DECOMPILE;
ErrorBuffer.print(errorBuffer, t);
}
finally {
out.finish();
}
return new ResultWithCode(code, memProvider.toByteArray());
}
@CEntryPoint(name = "unluac_create_isolate", builtin = CEntryPoint.Builtin.CREATE_ISOLATE)
public static native IsolateThread createIsolate();
@CEntryPoint(name = "unluac_tear_down_isolate", builtin = CEntryPoint.Builtin.TEAR_DOWN_ISOLATE)
public static native int tearDownIsolate(IsolateThread thread);
@CEntryPoint(name = "unluac_free")
public static void unluacFree(IsolateThread thread, CCharPointer ptr) {
if (ptr.isNonNull()) {
UnmanagedMemory.free(ptr);
}
}
@CEntryPoint(name = "unluac_decompile_buffer")
public static int processBuffer(
IsolateThread thread, int flags,
CCharPointer data, int dataLen,
CCharPointer opMapData, int opMapLen,
CCharPointerPointer outPtr, CIntPointer outLen,
CCharPointerPointer logPtr, CIntPointer logLen
) {
StringBuilder errorBuffer = new StringBuilder();
ResultCode outputResult = ResultCode.OK;
try {
ErrorBuffer.clear(errorBuffer);
ByteBuffer buffer = CTypeConversion.asByteBuffer(data, dataLen).order(ByteOrder.LITTLE_ENDIAN);
Configuration cfg = configFromFlags(flags);
BHeader header = new BHeader(buffer, cfg);
ResultCode opcodeResult = tryUpdateOpcodeMap(flags, opMapData, opMapLen, header, errorBuffer);
if (opcodeResult == ResultCode.OK) {
ResultWithCode result = getResult(flags, header, errorBuffer);
outputResult = result.code;
int dataLength = result.data.length;
CCharPointer mem = UnmanagedMemory.malloc(dataLength);
CTypeConversion.asByteBuffer(mem, dataLength).put(result.data);
outPtr.write(mem);
outLen.write(dataLength);
} else {
outputResult = opcodeResult;
}
} catch (Throwable t) {
ErrorBuffer.print(errorBuffer, t);
outPtr.write(WordFactory.nullPointer());
outLen.write(0);
outputResult = ResultCode.ERROR;
} finally {
String log = ErrorBuffer.get(errorBuffer);
if(log.isEmpty()) {
logPtr.write(WordFactory.nullPointer());
logLen.write(0);
} else {
byte[] logBytes = log.getBytes(StandardCharsets.UTF_8);
CCharPointer logMem = UnmanagedMemory.malloc(logBytes.length);
CTypeConversion.asByteBuffer(logMem, logBytes.length).put(logBytes);
logPtr.write(logMem);
logLen.write(logBytes.length);
}
ErrorBuffer.clear(errorBuffer);
}
return outputResult.value();
}
}