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 fieldref(object):
105 def __init__(self, cls, sig):
109 return hash(fieldref) + self.cls * 31 + self.sig
111 return isinstance(o, fieldref) and o.cls == s.cls and o.sig == s.sig
113 class methodref(object):
114 def __init__(self, cls, sig):
118 return hash(methodref) + self.cls * 31 + self.sig
120 return isinstance(o, methodref) and o.cls == s.cls and o.sig == s.sig
122 class imethodref(object):
123 def __init__(self, cls, sig):
127 return hash(imethodref) + self.cls * 31 + self.sig
129 return isinstance(o, imethodref) and o.cls == s.cls and o.sig == s.sig
132 def __init__(self, acc, nm, descr):
139 self.deprecated = False
144 class localdef(object):
145 def __init__(self, start, end, nm, descr, reg):
163 class method(object):
164 def __init__(self, acc, nm, descr):
172 self.deprecated = False
180 class annotation(object):
181 def __init__(self, tp):
185 class innerclass(object):
186 def __init__(self, cls, outer, nm, acc):
192 class classfile(object):
195 def __init__(self, ver, access=None):
205 self.innerclasses = []
206 self.enclosingmethod = None
209 self.deprecated = False
214 def loadconstant(self, buf):
216 if t == CONSTANT_Utf8:
217 return binfmt.mutf8dec(buf.splice(buf.uint16())), False
218 elif t == CONSTANT_Class:
219 return classref(buf.uint16()), False
220 elif t == CONSTANT_String:
221 return conststr(buf.uint16()), False
222 elif t == CONSTANT_Integer:
223 return constint(buf.int32()), False
224 elif t == CONSTANT_Float:
225 return constfloat(buf.float32()), False
226 elif t == CONSTANT_Long:
227 return constlong(buf.int64()), True
228 elif t == CONSTANT_Double:
229 return constdouble(buf.float64()), True
230 elif t == CONSTANT_Fieldref:
231 return fieldref(buf.uint16(), buf.uint16()), False
232 elif t == CONSTANT_Methodref:
233 return methodref(buf.uint16(), buf.uint16()), False
234 elif t == CONSTANT_InterfaceMethodref:
235 return imethodref(buf.uint16(), buf.uint16()), False
236 elif t == CONSTANT_NameAndType:
237 return sig(buf.uint16(), buf.uint16()), False
239 raise binfmt.fmterror("unknown constant tag: " + str(t))
241 def saveconstant(self, buf, const):
242 if isinstance(const, str):
243 enc = binfmt.mutf8enc(const)
244 buf.uint8(CONSTANT_Utf8).uint16(len(enc)).extend(enc)
245 elif isinstance(const, classref):
246 buf.uint8(CONSTANT_Class).uint16(const.nm)
247 elif isinstance(const, conststr):
248 buf.uint8(CONSTANT_String).uint16(const.idx)
249 elif isinstance(const, constint):
250 buf.uint8(CONSTANT_Integer).int32(const.val)
251 elif isinstance(const, constfloat):
252 buf.uint8(CONSTANT_Float).float32(const.val)
253 elif isinstance(const, constlong):
254 buf.uint8(CONSTANT_Long).int64(const.val)
255 elif isinstance(const, constdouble):
256 buf.uint8(CONSTANT_Double).float64(const.val)
257 elif isinstance(const, fieldref):
258 buf.uint8(CONSTANT_Fieldref).uint16(const.cls).uint16(const.sig)
259 elif isinstance(const, methodref):
260 buf.uint8(CONSTANT_Methodref).uint16(const.cls).uint16(const.sig)
261 elif isinstance(const, imethodref):
262 buf.uint8(CONSTANT_InterfaceMethodref).uint16(const.cls).uint16(const.sig)
263 elif isinstance(const, sig):
264 buf.uint8(CONSTANT_NameAndType).uint16(const.nm).uint16(const.tp)
266 raise Exception("unexpected object type in constant pool: " + const)
268 def checkcp(self, idx, tp):
269 return 0 <= idx < len(self.cp) and isinstance(self.cp[idx], tp)
271 def intern(self, const, new=Exception):
272 for i, cur in enumerate(self.cp):
276 raise Exception("constant not present in pool: " + const)
278 self.cp.append(const)
279 return len(self.cp) - 1
283 def loadattr(self, buf):
285 if not self.checkcp(nm, str):
286 raise binfmt.fmterror("invalid attribute name reference")
287 return nm, binfmt.decbuf(buf.splice(buf.uint32()))
289 def saveattrs(self, buf, attrs):
290 buf.uint16(len(attrs))
291 for nm, data in attrs:
292 buf.uint16(nm).uint32(len(data)).extend(data)
294 def loadannval(self, buf):
299 return (buf.uint16(), buf.uint16())
301 return classref(buf.uint16()) # XXX, but meh
303 return loadannotation(buf)
305 return [self.loadannval(buf) for i in range(buf.uint16())]
307 raise binfmt.fmterror("unknown annotation-value type tag: " + t)
309 def saveannval(self, buf, val):
310 if isinstance(val, int):
312 if isinstance(const, str):
313 buf.uint8(ord('s')).uint16(val)
315 raise Exception("unexpected constant type in annotation value: " + const)
316 elif isinstance(val, tuple) and len(val) == 2:
317 buf.uint8(ord('e')).uint16(val[0]).uint16(val[1])
318 elif isinstance(val, classref):
319 buf.uint8(ord('c')).uint16(val.nm)
320 elif isinstance(val, annotation):
322 saveannotation(buf, val)
323 elif isinstance(val, list):
325 for sval in val: self.saveannval(buf, sval)
327 raise Exception("unexpected annotation value type: " + val)
329 def loadannotation(self, buf):
331 if not self.checkcp(tp, str):
332 raise binfmt.fmterror("invalid annotation type reference")
335 for i in range(nval):
337 if not self.checkcp(nm, str):
338 raise binfmt.fmterror("invalid annotation-value name reference")
339 ret.vals[nm] = self.loadannval(buf)
342 def saveannotation(self, buf, ann):
344 buf.uint16(len(ann.vals))
345 for key, val in ann.vals.items():
347 self.saveannval(buf, val)
349 def loadfield(self, buf):
352 if not self.checkcp(nm, str):
353 raise binfmt.fmterror("invalid field name reference")
355 if not self.checkcp(descr, str):
356 raise binfmt.fmterror("invalid field descriptor reference")
357 ret = field(acc, nm, descr)
359 for i in range(nattr):
360 nm, data = self.loadattr(buf)
362 if pnm == "ConstantValue":
363 ret.const = data.uint16()
364 elif pnm == "Synthetic":
366 elif pnm == "Signature":
367 ret.sig = data.uint16()
368 elif pnm == "Deprecated":
369 ret.deprecated = True
370 elif pnm == "RuntimeVisibleAnnotations":
371 for o in range(data.uint16()):
372 ret.rtann.append(self.loadannotation(data))
373 elif pnm == "RuntimeInvisibleAnnotations":
374 for o in range(data.uint16()):
375 ret.cpann.append(self.loadannotation(data))
377 ret.attrs.append((nm, data.splice()))
380 def savefield(self, buf, field):
381 buf.uint16(field.acc)
382 buf.uint16(field.nm).uint16(field.descr)
383 attrs = list(field.attrs)
385 if field.const is not None:
386 attrs.append((self.intern("ConstantValue"), enc().uint16(field.const)))
388 attrs.append((self.intern("Synthetic"), b""))
389 if field.sig is not None:
390 attrs.append((self.intern("Signature"), enc().uint16(field.sig)))
392 attrs.append((self.intern("Deprecated"), b""))
393 if len(field.rtann) > 0:
395 data.uint16(len(field.rtann))
396 for ann in field.rtann: self.saveannotation(data, ann)
397 attrs.append((self.intern("RuntimeVisibleAnnotations"), data))
398 if len(field.cpann) > 0:
400 data.uint16(len(field.cpann))
401 for ann in field.cpann: self.saveannotation(data, ann)
402 attrs.append((self.intern("RuntimeInvisibleAnnotations"), data))
403 self.saveattrs(buf, attrs)
405 def loadcode(self, buf):
407 ret.maxstack = buf.uint16()
408 ret.maxlocals = buf.uint16()
409 ret.code = buf.splice(buf.uint32())
410 for i in range(buf.uint16()):
411 estart = buf.uint16()
415 if not (ctp == 0 or self.checkcp(ctp, classref)):
416 raise binfmt.fmterror("invalid exception-catch reference")
417 ret.exctab.append((estart, eend, ehnd, ctp))
419 for i in range(nattr):
420 nm, data = self.loadattr(buf)
422 if pnm == "LineNumberTable":
424 for o in range(data.uint16()):
427 lintab.append((pc, ln))
429 elif pnm in ("LocalVariableTable", "LocalVariableTypeTable"):
431 for o in range(data.uint16()):
432 start = data.uint16()
435 descr = data.uint16()
437 if not self.checkcp(nm, str):
438 raise binfmt.fmterror("invalid local variable name reference")
439 if not self.checkcp(descr, str):
440 raise binfmt.fmterror("invalid local variable descriptor reference")
441 locals.append(localdef(start, start + ln, nm, descr, reg))
442 if nm == "LocalVariableTypeTable":
447 ret.attrs.append((nm, data.splice()))
450 def savecode(self, buf, code):
451 buf.uint16(code.maxstack).uint16(code.maxlocals)
452 buf.uint32(len(code.code)).extend(code.code)
453 buf.uint16(len(code.exctab))
454 for estart, eend, ehnd, ctp in code.exctab:
455 buf.uint16(estart).uint16(eend).uint16(ehnd).uint16(ctp)
456 attrs = list(code.attrs)
458 if code.lintab is not None:
460 data.uint16(len(code.lintab))
461 for pc, ln in code.lintab:
462 data.uint16(pc).uint16(ln)
463 attrs.append((self.intern("LineNumberTable"), data))
464 def savelocals(ltab):
466 data.uint16(len(ltab))
468 data.uint16(local.start).uint16(local.end - local.start).uint16(local.nm).uint16(local.descr).uint16(local.reg)
470 if code.locals is not None:
471 attrs.append((self.intern("LocalVariableTable"), savelocals(code.locals)))
472 if code.tlocals is not None:
473 attrs.append((self.intern("LocalVariableTypeTable"), savelocals(code.tlocals)))
474 self.saveattrs(buf, attrs)
476 def loadmethod(self, buf):
479 if not self.checkcp(nm, str):
480 raise binfmt.fmterror("invalid field name reference")
482 if not self.checkcp(descr, str):
483 raise binfmt.fmterror("invalid field descriptor reference")
484 ret = method(acc, nm, descr)
486 for i in range(nattr):
487 nm, data = self.loadattr(buf)
490 ret.code = self.loadcode(data)
491 elif pnm == "Exceptions":
492 for o in range(data.uint16()):
494 if not self.checkcp(eref, classref):
495 raise binfmt.fmterror("invalid exception reference")
496 ret.throws.append(eref)
497 elif pnm == "Synthetic":
499 elif pnm == "Signature":
500 ret.sig = data.uint16()
501 elif pnm == "Deprecated":
502 ret.deprecated = True
503 elif pnm == "RuntimeVisibleAnnotations":
504 for o in range(data.uint16()):
505 ret.rtann.append(self.loadannotation(data))
506 elif pnm == "RuntimeInvisibleAnnotations":
507 for o in range(data.uint16()):
508 ret.cpann.append(self.loadannotation(data))
509 elif pnm == "RuntimeVisibleParameterAnnotations":
511 for o in range(data.uint8()):
513 for u in range(data.uint16()):
514 abuf.append(self.loadannotation(data))
515 ret.prtann.append(abuf)
516 elif pnm == "RuntimeInvisibleParameterAnnotations":
518 for o in range(data.uint8()):
520 for u in range(data.uint16()):
521 abuf.append(self.loadannotation(data))
522 ret.pcpann.append(abuf)
523 elif pnm == "AnnotationDefault":
524 ret.anndef = self.loadannval(data)
526 ret.attrs.append((nm, data.splice()))
529 def savemethod(self, buf, method):
530 buf.uint16(method.acc)
531 buf.uint16(method.nm).uint16(method.descr)
532 attrs = list(method.attrs)
536 self.savecode(data, method.code)
537 attrs.append((self.intern("Code"), data))
538 if len(method.throws) > 0:
540 data.uint16(len(method.throws))
541 for eref in method.throws: data.uint16(eref)
542 attrs.append((self.intern("Exceptions"), data))
544 attrs.append((self.intern("Synthetic"), b""))
545 if method.sig is not None:
546 attrs.append((self.intern("Signature"), enc().uint16(method.sig)))
547 if method.deprecated:
548 attrs.append((self.intern("Deprecated"), b""))
549 if len(method.rtann) > 0:
551 data.uint16(len(method.rtann))
552 for ann in method.rtann: self.saveannotation(data, ann)
553 attrs.append((self.intern("RuntimeVisibleAnnotations"), data))
554 if len(method.cpann) > 0:
556 data.uint16(len(method.cpann))
557 for ann in method.cpann: self.saveannotation(data, ann)
558 attrs.append((self.intern("RuntimeInvisibleAnnotations"), data))
559 if method.prtann is not None:
561 data.uint8(len(method.prtann))
562 for par in method.prtann:
564 for ann in par: self.saveannotation(data, ann)
565 attrs.append((self.intern("RuntimeVisibleParameterAnnotations"), data))
566 if method.pcpann is not None:
568 data.uint8(len(method.pcpann))
569 for par in method.pcpann:
571 for ann in par: self.saveannotation(data, ann)
572 attrs.append((self.intern("RuntimeInvisibleParameterAnnotations"), data))
573 if method.anndef is not None:
575 self.saveannval(data, method.anndef)
576 attrs.append((self.intern("AnnotationDefault"), data))
577 self.saveattrs(buf, attrs)
581 buf = binfmt.decstream(fp)
582 if buf.uint32() != cls.MAGIC:
583 raise binfmt.fmterror("invalid magic number")
584 minor, major = buf.uint16(), buf.uint16()
585 self = cls(version(major, minor))
589 raise binfmt.fmterror("invalid constant-pool length")
591 while len(self.cp) < cplen:
592 loaded, dbl = self.loadconstant(buf)
593 self.cp.append(loaded)
597 self.acc = buf.uint16()
598 self.this = buf.uint16()
599 self.super = buf.uint16()
600 if not self.checkcp(self.this, classref):
601 raise binfmt.fmterror("invalid class name reference")
602 if not self.checkcp(self.super, classref):
603 raise binfmt.fmterror("invalid super-class reference")
605 while len(self.ifaces) < iflen:
607 if not self.checkcp(iref, classref):
608 raise binfmt.fmterror("invalid interface reference")
609 self.ifaces.append(iref)
611 nfields = buf.uint16()
612 while len(self.fields) < nfields:
613 self.fields.append(self.loadfield(buf))
614 nmethods = buf.uint16()
615 while len(self.methods) < nmethods:
616 self.methods.append(self.loadmethod(buf))
618 nattrs = buf.uint16()
619 for i in range(nattrs):
620 nm, data = self.loadattr(buf)
622 if pnm == "SourceFile":
623 self.srcfile = data.uint16()
624 elif pnm == "Signature":
625 self.sig = data.uint16()
626 elif pnm == "Synthetic":
628 elif pnm == "Deprecated":
629 self.deprecated = True
630 elif pnm == "InnerClasses":
631 for o in range(data.uint16()):
633 outer = data.uint16()
636 if not self.checkcp(cref, classref):
637 raise binfmt.fmterror("invalid inner-class reference")
638 if not (outer == 0 or self.checkcp(outer, classref)):
639 raise binfmt.fmterror("invalid inner-class outer reference")
640 if not (cnm == 0 or self.checkcp(cnm, str)):
641 raise binfmt.fmterror("invalid inner-class name reference")
642 self.innerclasses.append(innerclass(cref, outer, cnm, acc))
643 elif pnm == "EnclosingMethod":
644 self.enclosingmethod = (data.uint16(), data.uint16())
645 if not self.checkcp(self.enclosingmethod[0], classref):
646 raise binfmt.fmterror("invalid enclosing-method class reference")
647 if not (self.enclosingmethod[1] == 0 or self.checkcp(self.enclosingmethod[1], sig)):
648 raise binfmt.fmterror("invalid enclosing-method method reference")
649 elif pnm == "RuntimeVisibleAnnotations":
650 for o in range(data.uint16()):
651 self.rtann.append(self.loadannotation(data))
652 elif pnm == "RuntimeInvisibleAnnotations":
653 for o in range(data.uint16()):
654 self.cpann.append(self.loadannotation(data))
656 self.attrs.append((nm, data.splice()))
660 def _save(self, buf):
661 buf.uint32(self.MAGIC)
662 buf.uint16(self.ver.minor).uint16(self.ver.major)
664 buf.uint16(len(self.cp))
665 for const in self.cp:
666 if const is not None:
667 self.saveconstant(buf, const)
670 buf.uint16(self.this).uint16(self.super)
671 buf.uint16(len(self.ifaces))
672 for iref in self.ifaces: buf.uint16(iref)
674 buf.uint16(len(self.fields))
675 for field in self.fields:
676 self.savefield(buf, field)
678 buf.uint16(len(self.methods))
679 for method in self.methods:
680 self.savemethod(buf, method)
683 attrs = list(self.attrs)
684 if self.srcfile is not None:
685 attrs.append((self.intern("SourceFile"), enc().uint16(self.srcfile)))
687 attrs.append((self.intern("Synthetic"), b""))
689 attrs.append((self.intern("Deprecated"), b""))
690 if self.sig is not None:
691 attrs.append((self.intern("Signature"), enc().uint16(self.sig)))
692 if len(self.innerclasses) > 0:
694 data.uint16(len(self.innerclasses))
695 for inner in self.innerclasses: data.uint16(inner.cls).uint16(inner.outer).uint16(inner.nm).uint16(inner.acc)
696 attrs.append((self.intern("InnerClasses"), data))
697 if self.enclosingmethod is not None:
698 attrs.append((self.intern("EnclosingMethod"), enc().uint16(self.enclosingmethod[0]).uint16(self.enclosingmethod[1])))
699 if len(self.rtann) > 0:
701 data.uint16(len(self.rtann))
702 for ann in self.rtann: self.saveannotation(data, ann)
703 attrs.append((self.intern("RuntimeVisibleAnnotations"), data))
704 if len(self.cpann) > 0:
706 data.uint16(len(self.cpann))
707 for ann in self.cpann: self.saveannotation(data, ann)
708 attrs.append((self.intern("RuntimeInvisibleAnnotations"), data))
709 self.saveattrs(buf, attrs)
712 return self._save(binfmt.encstream(fp))
715 def fromfile(cls, fn):
716 with open(fn, "rb") as fp:
719 def tofile(self, fn):
720 with open(fn, "wb") as fp: