I have a Win32 C++ application and I need to modify the command line arguments in the application. Specifically, I want to edit the command line arguments in such a way that GetCommandLineW()
returns my new arguments.
Believe it or not, this works (since we have a non-const pointer to the character array):
LPTSTR args = GetCommandLineW();
LPTSTR new_args = L"foo --bar=baz";
wmemcpy(args, new_args, lstrlenW(new_args));
// ...
LPTSTR args2 = GetGommentLineW(); // <- equals "foo --bar=baz"
But I don't know how long much memory Windows allocates for the LPTSTR
provided by GetCommandLineW()
.
Is there another way to do this? Or does anyone know if there is a predictable amount of memory allocated for the command line arguments?
The cleanest and safest way to modify what that function returns is to modify the function. Install a detour so that any calls to the function from inside your process are re-routed to a function that you provide.
GetCommandLineW()
does not allocate any memory. It simply returns a pointer to a buffer that is allocated by the OS in the process'sPEB
structure when the process is created. That buffer exists for the lifetime of the process.