0

How to get machine code of a file(mainly executables) in C? I have written a C program to convert machine code to assembly. But how to get machine code of a file? How would I go about programming a c program to convert a file to machine code?

1
  • 3
    Can you please write more about your understanding of what a file is, and why you need a program to "convert a file to machine code"? Like, why couldn't a file already contain machine code? Then we can better understand where you are coming from and answer, including clearing up any misconceptions if needed. Feb 6 at 15:59
1

You can make a program that interprets machine code using an engine like Capstone-engine, this is the easiest way to do something that gives you good results in an optimized way easily, keep in mind that this is not an easy task, it is much better to use a ready-made tool, we have many free and very good options and constantly updated like Ghidra, but if you still want to write your own enjoy and also read the manual IA-32 Intel manual.

2
  • Read the Capstone-Engine documentation and its implementation in C language here: capstone-engine.org/lang_c.html
    – 0x0A
    Feb 5 at 19:21
  • Thank you so much. This cleared my doubt. I have upvoted and accepted. Thanks for sharing your knowledge. Feb 6 at 10:34
1

its very hard to understand what you want

How to get machine code of a file(mainly executables) in C?

so you want a C program that loads an executable file (for example dos,windows,linux exucutable) and showing you the whole or parts of the image (that normaly contains machine code and data)?

so there are several documented file formats that can contain machine code

for example see IDAs supported files types: https://www.hex-rays.com/products/ida/file_formats/

I have written a C program to convert machine code to assembly.

so you've already got some sort of disassembler?

But how to get machine code of a file?

read the spec of your operating system file format and write a small loader/parser, there are serveral C,C++,go,python ... example on github/google...

How would I go about programming a c program to convert a file to machine code?

and now you revert you question completely - before - you ask how to load a file with machine-code and now you ask how to convert "a file" to machine-code

what format is "a file" in your example - some sort of source-code or object file format?

Normaly this is the way: C/C++/Assembler/whatever-Source --> Compiler --> Objectfiles --> OS-related-Executable-Format[Machine-Code+Data]

try to ask more precise - its easy to help you when its clear what your exact target is

1
from binascii import *
from pefile import *
from capstone import *

if(sys.argv[1]):
    pe      = PE(sys.argv[1])
    entry   = pe.OPTIONAL_HEADER.AddressOfEntryPoint
    base    = pe.OPTIONAL_HEADER.ImageBase
    OEP = base+entry
    bytes   = pe.get_data(entry,17)
    print(hexlify(bytes))
    for i in (Cs(CS_ARCH_X86,CS_MODE_64).disasm(bytes,OEP)):
        print("0x%x:\t%s\t%s" %(i.address, i.mnemonic, i.op_str))
    

result and confirmation

:\>python getbytatent.py c:\Windows\System32\calc.exe
b'e84bfdffff6a5868e82e0101e8eb99ffff'
0x1012d6c:      call    0x1012abc
0x1012d71:      push    0x58
0x1012d73:      push    0x1012ee8
0x1012d78:      call    0x100c768

:\>cdb -c "u @$exentry l4;q" c:\Windows\System32\calc.exe | awk "/Reading/,/quit/"
0:000> cdb: Reading initial command 'u @$exentry l4;q'
calc!WinMainCRTStartup:
00a92d6c e84bfdffff      call    calc!__security_init_cookie (00a92abc)
00a92d71 6a58            push    58h
00a92d73 68e82ea900      push    offset calc!_CT??_R0?AV_com_error+0xdc (00a92ee8)
00a92d78 e8eb99ffff      call    calc!_SEH_prolog4 (00a8c768)
quit:

i hate putting this here after that comment BY OP
it takes less than a minute to convert that into winapi
(i should state that winapi is not c )
and a pure c does not have the PE format structures defined
one can obviously do fopen(),fseek(),fread() but well that is beyond compare exercise in futility

:\>type mcc.cpp
#include <windows.h>
#include <dbghelp.h>
#include <stdio.h>
int main (int argc ,char * argv[]) {
    if(argc == 2) {
        HMODULE hMod = LoadLibraryA(argv[1]);
        if(hMod){
            DWORD AEP = ((PIMAGE_NT_HEADERS32)ImageNtHeader(hMod))->OptionalHeader.AddressOfEntryPoint;
            DWORD OEP = (DWORD)hMod + AEP;
            for (int i =0; i< 17 ; i++) {
                printf("%02x ",*(BYTE *)(OEP+i));
            }
        }
    }
}
:\>cl /Zi /W4 /analyze /Od mcc.cpp /nologo /link /release dbghelp.lib
mcc.cpp


:\>mcc.exe c:\Windows\System32\calc.exe
e8 4b fd ff ff 6a 58 68 e8 2e 82 00 e8 eb 99 ff ff
:\>

and just to complete the circle a fragile non productive c hack
for a specific application
in a specific os
with specific dos, nt headers,
aep in .code section starting at 0x400
file alignment of 0x200 and page alignment of 0x1000

:\>type futilemcc.cpp
//assume = ass u and me a beyond compare exercise in futility
#include <stdio.h>
int main (int argc ,char *argv[] ){
    if(argc ==2){
        FILE *fp = NULL;
        unsigned long nth = NULL;
        unsigned char mcc[17] ={0};
        errno_t err= fopen_s(&fp,argv[1],"rb");
        if(err == 0 && fp != NULL) {
            if ( fseek(fp,0x3c,SEEK_SET) == 0) {
                fread_s(&nth,sizeof(unsigned long),sizeof(unsigned long),1,fp);
                if ( fseek(fp,nth+0x28,SEEK_SET) == 0) {
                    fread_s(&nth,sizeof(unsigned long),sizeof(unsigned long),1,fp);
                    if ( fseek(fp,nth-(0x1000-0x400),SEEK_SET) == 0) {
                        fread_s(&mcc,sizeof(mcc),sizeof(unsigned char),sizeof(mcc),fp);
                        for(int i =0;i<17;i++){
                            printf("%02x ",mcc[i]);
                        }
                    }
                }
            }
        }
    }
}
:\>complink.bat futilemcc

:\>cl /Zi /W4 /analyze /nologo /Od /EHsc futilemcc.cpp /link /release
futilemcc.cpp

:\>futilemcc.exe c:\Windows\System32\calc.exe
e8 4b fd ff ff 6a 58 68 e8 2e 01 01 e8 eb 99 ff ff
:\>
2

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.