Search code examples
assemblyx86-64fasm

Assembly PE64 Console Can't Find Command-line Arguments Count and Array (argc) + (argv)


im working on an Assembly project for Win64 and i have a problem with Command-line Argument !!!! in a normal situation, the address of Command-line Argument is:

[rsp] = Number of Command-line Arguments
[rsp+8] = First Argument (Name of Executable)
[rsp+16] = First Client Argument
....

but in in my situation, these are not the Values that i want ! ([rsp] is not the number of ... and [rsp+8] is not argument and ....)

this is my source code (FASM PE64 CONSOLE)

FORMAT  PE64 CONSOLE
ENTRY   MAIN

SECTION '.text' CODE READABLE EXECUTABLE
MAIN:
        mov     r12, [rsp] ; now r12 is the number of Commandline Arguments (but it's not !!!!!!!!!!!!)
        sub     rsp, 56

        mov     ecx, -11
        call    [K32.GetStdHandle]

        cmp     r12, 1  ; Argument Count Must be More than 1 (because it's 1 by default (Executable name) and we want to print, if it's More than 1 (if Argument Provided))
        jle     .exit

        .write:
                mov     ecx, eax                ; STD_OUTPUT_HANDLE (EAX)
                mov     rdx, .hello
                mov     r8d, .hello_len
                xor     r9d, r9d
                mov     QWORD [rsp+32], 0
                call    [K32.WriteFile]

        .exit:
                add     rsp, 56

                xor     ecx, ecx
                call    [K32.ExitProcess]

                hlt

        .hello  DB 'Argument Received', 0x00
        .hello_len = $ - .hello

SECTION '.idata' IMPORT DATA READABLE WRITABLE
DD      0,0,0,RVA K32DLL,RVA K32
DD      0,0,0,0,0


K32DLL DB 'KERNEL32.DLL', 0x00

K32:
        .ExitProcess            DQ RVA ___ExitProcess
        .GetStdHandle           DQ RVA ___GetStdHandle
        .WriteFile              DQ RVA ___WriteFile
                                DQ 0

___ExitProcess          DB 0,0,'ExitProcess',0
___GetStdHandle         DB 0,0,'GetStdHandle',0
___WriteFile            DB 0,0,'WriteFile',0   

in My Program, if we add an argument, it's Must print the Message. otherwise it's Must just EXIT but it Always print that Message (The value of 'Number of Command-line Arguments' is wrong !)

Also i check the 'rcx' as the number of Command-line Arguments and 'rdx' as Arguments Array but still they aren't !!!

Where is the argc and argv !!!!!!!!!! is this about my Format ? (PE64 Console) ?


Solution

  • Command-line arguments, including the name of executable itself, are parsed by OS and put on stack in Linux but things are very different in Windows. You need to invoke kernel function GetCommandLineA() and parse the returned string by yourself.

    Invoking ExitProcess never returns to the exited program, so your instruction hlt will not execute and should be omitted.