1

Всем привет. Возникла проблема при работе с PE файлом.Что я с ним конкретно делал:

  1. Я загрузил в последнюю секцию ассемблерный код (размером 40 байт)
  2. Поправил точку входа в программу на последнюю секцию, изменил VirtualSize последней секции на 50 байт (чтобы наверняка хватило)
  3. Увеличил SizeOfRawData (приравнял его к VirtualSize и сделал выравнивание по FileAlignment)
  4. Далее я также изменил SizeOfImage, менял я его по разному, но во всех случаях при запуске файла пишется ошибка "is not a valid Win32 application". Сначала я изменил SizeofImage как сумма VirtualAddress и VirtualSize последней секции (без выравнивания) и это не помогло. Потом сделал с выраниванием, но ошибка не исчезла.

Может быть есть кто-нибудь, кто сможет мне объяснить, что же я делаю не так? В интернете очень сильно разнится информация об этом, а в самом стандарте про детали не сказано.

Ниже приведен лог dumpbin и код на C, который изменяет параметры PE файла.

    *Адрес точки входа в программу*/
    pHeader->OptionalHeader.AddressOfEntryPoint = pLastSectHeader->VirtualAddress + pLastSectHeader->Misc.VirtualSize;

    /*Данные загрузили - меняем значения о них в заголовке секции*/
    pLastSectHeader->Misc.VirtualSize += 50;
    pLastSectHeader->SizeOfRawData = pLastSectHeader->Misc.VirtualSize;

    if (pLastSectHeader->SizeOfRawData % FileAlignment) {
        unsigned long temp = pLastSectHeader->SizeOfRawData / FileAlignment;
        temp = pLastSectHeader->SizeOfRawData - (temp * FileAlignment);
        pLastSectHeader->SizeOfRawData += FileAlignment - temp;
    }

    /*Размер файла в памяти, включая все заголовки. Должен быть кратен SectionAlignment*/

   NewSize = pLastSectHeader->VirtualAddress + pLastSectHeader->Misc.VirtualSize;

   pHeader->OptionalHeader.SizeOfImage = NewSize;
   if (pHeader->OptionalHeader.SizeOfImage % SectionAlignment) {
        unsigned long temp = pHeader->OptionalHeader.SizeOfImage / SectionAlignment;
        temp = pHeader->OptionalHeader.SizeOfImage - (temp * SectionAlignment);
        pHeader->OptionalHeader.SizeOfImage += SectionAlignment - temp;
    }

Лог из DumpBin'а:

PE signature found

File Type: EXECUTABLE IMAGE

FILE HEADER VALUES
             14C machine (x86)
               5 number of sections
        5487EAB7 time date stamp Wed Dec 10 12:39:51 2014
               0 file pointer to symbol table
               0 number of symbols
              E0 size of optional header
             102 characteristics
                   Executable
                   32 bit word machine

OPTIONAL HEADER VALUES
             10B magic # (PE32)
           12.00 linker version
            1000 size of code
            1200 size of initialized data
               0 size of uninitialized data
            51DC entry point (004051DC)
            1000 base of code
            2000 base of data
          400000 image base (00400000 to 0040520D)
            1000 section alignment
             200 file alignment
            6.00 operating system version
            0.00 image version
            6.00 subsystem version
               0 Win32 version
            520E size of image
             400 size of headers
            5D44 checksum
               3 subsystem (Windows CUI)
            8140 DLL characteristics
                   Dynamic base
                   NX compatible
                   Terminal Server Aware
          100000 size of stack reserve
            1000 size of stack commit
          100000 size of heap reserve
            1000 size of heap commit
               0 loader flags
              10 number of directories
               0 [       0] RVA [size] of Export Directory
            25A4 [      3C] RVA [size] of Import Directory
            4000 [     1E0] RVA [size] of Resource Directory
               0 [       0] RVA [size] of Exception Directory
               0 [       0] RVA [size] of Certificates Directory
            5000 [     1DC] RVA [size] of Base Relocation Directory
            20E0 [      38] RVA [size] of Debug Directory
               0 [       0] RVA [size] of Architecture Directory
               0 [       0] RVA [size] of Global Pointer Directory
               0 [       0] RVA [size] of Thread Storage Directory
            2440 [      40] RVA [size] of Load Configuration Directory
               0 [       0] RVA [size] of Bound Import Directory
            2000 [      B8] RVA [size] of Import Address Table Directory
               0 [       0] RVA [size] of Delay Import Directory
               0 [       0] RVA [size] of COM Descriptor Directory
               0 [       0] RVA [size] of Reserved Directory


SECTION HEADER #1
   .text name
     FDA virtual size
    1000 virtual address (00401000 to 00401FD9)
    1000 size of raw data
     400 file pointer to raw data (00000400 to 000013FF)
       0 file pointer to relocation table
       0 file pointer to line numbers
       0 number of relocations
       0 number of line numbers
E0000020 flags
         Code
         Execute Read Write

SECTION HEADER #2
  .rdata name
     96C virtual size
    2000 virtual address (00402000 to 0040296B)
     A00 size of raw data
    1400 file pointer to raw data (00001400 to 00001DFF)
       0 file pointer to relocation table
       0 file pointer to line numbers
       0 number of relocations
       0 number of line numbers
C0000040 flags
         Initialized Data
         Read Write

  Debug Directories

        Time Type       Size      RVA  Pointer
    -------- ------ -------- -------- --------
    5487EAB7 cv           86 00002488     1888    Format: RSDS, {3581D185-A999-4981-BE01-B83BF7CE8537}, 33, C:\Users\Àðòóð\Documents\Visual Studio 2013\Projects\Ïåðåâîä ÑÑ\Release\Ïåðåâîä ÑÑ.pdb
    5487EAB7 feat         14 00002510     1910    Counts: Pre-VC++ 11.00=0, C/C++=22, /GS=22, /sdl=0, reserved=0

SECTION HEADER #3
   .data name
     380 virtual size
    3000 virtual address (00403000 to 0040337F)
     200 size of raw data
    1E00 file pointer to raw data (00001E00 to 00001FFF)
       0 file pointer to relocation table
       0 file pointer to line numbers
       0 number of relocations
       0 number of line numbers
C0000040 flags
         Initialized Data
         Read Write

SECTION HEADER #4
   .rsrc name
     1E0 virtual size
    4000 virtual address (00404000 to 004041DF)
     200 size of raw data
    2000 file pointer to raw data (00002000 to 000021FF)
       0 file pointer to relocation table
       0 file pointer to line numbers
       0 number of relocations
       0 number of line numbers
C0000040 flags
         Initialized Data
         Read Write

SECTION HEADER #5
  .reloc name
     20E virtual size
    5000 virtual address (00405000 to 0040520D)
     400 size of raw data
    2200 file pointer to raw data (00002200 to 000025FF)
       0 file pointer to relocation table
       0 file pointer to line numbers
       0 number of relocations
       0 number of line numbers
A0000020 flags
         Code
         Execute Write
3
  • да, именно в нее
    – mazahaka
    3 июн 2015 в 9:56
  • Туториалов прочитано уже огромное количество. Вы имеете в виду, что в эту секцию лучше не писать ничего? Если ее не расширять, все работает отлично.
    – mazahaka
    3 июн 2015 в 9:59
  • @Abyx, а какая секция "для того"?
    – Nakilon
    3 июн 2015 в 16:22

0

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Посмотрите другие вопросы с метками или задайте свой вопрос.