-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdissasembleClass.js
566 lines (516 loc) · 16.8 KB
/
dissasembleClass.js
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
module.exports = {
disassemble,parseClassFile
};
function disassemble(ast, constantPool) {
const output = [];
const constantPoolMap = {};
for (let i = 1; i < constantPool.length; i++) {
const entry = constantPool[i];
if (entry) {
constantPoolMap[i] = entry;
}
}
// Helper functions
function getUtf8(index) {
const entry = constantPoolMap[index];
if (entry && entry.tag === 1) {
return entry.info.bytes;
}
return null;
}
function getClassName(index) {
const entry = constantPoolMap[index];
if (entry && entry.tag === 7) {
const nameIndex = entry.info.name_index;
const name = getUtf8(nameIndex);
return name.replace(/\//g, ".");
}
return null;
}
function getNameAndType(index) {
const entry = constantPoolMap[index];
if (entry && entry.tag === 12) {
const name = getUtf8(entry.info.name_index);
const descriptor = getUtf8(entry.info.descriptor_index);
return { name, descriptor };
}
return null;
}
function getMethodRef(index) {
const entry = constantPoolMap[index];
if (entry && entry.tag === 10) {
const className = getClassName(entry.info.class_index);
const nameAndType = getNameAndType(entry.info.name_and_type_index);
return {
className,
name: nameAndType.name,
descriptor: nameAndType.descriptor
};
}
return null;
}
function getFieldRef(index) {
const entry = constantPoolMap[index];
if (entry && entry.tag === 9) {
const className = getClassName(entry.info.class_index);
const nameAndType = getNameAndType(entry.info.name_and_type_index);
return {
className,
name: nameAndType.name,
descriptor: nameAndType.descriptor
};
}
return null;
}
function getInterfaceMethodRef(index) {
const entry = constantPoolMap[index];
if (entry && entry.tag === 11) {
const className = getClassName(entry.info.class_index);
const nameAndType = getNameAndType(entry.info.name_and_type_index);
return {
className,
name: nameAndType.name,
descriptor: nameAndType.descriptor
};
}
return null;
}
function getAccessFlags(flags, context = "class") {
const access = [];
const flagMap = {
class: {
0x0001: "public",
0x0010: "final",
0x0020: "super",
0x0200: "interface",
0x0400: "abstract",
0x1000: "synthetic",
0x2000: "annotation",
0x4000: "enum",
0x8000: "module"
},
method: {
0x0001: "public",
0x0002: "private",
0x0004: "protected",
0x0008: "static",
0x0010: "final",
0x0020: "synchronized",
0x0040: "bridge",
0x0080: "varargs",
0x0100: "native",
0x0400: "abstract",
0x0800: "strictfp",
0x1000: "synthetic"
},
field: {
0x0001: "public",
0x0002: "private",
0x0004: "protected",
0x0008: "static",
0x0010: "final",
0x0040: "volatile",
0x0080: "transient",
0x1000: "synthetic",
0x4000: "enum"
}
};
for (const flag in flagMap[context]) {
if (flags & flag) {
access.push(flagMap[context][flag]);
}
}
return access.join(" ");
}
// Output header
if (ast.sourceFile) {
output.push(`Compiled from "${ast.sourceFile}"`);
}
// Class declaration
const classAccess = getAccessFlags(ast.accessFlags, "class");
const className = ast.className;
const superClassName = ast.superClassName;
output.push(`${classAccess} class ${className} extends ${superClassName} {`);
// Fields
for (const field of ast.fields) {
const fieldAccess = getAccessFlags(field.accessFlags, "field");
const fieldDescriptor = field.descriptor;
output.push(` ${fieldDescriptor} ${field.name};`);
}
output.push("");
// Methods
for (const method of ast.methods) {
const methodAccess = getAccessFlags(method.accessFlags, "method");
const methodDescriptor = method.descriptor;
const methodName = method.name;
const exceptions = method.exceptions;
// Simplify method signature for display purposes
const returnType = methodDescriptor.substring(
methodDescriptor.lastIndexOf(")") + 1
);
const methodSignature = `${methodAccess} ${returnType} ${methodName}(${methodDescriptor.substring(
1,
methodDescriptor.lastIndexOf(")")
)});`;
let methodLine = ` ${methodSignature}`;
if (exceptions && exceptions.length > 0) {
methodLine += ` throws ${exceptions.join(", ")}`;
}
output.push(methodLine);
// Output Code:
if (method.code) {
const codeOutput = processMethod(method);
codeOutput.split("\n").forEach((line) => output.push(` ${line}`));
}
output.push("");
}
output.push("}");
function processMethod(method) {
const output = [];
const instructions = method.code.instructions;
// Process instructions
for (const instr of instructions) {
const pc = instr.pc;
const opcodeName = instr.opcodeName;
const operands = instr.operands;
const comment = instr.comment;
// Output the instruction
let line = `${pc}: ${opcodeName}`;
// Process operands
if (opcodeName === "tableswitch") {
// Handle 'tableswitch'
line += " { // ";
line += `${operands.low} to ${operands.high}`;
output.push(line);
for (let i = 0; i < operands.jumpOffsets.length; i++) {
const value = operands.low + i;
const targetPc = operands.jumpOffsets[i];
output.push(` res ${value}: ${targetPc}`);
}
const defaultPc = operands.default;
output.push(` default: ${defaultPc}`);
output.push(" }");
continue;
} else if (
opcodeName.startsWith("if") ||
opcodeName === "goto" ||
opcodeName === "jsr"
) {
const targetPc = instr.pc + operands.branchoffset;
line += ` ${targetPc}`;
} else if (
[
"getstatic",
"putstatic",
"getfield",
"putfield",
"invokevirtual",
"invokespecial",
"invokestatic",
"invokeinterface",
"new",
"anewarray",
"checkcast",
"instanceof"
].includes(opcodeName)
) {
const index = operands.index;
line += ` #${index}`;
if (opcodeName === "invokeinterface") {
// Also include count and zero operands
line += `, ${operands.count}`;
}
// Now, resolve the comment
let commentText = "";
if (
opcodeName === "getfield" ||
opcodeName === "putfield" ||
opcodeName === "getstatic" ||
opcodeName === "putstatic"
) {
const fieldRef = getFieldRef(index);
commentText = `Field ${fieldRef.className}.${fieldRef.name}:${fieldRef.descriptor}`;
} else if (
opcodeName === "invokevirtual" ||
opcodeName === "invokespecial" ||
opcodeName === "invokestatic"
) {
const methodRef = getMethodRef(index);
commentText = `Method ${methodRef.className}.${methodRef.name}:${methodRef.descriptor}`;
} else if (opcodeName === "invokeinterface") {
const methodRef = getInterfaceMethodRef(index);
commentText = `InterfaceMethod ${methodRef.className}.${methodRef.name}:${methodRef.descriptor}`;
} else if (
opcodeName === "new" ||
opcodeName === "anewarray" ||
opcodeName === "checkcast" ||
opcodeName === "instanceof"
) {
const className = getClassName(index);
commentText = `Class ${className}`;
}
if (commentText) {
line = line.padEnd(40) + ` // ${commentText}`;
}
} else if (
opcodeName === "ldc" ||
opcodeName === "ldc_w" ||
opcodeName === "ldc2_w"
) {
const index = operands.index;
line += ` #${index}`;
const cpEntry = constantPoolMap[index];
let commentText = "";
if (cpEntry.tag === 8) {
const stringValue = getUtf8(cpEntry.info.string_index);
commentText = `String "${stringValue}"`;
} else if (cpEntry.tag === 3) {
commentText = `int ${cpEntry.info.bytes}`;
} else if (cpEntry.tag === 4) {
commentText = `float ${cpEntry.info.bytes}`;
} else if (cpEntry.tag === 7) {
const className = getClassName(cpEntry.info.name_index);
commentText = `Class ${className}`;
}
if (commentText) {
line = line.padEnd(40) + ` // ${commentText}`;
}
} else if ("index" in operands) {
line += ` ${operands.index}`;
} else if ("value" in operands) {
line += ` ${operands.value}`;
}
output.push(line);
}
// Output exception table
if (method.code.exceptionTable && method.code.exceptionTable.length > 0) {
output.push("Exception table:");
output.push(" from to target type");
for (const exception of method.code.exceptionTable) {
const startPc = exception.start_pc;
const endPc = exception.end_pc;
const handlerPc = exception.handler_pc;
const catchTypeIndex = exception.catch_type;
let catchTypeName = "any";
if (catchTypeIndex !== 0) {
catchTypeName = getClassName(catchTypeIndex);
}
output.push(
` ${startPc} ${endPc} ${handlerPc} Class ${catchTypeName}`
);
}
}
return output.join("\n");
}
return output.join("\n");
}
function parseClassFile(jsonObject, opcodeNames) {
const cpEntries = jsonObject.constant_pool.entries;
const constantPool = []; // Use 1-based indexing for constant pool
// Build the constant pool mapping
for (let i = 1; i < cpEntries.length; i++) {
constantPool[i] = cpEntries[i];
}
// Helper functions to resolve constant pool entries
function getUtf8(index) {
const entry = constantPool[index];
if (entry && entry.tag === 1) {
return entry.info.bytes;
}
return null;
}
function getClassName(index) {
const entry = constantPool[index];
if (entry && entry.tag === 7) {
return getUtf8(entry.info.name_index).replace(/\//g, ".");
}
return null;
}
function getNameAndType(index) {
const entry = constantPool[index];
if (entry && entry.tag === 12) {
const name = getUtf8(entry.info.name_index);
const descriptor = getUtf8(entry.info.descriptor_index);
return { name, descriptor };
}
return null;
}
function getMethodRef(index) {
const entry = constantPool[index];
if (entry && entry.tag === 10) {
const className = getClassName(entry.info.class_index);
const nameAndType = getNameAndType(entry.info.name_and_type_index);
return {
className,
name: nameAndType.name,
descriptor: nameAndType.descriptor
};
}
return null;
}
function getFieldRef(index) {
const entry = constantPool[index];
if (entry && entry.tag === 9) {
const className = getClassName(entry.info.class_index);
const nameAndType = getNameAndType(entry.info.name_and_type_index);
return {
className,
name: nameAndType.name,
descriptor: nameAndType.descriptor
};
}
return null;
}
function getInterfaceMethodRef(index) {
const entry = constantPool[index];
if (entry && entry.tag === 11) {
const className = getClassName(entry.info.class_index);
const nameAndType = getNameAndType(entry.info.name_and_type_index);
return {
className,
name: nameAndType.name,
descriptor: nameAndType.descriptor
};
}
return null;
}
// Parse the class file
const ast = {
sourceFile: null,
className: getClassName(jsonObject.this_class),
superClassName: getClassName(jsonObject.super_class),
accessFlags: jsonObject.access_flags,
fields: [],
methods: [],
major_version: jsonObject.major_version,
minor_version: jsonObject.minor_version
};
// Resolve source file name
const sourceFileAttr = jsonObject.attributes.find(
(attr) => getUtf8(attr.attribute_name_index.index) === "SourceFile"
);
if (sourceFileAttr) {
ast.sourceFile = getUtf8(sourceFileAttr.info.sourcefile_index);
}
// Process fields
for (const field of jsonObject.fields) {
const fieldName = getUtf8(field.name_index);
const fieldDescriptor = getUtf8(field.descriptor_index);
ast.fields.push({
name: fieldName,
descriptor: fieldDescriptor,
accessFlags: field.access_flags
});
}
// Process methods
for (const method of jsonObject.methods) {
const methodName = getUtf8(method.name_index);
const methodDescriptor = getUtf8(method.descriptor_index);
const methodInfo = {
name: methodName,
descriptor: methodDescriptor,
accessFlags: method.access_flags,
code: null,
exceptions: []
};
// Find the Code attribute
const codeAttr = method.attributes.find(
(attr) => getUtf8(attr.attribute_name_index.index) === "Code"
);
if (codeAttr) {
const codeInfo = codeAttr.info;
const instructions = [];
let pc = 0;
for (const inst of codeInfo.code.instructions) {
const opcode = inst.instruction.opcode;
const opcodeInfo = inst.instruction.info || {};
const opcodeLength = opcodeInfo.length || 1;
const instruction = {
pc,
opcode,
opcodeName: opcodeNames[opcode], // To be resolved later
operands: opcodeInfo,
comment: null
};
// Resolve operands for specific opcodes
if ("index" in opcodeInfo) {
const index = opcodeInfo.index;
if (
opcode === 178 ||
opcode === 179 ||
opcode === 180 ||
opcode === 181
) {
// getstatic, putstatic, getfield, putfield
const fieldRef = getFieldRef(index);
instruction.comment = `Field ${fieldRef.className}.${fieldRef.name}:${fieldRef.descriptor}`;
} else if (
opcode === 182 ||
opcode === 183 ||
opcode === 184 ||
opcode === 185
) {
// invokevirtual, invokespecial, invokestatic, invokeinterface
const methodRef =
opcode === 185
? getInterfaceMethodRef(index)
: getMethodRef(index);
instruction.comment = `Method ${methodRef.className}.${methodRef.name}:${methodRef.descriptor}`;
} else if (
opcode === 187 ||
opcode === 189 ||
opcode === 192 ||
opcode === 193
) {
// new, anewarray, checkcast, instanceof
const className = getClassName(index);
instruction.comment = `Class ${className}`;
} else if (opcode === 18 || opcode === 19 || opcode === 20) {
// ldc, ldc_w, ldc2_w
const cpEntry = constantPool[index];
if (cpEntry) {
if (cpEntry.tag === 8) {
const stringValue = getUtf8(cpEntry.info.string_index);
instruction.comment = `String "${stringValue}"`;
} else if (cpEntry.tag === 3) {
instruction.comment = `int ${cpEntry.info.bytes}`;
} else if (cpEntry.tag === 4) {
instruction.comment = `float ${cpEntry.info.bytes}`;
} else if (cpEntry.tag === 7) {
const className = getClassName(cpEntry.info.name_index);
instruction.comment = `Class ${className}`;
}
}
} else if (opcode === 197) {
// multianewarray
const className = getClassName(index);
instruction.comment = `Class ${className}`;
}
}
instructions.push(instruction);
pc += opcodeLength; // Simplification; in reality, instruction lengths vary
}
methodInfo.code = {
maxStack: codeInfo.max_stack,
maxLocals: codeInfo.max_locals,
codeLength: codeInfo.code_length,
instructions,
exceptionTable: codeInfo.exception_table,
attributes: codeInfo.attributes
};
}
// Process exceptions
const exceptionsAttr = method.attributes.find(
(attr) => getUtf8(attr.attribute_name_index.index) === "Exceptions"
);
if (exceptionsAttr) {
const exceptionIndexes = exceptionsAttr.info.exception_index_table;
for (const exceptionIndex of exceptionIndexes) {
const exceptionName = getClassName(exceptionIndex);
methodInfo.exceptions.push(exceptionName);
}
}
ast.methods.push(methodInfo);
}
return { ast, constantPool };
}