Problems with accessing MainModule too early.. (C#)

67 Views Asked by At

Okay so here's the long and short of it, and it's a problem that's been plaguing me for awhile now. I've written something that launches a game process, then in order to proceed with what the application does (it's for modding purposes) it needs to suspend the process and access the MainModule for retrieving the BaseAddress of the process - unfortunately this seems to "sometimes" but not always cause a Win32 Exception, presumably because MainModule is being accessed too early. (However for the purposes of the tool I'm writing, I need to access this as early as possible to apply game fixes before bootup proceeds too far..)

Process game = Process.Start(installPath + "game.exe", launchCommands);

            while (true) { if (game.MainModule != null) { game.Suspend(); break; } }

            int processId = game.Id;
            IntPtr baseAddress = game.MainModule.BaseAddress;

This is the current code I'm using, I originally thought that checking whether MainModule was null or not would avoid the entire problem (and in fact I haven't personally encountered it since writing this in) but one of my testers will sometimes hit a Win32Exception on the if statement..

Without the if statement and while loop, if I just suspend the process outright the same exception will occur anyway when it reaches baseAddress, for much the same problem as near as I can tell.. In a much earlier iteration of my code I did this:

public static IntPtr BaseAddrScan(int processId, ProcessLauncher process)
    {
        try 
        {
            IntPtr baseAddress = Process.GetProcessById(processId).MainModule.BaseAddress;
            return baseAddress;
        }
        catch
        {
            Process.GetProcessById(processId).Resume();
            System.Threading.Thread.Sleep(1);
            Process.GetProcessById(processId).Suspend();
            return BaseAddrScan(processId, process);
        }
    }

Effectively it tries to scan for the BaseAddress, and if it hits the exception it goes to the catch block that resumes the (previously) suspended process, waits a tick, then suspends it again and loops back in on itself and tries to do everything again, hopefully eventually edging closer to a point where it can access MainModule and all is well.. And I mean.. Yes this worked, but this seems horrible a "solution" to this problem, it feels like a nasty abuse of try\catch and just clumsy coding all and all. Surely there has to be some way to do a loop until MainModule is ready without causing an exception..?

Exception from Event Viewer

0

There are 0 best solutions below