303
303

Reputation: 4732

Writing to command line arguments

Is it safe (not causing undefined behavior) to overwrite the command line string that is returned from calling the GetCommandLine function?

*(GetCommandLineW() + 1) = L'x'; // should be fine, right?

I'm not sure whether to treat the returned string as a string literal as the assigned protection attributes of the corresponding memory pages seem to differentiate.

MEMORY_BASIC_INFORMATION mbiMemPage;

VirtualQuery(GetCommandLineW(), &mbiMemPage,
             sizeof(MEMORY_BASIC_INFORMATION)); // mbiMemPage.Protect = PAGE_READWRITE

VirtualQuery(L"some string", &mbiMemPage,
             sizeof(MEMORY_BASIC_INFORMATION)); // mbiMemPage.Protect = PAGE_EXECUTE_READ

Upvotes: 2

Views: 211

Answers (1)

Anders
Anders

Reputation: 101626

GetCommandLineW returns a pointer to a string stored in the PEB but that is a implementation detail. It is safe to modify the string on every released version of Windows NT but that does not mean that it will stay like that forever. However, the return type is LPTSTR and not LPCTSTR so I find it unlikely that it will be stored in a read-only page in the future.

It is really up to you if you want to risk it. Just keep in mind that you cannot exceed the initial string length and somebody could rename your application to "x.exe" and run it simply as "x" leaving you only two characters to play with.

If you just want to parse and extract a parameter you can use CommandLineToArgvW.

Upvotes: 4

Related Questions