How to find the main() function using IDAPython
Question:
I don’t know how to find the main() function using IDAPython.
How can I do this?
Answers:
Run this in the python console of IDA
, and it will print the address of a function named main
for funcAddr in idautils.Functions():
funcName = idc.get_func_name(funcAddr)
if funcName == 'main':
print(f"{funcAddr:#x}")
Your question is a little unclear, to be honest. You write main
function, but I wonder if you mean the C runtime’s main
or the (main) entry point of the binary?
These are two different things. The idautils
module offers an Entries()
function and a Names()
function.
The documentation for both is slightly misleading. They return generators, not a list — as documented.
By using Names()
you can do what the other answer suggests. Using a list comprehension makes it a little more concise:
import idautils
# by looking for "main", we look anywhere in the tuple
mainfunc = [name for name in idautils.Names() if "main" in name]
# mainfunc is a list of tuples of (ea, name)
# NB: if there is just a single match, it's a single list element
print(mainfunc)
… might yield an output like: [(5368942248, 'main')]
import idautils
# by accessing index 3, we access the name
mainfunc = [name for name in idautils.Entries() if "main" in name[3]]
# mainfunc is a list of tuples of (index, ordinal, ea, name)
print(mainfunc)
… might yield an output of [(0, 5369098092, 5369098092, 'wmainCRTStartup')]
I don’t know how to find the main() function using IDAPython.
How can I do this?
Run this in the python console of IDA
, and it will print the address of a function named main
for funcAddr in idautils.Functions():
funcName = idc.get_func_name(funcAddr)
if funcName == 'main':
print(f"{funcAddr:#x}")
Your question is a little unclear, to be honest. You write main
function, but I wonder if you mean the C runtime’s main
or the (main) entry point of the binary?
These are two different things. The idautils
module offers an Entries()
function and a Names()
function.
The documentation for both is slightly misleading. They return generators, not a list — as documented.
By using Names()
you can do what the other answer suggests. Using a list comprehension makes it a little more concise:
import idautils
# by looking for "main", we look anywhere in the tuple
mainfunc = [name for name in idautils.Names() if "main" in name]
# mainfunc is a list of tuples of (ea, name)
# NB: if there is just a single match, it's a single list element
print(mainfunc)
… might yield an output like: [(5368942248, 'main')]
import idautils
# by accessing index 3, we access the name
mainfunc = [name for name in idautils.Entries() if "main" in name[3]]
# mainfunc is a list of tuples of (index, ordinal, ea, name)
print(mainfunc)
… might yield an output of [(0, 5369098092, 5369098092, 'wmainCRTStartup')]