e@0ddlmZmZmZddlmZmZmZddlmZm 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.pyrr IrrceZdZgZy) MappingErrorNrrrrrr rrrceZdZgZy) ConstErrorNrrrrrrrrrceZdZgZy)ValidationErrorNrrrrrrrrrceZdZgZy) PaddingErrorNrrrrrrrrrc0eZdZdZgdZ 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__r"r#r$r%)selfsubconr"r#r$r%s rr(zBitIntegerAdapter.__init__(s.v&     rc|dkr|js td|t||j}|jrt ||j }|S)Nz+object is negative, but field is not signed)r"r%)r$rrr"r#rr%)r)objcontextobj2s r_encodezBitIntegerAdapter._encode/sN 74;;!"O #tzz2 <<dt}}=D rcv|jrt||j}t||jS)Nr-)r$)r#rr%rr$r)r.r/s r_decodezBitIntegerAdapter._decode7s* <<ST]];C# 44rN)FFrrr__doc__rr(r1r4rrrr!r!s# ;I@E!5rr!c0eZdZdZgdZeefdZdZdZy)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 decdefaultchtj||||_||_||_||_yr')rr(r;r:r=r<)r)r*r;r:r=r<s rr(zMappingAdapter.__init__Ms.v&    $$rc |j|S#ttf$r]|jtur&t d|d|j jd|jtur|cYS|jcYSwxYw)Nzno encoding mapping for  []) r:KeyError TypeErrorr<NotImplementedrr*namerr3s rr1zMappingAdapter._encodeTr #==% %)$ #.0"))$+,,$& ?? "  #AA=. A=<A=c |j|S#ttf$r]|jtur&t d|d|j jd|jtur|cYS|jcYSwxYw)Nzno decoding mapping for r@rA) r;rBrCr=rDrr*rErr3s rr4zMappingAdapter._decode^rFrGN) rrrr7rrDr(r1r4rrrr9r9<s#EI,>% # #rr9c(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(rK)r)r*rKs rr(zFlagsAdapter.__init__tv& rctd}|jjD]\}}t||ds||z}|S)Nr,F)rKitemsgetattr)r)r.r/rKrEvalues rr1zFlagsAdapter._encodewsC::++- KD%sD%(  rc t}|jjD]\}}t||t ||z |Sr')r rKrOsetattrbool)r)r.r/r0rErQs rr4zFlagsAdapter._decode}sD::++- 3KD% D$S5[ 1 2 3 rNr6rrrrJrJis I rrJc*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). r:Nc>tj||||_yr')rr(r:)r)r*r:s rr(zStringAdapter.__init__v&  rcT|jr|j|j}|Sr')r:encoder3s rr1zStringAdapter._encode ==**T]]+C rcT|jr|j|j}|Sr')r:decoder3s rr4zStringAdapter._decoder[rr'r6rrrrVrVs  I!rrVc0eZdZdZgdZ ddZdZdZy)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. )padcharpaddirtrimdirc|dvr td||dvr td|tj||||_||_||_y)N)rightleftcenterz*paddir must be 'right', 'left' or 'center')rdrez!trimdir must be 'right' or 'left') ValueErrorrr(r`rarb)r)r*r`rarbs rr(zPaddedStringAdapter.__init__sZ 4 4I  + +@'J Jv&   rc|jdk(r|j|j}|S|jdk(r|j|j}|S|j |j}|SNrdre)rarstripr`lstripstripr3s rr4zPaddedStringAdapter._decodesg ;;' !**T\\*C  [[F "**T\\*C ))DLL)C rcd|j|}|jdk(r|j||j}nH|jdk(r|j ||j}n|j ||j}t ||kDr|jdk(r|d|}|S|| d}|Sri)_sizeofraljustr`rjustrflenrb)r)r.r/sizes rr1zPaddedStringAdapter._encodes||G$ ;;' !))D$,,/C [[F "))D$,,/C**T4<<0C s8d?||w&%4j 4%&k rN)rdrdrrrr7rr(r4r1rrrr_r_s# 1I;B"  rr_c 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 ct||fSr')rqr3s rr1zLengthValueAdapter._encodesC#rc |dS)Nrrr3s rr4zLengthValueAdapter._decodes 1v rN)rrrr7rr1r4rrrrvrvsIrrvc*eZdZdZdgZddZdZdZy)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. terminatorsNcBtj|||||_y)N)r:)rVr(r{)r)r*r{r:s rr(zCStringAdapter.__init__stVA&rcPtj||||jddzS)Nr,r)rVr1r{r3s rr1zCStringAdapter._encodes)$$T384;K;KAa;PPPrcTtj|dj|dd|S)Nr)rVr4joinr3s rr4zCStringAdapter._decodes&$$T388CH+=wGGr)rsNr6rrrrzrzs! I'QHrrzc(eZdZdZdgZdZdZdZy) 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_subconc>tj||||_yr')rr(r)r)r*rs rr(zTunnelAdapter.__init__sv&(rcL|jjt||Sr')r_parser r3s rr4zTunnelAdapter._decode s  '' g>>rcpt}|jj||||jSr')r r_buildgetvalue)r)r.r/streams rr1zTunnelAdapter._encode s.   fg6  rNrtrrrrrs *  I)?!rrceZdZdZddgZdZy) 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, ) r1r4cLtj||||_||_yr')rr(r1r4)r)r*encoderdecoders rr(zExprAdapter.__init__$s v&  rN)rrrr7rr(rrrrrs$I&Irrc*eZdZdZdgZddZdZdZy)HexDumpAdapterzT Adapter for hex-dumping strings. It returns a HexString, which is a string linesizec>tj||||_yr')rr(r)r)r*rs rr(zHexDumpAdapter.__init__.rXrc|Sr'rr3s rr1zHexDumpAdapter._encode1s rc0t||jS)N)r)r rr3s rr4zHexDumpAdapter._decode3s77rN)r6rrrrr)s I!8rrc(eZdZdZdgZdZdZdZy) 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") rQc>tj||||_yr')rr(rQ)r)r*rQs rr(zConstAdapter.__init__CrMrcr|||jk(r |jStd|jd|Nz expected z, found rQrr3s rr1zConstAdapter._encodeFs0 ;#+::  CHI IrcZ||jk7rtd|jd||Srrr3s rr4zConstAdapter._decodeKs' $**  CHI I rNr6rrrrr6s   IJ rrc,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) )startstopstepNcLtj||||_||_yr')rr(rr)r)r*rrs rr(zSlicingAdapter.__init__[s v&  rcD|j|Sdg|jz|zSr')rr3s rr1zSlicingAdapter._encode_s' :: Jv "S((rc4||j|jSr')rrr3s rr4zSlicingAdapter._decodecs4::dii((rr'r6rrrrrPs*I))rrc(eZdZdZdgZdZdZdZy)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 indexctj||t|turt dt|||_y)Nzindex must be an integer)rr(typeintrCr)r)r*rs rr(zIndexingAdapter.__init__os7v& ;c !6U D D rc*dg|jz|gzSr'rr3s rr1zIndexingAdapter._encodetsv "cU**rc ||jSr'rr3s rr4zIndexingAdapter._decodevs4::rNr6rrrrrfs I +rrc,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) patternstrictcLtj||||_||_yr')rr(rr)r)r*rrs rr(zPaddingAdapter.__init__s v&  rc>|j||jzSr')rnrr3s rr1zPaddingAdapter._encodes||G$t||33rc|jr4|j||jz}||k7rtd|d||Sr)rrnrr)r)r.r/expecteds rr4zPaddingAdapter._decodes< ;;||G,t||;Hh"h#LMM rN)rsFr6rrrrrys"H%I4rrc&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 cB|j||s td||S)Nzinvalid object) _validaterr3s rr4zValidator._decodes#~~c7+!"2C8 8 rc&|j||Sr')r4r3s rr1zValidator._encodes||C))rctr')NotImplementedErrorr3s rrzValidator._validates !##rN)rrrr7rr4r1rrrrrrsI*$rrc"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')rr(r)r)r*rs rr(zOneOf.__init__s4( rc||jvSr')rr3s rrzOneOf._validatesdkk!!rNrrrr7rr(rrrrrrs( I"rrc"eZdZdZdgZdZdZy)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) invalidsc>tj||||_yr')rr(r)r)r*rs rr(zNoneOf.__init__s4(  rc||jvSr')rr3s rrzNoneOf._validates$--''rNrrrrrrs  I!(rrN)#corerrrlibrrrr r lib.py3compatr r rrrrrr!r9rJrVr_rvrzrrrrrrrrrrrrrrs%0033*/ o?o? "5"5H+#W+#Z74G0/'/b  H]H(!G!B'2 8W 874)W),g&W8$$$"I"8(Y(r