; _______________________________________________________________________________________
;|                                                                                       |
;| ..::FreshLib::..  Free, open source. Licensed under "BSD 2-clause" license."          |
;|_______________________________________________________________________________________|
;
;  Description: Win32 environment management library.
;
;  Target OS: Win32
;
;  Dependencies:
;
;  Notes:
;_________________________________________________________________________________________
uses kernel32, user32

proc GetAllEnvironment
.return dd ?
begin
        pushad

        invoke  GetEnvironmentStringsA
        push    eax
        mov     esi, eax

.end_loop:
        cmp     word [esi], 0
        lea     esi, [esi+1]
        jne     .end_loop

        stc
        sbb     esi, [esp]
        lea     ecx, [esi+8]

        stdcall GetMem, ecx
        mov     [.return], eax
        mov     edi, eax
        mov     ecx, esi
        mov     esi, [esp]
        rep movsb
        xor     eax, eax
        stosd

        invoke  FreeEnvironmentStringsA ; from the stack
        popad
        mov     eax, [.return]
        return
endp



proc GetEnvVariable, .varname
.buffer rb 1024
begin
        push    ebx ecx edx

        stdcall utf8ToWideChar, [.varname]
        mov     [.varname], eax

        lea     ebx, [.buffer]
        invoke  GetEnvironmentVariableW, [.varname], ebx, 512
        test    eax, eax
        jz      .missing

        stdcall FreeMem, [.varname]
        stdcall WideCharToUtf8, ebx
        clc
        pop     edx ecx ebx
        return

.missing:
        stdcall FreeMem, [.varname]
        stc
        pop     edx ecx ebx
        return


endp