10 printf("Converts a coff object file into a raw binary file.\n"
11 "Syntax: obj2bin <source file> <dest file> <base address>\n");
18 IMAGE_SECTION_HEADER
*pSectionHeader
,
19 PIMAGE_SYMBOL pSymbols
,
22 unsigned int i
, nOffset
;
23 PIMAGE_RELOCATION pReloc
;
28 pSection
= pData
+ pSectionHeader
->PointerToRawData
;
30 /* Calculate pointer to relocation table */
31 pReloc
= (PIMAGE_RELOCATION
)(pData
+ pSectionHeader
->PointerToRelocations
);
33 /* Loop all relocations */
34 for (i
= 0; i
< pSectionHeader
->NumberOfRelocations
; i
++)
36 nOffset
= pReloc
->VirtualAddress
- pSectionHeader
->VirtualAddress
;
38 if (nOffset
> pSectionHeader
->SizeOfRawData
) continue;
42 case IMAGE_REL_I386_ABSOLUTE
:
44 p16
= (void*)(pSection
+ nOffset
);
45 *p16
+= (WORD
)(pSymbols
[pReloc
->SymbolTableIndex
].Value
+ iOffset
);
48 case IMAGE_REL_I386_DIR32
:
49 p32
= (void*)(pSection
+ nOffset
);
50 *p32
+= (DWORD
)(pSymbols
[pReloc
->SymbolTableIndex
].Value
+ iOffset
);
54 printf("Unknown relocatation type %ld address %ld\n",
55 pReloc
->Type
, pReloc
->VirtualAddress
);
62 int main(int argc
, char *argv
[])
66 unsigned long nFileSize
, nBaseAddress
;
67 FILE *pSourceFile
, *pDestFile
;
68 IMAGE_FILE_HEADER
*pFileHeader
;
69 IMAGE_SECTION_HEADER
*pSectionHeader
;
72 PIMAGE_SYMBOL pSymbols
;
74 if ((argc
!= 4) || (strcmp(argv
[1], "--help") == 0))
80 pszSourceFile
= argv
[1];
81 pszDestFile
= argv
[2];
82 nBaseAddress
= strtol(argv
[3], 0, 16);
84 pSourceFile
= fopen(pszSourceFile
, "rb");
87 fprintf(stderr
, "Couldn't open source file '%s'\n", pszSourceFile
);
92 fseek(pSourceFile
, 0, SEEK_END
);
93 nFileSize
= ftell(pSourceFile
);
96 /* Allocate memory for the file */
97 pData
= malloc(nFileSize
);
100 fprintf(stderr
, "Failed to allocate %ld bytes\n", nFileSize
);
104 /* Read the whole source file */
105 if (!fread(pData
, nFileSize
, 1, pSourceFile
))
107 fprintf(stderr
, "Failed to read source file: %ld\n", nFileSize
);
111 /* Close source file */
114 /* Open the destination file */
115 pDestFile
= fopen(pszDestFile
, "wb");
118 fprintf(stderr
, "Couldn't open dest file '%s'\n", pszDestFile
);
122 /* Calculate table pointers */
123 pFileHeader
= (IMAGE_FILE_HEADER
*)pData
;
124 pSymbols
= (void*)(pData
+ pFileHeader
->PointerToSymbolTable
);
125 pSectionHeader
= (void*)(((char*)(pFileHeader
+ 1)) + pFileHeader
->SizeOfOptionalHeader
);
127 /* Loop all sections */
128 for (i
= 0; i
< pFileHeader
->NumberOfSections
; i
++)
130 /* Check if this is '.text' section */
131 if ((strcmp(pSectionHeader
->Name
, ".text") == 0) &&
132 (pSectionHeader
->SizeOfRawData
!= 0))
134 RelocateSection(pData
,
139 /* Write the section to the destination file */
140 if (!fwrite(pData
+ pSectionHeader
->PointerToRawData
,
141 pSectionHeader
->SizeOfRawData
, 1, pDestFile
))
143 fprintf(stderr
, "Failed to write data %ld\n",
144 pSectionHeader
->SizeOfRawData
);
148 nBaseAddress
+= pSectionHeader
->SizeOfRawData
;