-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjavaClass.py
More file actions
604 lines (457 loc) · 20.2 KB
/
javaClass.py
File metadata and controls
604 lines (457 loc) · 20.2 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
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
#!/usr/bin/env python
import sys
import struct
import opcodes
MAGIC_NUMBERS = bytes([int(mv, 0) for mv in ['0xCA', '0xFE', '0xBA', '0xBE']])
JVM_NAMES = {45: 'J2SE 1.1',
46: 'J2SE 1.2',
47: 'J2SE 1.3',
48: 'J2SE 1.4',
49: 'J2SE 5.0',
50: 'J2SE 6.0',
51: 'J2SE 7',
52: 'J2SE 8'}
CP_TYPE_UTF8 = 'CONSTANT_Utf8_info'
CP_TYPE_CLASS = 'CONSTANT_Class'
CP_TYPE_FIELDREF = 'CONSTANT_Fieldref'
CP_TYPE_METHODREF = 'CONSTANT_Methodref'
CP_TYPE_INFMETHREF = 'CONSTANT_InterfaceMethodref'
CP_TYPE_STRING = 'CONSTANT_String'
CP_TYPE_INTEGER = 'CONSTANT_Integer'
CP_TYPE_FLOAT = 'CONSTANT_Float'
CP_TYPE_LONG = 'CONSTANT_Long'
CP_TYPE_DOUBLE = 'CONSTANT_Double'
CP_TYPE_NAMETYPE = 'CONSTANT_NameAndType'
ATTRIBUTE_CONSTANT_VALUE = 'ConstantValue'
ATTRIBUTE_CODE = 'Code'
ATTRIBUTE_STACK_MAP_TABLE = 'StackMapTable'
ATTRIBUTE_EXCEPTIONS = 'Exceptions'
ATTRIBUTE_INNER_CLASSES = 'InnerClasses'
ATTRIBUTE_ENCLOSING_METHOD = 'EnclosingMethod'
ATTRIBUTE_SYNTHETIC = 'Synthetic'
ATTRIBUTE_SIGNATURE = 'Signature'
ATTRIBUTE_SOURCE_FILE = 'SourceFile'
ATTRIBUTE_SOURCE_DEBUG_EXTENSION = 'SourceDebugExtension'
ATTRIBUTE_LINE_NUMBER_TABLE = 'LineNumberTable'
ATTRIBUTE_LOCAL_VARIABLE_TABLE = 'LocalVariableTable'
ATTRIBUTE_LOCAL_VARIABLE_TYPE_TABLE = 'LocalVariableTypeTable'
ATTRIBUTE_DEPRECATED = 'Deprecated'
ATTRIBUTE_RUNTIME_VISIBLE_ANNOTATIONS = 'RuntimeVisibleAnnotations'
ATTRIBUTE_RUNTIME_INVISIBLE_ANNOTATIONS = 'RuntimeInvisibleAnnotations'
ATTRIBUTE_RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS = 'RuntimeVisibleParameterAnnotations'
ATTRIBUTE_RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS = 'RuntimeInvisibleParameterAnnotations'
ATTRIBUTE_ANNOTATION_DEFAULT = 'AnnotationDefault'
ATTRIBUTE_BOOTSTRAP_METHODS = 'BootstrapMethods'
def decode_jutf8(b):
return b.replace(b'\xC0\x80', b'\x00').decode('utf8')
class CPI:
def __init__(self, jc, tag):
self.jc = jc
self.tag = tag
class CPIUTF8(CPI):
cp_type = CP_TYPE_UTF8
def __init__(self, jclass, tag, length, bts):
self.length = length
self.bytes = bts
self.value = decode_jutf8(bts)
super(CPIUTF8, self).__init__(jclass, tag)
def __str__(self):
return 'CP UTF8:"%s"' % self.value
class CPIInt(CPI):
cp_type = CP_TYPE_INTEGER
def __init__(self, jclass, tag, value):
self.value = value
super(CPIInt, self).__init__(jclass, tag)
def __str__(self):
return 'CP int:%s' % self.value
class CPIFloat(CPI):
cp_type = CP_TYPE_FLOAT
def __init__(self, jclass, tag, value):
self.value = value
super(CPIFloat, self).__init__(jclass, tag)
def __str__(self):
return 'CP float:%s' % self.value
class CPILong(CPI):
cp_type = CP_TYPE_LONG
def __init__(self, jclass, tag, value):
self.value = value
super(CPILong, self).__init__(jclass, tag)
def __str__(self):
return 'CP long:%s' % self.value
class CPIDouble(CPI):
cp_type = CP_TYPE_DOUBLE
def __init__(self, jclass, tag, value):
self.value = value
super(CPIDouble, self).__init__(jclass, tag)
def __str__(self):
return 'CP double:%s' % self.value
class CPIClassReference(CPI):
cp_type = CP_TYPE_CLASS
def __init__(self, jclass, tag, name_index):
self.name_index = name_index
super(CPIClassReference, self).__init__(jclass, tag)
def get_name(self):
return self.jc.get_cpi(self.name_index)
def __str__(self):
return 'CP class reference index:%s name:%s' % (self.name_index, self.get_name().value)
class CPIStringReference(CPI):
cp_type = CP_TYPE_STRING
def __init__(self, jclass, tag, string_index):
self.string_index = string_index
super(CPIStringReference, self).__init__(jclass, tag)
def __str__(self):
return 'CP string reference index: %s' % self.string_index
class CPIFMI(CPI):
def __init__(self, jclass, tag, class_index, name_and_type_index):
self.class_index = class_index
self.name_and_type_index = name_and_type_index
super(CPIFMI, self).__init__(jclass, tag)
class CPIFieldReference(CPIFMI):
cp_type = CP_TYPE_FIELDREF
def __str__(self):
return 'CP field reference: class ref %s name and type descriptor %s' % \
(self.class_index, self.name_and_type_index)
class CPIMethodReference(CPIFMI):
cp_type = CP_TYPE_METHODREF
def __str__(self):
return 'CP method reference: class ref %s name and type descriptor %s' % \
(self.class_index, self.name_and_type_index)
class CPIInterfaceReference(CPIFMI):
cp_type = CP_TYPE_INFMETHREF
def __str__(self):
return 'CP interface reference: class ref %s name and type descriptor %s' % \
(self.class_index, self.name_and_type_index)
class CPINameAndTypeDescriptor(CPI):
cp_type = CP_TYPE_NAMETYPE
def __init__(self, jclass, tag, name_index, descriptor_index):
self.name_index = name_index
self.descriptor_index = descriptor_index
super(CPINameAndTypeDescriptor, self).__init__(jclass, tag)
def __str__(self):
return 'CP name and type descriptor: name index %s type index %s' % (
self.name_index, self.descriptor_index)
class AttributeInfo:
def __init__(self, jclass, attribute_name_index):
self.jc = jclass
self.attribute_name_index = attribute_name_index
self.attribute_length = jclass.read_uint32()
@property
def name(self):
return self.jc.cpi_val(self.attribute_name_index)
def __str__(self):
return 'Attribute: %s' % self.name
def __repr__(self):
return self.__str__()
class AttributeConstantValue(AttributeInfo):
def __init__(self, jclass, attribute_name_index):
super(AttributeConstantValue, self).__init__(jclass, attribute_name_index)
self.constantvalue_index = jclass.read_uint16()
@property
def value(self):
return self.jc.cpi_val(self.constantvalue_index)
def __str__(self):
return "%s %s" % (super(AttributeConstantValue, self), self.value)
class ExceptionItem:
def __init__(self, jclass):
self.start_pc = jclass.read_uint16()
self.end_pc = jclass.read_uint16()
self.handler = jclass.read_uint16()
self.catch = jclass.read_uint16()
class AttributeCode(AttributeInfo):
def __init__(self, jclass, attribute_name_index):
super(AttributeCode, self).__init__(jclass, attribute_name_index)
self.max_stack = jclass.read_uint16()
self.max_locals = jclass.read_uint16()
self.code_length = jclass.read_uint32()
self.code = [jclass.read_uint8() for _ in range(self.code_length)]
self.exception_table_length = jclass.read_uint16()
self.exception_table = [ExceptionItem(jclass) for _ in range(self.exception_table_length)]
self.attributes_count = jclass.read_uint16()
self.attributes = [make_attribute_info(jclass) for _ in range(self.attributes_count)]
@property
def opcodes(self):
return opcodes.decode(self.code)
def __str__(self):
return "%s %s" % (super(AttributeCode, self).__str__(), self.opcodes)
class AttributeException(AttributeInfo):
def __init__(self, jclass, attribute_name_index):
super(AttributeException, self).__init__(jclass, attribute_name_index)
self.number_of_exceptions = jclass.read_uint16()
self.exception_index_table = [jclass.read_uint16() for _ in range(self.number_of_exceptions)]
class InnerClass:
def __init__(self, jclass):
self.inner_class_info_index = jclass.read_uint16()
self.outer_class_info_index = jclass.read_uint16()
self.inner_name_index = jclass.read_uint16()
self.inner_class_access_flags = jclass.read_uint16()
class AttributeInnerClasses(AttributeInfo):
def __init__(self, jclass, attribute_name_index):
super(AttributeInnerClasses, self).__init__(jclass, attribute_name_index)
self.number_of_classes = jclass.read_uint16()
self.classes = [InnerClass(jclass) for _ in range(self.number_of_classes)]
class AttributeSynthetic(AttributeInfo):
def __init__(self, jclass, attribute_name_index):
super(AttributeSynthetic, self).__init__(jclass, attribute_name_index)
class AttributeSourceFile(AttributeInfo):
def __init__(self, jclass, attribute_name_index):
super(AttributeSourceFile, self).__init__(jclass, attribute_name_index)
self.sourcefile_index = jclass.read_uint16()
class LineNumber:
def __init__(self, jclass):
self.start_pc = jclass.read_uint16()
self.line_number = jclass.read_uint16()
class AttributeLineNumberTable(AttributeInfo):
def __init__(self, jclass, attribute_name_index):
super(AttributeLineNumberTable, self).__init__(jclass, attribute_name_index)
self.line_number_table_length = jclass.read_uint16()
self.line_number_table = [LineNumber(jclass) for _ in range(self.line_number_table_length)]
class LocalVariable:
def __init__(self, jclass):
self.start_pc = jclass.read_uint16()
self.length = jclass.read_uint16()
self.name_index = jclass.read_uint16()
self.descriptor_index = jclass.read_uint16()
self.index = jclass.read_uint16()
class AttributeLocalVariableTable(AttributeInfo):
def __init__(self, jclass, attribute_name_index):
super(AttributeLocalVariableTable, self).__init__(jclass, attribute_name_index)
self.local_variable_table_length = jclass.read_uint16()
self.local_variable_table = [LocalVariable(jclass) for _ in range(self.local_variable_table_length)]
class AttributeDeprecated(AttributeInfo):
def __init__(self, jclass, attribute_name_index):
super(AttributeDeprecated, self).__init__(jclass, attribute_name_index)
class AttributeOther(AttributeInfo):
def __init__(self, jclass, attribute_name_index):
super(AttributeOther, self).__init__(jclass, attribute_name_index)
self.info = [jclass.read_uint8() for _ in range(self.attribute_length)]
class AttributeNotImplementedError:
def __init__(self, *args):
raise NotImplementedError()
attribute_map = {ATTRIBUTE_CONSTANT_VALUE: AttributeConstantValue,
ATTRIBUTE_CODE: AttributeCode,
ATTRIBUTE_STACK_MAP_TABLE: AttributeNotImplementedError,
ATTRIBUTE_EXCEPTIONS: AttributeException,
ATTRIBUTE_INNER_CLASSES: AttributeInnerClasses,
ATTRIBUTE_ENCLOSING_METHOD: AttributeNotImplementedError,
ATTRIBUTE_SYNTHETIC: AttributeSynthetic,
ATTRIBUTE_SIGNATURE: AttributeNotImplementedError,
ATTRIBUTE_SOURCE_FILE: AttributeSourceFile,
ATTRIBUTE_SOURCE_DEBUG_EXTENSION: AttributeNotImplementedError,
ATTRIBUTE_LINE_NUMBER_TABLE: AttributeLineNumberTable,
ATTRIBUTE_LOCAL_VARIABLE_TABLE: AttributeLocalVariableTable,
ATTRIBUTE_LOCAL_VARIABLE_TYPE_TABLE: AttributeNotImplementedError,
ATTRIBUTE_DEPRECATED: AttributeDeprecated,
ATTRIBUTE_RUNTIME_VISIBLE_ANNOTATIONS: AttributeNotImplementedError,
ATTRIBUTE_RUNTIME_INVISIBLE_ANNOTATIONS: AttributeNotImplementedError,
ATTRIBUTE_RUNTIME_VISIBLE_PARAMETER_ANNOTATIONS: AttributeNotImplementedError,
ATTRIBUTE_RUNTIME_INVISIBLE_PARAMETER_ANNOTATIONS: AttributeNotImplementedError,
ATTRIBUTE_ANNOTATION_DEFAULT: AttributeNotImplementedError,
ATTRIBUTE_BOOTSTRAP_METHODS: AttributeNotImplementedError}
def make_attribute_info(jclass):
attribute_name_index = jclass.read_uint16()
cp_entry = jclass.get_cpi(attribute_name_index)
if type(cp_entry) != CPIUTF8:
raise Exception('attribute at %d is not UTF8' % attribute_name_index)
name = cp_entry.value
cl = attribute_map.get(name, AttributeOther)
return cl(jclass, attribute_name_index)
class FieldInfo:
def __init__(self, jclass):
self.jc = jclass
self.access_flags = jclass.read_uint16()
self.name_index = jclass.read_uint16()
self.descriptor_index = jclass.read_uint16()
self.attributes_count = jclass.read_uint16()
self.attributes = [make_attribute_info(jclass) for _ in range(self.attributes_count)]
def __str__(self):
return 'Field attrs:%s name:%s desc:%s att:%s' % \
(self.attributes_count, self.jc.cpi_val(self.name_index),
self.jc.cpi_val(self.descriptor_index), self.attributes)
class MethodInfo:
def __init__(self, jclass):
self.jc = jclass
self.access_flags = jclass.read_uint16()
self.name_index = jclass.read_uint16()
self.descriptor_index = jclass.read_uint16()
self.attributes_count = jclass.read_uint16()
self.attributes = [make_attribute_info(jclass) for _ in range(self.attributes_count)]
self.name = self.jc.cpi_val(self.name_index)
def __str__(self):
return 'Method attrs:%s \nname:%s \ndesc:%s \natt:%s\n' % \
(self.attributes_count, self.jc.cpi_val(self.name_index),
self.jc.cpi_val(self.descriptor_index), self.attributes)
# noinspection PyAttributeOutsideInit
#=====================================================
class JavaClass:
def __init__(self, byte_array, validate=False):
self.ba = byte_array
self.to_validate = validate
self.ba_data = iter(self.ba)
self.constant_pool = []
self.minor_version = None
self.major_version = None
self.constant_pool_size = None
self.methodTlb = None
self.fields =None
self.methods =None
self.interfaces =None
self.decode()
#could be optimized for memory
self.methodTlb = {mt.name:mt for mt in self.methods}
self.name = self.get_cpi(self.this_class).get_name().value
def getMethodObj(self,mName):
return self.methodTlb[mName]
#================================================
def version2string(self):
return JVM_NAMES[45]
def read_byte(self):
return bytes([next(self.ba_data)])
def read_bytes(self, count):
return bytes([next(self.ba_data) for _ in range(count)])
def unpack(self, fmt, size=1):
if size == 1:
data = self.read_byte()
else:
data = self.read_bytes(size)
return struct.unpack(fmt, data)[0]
def read_int8(self):
return self.unpack('>b')
def read_uint8(self):
return self.unpack('>B')
def read_uint16(self):
return self.unpack('>H', 2)
def read_int16(self):
return self.unpack('>h', 2)
def read_uint32(self):
return self.unpack('>I', 4)
def read_int32(self):
return self.unpack('>i', 4)
def read_float32(self):
return self.unpack('f', 4)
def read_double64(self):
return self.unpack('d', 8)
def read_int64(self):
return self.unpack('>q', 8)
def get_cpi(self, i):
return self.constant_pool[i - 1]
def cpi_val(self, i):
return self.constant_pool[i - 1].value
def read_constant_pool(self):
i = 1
while i < self.constant_pool_size:
v = self.read_uint8()
if v == 1:
pv = self.read_uint16()
self.constant_pool.append(CPIUTF8(self, v, pv, self.read_bytes(pv)))
elif v == 3:
self.constant_pool.append(CPIInt(self, v, self.read_int32()))
elif v == 4:
self.constant_pool.append(CPIFloat(self, v, self.read_float32()))
elif v == 5:
self.constant_pool.append(CPILong(self, v, self.read_int64()))
i += 1
elif v == 6:
self.constant_pool.append(CPIDouble(self, v, self.read_double64()))
i += 1
elif v == 7:
self.constant_pool.append(CPIClassReference(self, v, self.read_uint16()))
elif v == 8:
self.constant_pool.append(CPIStringReference(self, v, self.read_uint16()))
elif v == 9:
self.constant_pool.append(CPIFieldReference(self, v, self.read_uint16(), self.read_uint16()))
elif v == 10:
self.constant_pool.append(CPIMethodReference(self, v, self.read_uint16(), self.read_uint16()))
elif v == 11:
self.constant_pool.append(
CPIInterfaceReference(
self,
v,
self.read_uint16(),
self.read_uint16()))
elif v == 12:
self.constant_pool.append(
CPINameAndTypeDescriptor(
self,
v,
self.read_uint16(),
self.read_uint16()))
else:
raise Exception('constant pool unknown tag byte %s' % v)
i += 1
def read_interfaces(self):
self.interfaces = [self.read_int16() for _ in range(self.interfaces_count)]
def read_fields(self):
self.fields = [FieldInfo(self) for _ in range(self.fields_count)]
def read_methods(self):
self.methods = [MethodInfo(self) for _ in range(self.methods_count)]
def read_attributes(self):
self.attributes = [make_attribute_info(self) for _ in range(self.attributes_count)]
def decode(self):
mn = self.read_bytes(4)
if mn != MAGIC_NUMBERS:
raise Exception('magic numbers %s do not match %s' % (MAGIC_NUMBERS, mn))
self.minor_version = self.read_uint16()
#print('minor version: %s' % self.minor_version)
self.major_version = self.read_uint16()
#print('major version: %s' % self.major_version)
#print('name version: %s' % self.version2string())
self.constant_pool_size = self.read_uint16()
#print('pool size: %s' % self.constant_pool_size)
self.read_constant_pool()
#for i, cpi in enumerate(self.constant_pool):
##print(i, cpi)
self.access_flags = self.read_uint16()
##print('access flags: %s' % self.access_flags)
self.this_class = self.read_uint16()
#print('this class index: %s' % self.this_class)
self.super_class = self.read_uint16()
#print('super class index: %s' % self.super_class)
self.interfaces_count = self.read_uint16()
#print('interfaces count: %s' % self.interfaces_count)
self.read_interfaces()
#for ifc in self.interfaces:
##print(ifc)
self.fields_count = self.read_uint16()
##print('fields count: %s' % self.fields_count)
self.read_fields()
#for fld in self.fields:
#print(fld)
self.methods_count = self.read_uint16()
#print('methods count: %s' % self.methods_count)
self.read_methods()
for mtd in self.methods:
print(mtd)
self.attributes_count = self.read_uint16()
#print('attributes count: %s' % self.attributes_count)
self.read_attributes()
#for att in self.attributes:
#print(att)
try:
self.read_byte()
except StopIteration:
pass
def print_out(self):
print('minor version: %s' % self.minor_version)
print('major version: %s %s' % (self.major_version, self.version2string()))
print('pool size: %s' % self.constant_pool_size)
for cpi in self.constant_pool:
print(cpi)
print('access flags: %s' % self.access_flags)
print('this class index: %s' % self.this_class)
print(self.get_cpi(self.this_class))
print('super class index: %s' % self.super_class)
print(self.get_cpi(self.super_class))
print('interfaces count: %s' % self.interfaces_count)
for ifc in self.interfaces:
print(ifc)
print('fields count: %s' % self.fields_count)
for fld in self.fields:
print(fld)
print('methods count: %s' % self.methods_count)
for mtd in self.methods:
print(mtd)
print('attributes count: %s' % self.attributes_count)
for att in self.attributes:
print(att)
with open("java/Test.class",'rb') as f:
JavaClass(f.read()).print_out()