Skip to content

add new function to render the command line on windows #63

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 4 commits into from

Conversation

vylsaz
Copy link
Contributor

@vylsaz vylsaz commented May 2, 2025

This function is based on this article, also see this

Because the command line situation on Windows is a mess, this solution is not secure e.g. when someone runs cmd.exe, but I think it's good enough...

@rexim
Copy link
Member

rexim commented May 2, 2025

I extremely apologize. I haven't read the article yet, but I'm wondering why exactly do we have to count consequent backslashes? Couldn't we just escape the string like this?

            nob_da_append(quoted, '\"');
            for (size_t j = 0; j < len; ++j) {
                char x = arg[j];
                switch (x) {
                case '\\': nob_sb_append_cstr(quoted, "\\\\"); break;
                case '\"': nob_sb_append_cstr(quoted, "\\\""); break;
                default:   nob_da_append(quoted, x);           break;
                }
            }
            nob_da_append(quoted, '\"');

Am I missing something weird about Windows here?

@vylsaz
Copy link
Contributor Author

vylsaz commented May 2, 2025

Yes, Windows is very weird here.

For example:

#include <stdio.h>
#include <windows.h>
int main(int argc, char **argv)
{
    WCHAR *cmdline = GetCommandLineW(); // this is the raw command line the process sees
    printf("raw   : %S\n", cmdline);
    printf("parsed: ");
    for (int i = 0; i < argc; ++i) {
        printf("`%s` ", argv[i]);
    }
    printf("\n");
    return 0;
}

compile as cmdline.exe and run in powershell:

PS D:\> .\cmdline "\test "   
raw   : "D:\cmdline.exe" "\test "
parsed: `D:\cmdline.exe` `\test `
PS D:\> .\cmdline "\\test "
raw   : "D:\cmdline.exe" "\\test "
parsed: `D:\cmdline.exe` `\\test `
PS D:\> .\cmdline "\""test "
raw   : "D:\cmdline.exe" "\\\"test "
parsed: `D:\cmdline.exe` `\"test `
PS D:\> .\cmdline "\\""test "
raw   : "D:\cmdline.exe" "\\\\\"test "
parsed: `D:\cmdline.exe` `\\"test `

(here powershell also looks for the full path of the executable which I didn't do)

@Mrjiong438
Copy link

Mrjiong438 commented May 5, 2025

In short, Windows escapes double quotes and a string of backslashes with a double quote in the end.
see detail in here

@rexim
Copy link
Member

rexim commented May 15, 2025

Thank you! Merge at 8927dcb

@rexim rexim closed this May 15, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants