ioncodes / idacode

An integration for IDA and VS Code which connects both to easily execute and debug IDAPython scripts.
725 stars 77 forks source link

if __name__ ==... causes error #14

Closed OevreFlataeker closed 4 years ago

OevreFlataeker commented 4 years ago

If the python script to debug contains something like

if __name__ == '__main__':
    main()

the script will not run correctly. To fix, remove the "if" line and just directly call main().

ioncodes commented 4 years ago

I believe IDA sets __name__ to its own custom thing. Can you let us know what __name__ contains?

OevreFlataeker commented 4 years ago

Hm, if I am not mistaken... name gives "builtins" in the VS Code Terminal when breaking on that line...

ioncodes commented 4 years ago

Interesting! Well, it's not really an issue specific to IDACode so a possible fix would be to just not deal with if __name__ == ... source lines or the other would be to override the global to __main__. Not sure which "fix" would suit best in this scenario.

puppywang commented 4 years ago

idaapi.IDAPython_ExecScript called python's execfile, which just load all code into current context, so __builtin__ is returned instead of __main__, detail information is listed here: https://stackoverflow.com/questions/711066/calling-execfile-in-custom-namespace-executes-code-in-builtin-namespace

OevreFlataeker commented 4 years ago

And it means it is something that would need a change in IDA or how IDA calls the script, correct? Like the last post said: Use import() instead of execfile()

ioncodes commented 4 years ago

I would assume that setting __name__ when passing the globals into execute_sync should fix the issue, I will give that a shot.

ioncodes commented 4 years ago

I can confirm this does indeed work and doesn't cause any unexpected issues.
image

ioncodes commented 4 years ago

I introduced __name__ as __main__ in the following commit: https://github.com/ioncodes/idacode/commit/6c01131296e0ca2c20224d2978750b077a3b007c. A new version will be published in the next hour.

OevreFlataeker commented 4 years ago

That's awesome! Thanks!