modify.c

来自「一个类似windows」· C语言 代码 · 共 1,061 行 · 第 1/3 页

C
1,061
字号
                {
                    /* If we have a descriptor */
                    if (BoundImportDescriptor)
                    {
                        /* Zero the timestamp */
                        BoundImportDescriptor->TimeDateStamp = 0;
                    }

                    /* Quit the loop */
                    break;
                }

                /* Move on */
                TempThunk++;
                TempBoundThunk++;
            }

            /* Load the Second Thunk Array */
            TempThunk = ImageRvaToVa(File->FileHeader, 
                                     File->MappedAddress, 
                                     (ULONG)Imports->FirstThunk, 
                                     &File->LastRvaSection);
            if (TempThunk)
            {
                /* Check if the forwarder chain changed */
                if (TopForwarderChain != -1)
                {
                    /* It did. Update the chain and let caller know */
                    *ForwarderChain = -1;
                    *UpdateImage = TRUE;
                }

                /* Check if we're not pointing at the new top chain */
                if (Imports->ForwarderChain != TopForwarderChain)
                {
                    /* Update it, and let the caller know */
                    Imports->ForwarderChain = TopForwarderChain;
                    *UpdateImage = TRUE;
                }

                /* Check if thunks have changed */
                if (memcmp(TempThunk, BoundThunks, SizeOfThunks))
                {
                    /* Copy the Pointers and let caller know */
                    DPRINT("Copying Bound Thunks\n");
                    RtlCopyMemory(TempThunk, BoundThunks, SizeOfThunks);
                    *UpdateImage = TRUE;
                }

                /* Check if we have no bound entries */
                if (!TopBoundDescriptor)
                {
                    /* Check if the timestamp is different */
                    if (Imports->TimeDateStamp != FileHeader->TimeDateStamp)
                    {
                        /* Update it, and let the caller knmow */
                        Imports->TimeDateStamp = FileHeader->TimeDateStamp;
                        *UpdateImage = TRUE;
                    }
                }
                else if ((Imports->TimeDateStamp != 0xFFFFFFFF))
                {
                    /* Invalidate the timedate stamp */
                    Imports->TimeDateStamp = 0xFFFFFFFF;
                }
            }

            /* Free the Allocated Memory */
            HeapFree(IMAGEHLP_hHeap, 0, BoundThunks);

            DPRINT("Moving to next File\n");
            Imports++;
        }
    }

    /* Create the Bound Import Table */
    DPRINT("Creating Bound Import Section\n");
    BoundImportTable = BindpCreateNewImportSection(&TopBoundDescriptor,
                                                   &BoundImportTableSize);

    /* Check if the import table changed */
    if (OldBoundImportTableSize != BoundImportTableSize)
    {
        /* Let the caller know */
        *UpdateImage = TRUE;
    }

    /* 
     * At this point, check if anything that we've done until now has resulted
     * in the image being touched. If not, then we'll simply return to caller.
     */
    if (!(*UpdateImage)) return;

    /* Check if we have a new table */
    if (BoundImportTable)
    {
        /* Zero it out */
        OptionalHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT].VirtualAddress = 0;
        OptionalHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT].Size = 0;

        /* Check if we have enough space */
        DPRINT("Calculating Space\n");
        FirstFreeByte = GetImageUnusedHeaderBytes(File, &VirtBytesFree);
        HeaderBytesFree = File->Sections->VirtualAddress -
                          OptionalHeader->SizeOfHeaders + VirtBytesFree;
        PhysBytesFree = File->Sections->PointerToRawData -
                        OptionalHeader->SizeOfHeaders + VirtBytesFree;

        /* Check if we overflowed */
        if (BoundImportTableSize > VirtBytesFree)
        {
            /* Check if we have no space a tall */
            if (BoundImportTableSize > HeaderBytesFree)
            {
                DPRINT1("Not enough Space\n");
                return; /* Fail...not enough space */
            }

            /* Check if we have space on disk to enlarge it */
            if (BoundImportTableSize <= PhysBytesFree)
            {
                /* We have enough NULLs to add it, simply enlarge header data */
                DPRINT("Header Recalculation\n");
                OptionalHeader->SizeOfHeaders = OptionalHeader->SizeOfHeaders -
                                                VirtBytesFree +
                                                BoundImportTableSize +
                                                ((OptionalHeader->FileAlignment - 1) &
                                                ~(OptionalHeader->FileAlignment - 1));
            }
            else 
            {
                /* Resize the Headers */
                DPRINT1("UNIMPLEMENTED: Header Resizing\n");

                /* Recalculate Headers */
                FileHeader = &File->FileHeader->FileHeader;
                OptionalHeader = &File->FileHeader->OptionalHeader;
            }
        }
    
        /* Set Bound Import Table Data */
        OptionalHeader->DataDirectory
            [IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT].VirtualAddress = FirstFreeByte;
        OptionalHeader->DataDirectory
            [IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT].Size = BoundImportTableSize;
    
        /* Copy the Bound Import Table */
        DPRINT("Copying Bound Import Table\n");
        RtlCopyMemory(File->MappedAddress + FirstFreeByte,
                      BoundImportTable,
                      BoundImportTableSize);

        /* Free the data */
        HeapFree(IMAGEHLP_hHeap, 0, BoundImportTable);
    }
    
}

/*
 * @implemented
 */
BOOL 
IMAGEAPI 
BindImageEx(IN DWORD Flags,
            IN LPSTR ImageName,
            IN LPSTR DllPath,
            IN LPSTR SymbolPath,
            IN PIMAGEHLP_STATUS_ROUTINE StatusRoutine)
{
    LOADED_IMAGE FileData;
    PLOADED_IMAGE File;
    PIMAGE_FILE_HEADER FileHeader;
    PIMAGE_OPTIONAL_HEADER32 OptionalHeader;
    ULONG CheckSum, HeaderCheckSum, OldChecksum;
    SYSTEMTIME SystemTime;
    FILETIME LastWriteTime;
    BOOLEAN UpdateImage;
    DWORD DataSize;
    DPRINT("BindImageEx Called for: %s \n", ImageName);

    /* Set and Clear Buffer */
    File = &FileData;
    RtlZeroMemory(File, sizeof(*File));

    /* Request Image Data */
    if (MapAndLoad(ImageName, DllPath, File, TRUE, FALSE))
    {
        /* Write the image's name */
        DPRINT("Image Mapped and Loaded\n");
        File->ModuleName = ImageName;

        /* Check if the image is valid and if it should be bound */
        if ((File->FileHeader) &&
            ((Flags & BIND_ALL_IMAGES) || (!File->fSystemImage)))
        {
            /* Get the optional header */
            FileHeader = &File->FileHeader->FileHeader;
            OptionalHeader = &File->FileHeader->OptionalHeader;

            /* Check if this image should be bound */
            if (OptionalHeader->DllCharacteristics &
                IMAGE_DLLCHARACTERISTICS_NO_BIND)
            {
                /* Don't bind it */
                goto Skip;
            }

            /* Check if the image has security data */
            if ((ImageDirectoryEntryToData(File->MappedAddress,
                                           FALSE,
                                           IMAGE_DIRECTORY_ENTRY_SECURITY,
                                           &DataSize)) || DataSize)
            {
                /* It does, skip it */
                goto Skip;
            }

            /* Read Import Table */
            BindpWalkAndProcessImports(File, DllPath, &UpdateImage);

            /* Check if we need to update the image */
            if ((UpdateImage) && (File->hFile != INVALID_HANDLE_VALUE))
            {
                /* FIXME: Update symbols */
        
                /* Update Checksum */
                DPRINT("Binding Completed, getting Checksum\n");
                OldChecksum = File->FileHeader->OptionalHeader.CheckSum;
                CheckSumMappedFile(File->MappedAddress,
                                   GetFileSize(File->hFile, NULL),
                                   &HeaderCheckSum,
                                   &CheckSum);
                File->FileHeader->OptionalHeader.CheckSum = CheckSum;

                /* Save Changes */
                DPRINT("Saving Changes to file\n");
                FlushViewOfFile(File->MappedAddress, File->SizeOfImage);

                /* Save new Modified Time */
                DPRINT("Setting time\n");
                GetSystemTime(&SystemTime);
                SystemTimeToFileTime(&SystemTime, &LastWriteTime);
                SetFileTime(File->hFile, NULL, NULL, &LastWriteTime);
            }
        }
    }

Skip:

    /* Unmap the image */
    UnmapViewOfFile(File->MappedAddress);

    /* Close the handle if it's valid */
    if (File->hFile != INVALID_HANDLE_VALUE) CloseHandle(File->hFile);

    /* Unload all the images if we're not supposed to cache them */
    if (!(Flags & BIND_CACHE_IMPORT_DLLS)) UnloadAllImages();
   
    /* Return success */
    DPRINT("Done\n");
    return TRUE;
}

/*
 * @implemented
 */
BOOL
IMAGEAPI
BindImage(LPSTR ImageName,
          LPSTR DllPath,
          LPSTR SymbolPath)
{
    /* Call the newer API */
    return BindImageEx(0,
                       ImageName,
                       DllPath,
                       SymbolPath,
                       NULL);
}

/*
 * @unimplemented
 */
BOOL
IMAGEAPI
ReBaseImage(LPSTR CurrentImageName,
            LPSTR SymbolPath,
            BOOL fReBase,
            BOOL fRebaseSysfileOk,
            BOOL fGoingDown,
            ULONG CheckImageSize,
            ULONG *OldImageSize,
            ULONG *OldImageBase,
            ULONG *NewImageSize,
            ULONG *NewImageBase,
            ULONG TimeStamp)
{
    UNIMPLEMENTED;
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
}

/*
 * @unimplemented
 */
VOID
IMAGEAPI
RemoveRelocations(PCHAR ImageName)
{
    UNIMPLEMENTED;
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
}

/*
 * @unimplemented
 */
BOOL
IMAGEAPI
SplitSymbols(LPSTR ImageName,
             LPSTR SymbolsPath,
             LPSTR SymbolFilePath,
             DWORD Flags)
{
    UNIMPLEMENTED;
    SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
    return FALSE;
}

/*
 * @implemented
 */
BOOL
IMAGEAPI
TouchFileTimes(HANDLE FileHandle,
               LPSYSTEMTIME lpSystemTime)
{
    FILETIME FileTime;
    SYSTEMTIME SystemTime;
  
    if(lpSystemTime == NULL)
    {
        GetSystemTime(&SystemTime);
        lpSystemTime = &SystemTime;
    }

    return (SystemTimeToFileTime(lpSystemTime,
                                 &FileTime) &&
            SetFileTime(FileHandle,
                        NULL,
                        NULL,
                        &FileTime));
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?