
    #)di                     v   d Z dZddlmZ ddlmZmZ ddlmZ ddlZddl	Z	ddl
mZmZmZmZmZmZmZmZmZmZmZ ddlmZ  G d	 d
e          Z e            Z G d de          Z G d de          ZdBdZdCdZdDdZ G d de          Z  G d de!          Z"dEdZ# G d de!          Z$ G d de$          Z% G d de$          Z& G d  d!e&          Z' G d" d#e&          Z( G d$ d%e(          Z) G d& d'e(          Z* G d( d)e(          Z+ G d* d+e(          Z, G d, d-e(          Z- G d. d/e-          Z. G d0 d1e-          Z/ G d2 d3e(          Z0 G d4 d5e0          Z1 G d6 d7e0          Z2 G d8 d9e0          Z3 G d: d;e0          Z4 G d< d=e$          Z5 G d> d?e5          Z6 G d@ dAe$          Z7dS )Fz&Intel HEX format manipulation library.javadoc    )array)hexlify	unhexlify)bisect_rightN)IntTypesStrTypeStringIOarray_tobytesasbytesasstrdict_items_g	dict_keysdict_keys_grange_grange_l)
total_sizec                       e Zd ZdS )_DeprecatedParamN)__name__
__module____qualname__     X/var/www/menimich/repos/protonApp/venv/lib/python3.11/site-packages/intelhex/__init__.pyr   r   =   s        Dr   r   c                   &   e Zd ZdZd+dZd,dZd Zd,dZd ZeZ	d	 Z
d,d
Zd-dZddedfdZd ZddedfdZd ZddedfdZd Zd Zd Zd Zd Zd Zd Zd Zd Z ee          Zd.dZd/dZd Zd  Z d! Z!d" Z"d0d#Z#d1d%Z$d2d'Z%d3d)Z&d* Z'dS )4IntelHexz Intel HEX file reader. Nc                    d| _         d| _        i | _        d| _        |t	          |t
                    st          |dd          r|                     |           dS t	          |t                    r| 	                    |           dS t	          |t                    rQ|j         | _         |j        r|j                                        | _        |j                                        | _        dS t          d          dS )aH   Constructor. If source specified, object will be initialized
        with the contents of source. Otherwise the object will be empty.

        @param  source      source for initialization
                            (file name of HEX file, file object, addr dict or
                             other IntelHex object)
           Nr   readzsource: bad initializer type)padding
start_addr_buf_offset
isinstancer	   getattrloadhexdictfromdictr   copy
ValueErrorselfsources     r   __init__zIntelHex.__init__F   s      	&'** Agffd.K.K AV$$$$$FD)) Af%%%%%FH-- A%~$ ?&,&7&<&<&>&>DO"K,,..			 !?@@@ r   r   c           
      @   |                     d          }|sdS |d         dk    r	 t          dt          t          |dd                                       }n%# t          t
          f$ r t          |          w xY wt          |          }|dk     rt          |          nt          |          |d         }|d|z   k    rt          |          |d         d	z  |d
         z   }|d         }d|cxk    rdk    sn t          |          t          |          }|dz  }|dk    rt          |          |dk    rc|| j        z  }t          dd|z             D ]C}	| j                            |d          t!          ||          ||	         | j        |<   |dz  }DdS |dk    r|dk    rt#          |          t$          |d
k    r:|d
k    s|dk    rt'          |          |d         d	z  |d         z   dz  | _        dS |dk    r:|d
k    s|dk    rt)          |          |d         d	z  |d         z   dz  | _        dS |dk    rc|dk    s|dk    rt+          |          | j        rt/          |          |d         d	z  |d         z   |d         d	z  |d         z   d| _        dS |dk    rh|dk    s|dk    rt1          |          | j        rt/          |          d|d         dz  |d         dz  z   |d         d	z  z   |d         z   i| _        dS dS )zDecode one record of HEX file.

        @param  s       line with HEX record.
        @param  line    line number (for error messages).

        @raise  EndOfFile   if EOF record encountered.
        
Nr   :B   )line            r      )addressr5               )CSIPEIPi   )rstripr   r   r   	TypeErrorr+   HexRecordErrorlenRecordLengthErrorRecordTypeErrorsumRecordChecksumErrorr$   r   r#   getAddressOverlapErrorEOFRecordError
_EndOfFile!ExtendedSegmentAddressRecordError ExtendedLinearAddressRecordErrorStartSegmentAddressRecordErrorr"    DuplicateStartAddressRecordErrorStartLinearAddressRecordError)
r-   sr5   binlengthrecord_lengthaddrrecord_typecrcis
             r   _decode_recordzIntelHex._decode_recorde   s    HHV 	FQ43;;0C71QRR5>>!:!:;;z* 0 0 0$$////0 XXFzz$$////  !d++++Aa-'((#....1vczCF"!f[%%%%A%%%%!t,,,,#hhu!88%40000!DL DQ-00  y}}T4008-dFFFF"%a&	$		  A!!$$////A!!TQYY7TBBBBF3JQ/25DLLLA!!TQYY6DAAAAF3JQ/58DLLLA!!TQYY4$???? B6DAAAA%(VCZ#a&%8%(VCZ#a&%8   DOOO A!!TQYY3>>>> B6DAAAA$s1vh'*1ve|(4'*1vcz(2 (+1v(.  DOOO s   2A "A<c                    t          |dd          t          |d          }|j        }nd}d| _        d}	 | j        }	 |D ]}|dz  } |||           n# t
          $ r Y nw xY w|r |             dS dS # |r |             w w xY w)zLoad hex file into internal buffer. This is not necessary
        if object was initialized with source set. This will overwrite
        addresses if object was already initialized.

        @param  fobj        file name or file-like object
        r    Nrr   r4   )r&   opencloser$   r\   rN   )r-   fobjfcloser5   decoderT   s         r   r'   zIntelHex.loadhex   s     4&&.c??DZFFF
	(F $ $AAIDF1dOOOO$       v s.   A5 A A5 
A"A5 !A""A5 5Bc           	      $   t          |dd          }|t          |d          }|j        }|j        }nd}	 |                     t          dt           |                                |           |r |             dS dS # |r |             w w xY w)a%  Load bin file into internal buffer. Not needed if source set in
        constructor. This will overwrite addresses without warning
        if object was already initialized.

        @param  fobj        file name or file-like object
        @param  offset      starting address offset
        r    Nrbr3   )offset)r&   r_   r    r`   	frombytesr   r   )r-   ra   rf   freadfrb   s         r   loadbinzIntelHex.loadbin   s     fd++=T4  AFEWFFF	NN5geegg&6&677NGGG  v s   :B   Bc                     |dk    r|                      |           dS |dk    r|                     |           dS t          d|z            )zLoad data file into internal buffer. Preferred wrapper over
        loadbin or loadhex.

        @param  fobj        file name or file-like object
        @param  format      file format ("hex" or "bin")
        hexrU   6format should be either "hex" or "bin"; got %r insteadN)r'   rj   r+   )r-   ra   formats      r   loadfilezIntelHex.loadfile   se     U??LLu__LL "$*+ , , ,r   c                 &   |                                 }|                    d          }||d= t          |          D ]-}t          |          t          vs|dk     rt          d          .| j                            |           |	|| _        dS dS )a"  Load data from dictionary. Dictionary should contain int keys
        representing addresses. Values should be the data to be stored in
        those addresses in unsigned char form (i.e. not strings).
        The dictionary may contain the key, ``start_addr``
        to indicate the starting address of the data as described in README.

        The contents of the dict will be merged with this object and will
        overwrite any conflicts. This function is not necessary if the
        object was initialized with source specified.
        r"   Nr   z+Source dictionary should have only int keys)	r*   rK   r   typer   r+   r#   updater"   )r-   diktrT   r"   ks        r   r)   zIntelHex.fromdict  s     IIKKUU<((
!,Q 	P 	PAAwwh&&!a%% !NOOO +0	!(DOOO "!r   c                 .    |D ]}|| j         |<   |dz  }dS )z{Load data from array or list of bytes.
        Similar to loadbin() method but works directly with iterable bytes.
        r4   N)r#   )r-   bytesrf   bs       r   rg   zIntelHex.frombytes  s4      	 	A !DIfaKFF	 	r   c                 l   ||fdk    r| j         i k    rt          |_d||fvrt          d          ||fdk    r|                                 }|	||z   dz
  }nY||z
  dz   }|dk     rt          d||fz            n6||                                 }||                                 }||k    r||}}||fS )zReturn default values for start and end if they are None.
        If this IntelHex object is empty then it's error to
        invoke this method with both start and end as None. 
        NNNzGtobinarray: you can't use start,end and size arguments in the same timer4   r   z8tobinarray: invalid size (%d) for given end address (%d))r#   EmptyIntelHexErrorr+   minaddrmaxaddr)r-   startendsizes       r   _get_start_endzIntelHex._get_start_end!  s	   
 #;+%%$)r//$$E3<''  "? @ @ @s||++ dlQ&d
Q199$ &BEI#J&O P P P  }{llnns{{ %sczr   c                     t          |t                    s@t          d           |t          d           n!t          d           t          d           nd}|                     ||||          S )aS   Convert this object to binary form as array. If start and end 
        unspecified, they will be inferred from the data.
        @param  start   start address of output bytes.
        @param  end     end address of output bytes (inclusive).
        @param  pad     [DEPRECATED PARAMETER, please use self.padding instead]
                        fill empty spaces with this value
                        (if pad is None then this method uses self.padding).
        @param  size    size of the block, used with start or end parameter.
        @return         array of unsigned char data.
        z3IntelHex.tobinarray: 'pad' parameter is deprecated.N/Please, use IntelHex.padding attribute instead.!Please, don't pass it explicitly.zAUse syntax like this: ih.tobinarray(start=xxx, end=yyy, size=zzz))r%   r   print_tobinarray_reallyr-   r}   r~   padr   s        r   
tobinarrayzIntelHex.tobinarray>  s}     #/00 	HIIIHIIII:;;;Z[[[[C&&uc3===r   c                 F   || j         }t          d          }| j        i k    rd||fv r|S ||dk    rt          d          |                     |||          \  }}t          ||dz             D ]0}|                    | j                            ||                     1|S )zReturn binary array.Nr3   r    tobinarray: wrong value for sizer4   )r!   r   r#   r+   r   r   appendrK   )r-   r}   r~   r   r   rU   r[   s          r   r   zIntelHex._tobinarray_reallyT  s    ;,CCjj9??ts|33J		?@@@((T::
sA&& 	. 	.AJJty}}Q,,----
r   c                     t          |t                    s@t          d           |t          d           n!t          d           t          d           nd}|                     ||||          S )a   Convert to binary form and return as binary string.
        @param  start   start address of output bytes.
        @param  end     end address of output bytes (inclusive).
        @param  pad     [DEPRECATED PARAMETER, please use self.padding instead]
                        fill empty spaces with this value
                        (if pad is None then this method uses self.padding).
        @param  size    size of the block, used with start or end parameter.
        @return         bytes string of binary data.
        z1IntelHex.tobinstr: 'pad' parameter is deprecated.Nr   r   z?Use syntax like this: ih.tobinstr(start=xxx, end=yyy, size=zzz))r%   r   r   _tobinstr_reallyr   s        r   tobinstrzIntelHex.tobinstrb  s}     #/00 	FGGGHIIII:;;;XYYYYC$$UCd;;;r   c                 L    t          |                     ||||                    S N)r   r   r   s        r   r   zIntelHex._tobinstr_reallyw  s$    T44UCdKKLLLr   c                    t          |t                    s@t          d           |t          d           n!t          d           t          d           nd}t          |dd          t	          |d          }d}nd	}|                    |                     ||||                     |r|                                 dS dS )
a  Convert to binary and write to file.

        @param  fobj    file name or file object for writing output bytes.
        @param  start   start address of output bytes.
        @param  end     end address of output bytes (inclusive).
        @param  pad     [DEPRECATED PARAMETER, please use self.padding instead]
                        fill empty spaces with this value
                        (if pad is None then this method uses self.padding).
        @param  size    size of the block, used with start or end parameter.
        z2IntelHex.tobinfile: 'pad' parameter is deprecated.Nr   r   z@Use syntax like this: ih.tobinfile(start=xxx, end=yyy, size=zzz)writewbTF)r%   r   r   r&   r_   r   r   r`   )r-   ra   r}   r~   r   r   close_fds          r   	tobinfilezIntelHex.tobinfilez  s     #/00 	GHHHHIIII:;;;YZZZZC4$''/d##DHHH

4((S$??@@@ 	JJLLLLL	 	r   c                 `    i }|                     | j                   | j        r
| j        |d<   |S )zwConvert to python dictionary.

        @return         dict suitable for initializing another IntelHex object.
        r"   )rr   r#   r"   )r-   r^   s     r   todictzIntelHex.todict  s7    
 	? 	."oAlOr   c                 V    t          | j                  }|                                 |S )z~Returns all used addresses in sorted order.
        @return         list of occupied data addresses in sorted order. 
        )r   r#   sortr-   aas     r   	addresseszIntelHex.addresses  s%     ty!!
				r   c                 X    t          | j                  }|g k    rdS t          |          S )zgGet minimal address of HEX content.
        @return         minimal address or None if no data
        Nr   r#   minr   s     r   r{   zIntelHex.minaddr  ,     ty!!884r77Nr   c                 X    t          | j                  }|g k    rdS t          |          S )zgGet maximal address of HEX content.
        @return         maximal address or None if no data
        Nr   r#   maxr   s     r   r|   zIntelHex.maxaddr  r   r   c                    t          |          }|t          v r5|dk     rt          d          | j                            || j                  S |t          k    rt          | j                  }t                      }|rs|	                                 |j
        p|d         }|j        p
|d         dz   }|j        pd}t          |||          D ]#}| j                            |          }	|	|	||<   $|S t          d|z            )z Get requested byte from address.
        @param  addr    address of byte.
        @return         byte if address exists in HEX file, or self.padding
                        if no data found.
        r   Address should be >= 0.r4   N Address has unsupported type: %s)rq   r   rD   r#   rK   r!   slicer   r   r   r}   stopstepr   )
r-   rX   tr   ihr}   r   r   r[   xs
             r   __getitem__zIntelHex.__getitem__  s    JJ==axx 9:::9==t|444%ZZ!$),,IB "   
2ily5Yr]1_y~A d33 " "A	a((A} !1I>BCCCr   c                    t          |          }|t          v r!|dk     rt          d          || j        |<   dS |t          k    r t          |t          t          f          st          d          |j	        }|j
        }|j        pd}d||fvrAt          |||          }t          |          t          |          k    rt          d          n@||fdk    rt          d          ||t          |          z
  }n||t          |          z   }|dk     rt          d	          |dk     rt          d
          d}t          |||          D ]}	||         | j        |	<   |dz  }dS t          d|z            )zSet byte at address.r   r   z)Slice operation expects sequence of bytesr4   Nz5Length of bytes sequence does not match address rangery   zUnsupported address rangez start address cannot be negativezstop address cannot be negativer   )rq   r   rD   r#   r   r%   listtupler+   r}   r   r   r   rF   r   )
r-   rX   byter   r}   r   r   rajr[   s
             r   __setitem__zIntelHex.__setitem__  s   JJ==axx 9:::"DIdOOO%ZZdT5M22 N !LMMMJE9D9>DE4=((UD$//r77c$ii''$ &( ) ) ) ( ,.. ;<<<s4yy(s4yy(qyy BCCCaxx ABBBAUD$//  #Aw	!Q  >BCCCr   c                    t          |          }|t          v r|dk     rt          d          | j        |= dS |t          k    rt          | j                  }|rv|                                 |j        p|d         }|j        p
|d         dz   }|j	        pd}t          |||          D ](}| j                            |          }|| j        |= 'dS dS t          d|z            )zDelete byte at address.r   r   r   r4   Nr   )rq   r   rD   r#   r   r   r   r}   r   r   r   rK   )	r-   rX   r   r   r}   r   r   r[   r   s	            r   __delitem__zIntelHex.__delitem__  s   JJ==axx 9:::	$%ZZ!$),,I )   
2ily5Yr]1_y~A d33 ) )A	a((A} IaL) )
) )
 >BCCCr   c                 D    t          t          | j                            S )z'Return count of bytes with real values.)rF   r   r#   )r-   s    r   __len__zIntelHex.__len__  s    9TY''(((r   c                 p    | dk    rdS | dk    r
|dk    rdS dS t          dt          |           z            )Nnative
CRLFwin32r1   zwrong eolstyle %s)r+   repr)eolstyleplatforms     r   _get_eol_textfilezIntelHex._get_eol_textfile  sL    x47""vt04>>ABBBr   Tr   r<   c           
      T   |dk    s|dk     rt          d|z            t          |dd          }|r|}d}nt          |d          }|j        }|j        }t
                              |t          j                  }t          j	        d         dk    r/t          t          d	                                                    }	n,d
                    d t          d	          D                       }	| j        r|rt!          | j                  }
|
                                 t%          dt'          d                    }|
ddgk    rd|d<   d|d<   d|d<   d|d<   | j        d         }|dz	  dz  |d<   |dz  |d<   | j        d         }|dz	  dz  |d<   |dz  |d<   t)          |           dz  |d<    |dt+          t-          t/          |                                        |	                    z   |z              n|
dgk    rd|d<   d|d<   d|d<   d|d<   | j        d         }|dz	  dz  |d<   |dz	  dz  |d<   |dz	  dz  |d<   |dz  |d<   t)          |           dz  |d<    |dt+          t-          t/          |                                        |	                    z   |z              n!|r
 |             t3          | j                  t!          | j                  }|                                 t7          |          }|r|d         }|d         }|dk    rd}nd}d}|}d}||k    r]|rt%          dt'          d                    }d|d<   d|d<   d|d<   d|d<   t9          |dz	            }t;          |d	          }|d         |d<   |d         |d<   t)          |           dz  |d<    |dt+          t-          t/          |                                        |	                    z   |z              	 |dz  }t=          |dz
  d|z
  ||z
            }||z   }|r,t?          |||t=          ||z   dz   |                    }||z
  }nd}t%          dt'          d d|z   z                      }t;          |d	          }|d         |d<   |d         |d<   d|d<   	 t          |          D ]}| j        ||z            |d|z   <   n# t@          $ r |}|dd|z            }Y nw xY w||d<   t)          |           dz  |d|z   <    |dt+          t-          t/          |                                        |	                    z   |z              ||z  }||k     r	||         }n|dz   }nt9          |dz	            }||k    rn||k    ] |d!|z              |r |             dS dS )"a  Write data to file f in HEX format.

        @param  f                   filename or file-like object for writing
        @param  write_start_addr    enable or disable writing start address
                                    record to file (enabled by default).
                                    If there is no start address in obj, nothing
                                    will be written regardless of this setting.
        @param  eolstyle            can be used to force CRLF line-endings
                                    for output file on different platforms.
                                    Supported eol styles: 'native', 'CRLF'.
        @param byte_count           number of bytes in the data field
        r   r4   zwrong byte_count value: %sr   Nwr   r9   r7    c              3   X   K   | ]%}t          |                                          V  &d S r   )chrupper.0r[   s     r   	<genexpr>z*IntelHex.write_hex_file.<locals>.<genexpr>F  s0      AAqCFFLLNNAAAAAAr   r3   z	         r@   rA   r:   r8      r6   r>   r?   r2   rB      r<   )r"   r     TFz        :00000001FF)!r+   r&   r_   r   r`   r   r   sysr   version_inforv   r   r   joinr   r"   r   r   r   r   rI   r   r   r   	translateInvalidStartAddressValueErrorr#   rF   intdivmodr   r   KeyError)r-   ri   write_start_addrr   
byte_countfwritera   rb   eoltablekeysrU   csipeipr   addr_lenr{   r|   need_offset_recordhigh_ofscur_addrcur_ixrw   low_addr	chain_len	stop_addrixr[   	high_addrs                                 r   write_hex_filezIntelHex.write_hex_file#  s    zA~~9JFGGGGT** 	 DFF3<<DZFZF((3<@@ A!##'#,,''--//EE GGAAGCLLAAAAAE ? &	P/ &	PT_--DIIKKKWV__--CT{""AAAA_T*'U*AeA_T*'U*AeAs88)u,AsW]3%7%788BB5IIJJK     %AAAAoe,)u,A)u,A(e+AuAs88)u,AsW]3%7%788BB5IIJJK      FHHH3tOOOO di((	y>> L	lGmG%)""%*"HHFg%%%  WV__55CCFCFCFCF"8R<00Hx--AqTCFqTCF"3xxi50CFF3 s););!<!<!F!Fu!M!MNNO      /''1H #JqL%.'(BR S SI !)9 4I  
&))Y*0*-fY.>q.@(*K*KM M %'K		 %&	WT1Y;-?%@%@AACx--AqTCFqTCFCF(!(!3!3 = =A'+y!'<C!HH=# ( ( ($%	!$1Q3$i( 'CF),S	U':C)$F3 s););!<!<!F!Fu!M!MNNO      
 i'F((#,V#4#*Q; #HbL 1 1I 8++_/! g%%D 	}S !!! 	FHHHHH	 	s   (S S$#S$c                     |dk    r|                      ||           dS |dk    r|                     |           dS t          d|z            )zWrite data to hex or bin file. Preferred method over tobin or tohex.

        @param  fobj        file name or file-like object
        @param  format      file format ("hex" or "bin")
        @param  byte_count  bytes per line
        rl   )r   rU   rm   N)r   r   r+   )r-   ra   rn   r   s       r   tofilezIntelHex.tofile  sl     U??<<<<<u__NN4      "$*+ , , ,r   c                     t          dt          d|z                      }	 t          |          D ]}| j        ||z            ||<   n# t          $ r t          ||          w xY wt          |          S )zGet string of bytes from given address. If any entries are blank
        from addr through addr+length, a NotEnoughDataError exception will
        be raised. Padding is not used.
        r3   r   )r;   rV   )r   r   r   r#   r   NotEnoughDataErrorr   )r-   rX   rV   ar[   s        r   getszIntelHex.gets  s    
 #wtF{++,,	BV__ ) )ya(!) 	B 	B 	B$T&AAAA	BQs   %A A$c                     t          dt          |                    }t          t          |                    D ]}||         | j        ||z   <   dS )z[Put string of bytes at given address. Will overwrite any previous
        entries.
        r3   N)r   r   r   rF   r#   )r-   rX   rT   r   r[   s        r   putszIntelHex.puts  sU     #wqzz""Q 	% 	%A !!DId1f	% 	%r   c                     d}	 	 | j         ||z            dk    rn|dz  }n!# t          $ r t          d|z            w xY w|                     ||          S )zGet zero-terminated bytes string from given address. Will raise 
        NotEnoughDataError exception if a hole is encountered before a 0.
        r   Tr4   zBBad access at 0x%X: not enough data to read zero-terminated string)msg)r#   r   r   r   )r-   rX   r[   s      r   getszzIntelHex.getsz  s     	J9T!V$))Q 	J 	J 	J$ +ADH*I J J J J	J yyq!!!s   ! ?c                 f    |                      ||           d| j        |t          |          z   <   dS )zFPut bytes string in object at addr and append terminating zero at end.r   N)r   r#   rF   )r-   rX   rT   s      r   putszzIntelHex.putsz  s2    		$!"	$s1vv+r   c                     t          |          }| t          ||                                                   D ]@\  }}|                     |||z
            }|                    |          }|dk    r||z   c S AdS )ah  Return the lowest index in self[start:end] where subsection sub is found.
        Optional arguments start and end are interpreted as in slice notation.
        
        @param  sub     bytes-like subsection to find
        @param  start   start of section to search within (optional)
        @param  end     end of section to search within (optional)
        r   )rv   r   segmentsr   find)r-   subr}   r~   rw   r[   s         r   r   zIntelHex.find   s     CjjuU3//099;; 	 	JE3		%U++AsABwwQw rr   Fc                 x   t          |t                    r|dk     rt          d          t          |          }|t          j        }| j        | j                            d          }| j                            d          }| j                            d          }||||                    d|z             n>||||                    d||fz             n|                    d	t
          z             t          | j	                  }|r|
                                 |d
         }|d         }	||z  |z  }
|	|z  dz   |z  }t          t          t          |                    dz
  d          }d|z  }t          |          }|r| j        }nd}t!          |
||          D ]}|                    ||z             |                    d           g }|D ]}| j	                            ||z   |          }|a|                    d|z             d|cxk    rdk     r&n n#|                    t%          |                     m|                    d           |                    d           |                    d           |                    dd                    |          z   dz              dS dS )a  Dump object content to specified file object or to stdout if None.
        Format is a hexdump with some header information at the beginning,
        addresses on the left, and data on right.

        @param  tofile          file-like object to dump to
        @param  width           number of bytes per line (i.e. columns)
        @param  withpadding     print padding character instead of '--'
        @raise  ValueError      if width is not a positive integer
        r4   z!width must be a positive integer.Nr@   rA   rB   zEIP = 0x%08X
zCS = 0x%04X, IP = 0x%04X
zstart_addr = %r
r   r   r8   r:   z%%0%dX z %02X       .z --z  |r   z|
)r%   r   r+   r   stdoutr"   rK   r   r   r#   r   r   rF   rl   r   r!   r   r   r   r   )r-   r   widthwithpaddingr   r   r   r   r{   r|   	startaddrendaddr	maxdigitstempla
rangewidthr   r[   rT   r   r   s                       r   dumpzIntelHex.dump  s    %$$ 	B		@AAAE

>ZF ?&$$T**B$$T**B/%%e,,C2:"*-34444BN9RHDEEEE0:=>>>di((	 	9NNlGmG E)U2I5(A-6GCG--1155I	)F J lY77 9 9VaZ(((S!!!# 
& 
&A	ac3//A}Wq[111====S=====HHSVV,,,,HHSMMMMU+++URWWQZZ/%788889	9 	99 9r   errorc                    t          |t                    st          d          || u rt          d          |dvrt          d          | j        }|j        }|D ]0}||v r|dk    rt          d|z            |dk    r%||         ||<   1| j        |j        k    rG| j        |j        | _        dS |j        dS |dk    rt          d	          |d
k    r|j        | _        dS dS dS )a6  Merge content of other IntelHex object into current object (self).
        @param  other   other IntelHex object.
        @param  overlap action on overlap of data or starting addr:
                        - error: raising OverlapError;
                        - ignore: ignore other data and keep current data
                                  in overlapping region;
                        - replace: replace data with other data
                                  in overlapping region.

        @raise  TypeError       if other is not instance of IntelHex
        @raise  ValueError      if other is the same object as self 
                                (it can't merge itself)
        @raise  ValueError      if overlap argument has incorrect value
        @raise  AddressOverlapError    on overlapped data
        zother should be IntelHex objectzCan't merge itself)r  ignorereplacez@overlap argument should be either 'error', 'ignore' or 'replace'r  zData overlapped at address 0x%Xr  Nz Starting addresses are differentr  )r%   r   rD   r+   r#   rL   r"   )r-   otheroverlapthis_buf	other_bufr[   s         r   mergezIntelHex.mergeM  sG   " %** 	?=>>>D==1222888 1 2 2 2 9J	 	' 	'AH}}g%%-9A=? ? ?((#A,HQKK?e...&"'"2!)g%%-:< < <	))&+&6DOOO /. *)r   r4   c                    |                                  sg S t                    dk    rd         d         dz   fgS d t          dd         dd                   D             }fdt          |          D             }fd|D             }|                    d                    fd|D             }|                    dd                    d	 t          ||          D             S )
a|  Return a list of ordered tuple objects, representing contiguous occupied data addresses.
        Each tuple has a length of two and follows the semantics of the range and xrange objects.
        The second entry of the tuple is always an integer greater than the first entry.
        @param min_gap      the minimum gap size between data in order to separate the segments
        r4   r   c                     g | ]
\  }}||z
  S r   r   r   r   rw   s      r   
<listcomp>z%IntelHex.segments.<locals>.<listcomp>  s     YYYFQQYYYr   Nr   c                 &    g | ]\  }}|k    |S r   r   )r   r[   r   min_gaps      r   r  z%IntelHex.segments.<locals>.<listcomp>  s"    QQQAQ[[![[[r   c                      g | ]
}|         S r   r   r   rw   r   s     r   r  z%IntelHex.segments.<locals>.<listcomp>  s    000A9Q<000r   c                 &    g | ]}|d z            S r4   r   r  s     r   r  z%IntelHex.segments.<locals>.<listcomp>  s!    555i!n555r   c                 "    g | ]\  }}||d z   fS r  r   r  s      r   r  z%IntelHex.segments.<locals>.<listcomp>  s$    @@@VaAaC@@@r   )r   rF   zip	enumerater   insert)r-   r  adjacent_differencesbreaksendings
beginningsr   s    `    @r   r   zIntelHex.segments}  s     NN$$	 	5I^^q  q\9Q<>234YYc)CRC.)TUTVTV-6X6XYYYQQQQ),@"A"AQQQ0000000y}%%%5555f555
!Yq\***@@s:w'?'?@@@@r   c                     t          j        |           }|t          j        | j                  z  }|t          | j                  z  }|t          | j                  z  }|t          j        | j                  z  }|S )z2Returns the approximate memory footprint for data.)r   	getsizeofr!   r   r"   r#   r$   )r-   ns     r   get_memory_sizezIntelHex.get_memory_size  sj    M$	S]4<(((	Z(((	Z	"""	S]4<(((r   r   r   NNN)Tr   r<   )r<   ry   )Nr<   F)r  r  )(r   r   r   __doc__r/   r\   r'   rj   ro   fromfiler)   rg   r   _DEPRECATEDr   r   r   r   r   r   r   r{   r|   r   r   r   r   r   staticmethodr   r   r   r   r   r   r   r  r  r   r*  r   r   r   r   r   C   s       ""A A A A>X  X  X  X t  8   ,, , ,  H) ) ),      :  $;T > > > >,   "t4 < < < <*M M M %)d$    >	 	 	      D D D6!D !D !DFD D D*) ) )	C 	C 	C %%677c c c cJ, , , ,     % % %" " "# # #
    ;9 ;9 ;9 ;9z.7 .7 .7 .7`A A A A&    r   r   c                   :    e Zd ZdZd	dZd Zd Zd Zd Zd
dZ	dS )IntelHex16bitzIAccess to data as 16-bit words. Intended to use with Microchip HEX files.Nc                 8   t          |t                    r1|j        | _        |j        | _        |j        | _        |j        | _        n?t          |t                    rt          d          t                              | |           | j        dk    r	d| _        dS dS )a/  Construct class from HEX file
        or from instance of ordinary IntelHex class. If IntelHex object
        is passed as source, the original IntelHex object should not be used
        again because this class will alter it. This class leaves padding
        alone unless it was precisely 0xFF. In that instance it is sign
        extended to 0xFFFF.

        @param  source  file name of HEX file or file object
                        or instance of ordinary IntelHex class.
                        Will also accept dictionary from todict method.
        zWIntelHex16bit does not support initialization from dictionary yet.
Patches are welcome.r   r   N)	r%   r   r!   r"   r#   r$   r(   IntelHexErrorr/   r,   s     r   r/   zIntelHex16bit.__init__  s     fh'' 	,!>DL$/DODI!>DLL%% 	, !7 8 8 8 dF+++<5  "DLLL ! r   c                     |dz  }|dz   }| j                             |d          }| j                             |d          }|dk    r|dk    r||dz  z  S |dk    r|dk    r| j        S t          |          )aV  Get 16-bit word from address.
        Raise error if only one byte from the pair is set.
        We assume a Little Endian interpretation of the hex file.

        @param  addr16  address of word (addr8 = 2 * addr16).
        @return         word if bytes exists in HEX file, or self.padding
                        if no data found.
        r8   r4   Nr   )r;   )r#   rK   r!   BadAccess16bit)r-   addr16addr1addr2byte1byte2s         r   r   zIntelHex16bit.__getitem__  s     
		eT**	eT**D==Ud]]EQJ''D==Ud]]<V,,,,r   c                 v    |dz  }t          |d          }|d         | j        |<   |d         | j        |dz   <   dS )zHSets the address at addr16 to word assuming Little Endian mode.
        r8   r7   r4   r   N)r   r#   )r-   r7  word	addr_byterw   s        r   r   zIntelHex16bit.__setitem__  sF     QJ	4 t	)!"1	)A+r   c                 ^    t          | j                  }|g k    rdS t          |          dz	  S )zxGet minimal address of HEX content in 16-bit mode.

        @return         minimal address used in this object
        r   r4   r   r   s     r   r{   zIntelHex16bit.minaddr  1    
 ty!!881r77A:r   c                 ^    t          | j                  }|g k    rdS t          |          dz	  S )zyGet maximal address of HEX content in 16-bit mode.

        @return         maximal address used in this object 
        r   r4   r   r   s     r   r|   zIntelHex16bit.maxaddr  r@  r   c                    t          d          }| j        i k    rd||fv r|S ||dk    rt          d          |                     |||          \  }}t	          ||dz             D ]}|                    | |                    |S )a  Convert this object to binary form as array (of 2-bytes word data).
        If start and end unspecified, they will be inferred from the data.
        @param  start   start address of output data.
        @param  end     end address of output data (inclusive).
        @param  size    size of the block (number of words),
                        used with start or end parameter.
        @return         array of unsigned short (uint16_t) data.
        HNr   r   r4   )r   r#   r+   r   r   r   )r-   r}   r~   r   rU   rX   s         r   r   zIntelHex16bit.tobinarray  s     Cjj9??ts|33J		?@@@((T::
sE3q5)) 	# 	#DJJtDz""""
r   r   r,  )
r   r   r   r-  r/   r   r   r{   r|   r   r   r   r   r2  r2    s~        SS# # # #8- - -,& & &	 	 		 	 	     r   r2  c                 0   	 t          |           }nK# t          $ r> t          j                    d         }dt	          |          z  }t          |           Y dS w xY w|dk    rC|dk    r=|dk    r#|dk    r|                                }||z   dz
  }n|dz   |k    r	|dz   |z
  }nd}	 |||_        |                    |||           nN# t          $ rA t          j                    d         }d|dt	          |          }t          |           Y dS w xY wdS )a  Hex-to-Bin convertor engine.
    @return     0   if all OK

    @param  fin     input hex file (filename or file-like object)
    @param  fout    output bin file (filename or file-like object)
    @param  start   start of address range (optional)
    @param  end     end of address range (inclusive; optional)
    @param  size    size of resulting file (in bytes) (optional)
    @param  pad     padding byte (optional)
    r4   zERROR: bad HEX file: %sNr    ERROR: Could not write to file: : )
r   HexReaderErrorr   exc_infostrr   r{   r!   r   IOError)	finfoutr}   r~   r   r   hetxts	            r   hex2binrP    sJ   SMM   LNN1'#a&&0c


qq	 t||		$;;}}		$,"CCA$a$	?AI	D%%%%%   LNN1:>$$AGc


qq	 1s#    AAA' C ADDc                    t                      }	 |                    | |           nJ# t          $ r= t          j                    d         }dt          |          f}t          |           Y dS w xY w	 |                    |d           nN# t          $ rA t          j                    d         }d|dt          |          }t          |           Y dS w xY wdS )a  Simple bin-to-hex convertor.
    @return     0   if all OK

    @param  fin     input bin file (filename or file-like object)
    @param  fout    output hex file (filename or file-like object)
    @param  offset  starting address offset for loading bin
    r4   zERROR: unable to load bin file:rl   )rn   rE  rF  r   )r   rj   rJ  r   rH  rI  r   r   )rK  rL  rf   rM  rN  rO  s         r   bin2hexrR  9  s     	

A			#v   LNN1/Q7c


qq		e$$$$   LNN1:>$$AGc


qq	 1s#   ' AA.-A.2B
 
ACCr   rw   r9   c           
         d } ||           } ||          }ddl }	t          |	                    |||||d                    }
|t          j        }d                    |
          dz   }|                    |           dS )a  Diff 2 IntelHex objects and produce unified diff output for their
    hex dumps.

    @param ih1        first IntelHex object to compare
    @param ih2        second IntelHex object to compare
    @param tofile     file-like object to write output
    @param name1      name of the first hex file to show in the diff header
    @param name2      name of the first hex file to show in the diff header
    @param n_context  number of context lines in the unidiff output
    c                     t                      }|                     |           |                                }|                                }|S r   )r
   r  getvalue
splitlines)r   sior  liness       r   prepare_linesz!diff_dumps.<locals>.prepare_linesa  s;    jj
||~~!!r   r   Nr   )r.  r   r)  linetermr   )difflibr   unified_diffr   r  r   r   )ih1ih2r   name1name2	n_contextrY  r   rw   r[  resultoutputs               r   
diff_dumpsrd  V  s       	cAcANNN'&&q!eEYac&ddeeF~YYvt#F
LLr   c                       e Zd ZdZd Z ee          Zd Z ee          Zd Z ee          Zd Z ee          Zd Z	 ee	          Z	d Z
 ee
          Z
d Z ee          Zd	S )
Recordz+Helper methods to build valid ihex records.c                     t          |           dk    sJ t          |            dz  }t          d| |gz             }dt          t	          t          |                                                              z   S )a>  Takes a list of bytes, computes the checksum, and outputs the entire
        record as a string. bytes should be the hex record without the colon
        or final checksum.

        @param  bytes   list of byte values so far to pack into record.
        @return         String representation of one HEX record
        r:   r   r3   r2   )rF   rI   r   r   r   r   r   )rv   rT   rU   s      r   _from_byteszRecord._from_bytest  sm     5zzQ%jj[E!C!%%U7=#5#56677==????r   c                     d| cxk    rdk     sn J dt          |          cxk     rdk     sn J t          |          | dz	  dz  | dz  dg|z   }t                              |          S )a[  Return Data record. This constructs the full record, including
        the length information, the record type (0x00), the
        checksum, and the offset.

        @param  offset  load offset of first byte.
        @param  bytes   list of byte values to pack into record.

        @return         String representation of one HEX record
        r   r=   r7   r   r   )rF   rf  rh  )rf   rv   rw   s      r   datazRecord.data  s     F""""U""""""3u::##########ZZ&!)U*F5L$?%G!!!$$$r   c                      dS )zvReturn End of File record as a string.
        @return         String representation of Intel Hex EOF record 
        r   r   r   r   r   eofz
Record.eof  s	     }r   c                 X    dddd| dz	  dz  | dz  g}t                               |          S )zReturn Extended Segment Address Record.
        @param  usba     Upper Segment Base Address.

        @return         String representation of Intel Hex USBA record.
        r8   r   r   r   rf  rh  )usbarw   s     r   extended_segment_addresszRecord.extended_segment_address  6     1dT1WeOT%Z8!!!$$$r   c           	      n    dddd| dz	  dz  | dz  |dz	  dz  |dz  g}t                               |          S )zReturn Start Segment Address Record.
        @param  cs      16-bit value for CS register.
        @param  ip      16-bit value for IP register.

        @return         String representation of Intel Hex SSA record.
        r:   r   r9   r   r   rn  )r   r   rw   s      r   start_segment_addresszRecord.start_segment_address  sI     1dRUEM2e8!eU]BuH&!!!$$$r   c                 X    dddd| dz	  dz  | dz  g}t                               |          S )zReturn Extended Linear Address Record.
        @param  ulba    Upper Linear Base Address.

        @return         String representation of Intel Hex ELA record.
        r8   r   r:   r   r   rn  )ulbarw   s     r   extended_linear_addresszRecord.extended_linear_address  rq  r   c           	      t    dddd| dz	  dz  | dz	  dz  | dz	  dz  | dz  g}t                               |          S )zReturn Start Linear Address Record.
        @param  eip     32-bit linear address for the EIP register.

        @return         String representation of Intel Hex SLA record.
        r:   r   r6   r   r   r<   r   rn  )r   rw   s     r   start_linear_addresszRecord.start_linear_address  sM     1dS"WeOc2gu_1fe^SY(!!!$$$r   N)r   r   r   r-  rh  r0  rj  rl  rp  rs  rv  rx  r   r   r   rf  rf  q  s       55@ @ @ ,{++K% % % <D  
 ,s

C% % %  ,|,DEE	% 	% 	% )L)>??% % % +l+BCC% % % (<(<==r   rf  c                       e Zd ZdZdS )_BadFileNotationz9Special error class to use with _get_file_and_addr_range.N)r   r   r   r-  r   r   r   rz  rz    s        CCDr   rz  c           
      4   |t           j        dk    }d}|r| dd         dk    rx| d                                         d                    d t	          t          d	          t          d
          dz             D                       v r| dd         }| dd         } |                     d          }t          |          }|dk    r|d         }d}d}n>|dk    rt          |d         }d } ||d         pd          } ||d         pd          }||z   ||fS )zSpecial method for hexmerge.py script to split file notation
    into 3 parts: (filename, start, end)

    @raise _BadFileNotation  when string cannot be safely split.
    Nntr   r4   r8   r2   r   c                 ,    g | ]}t          |          S r   )r   r   s     r   r  z,_get_file_and_addr_range.<locals>.<listcomp>  s    5d5d5dc!ff5d5d5dr   AZr9   c                 V    | &	 t          | d          S # t          $ r t          w xY w| S )Nr<   )r   r+   rz  )asciis    r   ascii_hex_to_intz2_get_file_and_addr_range.<locals>.ascii_hex_to_int  sA     +ub>>)! + + +**+Ls    &)	osnamer   r   r   ordsplitrF   rz  )	rT   _support_drive_letterdrivepartsr)  fnamefstartfendr  s	            r   _get_file_and_addr_ranger    sD    $!#DE QqS6S==QqTZZ\\RWW5d5dgcRUhhX[\_X`X`abXbFcFc5d5d5d-e-eeebqbEE!""AGGCLLEE

AAvva	
aa	 	 	 "!%("2d33a 0D11;$$r   c                   $    e Zd ZdZdZddZd ZdS )r4  z(Base Exception class for IntelHex modulezIntelHex base errorNc                 `    || _         t          |          D ]\  }}t          | ||           dS )z9Initialize the Exception with the given message.
        N)r   r   setattr)r-   r   kwkeyvalues        r   r/   zIntelHexError.__init__
  sE     &r** 	& 	&JCD#u%%%%	& 	&r   c                     | j         r| j         S 	 | j        | j        z  S # t          t          t
          f$ r> t          j                    d         }dt          |          dt          |          cY S w xY w)z%Return the message in this Exception.r4   zUnprintable exception rF  )
r   _fmt__dict__	NameErrorr+   r   r   rH  r   rI  )r-   rN  s     r   __str__zIntelHexError.__str__  s    8 	8O	$9t},,:x0 	$ 	$ 	$q!AA7777CFFF$ $ $ $	$s    AA43A4r   )r   r   r   r-  r  r/   r  r   r   r   r4  r4    sB        22 D& & & &	$ 	$ 	$ 	$ 	$r   r4  c                       e Zd ZdZdZdS )rN   zUsed for internal needs only.z.EOF record reached -- signal to stop read fileN)r   r   r   r-  r  r   r   r   rN   rN     s        '';DDDr   rN   c                       e Zd ZdZdS )rG  zHex reader base errorNr   r   r   r  r   r   r   rG  rG     s        "DDDr   rG  c                       e Zd ZdZdS )rL   zCHex file has data overlap at address 0x%(address)X on line %(line)dNr  r   r   r   rL   rL   #  s        PDDDr   rL   c                       e Zd ZdZdS )rE   z1Hex file contains invalid record at line %(line)dNr  r   r   r   rE   rE   )  s        >DDDr   rE   c                       e Zd ZdZdS )rG   z*Record at line %(line)d has invalid lengthNr  r   r   r   rG   rG   -          7DDDr   rG   c                       e Zd ZdZdS )rH   z/Record at line %(line)d has invalid record typeNr  r   r   r   rH   rH   0  s        <DDDr   rH   c                       e Zd ZdZdS )rJ   z,Record at line %(line)d has invalid checksumNr  r   r   r   rJ   rJ   3  s        9DDDr   rJ   c                       e Zd ZdZdS )rM   z#File has invalid End-of-File recordNr  r   r   r   rM   rM   6  s        0DDDr   rM   c                       e Zd ZdZdS )ExtendedAddressRecordErrorz*Base class for extended address exceptionsNr  r   r   r   r  r  :  r  r   r  c                       e Zd ZdZdS )rO   z8Invalid Extended Segment Address Record at line %(line)dNr  r   r   r   rO   rO   =          EDDDr   rO   c                       e Zd ZdZdS )rP   z7Invalid Extended Linear Address Record at line %(line)dNr  r   r   r   rP   rP   @  s        DDDDr   rP   c                       e Zd ZdZdS )StartAddressRecordErrorz'Base class for start address exceptionsNr  r   r   r   r  r  D  s        4DDDr   r  c                       e Zd ZdZdS )rQ   z5Invalid Start Segment Address Record at line %(line)dNr  r   r   r   rQ   rQ   G  s        BDDDr   rQ   c                       e Zd ZdZdS )rS   z4Invalid Start Linear Address Record at line %(line)dNr  r   r   r   rS   rS   J  s        ADDDr   rS   c                       e Zd ZdZdS )rR   z3Start Address Record appears twice at line %(line)dNr  r   r   r   rR   rR   M  s        @DDDr   rR   c                       e Zd ZdZdS )r   z+Invalid start address value: %(start_addr)sNr  r   r   r   r   r   P  s        8DDDr   r   c                       e Zd ZdZdS )r   zPBad access at 0x%(address)X: not enough data to read %(length)d contiguous bytesNr  r   r   r   r   r   T  s        BDDDr   r   c                       e Zd ZdZdS )r6  zABad access at 0x%(address)X: not enough data to read 16 bit valueNr  r   r   r   r6  r6  X  s        NDDDr   r6  c                       e Zd ZdZdS )rz   z8Requested operation cannot be executed with empty objectNr  r   r   r   rz   rz   [  r  r   rz   )NNNNr+  )Nr   rw   r9   r   )8r-  __docformat__r   binasciir   r   bisectr   r  r   intelhex.compatr   r	   r
   r   r   r   r   r   r   r   r   intelhex.getsizeofr   objectr   r/  r   r2  rP  rR  rd  rf  	Exceptionrz  r  r4  rN   rG  rL   rE   rG   rH   rJ   rM   r  rO   rP   r  rQ   rS   rR   r   r   r6  rz   r   r   r   <module>r     s  D - ,       ' ' ' ' ' ' ' '       				 



                          * ) ) ) ) )	 	 	 	 	v 	 	 	   T T T T Tv T T Tri i i i iH i i i^* * * *\   :   6R> R> R> R> R>V R> R> R>j	 	 	 	 	y 	 	 	 %  %  %  %v$ $ $ $ $I $ $ $.< < < < < < < <# # # # #] # # #Q Q Q Q Q. Q Q Q? ? ? ? ?^ ? ? ?8 8 8 8 8 8 8 8= = = = =n = = =: : : : :. : : :1 1 1 1 1^ 1 1 18 8 8 8 8 8 8 8F F F F F(B F F FE E E E E'A E E E5 5 5 5 5n 5 5 5C C C C C%< C C CB B B B B$; B B BA A A A A'> A A A9 9 9 9 9$; 9 9 9C C C C C C C CO O O O O' O O OF F F F F F F F F Fr   