66from qiling import Qiling
77from qiling .const import QL_ARCH , QL_OS , QL_VERBOSE
88from qiling .extensions .coverage import utils as cov_utils
9+ from qiling .loader .loader import Image
910
1011BASE_ADDRESS = 0x10000000
1112CHECKSUM_FUNC_ADDR = BASE_ADDRESS + 0x8
@@ -29,6 +30,7 @@ def checksum_function(input_data_buffer: bytes):
2930 for i in range (input_data_len ):
3031 expected_checksum_python += input_data_buffer [i ]
3132 expected_checksum_python &= 0xFF # Ensure it's a single byte
33+ return expected_checksum_python
3234
3335def unmapped_handler (ql , type , addr , size , value ):
3436
@@ -37,18 +39,24 @@ def unmapped_handler(ql, type, addr, size, value):
3739def emulate_checksum_function (input_data_buffer : bytes ):
3840 print (f"\n --- Testing with input: { input_data_buffer .hex ()} ---" )
3941
40- ql = Qiling (archtype = QL_ARCH .ARM , ostype = QL_OS .BLOB , profile = "blob_raw.ql" , verbose = QL_VERBOSE .DEBUG , thumb = True )
42+ with open ("rootfs/blob/example_raw.bin" , "rb" ) as f :
43+ raw_code = f .read ()
44+
45+ ql = Qiling (code = raw_code , archtype = QL_ARCH .ARM , ostype = QL_OS .BLOB , profile = "blob_raw.ql" , verbose = QL_VERBOSE .DEBUG , thumb = True )
46+
47+ # monkeypatch - Correcting the loader image name, used for coverage collection
48+ # Remove all images with name 'blob_code' that were created by the blob loader
49+ ql .loader .images = [img for img in ql .loader .images if img .path != 'blob_code' ]
50+ # Add image back with correct info
51+ ql .loader .images .append (Image (ql .loader .load_address , ql .loader .load_address + ql .os .code_ram_size , 'example_raw.bin' ))
52+
4153
4254 input_data_len = len (input_data_buffer )
4355
44- # Map memory for the binary, data and stack
45- ql .mem .map (BASE_ADDRESS , 0x10000 )
56+ # Map memory for the data and stack
4657 ql .mem .map (STACK_ADDR , 0x2000 )
4758 ql .mem .map (DATA_ADDR , ql .mem .align_up (input_data_len + 0x100 )) # Map enough space for data
4859
49- # Write the binary into memory
50- ql .mem .write (BASE_ADDRESS , open ("rootfs/blob/example_raw.bin" , "rb" ).read ())
51-
5260 # Write input data
5361 ql .mem .write (DATA_ADDR , input_data_buffer )
5462
@@ -70,12 +78,14 @@ def emulate_checksum_function(input_data_buffer: bytes):
7078 # Start emulation
7179 print (f"Starting emulation at PC: { hex (ql .arch .regs .pc )} " )
7280 try :
73- ql .run (begin = CHECKSUM_FUNC_ADDR , end = END_ADDRESS )
81+ with cov_utils .collect_coverage (ql , 'drcov' , 'output.cov' ):
82+ ql .run (begin = CHECKSUM_FUNC_ADDR , end = END_ADDRESS )
7483 except Exception as e :
7584 print (f"Emulation error: { e } " )
7685
7786 print (f"Emulated checksum: { hex (ql .arch .regs .r0 )} " )
7887
7988if __name__ == "__main__" :
8089 data = b"\x01 \x02 \x03 \x04 \x05 " # Example input data
81- emulate_checksum_function (data )
90+ emulate_checksum_function (data )
91+ print (hex (checksum_function (data )))
0 commit comments