【发布时间】:2012-11-25 06:46:56
【问题描述】:
我对他们为什么在这里使用 - 1 感到困惑。有人可以解释一下这条线在非常非常非常低级的细节中做了什么...不是它减去 1 的结构....我需要了解更多...关于低级...谢谢...
PIMAGE_SECTION_HEADER last_section = IMAGE_FIRST_SECTION(nt_headers) + (nt_headers->FileHeader.NumberOfSections - 1);
上面的代码在下面的函数中:
//Reference: http://www.codeproject.com/KB/system/inject2exe.aspx
PIMAGE_SECTION_HEADER add_section(const char *section_name, unsigned int section_size, void *image_addr) {
PIMAGE_DOS_HEADER dos_header = (PIMAGE_DOS_HEADER)image_addr;
if(dos_header->e_magic != 0x5A4D) {
wprintf(L"Could not retrieve DOS header from %p", image_addr);
return NULL;
}
PIMAGE_NT_HEADERS nt_headers = (PIMAGE_NT_HEADERS)((DWORD_PTR)dos_header + dos_header->e_lfanew);
if(nt_headers->OptionalHeader.Magic != 0x010B) {
wprintf(L"Could not retrieve NT header from %p", dos_header);
return NULL;
}
const int name_max_length = 8;
PIMAGE_SECTION_HEADER last_section = IMAGE_FIRST_SECTION(nt_headers) + (nt_headers->FileHeader.NumberOfSections - 1);
PIMAGE_SECTION_HEADER new_section = IMAGE_FIRST_SECTION(nt_headers) + (nt_headers->FileHeader.NumberOfSections);
memset(new_section, 0, sizeof(IMAGE_SECTION_HEADER));
new_section->Characteristics = IMAGE_SCN_MEM_READ | IMAGE_SCN_MEM_EXECUTE | IMAGE_SCN_CNT_CODE;
memcpy(new_section->Name, section_name, name_max_length);
new_section->Misc.VirtualSize = section_size;
new_section->PointerToRawData = align_to_boundary(last_section->PointerToRawData + last_section->SizeOfRawData,
nt_headers->OptionalHeader.FileAlignment);
new_section->SizeOfRawData = align_to_boundary(section_size, nt_headers->OptionalHeader.SectionAlignment);
new_section->VirtualAddress = align_to_boundary(last_section->VirtualAddress + last_section->Misc.VirtualSize,
nt_headers->OptionalHeader.SectionAlignment);
nt_headers->OptionalHeader.SizeOfImage = new_section->VirtualAddress + new_section->Misc.VirtualSize;
nt_headers->FileHeader.NumberOfSections++;
return new_section;
}
【问题讨论】:
-
要获得最后一节,您需要转到第一节加上节数减一。例如,如果只有一个部分,那也是最后一个部分,您必须添加零。如果有两个部分,最后一个部分是第一个加一个。
-
因为数组的索引从零开始。最后一个元素的索引是
count - 1。last_section是指向最后一个现有节的指针,new_section是指向下一个节的指针(尽管我不知道它如何确保它正在寻址有效内存)。
标签: c++ c file format portable-executable