10 ACC_SYNCHRONIZED = 0x0020
13 ACC_TRANSIENT = 0x0080
16 ACC_INTERFACE = 0x0200
19 ACC_SYNTHETIC = 0x1000
20 ACC_ANNOTATION = 0x2000
25 CONSTANT_Methodref = 10
26 CONSTANT_InterfaceMethodref = 11
32 CONSTANT_NameAndType = 12
34 CONSTANT_MethodHandle = 15
35 CONSTANT_MethodType = 16
36 CONSTANT_InvokeDynamic = 18
38 version = collections.namedtuple("version", ["major", "minor"])
39 version.__eq__ = lambda s, o: s.major == o.major and s.minor == o.minor
40 version.__ne__ = lambda s, o: s.major != o.major or s.minor != o.minor
41 version.__lt__ = lambda s, o: (s.major < o.major) or (s.major == o.major and s.minor < o.minor)
42 version.__gt__ = lambda s, o: (s.major > o.major) or (s.major == o.major and s.minor > o.minor)
43 version.__le__ = lambda s, o: (s.major < o.major) or (s.major == o.major and s.minor <= o.minor)
44 version.__ge__ = lambda s, o: (s.major > o.major) or (s.major == o.major and s.minor >= o.minor)
45 version.J5 = version(49, 0)
46 version.J6 = version(50, 0)
47 version.J7 = version(51, 0)
48 version.J8 = version(52, 0)
50 class constint(object):
51 def __init__(self, val):
54 return hash(constint) + self.val
56 return isinstance(o, constint) and o.val == s.val
57 class constfloat(object):
58 def __init__(self, val):
61 return hash(constfloat) + self.val
63 return isinstance(o, constfloat) and o.val == s.val
64 class constlong(object):
65 def __init__(self, val):
68 return hash(constlong) + self.val
70 return isinstance(o, constlong) and o.val == s.val
71 class constdouble(object):
72 def __init__(self, val):
75 return hash(constdouble) + self.val
77 return isinstance(o, constdouble) and o.val == s.val
79 class conststr(object):
80 def __init__(self, idx):
83 return hash(conststr) + self.idx
85 return isinstance(o, conststr) and o.idx == s.idx
87 class classref(object):
88 def __init__(self, nm):
91 return hash(classref) + self.nm
93 return isinstance(o, classref) and o.nm == s.nm
96 def __init__(self, nm, tp):
100 return hash(sig) + self.nm * 31 + self.tp
102 return isinstance(o, sig) and o.nm == s.nm and o.tp == s.tp
104 class methodhandle(object):
105 def __init__(self, kind, ref):
109 return hash(methodhandle) + self.kind * 31 + self.ref
111 return isinstance(o, methodhandle) and o.kind == s.kind and o.ref == s.ref
113 class methodtype(object):
114 def __init__(self, desc):
117 return hash(methodhandle) + self.desc
119 return isinstance(o, methodtype) and o.desc == s.desc
121 class callsite(object):
122 def __init__(self, boot, sig):
126 return hash(callsite) + self.boot * 31 + self.sig
128 return isinstance(o, callsite) and o.boot == s.boot and o.sig == s.sig
130 class fieldref(object):
131 def __init__(self, cls, sig):
135 return hash(fieldref) + self.cls * 31 + self.sig
137 return isinstance(o, fieldref) and o.cls == s.cls and o.sig == s.sig
139 class methodref(object):
140 def __init__(self, cls, sig):
144 return hash(methodref) + self.cls * 31 + self.sig
146 return isinstance(o, methodref) and o.cls == s.cls and o.sig == s.sig
148 class imethodref(object):
149 def __init__(self, cls, sig):
153 return hash(imethodref) + self.cls * 31 + self.sig
155 return isinstance(o, imethodref) and o.cls == s.cls and o.sig == s.sig
158 def __init__(self, acc, nm, descr):
165 self.deprecated = False
170 class localdef(object):
171 def __init__(self, start, end, nm, descr, reg):
189 class method(object):
190 def __init__(self, acc, nm, descr):
198 self.deprecated = False
206 class annotation(object):
207 def __init__(self, tp):
211 class innerclass(object):
212 def __init__(self, cls, outer, nm, acc):
218 class classfile(object):
221 def __init__(self, ver, access=None):
231 self.innerclasses = []
232 self.enclosingmethod = None
235 self.deprecated = False
240 def loadconstant(self, buf):
242 if t == CONSTANT_Utf8:
243 return binfmt.mutf8dec(buf.splice(buf.uint16())), False
244 elif t == CONSTANT_Class:
245 return classref(buf.uint16()), False
246 elif t == CONSTANT_String:
247 return conststr(buf.uint16()), False
248 elif t == CONSTANT_Integer:
249 return constint(buf.int32()), False
250 elif t == CONSTANT_Float:
251 return constfloat(buf.float32()), False
252 elif t == CONSTANT_Long:
253 return constlong(buf.int64()), True
254 elif t == CONSTANT_Double:
255 return constdouble(buf.float64()), True
256 elif t == CONSTANT_Fieldref:
257 return fieldref(buf.uint16(), buf.uint16()), False
258 elif t == CONSTANT_Methodref:
259 return methodref(buf.uint16(), buf.uint16()), False
260 elif t == CONSTANT_InterfaceMethodref:
261 return imethodref(buf.uint16(), buf.uint16()), False
262 elif t == CONSTANT_NameAndType:
263 return sig(buf.uint16(), buf.uint16()), False
264 elif t == CONSTANT_MethodHandle:
265 return methodhandle(buf.uint8(), buf.uint16()), False
266 elif t == CONSTANT_MethodType:
267 return methodtype(buf.uint16()), False
268 elif t == CONSTANT_InvokeDynamic:
269 return callsite(buf.uint16(), buf.uint16()), False
271 raise binfmt.fmterror("unknown constant tag: " + str(t))
273 def saveconstant(self, buf, const):
274 if isinstance(const, str):
275 enc = binfmt.mutf8enc(const)
276 buf.uint8(CONSTANT_Utf8).uint16(len(enc)).extend(enc)
277 elif isinstance(const, classref):
278 buf.uint8(CONSTANT_Class).uint16(const.nm)
279 elif isinstance(const, conststr):
280 buf.uint8(CONSTANT_String).uint16(const.idx)
281 elif isinstance(const, constint):
282 buf.uint8(CONSTANT_Integer).int32(const.val)
283 elif isinstance(const, constfloat):
284 buf.uint8(CONSTANT_Float).float32(const.val)
285 elif isinstance(const, constlong):
286 buf.uint8(CONSTANT_Long).int64(const.val)
287 elif isinstance(const, constdouble):
288 buf.uint8(CONSTANT_Double).float64(const.val)
289 elif isinstance(const, fieldref):
290 buf.uint8(CONSTANT_Fieldref).uint16(const.cls).uint16(const.sig)
291 elif isinstance(const, methodref):
292 buf.uint8(CONSTANT_Methodref).uint16(const.cls).uint16(const.sig)
293 elif isinstance(const, imethodref):
294 buf.uint8(CONSTANT_InterfaceMethodref).uint16(const.cls).uint16(const.sig)
295 elif isinstance(const, sig):
296 buf.uint8(CONSTANT_NameAndType).uint16(const.nm).uint16(const.tp)
297 elif isinstance(const, methodhandle):
298 buf.uint8(CONSTANT_MethodHandle).uint8(const.kind).uint16(const.ref)
299 elif isinstance(const, methodtype):
300 buf.uint8(CONSTANT_MethodType).uint16(const.desc)
301 elif isinstance(const, callsite):
302 buf.uint8(CONSTANT_InvokeDynamic).uint16(const.boot).uint16(const.sig)
304 raise Exception("unexpected object type in constant pool: " + const)
306 def checkcp(self, idx, tp):
307 return 0 <= idx < len(self.cp) and isinstance(self.cp[idx], tp)
309 def intern(self, const, new=Exception):
310 for i, cur in enumerate(self.cp):
314 raise Exception("constant not present in pool: " + const)
316 self.cp.append(const)
317 return len(self.cp) - 1
321 def loadattr(self, buf):
323 if not self.checkcp(nm, str):
324 raise binfmt.fmterror("invalid attribute name reference")
325 return nm, binfmt.decbuf(buf.splice(buf.uint32()))
327 def saveattrs(self, buf, attrs):
328 buf.uint16(len(attrs))
329 for nm, data in attrs:
330 buf.uint16(nm).uint32(len(data)).extend(data)
332 def loadannval(self, buf):
337 return (buf.uint16(), buf.uint16())
339 return classref(buf.uint16()) # XXX, but meh
341 return loadannotation(buf)
343 return [self.loadannval(buf) for i in range(buf.uint16())]
345 raise binfmt.fmterror("unknown annotation-value type tag: " + t)
347 def saveannval(self, buf, val):
348 if isinstance(val, int):
350 if isinstance(const, str):
351 buf.uint8(ord('s')).uint16(val)
353 raise Exception("unexpected constant type in annotation value: " + const)
354 elif isinstance(val, tuple) and len(val) == 2:
355 buf.uint8(ord('e')).uint16(val[0]).uint16(val[1])
356 elif isinstance(val, classref):
357 buf.uint8(ord('c')).uint16(val.nm)
358 elif isinstance(val, annotation):
360 saveannotation(buf, val)
361 elif isinstance(val, list):
363 for sval in val: self.saveannval(buf, sval)
365 raise Exception("unexpected annotation value type: " + val)
367 def loadannotation(self, buf):
369 if not self.checkcp(tp, str):
370 raise binfmt.fmterror("invalid annotation type reference")
373 for i in range(nval):
375 if not self.checkcp(nm, str):
376 raise binfmt.fmterror("invalid annotation-value name reference")
377 ret.vals[nm] = self.loadannval(buf)
380 def saveannotation(self, buf, ann):
382 buf.uint16(len(ann.vals))
383 for key, val in ann.vals.items():
385 self.saveannval(buf, val)
387 def loadfield(self, buf):
390 if not self.checkcp(nm, str):
391 raise binfmt.fmterror("invalid field name reference")
393 if not self.checkcp(descr, str):
394 raise binfmt.fmterror("invalid field descriptor reference")
395 ret = field(acc, nm, descr)
397 for i in range(nattr):
398 nm, data = self.loadattr(buf)
400 if pnm == "ConstantValue":
401 ret.const = data.uint16()
402 elif pnm == "Synthetic":
404 elif pnm == "Signature":
405 ret.sig = data.uint16()
406 elif pnm == "Deprecated":
407 ret.deprecated = True
408 elif pnm == "RuntimeVisibleAnnotations":
409 for o in range(data.uint16()):
410 ret.rtann.append(self.loadannotation(data))
411 elif pnm == "RuntimeInvisibleAnnotations":
412 for o in range(data.uint16()):
413 ret.cpann.append(self.loadannotation(data))
415 ret.attrs.append((nm, data.splice()))
418 def savefield(self, buf, field):
419 buf.uint16(field.acc)
420 buf.uint16(field.nm).uint16(field.descr)
421 attrs = list(field.attrs)
423 if field.const is not None:
424 attrs.append((self.intern("ConstantValue"), enc().uint16(field.const)))
426 attrs.append((self.intern("Synthetic"), b""))
427 if field.sig is not None:
428 attrs.append((self.intern("Signature"), enc().uint16(field.sig)))
430 attrs.append((self.intern("Deprecated"), b""))
431 if len(field.rtann) > 0:
433 data.uint16(len(field.rtann))
434 for ann in field.rtann: self.saveannotation(data, ann)
435 attrs.append((self.intern("RuntimeVisibleAnnotations"), data))
436 if len(field.cpann) > 0:
438 data.uint16(len(field.cpann))
439 for ann in field.cpann: self.saveannotation(data, ann)
440 attrs.append((self.intern("RuntimeInvisibleAnnotations"), data))
441 self.saveattrs(buf, attrs)
443 def loadcode(self, buf):
445 ret.maxstack = buf.uint16()
446 ret.maxlocals = buf.uint16()
447 ret.code = buf.splice(buf.uint32())
448 for i in range(buf.uint16()):
449 estart = buf.uint16()
453 if not (ctp == 0 or self.checkcp(ctp, classref)):
454 raise binfmt.fmterror("invalid exception-catch reference")
455 ret.exctab.append((estart, eend, ehnd, ctp))
457 for i in range(nattr):
458 nm, data = self.loadattr(buf)
460 if pnm == "LineNumberTable":
462 for o in range(data.uint16()):
465 lintab.append((pc, ln))
467 elif pnm in ("LocalVariableTable", "LocalVariableTypeTable"):
469 for o in range(data.uint16()):
470 start = data.uint16()
473 descr = data.uint16()
475 if not self.checkcp(nm, str):
476 raise binfmt.fmterror("invalid local variable name reference")
477 if not self.checkcp(descr, str):
478 raise binfmt.fmterror("invalid local variable descriptor reference")
479 locals.append(localdef(start, start + ln, nm, descr, reg))
480 if nm == "LocalVariableTypeTable":
485 ret.attrs.append((nm, data.splice()))
488 def savecode(self, buf, code):
489 buf.uint16(code.maxstack).uint16(code.maxlocals)
490 buf.uint32(len(code.code)).extend(code.code)
491 buf.uint16(len(code.exctab))
492 for estart, eend, ehnd, ctp in code.exctab:
493 buf.uint16(estart).uint16(eend).uint16(ehnd).uint16(ctp)
494 attrs = list(code.attrs)
496 if code.lintab is not None:
498 data.uint16(len(code.lintab))
499 for pc, ln in code.lintab:
500 data.uint16(pc).uint16(ln)
501 attrs.append((self.intern("LineNumberTable"), data))
502 def savelocals(ltab):
504 data.uint16(len(ltab))
506 data.uint16(local.start).uint16(local.end - local.start).uint16(local.nm).uint16(local.descr).uint16(local.reg)
508 if code.locals is not None:
509 attrs.append((self.intern("LocalVariableTable"), savelocals(code.locals)))
510 if code.tlocals is not None:
511 attrs.append((self.intern("LocalVariableTypeTable"), savelocals(code.tlocals)))
512 self.saveattrs(buf, attrs)
514 def loadmethod(self, buf):
517 if not self.checkcp(nm, str):
518 raise binfmt.fmterror("invalid field name reference")
520 if not self.checkcp(descr, str):
521 raise binfmt.fmterror("invalid field descriptor reference")
522 ret = method(acc, nm, descr)
524 for i in range(nattr):
525 nm, data = self.loadattr(buf)
528 ret.code = self.loadcode(data)
529 elif pnm == "Exceptions":
530 for o in range(data.uint16()):
532 if not self.checkcp(eref, classref):
533 raise binfmt.fmterror("invalid exception reference")
534 ret.throws.append(eref)
535 elif pnm == "Synthetic":
537 elif pnm == "Signature":
538 ret.sig = data.uint16()
539 elif pnm == "Deprecated":
540 ret.deprecated = True
541 elif pnm == "RuntimeVisibleAnnotations":
542 for o in range(data.uint16()):
543 ret.rtann.append(self.loadannotation(data))
544 elif pnm == "RuntimeInvisibleAnnotations":
545 for o in range(data.uint16()):
546 ret.cpann.append(self.loadannotation(data))
547 elif pnm == "RuntimeVisibleParameterAnnotations":
549 for o in range(data.uint8()):
551 for u in range(data.uint16()):
552 abuf.append(self.loadannotation(data))
553 ret.prtann.append(abuf)
554 elif pnm == "RuntimeInvisibleParameterAnnotations":
556 for o in range(data.uint8()):
558 for u in range(data.uint16()):
559 abuf.append(self.loadannotation(data))
560 ret.pcpann.append(abuf)
561 elif pnm == "AnnotationDefault":
562 ret.anndef = self.loadannval(data)
564 ret.attrs.append((nm, data.splice()))
567 def savemethod(self, buf, method):
568 buf.uint16(method.acc)
569 buf.uint16(method.nm).uint16(method.descr)
570 attrs = list(method.attrs)
574 self.savecode(data, method.code)
575 attrs.append((self.intern("Code"), data))
576 if len(method.throws) > 0:
578 data.uint16(len(method.throws))
579 for eref in method.throws: data.uint16(eref)
580 attrs.append((self.intern("Exceptions"), data))
582 attrs.append((self.intern("Synthetic"), b""))
583 if method.sig is not None:
584 attrs.append((self.intern("Signature"), enc().uint16(method.sig)))
585 if method.deprecated:
586 attrs.append((self.intern("Deprecated"), b""))
587 if len(method.rtann) > 0:
589 data.uint16(len(method.rtann))
590 for ann in method.rtann: self.saveannotation(data, ann)
591 attrs.append((self.intern("RuntimeVisibleAnnotations"), data))
592 if len(method.cpann) > 0:
594 data.uint16(len(method.cpann))
595 for ann in method.cpann: self.saveannotation(data, ann)
596 attrs.append((self.intern("RuntimeInvisibleAnnotations"), data))
597 if method.prtann is not None:
599 data.uint8(len(method.prtann))
600 for par in method.prtann:
602 for ann in par: self.saveannotation(data, ann)
603 attrs.append((self.intern("RuntimeVisibleParameterAnnotations"), data))
604 if method.pcpann is not None:
606 data.uint8(len(method.pcpann))
607 for par in method.pcpann:
609 for ann in par: self.saveannotation(data, ann)
610 attrs.append((self.intern("RuntimeInvisibleParameterAnnotations"), data))
611 if method.anndef is not None:
613 self.saveannval(data, method.anndef)
614 attrs.append((self.intern("AnnotationDefault"), data))
615 self.saveattrs(buf, attrs)
619 buf = binfmt.decstream(fp)
620 if buf.uint32() != cls.MAGIC:
621 raise binfmt.fmterror("invalid magic number")
622 minor, major = buf.uint16(), buf.uint16()
623 self = cls(version(major, minor))
627 raise binfmt.fmterror("invalid constant-pool length")
629 while len(self.cp) < cplen:
630 loaded, dbl = self.loadconstant(buf)
631 self.cp.append(loaded)
635 self.acc = buf.uint16()
636 self.this = buf.uint16()
637 self.super = buf.uint16()
638 if not self.checkcp(self.this, classref):
639 raise binfmt.fmterror("invalid class name reference")
640 if not self.checkcp(self.super, classref) and self.cp[self.super] is not None:
641 raise binfmt.fmterror("invalid super-class reference")
643 while len(self.ifaces) < iflen:
645 if not self.checkcp(iref, classref):
646 raise binfmt.fmterror("invalid interface reference")
647 self.ifaces.append(iref)
649 nfields = buf.uint16()
650 while len(self.fields) < nfields:
651 self.fields.append(self.loadfield(buf))
652 nmethods = buf.uint16()
653 while len(self.methods) < nmethods:
654 self.methods.append(self.loadmethod(buf))
656 nattrs = buf.uint16()
657 for i in range(nattrs):
658 nm, data = self.loadattr(buf)
660 if pnm == "SourceFile":
661 self.srcfile = data.uint16()
662 elif pnm == "Signature":
663 self.sig = data.uint16()
664 elif pnm == "Synthetic":
666 elif pnm == "Deprecated":
667 self.deprecated = True
668 elif pnm == "InnerClasses":
669 for o in range(data.uint16()):
671 outer = data.uint16()
674 if not self.checkcp(cref, classref):
675 raise binfmt.fmterror("invalid inner-class reference")
676 if not (outer == 0 or self.checkcp(outer, classref)):
677 raise binfmt.fmterror("invalid inner-class outer reference")
678 if not (cnm == 0 or self.checkcp(cnm, str)):
679 raise binfmt.fmterror("invalid inner-class name reference")
680 self.innerclasses.append(innerclass(cref, outer, cnm, acc))
681 elif pnm == "EnclosingMethod":
682 self.enclosingmethod = (data.uint16(), data.uint16())
683 if not self.checkcp(self.enclosingmethod[0], classref):
684 raise binfmt.fmterror("invalid enclosing-method class reference")
685 if not (self.enclosingmethod[1] == 0 or self.checkcp(self.enclosingmethod[1], sig)):
686 raise binfmt.fmterror("invalid enclosing-method method reference")
687 elif pnm == "RuntimeVisibleAnnotations":
688 for o in range(data.uint16()):
689 self.rtann.append(self.loadannotation(data))
690 elif pnm == "RuntimeInvisibleAnnotations":
691 for o in range(data.uint16()):
692 self.cpann.append(self.loadannotation(data))
694 self.attrs.append((nm, data.splice()))
698 def _save(self, buf):
699 buf.uint32(self.MAGIC)
700 buf.uint16(self.ver.minor).uint16(self.ver.major)
702 buf.uint16(len(self.cp))
703 for const in self.cp:
704 if const is not None:
705 self.saveconstant(buf, const)
708 buf.uint16(self.this).uint16(self.super)
709 buf.uint16(len(self.ifaces))
710 for iref in self.ifaces: buf.uint16(iref)
712 buf.uint16(len(self.fields))
713 for field in self.fields:
714 self.savefield(buf, field)
716 buf.uint16(len(self.methods))
717 for method in self.methods:
718 self.savemethod(buf, method)
721 attrs = list(self.attrs)
722 if self.srcfile is not None:
723 attrs.append((self.intern("SourceFile"), enc().uint16(self.srcfile)))
725 attrs.append((self.intern("Synthetic"), b""))
727 attrs.append((self.intern("Deprecated"), b""))
728 if self.sig is not None:
729 attrs.append((self.intern("Signature"), enc().uint16(self.sig)))
730 if len(self.innerclasses) > 0:
732 data.uint16(len(self.innerclasses))
733 for inner in self.innerclasses: data.uint16(inner.cls).uint16(inner.outer).uint16(inner.nm).uint16(inner.acc)
734 attrs.append((self.intern("InnerClasses"), data))
735 if self.enclosingmethod is not None:
736 attrs.append((self.intern("EnclosingMethod"), enc().uint16(self.enclosingmethod[0]).uint16(self.enclosingmethod[1])))
737 if len(self.rtann) > 0:
739 data.uint16(len(self.rtann))
740 for ann in self.rtann: self.saveannotation(data, ann)
741 attrs.append((self.intern("RuntimeVisibleAnnotations"), data))
742 if len(self.cpann) > 0:
744 data.uint16(len(self.cpann))
745 for ann in self.cpann: self.saveannotation(data, ann)
746 attrs.append((self.intern("RuntimeInvisibleAnnotations"), data))
747 self.saveattrs(buf, attrs)
750 return self._save(binfmt.encstream(fp))
753 def fromfile(cls, fn):
754 with open(fn, "rb") as fp:
757 def tofile(self, fn):
758 with open(fn, "wb") as fp: