e@cs0ddlmZmZmZddlmZmZmZddlmZm Z ddl m Z m Z GddeZ GddeZGd d eZGd d eZGd deZGddeZGddeZGddeZGddeZGddeZGddeZGddeZGddeZGdd eZGd!d"eZGd#d$eZGd%d&eZGd'd(eZGd)d*eZGd+d,eZ Gd-d.e Z!Gd/d0e Z"y1)2)AdapterAdaptationErrorPass) int_to_bin bin_to_int swap_bytes)FlagsContainer HexString)BytesIO decodebytesceZdZgZy)BitIntegerErrorN__name__ __module__ __qualname__ __slots__@/usr/lib/python3.12/site-packages/elftools/construct/adapters.pyr r Irr cr ) MappingErrorNr rrrrr rrrcr ) ConstErrorNr rrrrrrrrcr )ValidationErrorNr rrrrrrrrcr ) PaddingErrorNr rrrrrrrrc0eZdZdZgdZ ddZdZdZy)BitIntegerAdaptera Adapter for bit-integers (converts bitstrings to integers, and vice versa). See BitField. Parameters: * subcon - the subcon to adapt * width - the size of the subcon, in bits * swapped - whether to swap byte order (little endian/big endian). default is False (big endian) * signed - whether the value is signed (two's complement). the default is False (unsigned) * bytesize - number of bits per byte, used for byte-swapping (if swapped). default is 8. )widthswappedsignedbytesizechtj||||_||_||_||_yN)r__init__rrrr)selfsubconrrrr rr"zBitIntegerAdapter.__init__(s.v&     rcs|dkr|js td|t||j}|jrt ||j }|S)Nz+object is negative, but field is not signed)rr)rr rrrrr)r#objcontextobj2 r_encodezBitIntegerAdapter._encode/sN 74;;!"O #tzz2 <<dt}}=D rcsv|jrt||j}t||jS)Nr')r)rrrrrr#r(r) r_decodezBitIntegerAdapter._decode7s* <<ST]];C# 44rN)FFirrr__doc__rr"r,r/rrrrrs# ;I@E!5rrcs0eZdZdZgdZeefdZdZdZy)MappingAdaptera Adapter that maps objects to other objects. See SymmetricMapping and Enum. Parameters: * subcon - the subcon to map * decoding - the decoding (parsing) mapping (a dict) * encoding - the encoding (building) mapping (a dict) * decdefault - the default return value when the object is not found in the decoding mapping. if no object is given, an exception is raised. if `Pass` is used, the unmapped object will be passed as-is * encdefault - the default return value when the object is not found in the encoding mapping. if no object is given, an exception is raised. if `Pass` is used, the unmapped object will be passed as-is )encodingdecoding encdefault decdefaultcr r!)rr"r4r3r6r5)r#r$r4r3r6r5r%rr"zMappingAdapter.__init__Ms.v&    $$rc |j|S#ttf$r]|jtur&t d|d|j jd|jtur|cYS|jcYSwxYw)Nzno encoding mapping for  []) r3KeyError TypeErrorr5NotImplementedrr$namerr-r.rr,zMappingAdapter._encodeTr #==% %)$ #.0"))$+,,$& ?? "  #AA=. A=<A=cr7)Nzno decoding mapping for r8r9) r4r:r;r6r<rr$r=rr-r.rr/zMappingAdapter._decode^r>r?N) rrrr1rr<r"r,r/rrrr2r2<s#EI,>% # #rr2c(eZdZdZdgZdZdZdZy) FlagsAdaptera Adapter for flag fields. Each flag is extracted from the number, resulting in a FlagsContainer object. Not intended for direct usage. See FlagsEnum. Parameters * subcon - the subcon to extract * flags - a dictionary mapping flag-names to their value flagsc>tj||||_yr!)rr"rB)r#r$rBr.rr"zFlagsAdapter.__init__tv& rcstd}|jjD]\}}t||ds||z}|S)Nr&F)rBitemsZgetattr)r#r(r)rBr=valuer%rr,zFlagsAdapter._encodewsC::++- KD%sD%(  rc st}|jjD]\}}t||t ||z |Sr!)rrBrEZsetattrZbool)r#r(r)r*r=rFr%rr/zFlagsAdapter._decode}sD::++- 3KD% D$S5[ 1 2 3 rNr0rrrrArAis I rrAc*eZdZdZdgZddZdZdZy) StringAdapteraA Adapter for strings. Converts a sequence of characters into a python string, and optionally handles character encoding. See String. Parameters: * subcon - the subcon to convert * encoding - the character encoding name (e.g., "utf8"), or None to return raw bytes (usually 8-bit ASCII). r3NcrCr!)rr"r3)r#r$r3r.rr"zStringAdapter.__init__v&  rcT|jr|j|j}|Sr!)r3Zencoder-r.rr,zStringAdapter._encode ==**T]]+C rcrJr!)r3Zdecoder-r.rr/zStringAdapter._decoderKrr!r0rrrrHrHs  I!rrHcr)PaddedStringAdaptera Adapter for padded strings. See String. Parameters: * subcon - the subcon to adapt * padchar - the padding character. default is b"\x00". * paddir - the direction where padding is placed ("right", "left", or "center"). the default is "right". * trimdir - the direction where trimming will take place ("right" or "left"). the default is "right". trimming is only meaningful for building, when the given string is too long. )padcharpaddirtrimdircs|dvr td||dvr td|tj||||_||_||_y)N)rightleftcenterz*paddir must be 'right', 'left' or 'center')rPrQz!trimdir must be 'right' or 'left')Z ValueErrorrr"rMrNrO)r#r$rMrNrOs rr"zPaddedStringAdapter.__init__sZ 4 4I  + +@'J Jv&   rcs|jdk(r|j|j}|S|jdk(r|j|j}|S|j |j}|SNrPrQ)rNZrstriprMZlstripZstripr-r.rr/zPaddedStringAdapter._decodesg ;;' !**T\\*C  [[F "**T\\*C ))DLL)C rcsd|j|}|jdk(r|j||j}nH|jdk(r|j ||j}n|j ||j}t ||kDr|jdk(r|d|}|S|| d}|SrS)_sizeofrNZljustrMZrjustrRlenrO)r#r(r)Zsizer+rr,zPaddedStringAdapter._encodes||G$ ;;' !))D$,,/C [[F "))D$,,/C**T4<<0C s8d?||w&%4j 4%&k rN)rPrPrrrr1rr"r/r,rrrrLrLs# 1I;B"  rrLcs eZdZdZgZdZdZy)LengthValueAdapterz Adapter for length-value pairs. It extracts only the value from the pair, and calculates the length based on the value. See PrefixedArray and PascalString. Parameters: * subcon - the subcon returning a length-value pair cst||fSr!)rUr-r.rr,zLengthValueAdapter._encodesC#rcs |dS)Nrrr-r.rr/zLengthValueAdapter._decodes 1v rN)rrrr1rr,r/rrrrXrXsIrrXcrG)CStringAdapterar Adapter for C-style strings (strings terminated by a terminator char). Parameters: * subcon - the subcon to convert * terminators - a sequence of terminator chars. default is b"\x00". * encoding - the character encoding to use (e.g., "utf8"), or None to return raw-bytes. the terminator characters are not affected by the encoding. terminatorsNcsBtj|||||_y)N)r3)rHr"rZ)r#r$rZr3r+rr"zCStringAdapter.__init__stVA&rcsPtj||||jddzS)Nr&r)rHr,rZr-r.rr,zCStringAdapter._encodes)$$T384;K;KAa;PPPrcsTtj|dj|dd|S)Nri)rHr/Zjoinr-r.rr/zCStringAdapter._decodes&$$T388CH+=wGGr)rVNr0rrrrYrYs! I'QHrrYcr@) TunnelAdapteraC Adapter for tunneling (as in protocol tunneling). A tunnel is construct nested upon another (layering). For parsing, the lower layer first parses the data (note: it must return a string!), then the upper layer is called to parse that data (bottom-up). For building it works in a top-down manner; first the upper layer builds the data, then the lower layer takes it and writes it to the stream. Parameters: * subcon - the lower layer subcon * inner_subcon - the upper layer (tunneled/nested) subcon Example: # a pascal string containing compressed data (zlib encoding), so first # the string is read, decompressed, and finally re-parsed as an array # of UBInt16 TunnelAdapter( PascalString("data", encoding = "zlib"), GreedyRange(UBInt16("elements")) ) inner_subconcrCr!)rr"r\)r#r$r\r.rr"zTunnelAdapter.__init__sv&(rcsL|jjt||Sr!)r\Z_parser r-r.rr/zTunnelAdapter._decode s  '' g>>rcspt}|jj||||jSr!)r r\Z_buildZgetvalue)r#r(r)Zstreamr+rr,zTunnelAdapter._encode s.   fg6  rNrWrrrr[r[s *  I)?!rr[cseZdZdZddgZdZy) ExprAdaptera> A generic adapter that accepts 'encoder' and 'decoder' as parameters. You can use ExprAdapter instead of writing a full-blown class when only a simple expression is needed. Parameters: * subcon - the subcon to adapt * encoder - a function that takes (obj, context) and returns an encoded version of obj * decoder - a function that takes (obj, context) and returns a decoded version of obj Example: ExprAdapter(UBInt8("foo"), encoder = lambda obj, ctx: obj / 4, decoder = lambda obj, ctx: obj * 4, ) r,r/cLtj||||_||_yr!)rr"r,r/)r#r$ZencoderZdecoderr+rr"zExprAdapter.__init__$s v&  rN)rrrr1rr"rrrr]r]s$I&Irr]cs*eZdZdZdgZddZdZdZy)HexDumpAdapterzT Adapter for hex-dumping strings. It returns a HexString, which is a string linesizecrCr!)rr"r`)r#r$r`r.rr"zHexDumpAdapter.__init__.rIrcs|Sr!rr-r.rr,zHexDumpAdapter._encode1s rcs0t||jS)N)r`)rr`r-r.rr/zHexDumpAdapter._decode3s77rN)ir0rrrr_r_)s I!8rr_cr@) ConstAdaptera, Adapter for enforcing a constant value ("magic numbers"). When decoding, the return value is checked; when building, the value is substituted in. Parameters: * subcon - the subcon to validate * value - the expected value Example: Const(Field("signature", 2), "MZ") rFcrCr!)rr"rF)r#r$rFr.rr"zConstAdapter.__init__CrDrcsr|||jk(r |jStd|jd|Nz expected z, found rFrr-r.rr,zConstAdapter._encodeFs0 ;#+::  CHI IrcsZ||jk7rtd|jd||Srbrcr-r.rr/zConstAdapter._decodeKs' $**  CHI I rNr0rrrrara6s   IJ rracs,eZdZdZgdZddZdZdZy)SlicingAdapterz Adapter for slicing a list (getting a slice from that list) Parameters: * subcon - the subcon to slice * start - start index * stop - stop index (or None for up-to-end) * step - step (or None for every element) )startstopZstepNcr^r!)rr"rerf)r#r$rerfr+rr"zSlicingAdapter.__init__[s v&  rcsD|j|Sdg|jz|zSr!)rer-r.rr,zSlicingAdapter._encode_s' :: Jv "S((rcs4||j|jSr!)rerfr-r.rr/zSlicingAdapter._decodecs4::dii((rr!r0rrrrdrdPs*I))rrdcr@)IndexingAdapterz Adapter for indexing a list (getting a single item from that list) Parameters: * subcon - the subcon to index * index - the index of the list to get indexcstj||t|turt dt|||_y)Nzindex must be an integer)rr"ZtypeZintr;rh)r#r$rhr.rr"zIndexingAdapter.__init__os7v& ;c !6U D D rcs*dg|jz|gzSr!rhr-r.rr,zIndexingAdapter._encodetsv "cU**rcs ||jSr!rir-r.rr/zIndexingAdapter._decodevs4::rNr0rrrrgrgfs I +rrgcs,eZdZdZddgZddZdZdZy) PaddingAdaptera+ Adapter for padding. Parameters: * subcon - the subcon to pad * pattern - the padding pattern (character as byte). default is b"\x00" * strict - whether or not to verify, during parsing, that the given padding matches the padding pattern. default is False (unstrict) patternstrictcr^r!)rr"rkrl)r#r$rkrlr+rr"zPaddingAdapter.__init__s v&  rcs>|j||jzSr!)rTrkr-r.rr,zPaddingAdapter._encodes||G$t||33rcs|jr4|j||jz}||k7rtd|d||Srb)rlrTrkr)r#r(r)Zexpectedr+rr/zPaddingAdapter._decodes< ;;||G,t||;Hh"h#LMM rN)rVFr0rrrrjrjys"H%I4rrjcs&eZdZdZgZdZdZdZy) Validatorz Abstract class: validates a condition on the encoded/decoded object. Override _validate(obj, context) in deriving classes. Parameters: * subcon - the subcon to validate csB|j||s td||S)Nzinvalid object) _validaterr-r.rr/zValidator._decodes#~~c7+!"2C8 8 rcs&|j||Sr!)r/r-r.rr,zValidator._encodes||C))rcstr!)ZNotImplementedErrorr-r.rrnzValidator._validates !##rN)rrrr1rr/r,rnrrrrmrmsI*$rrmc"eZdZdZdgZdZdZy)OneOfai Validates that the object is one of the listed values. :param ``Construct`` subcon: object to validate :param iterable valids: a set of valid values >>> OneOf(UBInt8("foo"), [4,5,6,7]).parse("\x05") 5 >>> OneOf(UBInt8("foo"), [4,5,6,7]).parse("\x08") Traceback (most recent call last): ... construct.core.ValidationError: ('invalid object', 8) >>> >>> OneOf(UBInt8("foo"), [4,5,6,7]).build(5) '\x05' >>> OneOf(UBInt8("foo"), [4,5,6,7]).build(9) Traceback (most recent call last): ... construct.core.ValidationError: ('invalid object', 9) validsc>tj||||_yr!)rmr"rq)r#r$rqr.rr"zOneOf.__init__s4( rcs||jvSr!)rqr-r.rrnzOneOf._validatesdkk!!rNrrrr1rr"rnrrrrprps( I"rrpcro)NoneOfa Validates that the object is none of the listed values. :param ``Construct`` subcon: object to validate :param iterable invalids: a set of invalid values >>> NoneOf(UBInt8("foo"), [4,5,6,7]).parse("\x08") 8 >>> NoneOf(UBInt8("foo"), [4,5,6,7]).parse("\x06") Traceback (most recent call last): ... construct.core.ValidationError: ('invalid object', 6) invalidscrrr!)rmr"ru)r#r$rur.rr"zNoneOf.__init__s4(  rcs||jvSr!)rur-r.rrnzNoneOf._validates$--''rNrsrrrrtrts  I!(rrtN)#ZcorerrrZlibrrrrrZ lib.py3compatr r r rrrrrr2rArHrLrXrYr[r]r_rardrgrjrmrprtrrrrvs%0033*/ o?o? "5"5H+#W+#Z74G0/'/b  H]H(!G!B'2 8W 874)W),g&W8$$$"I"8(Y(r