import os
import shutil

def extract_libc(png_path, output_path, start_offset, total_size):
    """
    Extract libc.so.6 data from a PNG file.
    """
    with open(png_path, 'rb') as png_file:
        # Read the exact number of bytes for libc.so.6
        png_file.seek(start_offset)
        extracted_data = png_file.read(total_size)
   
    with open(output_path, 'wb') as output_file:
        output_file.write(extracted_data)
   
    print(f"Extracted libc.so.6 data to {output_path}")
    print(f"Extracted size: {len(extracted_data)} bytes")

def append_valid_section_headers(libc_path, reference_libc_path):
    """
    Append valid section headers from a reference libc.so.6 to the extracted file.
    """
    with open(reference_libc_path, 'rb') as ref_file:
        ref_file.seek(section_headers_offset)
        section_headers_data = ref_file.read(total_section_headers_size)
   
    with open(libc_path, 'ab') as libc_file:
        libc_file.write(section_headers_data)
   
    print(f"Appended section headers from reference libc.so.6.")

# Paths to files
# png_file_path = 'mypng.png'
reference_libc_path = 'mylibc.so.6'
output_libc_path = 'target_libc.so.6'

# Known offsets and sizes
elf_start_offset = 9  # ELF header start offset in 1-40.png
section_headers_offset = 0x1D7278  # Section headers offset in reference libc.so.6
total_section_headers_size = 60 * 64  # 60 section headers, each 64 bytes
total_size = section_headers_offset + total_section_headers_size - elf_start_offset  # Full size of libc.so.6

# Step 1: Extract the main ELF data from 1-40.png
# extract_libc(
#     png_path=png_file_path,
#     output_path=output_libc_path,
#     start_offset=elf_start_offset,
#     total_size=total_size
# )

# Step 2: Append section headers from the reference libc.so.6
append_valid_section_headers(
    libc_path=output_libc_path,
    reference_libc_path=reference_libc_path
)

print(f"Fixed libc.so.6 saved to: {output_libc_path}")