; Listing5-9.asm
;
; A program that demonstrates running a separate program
; as a new process.

            option     casemap:none
            include    aoalib.inc   ;AoA library + constants
            includelib aoalib.lib   ;Link in aoalib library
            include    c:\masm32\include64\win64.inc
            include    c:\masm32\include64\kernel32.inc
            includelib c:\masm32\lib64\kernel32.lib  
            
            .const

; Program title:

            align   word
ttlStr      byte    "Listing 5-9", 0

            .data
            
StartupInfo STARTUPINFO             {}      ;Note: initialized with zeros
ProcessInfo PROCESS_INFORMATION     {}      ;Note: initialized with zeros
pgmName     byte    "listing5-8.exe", 0     ;Run from current directory
cmdLine     byte    "listing5-8.exe arg1 arg2", 0

            .code

; Here is the main assembly language function.
            
            public  asmMain
asmMain     proc
            
            push    rbp
            mov     rbp, rsp
            sub     rsp, 128        ;Locals and shadow storage
            mov     [rbp-8], rbx
            
            lea     rcx, pgmName
            lea     rdx, cmdLine
            xor     r8, r8          ;NULL process attributes
            xor     r9, r9          ;NULL thread attributes
            mov     [rsp+32], r9    ;false on inherit handles
            mov     [rsp+40], r9    ;dwFlags - use current console
            mov     [rsp+48], r9    ;Just inherit env vars
            mov     [rsp+56], r9    ;Use same current dir
            lea     rax, StartupInfo
            mov     [rsp+64], rax   ;Default startup info
            lea     rax, ProcessInfo
            mov     [rsp+72], rax   ;Put process info here
            call    CreateProcess
            test    eax, eax        ;Check for error
            jz      badProcess
            
; Wait for the process we started to terminate:

            mov     rcx, ProcessInfo.hProcess
            mov     edx, INFINITE
            call    WaitForSingleObject
            call    print
            byte    "Created process has quit and returned"
            byte    nl, 0
            jmp     allDone
            
            
badProcess: call    GetLastError
            mov     edx, eax
            call    print
            byte    "Bad process creation: %d", nl, 0                        
            
; Terminate the program.

allDone:    
            mov     rbx, [rbp-8]
            leave
            ret     ;Returns to caller
        
asmMain     endp
            end