Delphi-PRAXiS

Delphi-PRAXiS (https://www.delphipraxis.net/forum.php)
-   Programmieren allgemein (https://www.delphipraxis.net/40-programmieren-allgemein/)
-   -   NASM - Erstellung eines Win64-Bit Images für die Verwendung mit mehr als 2 Funccalls (https://www.delphipraxis.net/213960-nasm-erstellung-eines-win64-bit-images-fuer-die-verwendung-mit-mehr-als-2-funccalls.html)

paule32.jk 29. Okt 2023 02:01

NASM - Erstellung eines Win64-Bit Images für die Verwendung mit mehr als 2 Funccalls
 
Hallo,
ich würde gerne Wissen wollen, wie man mehr als nur eine Funktion in den folgenden Snippet aufrufen kann.
Ich habe dazu eine kleine .DLL geschrieben, die ein einziges Export hat.
Ich würde gerne mehr Exports verwenden wollen.
Der vorliegende Code funktioniert und kann mittels: C:\nasm -f bin -o win.exe win.asm übersetzt werden.

Danke schonmal für sachdienliche Hinweise.
Code:
BITS 64

%define align(n,r) (((n+(r-1))/r)*r)

; DOS Header
    dw 'MZ'                ; e_magic
    dw 0                    ; [UNUSED] e_cblp
    dw 0                    ; [UNUSED] c_cp
    dw 0                    ; [UNUSED] e_crlc
    dw 0                    ; [UNUSED] e_cparhdr
    dw 0                    ; [UNUSED] e_minalloc
    dw 0                    ; [UNUSED] e_maxalloc
    dw 0                    ; [UNUSED] e_ss
    dw 0                    ; [UNUSED] e_sp
    dw 0                    ; [UNUSED] e_csum
    dw 0                    ; [UNUSED] e_ip
    dw 0                    ; [UNUSED] e_cs
    dw 0                    ; [UNUSED] e_lfarlc
    dw 0                    ; [UNUSED] e_ovno
    times 4 dw 0            ; [UNUSED] e_res
    dw 0                    ; [UNUSED] e_oemid
    dw 0                    ; [UNUSED] e_oeminfo
    times 10 dw 0           ; [UNUSED] e_res2
    dd pe_hdr              ; e_lfanew

; PE Header
pe_hdr:
    dw 'PE', 0              ; Signature

; Image File Header
    dw 0x8664               ; Machine
    dw 0x01                 ; NumberOfSections
    dd 0                    ; [UNUSED] TimeDateStamp
    dd 0                    ; PointerToSymbolTable
    dd 0                    ; NumberOfSymbols
    dw opt_hdr_size        ; SizeOfOptionalHeader
    dw 0x22                 ; Characteristics

; Optional Header, COFF Standard Fields
opt_hdr:
    dw 0x020b              ; Magic (PE32+)
    db 0x0e                ; MajorLinkerVersion
    db 0x16                 ; MinorLinkerVersion
    dd code_size           ; SizeOfCode
    dd 0                    ; SizeOfInitializedData
    dd 0                    ; SizeOfUninitializedData
    dd entry               ; AddressOfEntryPoint
    dd iatbl               ; BaseOfCode

; Optional Header, NT Additional Fields
    dq 0x000140000000       ; ImageBase
    dd 0x10                 ; SectionAlignment
    dd 0x10                 ; FileAlignment
    dw 0x06                 ; MajorOperatingSystemVersion
    dw 0                    ; MinorOperatingSystemVersion
    dw 0                    ; MajorImageVersion
    dw 0                    ; MinorImageVersion
    dw 0x06                 ; MajorSubsystemVersion
    dw 0                    ; MinorSubsystemVersion
    dd 0                    ; Reserved1
    dd file_size           ; SizeOfImage
    dd hdr_size            ; SizeOfHeaders
    dd 0                    ; CheckSum
    dw 0x02                 ; Subsystem (Windows GUI)
    dw 0x8160               ; DllCharacteristics
    dq 0x100000             ; SizeOfStackReserve
    dq 0x1000               ; SizeOfStackCommit
    dq 0x100000             ; SizeOfHeapReserve
    dq 0x1000               ; SizeOfHeapCommit
    dd 0                    ; LoaderFlags
    dd 0x02                 ; NumberOfRvaAndSizes

; Optional Header, Data Directories
    dd 0                    ; Export, RVA
    dd 0                    ; Export, Size
    dd itbl                ; Import, RVA
    dd itbl_size           ; Import, Size

opt_hdr_size equ $-opt_hdr

; Section Table
    section_name db '.'    ; Name
    times 8-($-section_name) db 0
    dd sect_size           ; VirtualSize
    dd iatbl               ; VirtualAddress
    dd code_size           ; SizeOfRawData
    dd iatbl               ; PointerToRawData
    dd 0                    ; PointerToRelocations
    dd 0                    ; PointerToLinenumbers
    dw 0                    ; NumberOfRelocations
    dw 0                    ; NumberOfLinenumbers
    dd 0x60000020           ; Characteristics

hdr_size equ $-$$

code:
; Import Address Directory
iatbl:
    dq symbol
    dq 0

iatbl_size equ $-iatbl

; Strings
title:
    db "Hallo Welt !!!", 0
content:
    db "ABCDEFGHIJKL", 0

; Entry
entry:
    mov r9d, 0x00240040     ; uType
    lea r8, [rel title]    ; lpCaption
    lea rdx, [rel content] ; lpText
    xor ecx, ecx           ; hWnd
    jmp [rel iatbl]        ; MessageBoxN

    times align($-$$,16)-($-$$) db 0xcc

; Import Directory
itbl:
    dq intbl               ; OriginalFirstThunk
    dd 0                    ; TimeDateStamp
    dd dll_name            ; ForwarderChain
    dd iatbl               ; Name
    dq 0                    ; FirstThunk

itbl_size equ $-itbl

; Import Name Table
intbl:
    dq symbol
    dq 0

; Symbol
symbol:
    dw 0x0                   ; [UNUSED] Function Order
    db 'ShowMessageA', 0     ; Function Name
    dw 0x0
    db 'kalli', 0
dll_name:
    db 'kalle32.dll', 0
    db 0

sect_size equ $-code

    times align($-$$,16)-($-$$) db 0

code_size equ $-code
file_size equ $-$$

Kas Ob. 29. Okt 2023 14:28

AW: NASM - Erstellung eines Win64-Bit Images für die Verwendung mit mehr als 2 Funcca
 
Hi,

You said you are calling one export, but i don't see any export, your code is showing the message in the DllEntry, that DLL doesn't have any export at all.

Point on that code:
1) You are complicating things for yourself with all the handmade headers, just don't !, NASM will do it all for your, and it will be right.
2) Use export section instead of building the export and import sections by hand.
3) Please search the net for a good example like this post https://forum.nasm.us/index.php?topic=2365.15 and you can read the code in that thread, that how a everyday DLL should like, writing the PE manually is dangerous zone and easily can blocked by AntiViruses, writing a DLL in NASM or MASM is way easier and shorter.


There is many resources for NASM on the internet and they have a very nice forum too.

Hope that helps, and good luck.

paule32.jk 29. Okt 2023 14:55

AW: NASM - Erstellung eines Win64-Bit Images für die Verwendung mit mehr als 2 Funcca
 
Hi,
I don't want use a Linker.
I would like produce a Flat-Image on the fly.

The DLL Library Code looks like:

Delphi-Quellcode:
library kalle32;
uses windows;
procedure kalli(h: HWND; lpText: PChar; lpCaption: PChar; mb: UINT); stdcall; export;
begin
  MessageBoxA(h,Pchar(lpText),PChar(lpCaption),mb);
end;

exports kalli;
begin
  MessageBoxA(0,'hallo','kaaass',0);
end.
Then I have extend the Assembly Code:
Code:
BITS 64
 
%define align(n,r) (((n+(r-1))/r)*r)
 
; DOS Header
    dw 'MZ'                ; e_magic
    dw 0                    ; [UNUSED] e_cblp
    dw 0                    ; [UNUSED] c_cp
    dw 0                    ; [UNUSED] e_crlc
    dw 0                    ; [UNUSED] e_cparhdr
    dw 0                    ; [UNUSED] e_minalloc
    dw 0                    ; [UNUSED] e_maxalloc
    dw 0                    ; [UNUSED] e_ss
    dw 0                    ; [UNUSED] e_sp
    dw 0                    ; [UNUSED] e_csum
    dw 0                    ; [UNUSED] e_ip
    dw 0                    ; [UNUSED] e_cs
    dw 0                    ; [UNUSED] e_lfarlc
    dw 0                    ; [UNUSED] e_ovno
    times 4 dw 0            ; [UNUSED] e_res
    dw 0                    ; [UNUSED] e_oemid
    dw 0                    ; [UNUSED] e_oeminfo
    times 10 dw 0           ; [UNUSED] e_res2
    dd pe_hdr              ; e_lfanew
 
; PE Header
pe_hdr:
    dw 'PE', 0              ; Signature
 
; Image File Header
    dw 0x8664               ; Machine
    dw 0x01                 ; NumberOfSections
    dd 0                    ; [UNUSED] TimeDateStamp
    dd 0                    ; PointerToSymbolTable
    dd 0                    ; NumberOfSymbols
    dw opt_hdr_size        ; SizeOfOptionalHeader
    dw 0x22                 ; Characteristics
 
; Optional Header, COFF Standard Fields
opt_hdr:
    dw 0x020b              ; Magic (PE32+)
    db 0x0e                ; MajorLinkerVersion
    db 0x16                 ; MinorLinkerVersion
    dd code_size           ; SizeOfCode
    dd 0                    ; SizeOfInitializedData
    dd 0                    ; SizeOfUninitializedData
    dd entry               ; AddressOfEntryPoint
    dd iatbl               ; BaseOfCode
 
; Optional Header, NT Additional Fields
    dq 0x000140000000       ; ImageBase
    dd 0x10                 ; SectionAlignment
    dd 0x10                 ; FileAlignment
    dw 0x06                 ; MajorOperatingSystemVersion
    dw 0                    ; MinorOperatingSystemVersion
    dw 0                    ; MajorImageVersion
    dw 0                    ; MinorImageVersion
    dw 0x06                 ; MajorSubsystemVersion
    dw 0                    ; MinorSubsystemVersion
    dd 0                    ; Reserved1
    dd file_size           ; SizeOfImage
    dd hdr_size            ; SizeOfHeaders
    dd 0                    ; CheckSum
    dw 0x02                 ; Subsystem (Windows GUI)
    dw 0x8160               ; DllCharacteristics
    dq 0x100000             ; SizeOfStackReserve
    dq 0x1000               ; SizeOfStackCommit
    dq 0x100000             ; SizeOfHeapReserve
    dq 0x1000               ; SizeOfHeapCommit
    dd 0                    ; LoaderFlags
    dd 0x02                 ; NumberOfRvaAndSizes
 
; Optional Header, Data Directories
    dd 0                    ; Export, RVA
    dd 0                    ; Export, Size
    dd itbl                ; Import, RVA
    dd itbl_size           ; Import, Size
 
opt_hdr_size equ $-opt_hdr
 
; Section Table
    section_name db '.'    ; Name
    times 8-($-section_name) db 0
    dd sect_size           ; VirtualSize
    dd iatbl               ; VirtualAddress
    dd code_size           ; SizeOfRawData
    dd iatbl               ; PointerToRawData
    dd 0                    ; PointerToRelocations
    dd 0                    ; PointerToLinenumbers
    dw 0                    ; NumberOfRelocations
    dw 0                    ; NumberOfLinenumbers
    dd 0x60000020           ; Characteristics
 
hdr_size equ $-$$
 
code:
; Import Address Directory
iatbl:
    dq symbol_1
    dq symbol_2
    dq 0
iatbl_size equ $-iatbl
 
; Strings
title:
    db "Hallo Welt !!!", 0
content:
    db "ABCDEFGHIJKL", 0
 
; Entry
entry:
  mov r9d, 0x00240040     ; uType
  lea r8, [rel title]    ; lpCaption
  lea rdx, [rel content] ; lpText
  xor ecx, ecx           ; hWnd
  mov rax, [rel iatbl + 8] ; MessageBoxN
  call rax
 
 
    times align($-$$,16)-($-$$) db 0xcc
 
; Import Directory 1
itbl:
    dq intbl_1              ; OriginalFirstThunk
    dd 0                    ; TimeDateStamp
    dd dll_name_1           ; ForwarderChain
    dd iatbl               ; Name
    dq 0                    ; FirstThunk

; Import Directory 2
itbl_2:
    dq intbl_2              ; OriginalFirstThunk
    dd 0                    ; TimeDateStamp
    dd dll_name_2           ; ForwarderChain
    dd iatbl + 8            ; Name
    dq 0                    ; FirstThunk

itbl_size equ $-itbl
 
; Import Name Table 1
intbl_1:
    dq symbol_1
    dq 0

; Import Name Table 2
intbl_2:
    dq symbol_2
    dq 0
 
; Symbol 1
symbol_1:
    dw 0                    ; [UNUSED] Function Order
    db 'MessageBoxA', 0     ; Function Name

; Symbol 2
symbol_2:
    dw 0
    db 'kalli', 0

dll_name_2: db 'kalle32.dll', 0
dll_name_1: db 'USER32.dll' , 0
 
sect_size equ $-code
 
    times align($-$$,16)-($-$$) db 0
 
code_size equ $-code
file_size equ $-$$
There must be an mistake somewhere.
Because, when I use the Lines:

Code:
  mov r9d, 0x00240040     ; uType
  lea r8, [rel title]    ; lpCaption
  lea rdx, [rel content] ; lpText
  xor ecx, ecx           ; hWnd
  mov rax, [rel iatbl]   ; MessageBoxN
  call rax
The Application run fine on my Windows Station.

Kas Ob. 29. Okt 2023 17:33

AW: NASM - Erstellung eines Win64-Bit Images für die Verwendung mit mehr als 2 Funcca
 
I am really sorry, something went very wrong with translation and my brain understanding what is the question is.

I answered different thing as the translation gave me that you are building an DLL with NASM :oops:

Anyway, i looked and it seems you are putting the import directory iatbl in code section, this will be a problem as code section should be with execute memory protection and the import usually will only be read and write with no execution, that one also the size of the import table and thunk looks off, in fact the two sizes should be recalculated, for both code section and the extra '.' section, as for the import the indexes are off too.

Using one section is considered malicious and will not be allowed to run by any AntiVirus or security software, so when say you want flat image i understand it as you want one section with the PE header, i would suggest to to make sure there is two distinctive section that not overlapping like your code above, and make sure they are aligned (padded is not essential as the RVA size id right), only then you can build the import right.

You said it is working and showing a message with the alternative code, there is a chance that Windows resolved only one and filled it then stopped because the section is marked as execute allowed not read/wite.

Another thing: without ExitProcess explicitly called, that EXE will be raising exception on exit.

paule32.jk 29. Okt 2023 18:07

AW: NASM - Erstellung eines Win64-Bit Images für die Verwendung mit mehr als 2 Funcca
 
during the waiting Time of your Response, I asked ChatGPT, and formed the following Code.
But it can not execute - I get Windows Error 0x0c - not a valid win32 application.
I dont know why - Did you can see my mistake ?
Thanks for helping.

Code:
BITS 64
 
; DOS Header
    dw 'MZ'                ; e_magic
    dw 0                    ; [UNUSED] e_cblp
    dw 0                    ; [UNUSED] c_cp
    dw 0                    ; [UNUSED] e_crlc
    dw 0                    ; [UNUSED] e_cparhdr
    dw 0                    ; [UNUSED] e_minalloc
    dw 0                    ; [UNUSED] e_maxalloc
    dw 0                    ; [UNUSED] e_ss
    dw 0                    ; [UNUSED] e_sp
    dw 0                    ; [UNUSED] e_csum
    dw 0                    ; [UNUSED] e_ip
    dw 0                    ; [UNUSED] e_cs
    dw 0                    ; [UNUSED] e_lfarlc
    dw 0                    ; [UNUSED] e_ovno
    times 4 dw 0            ; [UNUSED] e_res
    dw 0                    ; [UNUSED] e_oemid
    dw 0                    ; [UNUSED] e_oeminfo
    times 10 dw 0           ; [UNUSED] e_res2
    dd pe_hdr              ; e_lfanew
 
; PE Header
pe_hdr:
    dw 'PE', 0              ; Signature
 
; Image File Header
    dw 0x8664               ; Machine
    dw 0x01                 ; NumberOfSections
    dd 0                    ; [UNUSED] TimeDateStamp
    dd 0                    ; PointerToSymbolTable
    dd 0                    ; NumberOfSymbols
    dw opt_hdr_size        ; SizeOfOptionalHeader
    dw 0x22                 ; Characteristics
 
; Optional Header, COFF Standard Fields
opt_hdr:
    dw 0x020b              ; Magic (PE32+)
    db 0x0e                ; MajorLinkerVersion
    db 0x16                 ; MinorLinkerVersion
    dd code_size           ; SizeOfCode
    dd 0                    ; SizeOfInitializedData
    dd 0                    ; SizeOfUninitializedData
    dd entry               ; AddressOfEntryPoint
    dd file_size           ; BaseOfCode
 
; Optional Header, NT Additional Fields
    dq 0x000140000000       ; ImageBase
    dd 0x10                 ; SectionAlignment
    dd 0x10                 ; FileAlignment
    dw 0x06                 ; MajorOperatingSystemVersion
    dw 0                    ; MinorOperatingSystemVersion
    dw 0                    ; MajorImageVersion
    dw 0                    ; MinorImageVersion
    dw 0x06                 ; MajorSubsystemVersion
    dw 0                    ; MinorSubsystemVersion
    dd 0                    ; Reserved1
    dd file_size           ; SizeOfImage
    dd hdr_size            ; SizeOfHeaders
    dd 0                    ; CheckSum
    dw 0x02                 ; Subsystem (Windows GUI)
    dw 0x8160               ; DllCharacteristics
    dq 0x100000             ; SizeOfStackReserve
    dq 0x1000               ; SizeOfStackCommit
    dq 0x100000             ; SizeOfHeapReserve
    dq 0x1000               ; SizeOfHeapCommit
    dd 0                    ; LoaderFlags
    dd 0x02                 ; NumberOfRvaAndSizes
 
; Optional Header, Data Directories
    dd 0                      ; Export, RVA
    dd 0                      ; Export, Size
   
    dd import_descriptor     ; Import, RVA
    dd import_descriptor_size ; Import, Size
   
    dd 0                      ; Resources, RVA
    dd 0                      ; Resources, Size
 
opt_hdr_size equ $-opt_hdr
 
; Section Table
    section_name db '.text', 0, 0,0     ; Name
    times 8-($-section_name) db 0
    dd sect_size           ; VirtualSize
    dd virtual_address_text ; VirtualAddress
    dd code_size           ; SizeOfRawData
    dd ptr_to_raw_data_text ; PointerToRawData
    dd 0                    ; PointerToRelocations
    dd 0                    ; PointerToLinenumbers
    dw 0                    ; NumberOfRelocations
    dw 0                    ; NumberOfLinenumbers
    dd 0x60000020           ; Characteristics
sect_size equ $-$$ 
 
hdr_size equ $-$$
 
code_src:
section .idata
    ; Import Directory Entry for "user32.dll"
    import_descriptor:
        dq 0                    ; OriginalFirstThunk
        dq 0                    ; TimeDateStamp
        dd 0                    ; ForwarderChain
        dq import_address_table ; RVA to imported functions
        dq dll_name_1           ; Name of import dll
        dq import_name_table   ; RVA for inport name table
        dq 0                    ; Reserved
       
    import_descriptor_size equ $-import_descriptor
   
    ; Import Name Table for imported functions
    import_name_table:
        dq function_1_hint
        dq function_1_name
        dq 0                    ; null-terminator
   
    ; Import Address Table (IAT)
    import_address_table:
        dq 0
        dq 0
       
    function_1_name db 'MessageBoxA', 0
    function_1_hint dw 283

    dll_name_1: db 'user32.dll', 0
   
section .text
 
; Entry
entry:
  ret
  mov r9d, 0x00240040     ; uType
  lea r8, [rel title]    ; lpCaption
  lea rdx, [rel content] ; lpText
  xor ecx, ecx           ; hWnd
; ;mov rax, [rel iatbl]  ; MessageBoxN
  call rax

code_size equ $ - code_src
 
section .data
title:
    db "Hallo Welt !!!", 0
content:
    db "ABCDEFGHIJKL", 0

image_base dq 0x00400000

virtual_address_text dd $ - $$ + image_base
ptr_to_raw_data_text dd $ - $$

file_size equ $-$$

Fritzew 29. Okt 2023 19:42

AW: NASM - Erstellung eines Win64-Bit Images für die Verwendung mit mehr als 2 Funcca
 
Lade Dir die fpc sourcen und schaue da wie es gemacht wird. Zu glauben das chatgpt dir ne funktionierende Antwort gibt hat schon was von esoterisch 😀

paule32.jk 29. Okt 2023 19:48

AW: NASM - Erstellung eines Win64-Bit Images für die Verwendung mit mehr als 2 Funcca
 
naja. ich hatte gedacht, das ich mit Posting #3 nahe dran liege.
Es wird ja kommischerweise mit diesen #3 Codes ausgeführt. Allerdings sollte das jetzt mit weiteren Funktionen und DLL Dateien funktionieren.
Entweder die .DLL ist futsch, oder da steckt noch wo anders ein Fehler.

Kas Ob. 29. Okt 2023 19:55

AW: NASM - Erstellung eines Win64-Bit Images für die Verwendung mit mehr als 2 Funcca
 
Well I am sorry i can't find time to rebuild it for you now, i have guests :-D

But there is very visible problem with Image Base addresses
Code:
; Optional Header, NT Additional Fields
    dq 0x000140000000       ; ImageBase
Code:
image_base dq 0x00400000

virtual_address_text dd $ - $$ + image_base
Such miss addressing will render the PE unrecognizable for Windows.

paule32.jk 29. Okt 2023 19:58

AW: NASM - Erstellung eines Win64-Bit Images für die Verwendung mit mehr als 2 Funcca
 
this does the same as before, when I use:

; Optional Header, NT Additional Fields
dq image_base ; ImageBase

image_base dq 0x00400000

Kas Ob. 30. Okt 2023 12:10

AW: NASM - Erstellung eines Win64-Bit Images für die Verwendung mit mehr als 2 Funcca
 
Will try today or may till tomorrow and will build a working code for you, my interest started to grow in this for x64.

Kas Ob. 31. Okt 2023 14:55

AW: NASM - Erstellung eines Win64-Bit Images für die Verwendung mit mehr als 2 Funcca
 
This is working and i added few imports not used but for the sake of example to replicate, and hope it is clear
Code:
nasm -f bin Win64.asm -o Win64.exe
Code:
; win64.asm
SECTIONS   equ 2
TIME_DATE   equ 0
IMAGE_BASE        equ    0x000140000000 ;0x400000 ; org
SECTION_ALIGNMENT   equ     0x200
FILE_ALIGNMENT    equ      0x200

BSS_SIZE equ 0

%define nagoa_round(size) ((size + SECTION_ALIGNMENT - 1) & ~(SECTION_ALIGNMENT - 1))

bits 64
org IMAGE_BASE

section .text

;;******************************************************************************************************
;; if the header is part of the image, define it as section .text because .text is put
;; first in the image, and rename the code section as section .code

header:

   dw "MZ"                   ; e_magic
   dw 0                       ; e_cblp
   dw 0                       ; e_cp
   dw 0                       ; e_crlc
   dw 0                       ; e_cparhdr
   dw 0                       ; e_minalloc
   dw 0                       ; e_maxalloc
   dw 0                       ; e_ss
   dw 0                       ; e_sp
   dw 0                       ; e_csum
   dw 0                       ; e_ip
   dw 0                       ; e_cs
   dw 0                       ; e_lsarlc
   dw 0                       ; e_ovno
   dq 0                       ; e_res
   dw 0                       ; e_oemid
   dw 0                       ; e_oeminfo
   dd 0,0,0,0,0                    ; e_res2
   dd imageHeader - IMAGE_BASE   ; e_lfanew

imageHeader:

   dd "PE"               ; Signature
   dw 0x8664              ; Machine
   dw SECTIONS           ; NumberOfSections
   dd TIME_DATE          ; TimeDateStamp
   dd 0                   ; PointerToSymbolTable
   dd 0                   ; NumberOfSymbols
   dw optionalHeader.SIZE   ; SizeOfOptionalHeader
   dw 0x022               ; Characteristics

optionalHeader:

    dw 0x20B                      ; Magic
    db 0                           ; MajorLinkerVersion
    db 0                           ; MinorLinkerVersion
    dd nagoa_round(RAW_CODE.SIZE)   ; SizeOfCode
    dd nagoa_round(RAW_DATA.SIZE)   ; SizeOfInitializedData
    dd nagoa_round(BSS_SIZE)      ; SizeOfUninitializedData
    dd entryPoint                 ; AddressOfEntryPoint
    dd code                        ; BaseOfCode
    ;dd data - IMAGE_BASE          ; BaseOfData
    dq IMAGE_BASE                 ; ImageBase
    dd SECTION_ALIGNMENT          ; SectionAlignment
    dd FILE_ALIGNMENT             ; FileAlignment
    dw 4                           ; MajorOperatingSystemVersion
    dw 0                           ; MinorOperatingSystemVersion
    dw 0                           ; MajorImageVersion
    dw 0                           ; MinorImageVersion
    dw 4                           ; MajorSubsystemVersion
    dw 0                           ; MinorSubsystemVersion
    dd 0                           ; Win32VersionValue
    dd (RAW_HEADER.SIZE + RAW_CODE.SIZE + RAW_DATA.SIZE); SizeOfImage

    dd RAW_HEADER.SIZE            ; SizeOfHeaders
    dd 0                           ; CheckSum
    dw 2                           ; Subsystem
    dw 0                           ; DllCharacteristics
    dq 0x40000                     ; SizeOfStackReserve
    dq 0x6000                      ; SizeOfStackCommit
    dq 0x100000                    ; SizeOfHeapReserve
    dq 0x1000                      ; SizeOfHeapCommit
    dd 0                           ; LoaderFlags
    dd 16                          ; NumberOfRvaAndSizes
   dd 0, 0                        ; IMAGE_DIRECTORY_ENTRY_EXPORT
   dd Import_Directory_Table, Import_Directory_Table_Size                       ; IMAGE_DIRECTORY_ENTRY_IMPORT
   dd 0, 0                        ; IMAGE_DIRECTORY_ENTRY_RESOURCE
   dd 0, 0                        ; IMAGE_DIRECTORY_ENTRY_EXCEPTION
   dd 0, 0                        ; IMAGE_DIRECTORY_ENTRY_SECURITY
   dd 0, 0                        ; IMAGE_DIRECTORY_ENTRY_BASERELOC
   dd 0, 0                        ; IMAGE_DIRECTORY_ENTRY_DEBUG
   dd 0, 0                        ; IMAGE_DIRECTORY_ENTRY_COPYRIGHT
   dd 0, 0                        ; IMAGE_DIRECTORY_ENTRY_GLOBALPTR
   dd 0, 0                        ; IMAGE_DIRECTORY_ENTRY_TLS
   dd 0, 0                        ; IMAGE_DIRECTORY_ENTRY_LOAD_CONFIG
   dd 0, 0                        ; IMAGE_DIRECTORY_ENTRY_BOUND_IMPORT
   ;dd Import_Address_Table, Import_Address_Table_Size                       ; IMAGE_DIRECTORY_ENTRY_IAT
   dd 0,0
   dd 0, 0                        ; IMAGE_DIRECTORY_ENTRY_DELAY_IMPORT
   dd 0, 0                        ; IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR
   dd 0, 0                        ; reserved

optionalHeader.SIZE equ $ - optionalHeader

sectionHeaders:

    db ".text", 0, 0, 0            ; Name
    dd nagoa_round(RAW_CODE.SIZE)   ; VirtualSize
    dd code                       ; VirtualAddress
    dd RAW_CODE.SIZE              ; SizeOfRawData
    dd RAW_CODE.OFFSET            ; PointerToRawData
    dd 0                           ; PointerToRelocations
    dd 0                           ; PointerToLinenumbers
    dw 0                           ; NumberOfRelocations
    dw 0                           ; NumberOfLinenumbers
    dd 0x60000020                  ; Characteristics

    db ".data", 0, 0, 0            ; Name
    dd nagoa_round(RAW_DATA.SIZE)   ; VirtualSize
    dd data                       ; VirtualAddress
    dd RAW_DATA.SIZE              ; SizeOfRawData
    dd RAW_DATA.OFFSET            ; PointerToRawData
    dd 0                           ; PointerToRelocations
    dd 0                           ; PointerToLinenumbers
    dw 0                           ; NumberOfRelocations
    dw 0                           ; NumberOfLinenumbers
    dd 0xC0000040                  ; Characteristics

align FILE_ALIGNMENT, db 0
RAW_HEADER.SIZE equ $ - header

;;******************************************************************************************************
;;   F I R S T  . c o d e  S E C T I O N
;;******************************************************************************************************

VS_CODE   EQU ( ( ( 1 + ( (RAW_HEADER.SIZE-1) >> 12 ) ) * SECTION_ALIGNMENT ) )

section .code vstart=VS_CODE

   code:
   entryPoint:
      mov rcx,500
      call [rel Sleep]
      mov r9d, 0x00240040 ; uType
      lea r8, [rel title] ; lpCaption
      lea rdx, [rel content] ; lpText
      xor ecx, ecx ; hWnd
      call [rel MessageBoxA]
      mov rcx,500
      call [rel Sleep]
      mov r9d, 0x00240040 ; uType
      lea r8, [rel TITLE_W] ; lpCaption
      lea rdx, [rel CONTENT_W] ; lpText
      xor ecx, ecx ; hWnd
      call [rel MessageBoxW]
      jmp [rel ExitProcess]

   align SECTION_ALIGNMENT, db 0

;;******************************************************************************************************
;;   F I R S T  . d a t a  S E C T I O N
;;******************************************************************************************************

VS_DATA   EQU ( VS_CODE + ( ( 1 + ( (RAW_CODE.SIZE-1) >> 12 ) ) * SECTION_ALIGNMENT ) )

section .data vstart=VS_DATA
data :
    Import_Address_Table:
      DLL_1:
        Sleep:         dq I_Sleep
        ExitProcess:   dq I_ExitProcess
        GetStdHandle:  dq I_GetStdHandle
        dq              0
      DLL_2:
      MessageBoxA    dq I_MessageBoxA
      MessageBoxW    dq I_MessageBoxW
      dq              0
   Import_Address_Table_Size equ $ - Import_Address_Table
   
      align 0x20, db 0
        Import_Directory_Table:
            KERNEL32.originalfthk    dd DLL_1_thunk_table
            KERNEL32.timedate        dd 0 
            KERNEL32.forwarder       dd 0 
            KERNEL32.name            dd dll_name_1
            KERNEL32.firstthunk      dd DLL_1

            USER32.originalfthk    dd DLL_2_thunk_table
            USER32.timedate        dd 0 
            USER32.forwarder       dd 0 
            USER32.name            dd dll_name_2
            USER32.firstthunk      dd DLL_2
         
      align 0x20, db 0            ; should be always at the end of Import_Directory_Table
      
      Import_Directory_Table_Size equ $ - Import_Directory_Table

      DLL_1_thunk_table :
         dq I_Sleep
         dq   I_ExitProcess
         dq   I_GetStdHandle
         dq 0
      DLL_2_thunk_table :
         dq I_MessageBoxA
         dq   I_MessageBoxW
         dq 0
        I_Sleep:          
            dw               0
            db               'Sleep', 0 
            align            2 , db 0 
        I_ExitProcess:  
            dw               0 
            db               'ExitProcess', 0
            align            2 , db 0 
        I_GetStdHandle:
            dw               0 
            db               'GetStdHandle', 0
         align            2 , db 0 
        I_MessageBoxA:
            dw               0 
            db               'MessageBoxA', 0
         align            2 , db 0 
        I_MessageBoxW:
            dw               0 
            db               'MessageBoxW', 0
         align            2 , db 0 
        dll_name_1:            db 'kernel32.dll', 0
        dll_name_2:           db 'user32.dll', 0
   
    STRING_TABLE:
   %define u(x) __?utf16le?__(x)
   %define w(x) __?utf32le?__(x)
   title:
         db "Hello world !!!", 0
         align            2 , db 0 
   content:
         db "ABCDEFGHIJKL", 0
         align            2 , db 0    
   TITLE_W:         
         dw u("Hello World !!! in Unicode"),0
         align            2 , db 0 
   CONTENT_W:
         db u("ABCDEFGHIJKL"), 0
         align            2 , db 0 
   align SECTION_ALIGNMENT, db 0
;;******************************************************************************************************
;;   L A S T  . c o d e  S E C T I O N
;;******************************************************************************************************
section .code

align FILE_ALIGNMENT, db 0

RAW_CODE.OFFSET   equ RAW_HEADER.SIZE
RAW_CODE.SIZE   equ $ - $$

;;******************************************************************************************************
;;   L A S T  . d a t a  S E C T I O N
;;******************************************************************************************************
section .data

align FILE_ALIGNMENT, db 0

RAW_DATA.OFFSET   equ RAW_CODE.OFFSET + RAW_CODE.SIZE
RAW_DATA.SIZE   equ $ - $$

;;******************************************************************************************************

IMAGE_END equ $

;; -- eof --
It can use some cleaning, and it is two sections instead of one, this will minimize the confliction in page protection, but you can remove one and consolidate them in one section.

ps. i liked the idea of generating an EXE in from one file, no linker and no library, you called it flat and indeed seems flat, it was nice journey.

Kas Ob. 31. Okt 2023 14:58

AW: NASM - Erstellung eines Win64-Bit Images für die Verwendung mit mehr als 2 Funcca
 
:cry: i used Notepad++ and many tabs and now the text is dancing around :cry:

paule32.jk 31. Okt 2023 18:01

AW: NASM - Erstellung eines Win64-Bit Images für die Verwendung mit mehr als 2 Funcca
 
no problem for the formats of source code.
Thank you very much for your efforts !
I overlook the source on the fly, and I can create a Flat image, that work.
How did you get it working ?

For your interesst:
in the Time, you present your Source Solution, I worked on a Compiler/Transpiler that is used AsmJit, wich you can use, to create Assembly Code with C++.
My Environment is MSYS2 MinGW32/64.

It emulate a POSIX BASH Shell, with powerful Tools.

I create a Bash Shell script, to compile, and link the Applications.
It comes with a Lexer/Parser (pc.exe) - that should read-up Pascal Syntax, and form a AsmJit Assembly file.
This Assembly file can then reverse create AsmJit Assembly. So you have Pascal scripts that will be transpile to Assembly. And when you have Assembly source file, it will transpiled back to AsmJit, so you can do things like execute, and/or code injections.

Feel free, and drop a message - if you have Questions.

Kas Ob. 1. Nov 2023 08:03

AW: NASM - Erstellung eines Win64-Bit Images für die Verwendung mit mehr als 2 Funcca
 
Zitat:

Zitat von paule32.jk (Beitrag 1528800)
no problem for the formats of source code.
Thank you very much for your efforts !
I overlook the source on the fly, and I can create a Flat image, that work.
How did you get it working ?

You are welcome,
I have played with the PE headers for years, so this wasn't a problem, years ago when i am bored i just go and download viruses and trojans just to disassemble them and see how they work, it was fun and still, alas life doesn't have mercy and spare you time, any way if you are interested but be careful, i mean extra careful and use protection like dissect and run the on VM like Hyper-V, of course if you wish then see this https://github.com/Endermanch/MalwareDatabase
Again many scary things are there, but the things of manipulated are unimaginable.

Back to this PE header, first i tried to search the internet, very little i found, i thought there must be a ready solution like yours, but i couldn't found anything else than two examples, one on StackOverflow https://stackoverflow.com/questions/...-assembly-nasm also and few threads on NAsm forum https://forum.nasm.us/index.php?topic=1663.15

But this forum looks down now, it seems someone forgot to pay the hosting or something !!! and i can't recognize which is links from history as i spend hours in nice journey just reading more and more on PE and playing, never got to my mind to use NASM in such way, as i always use MASM with NotePad++ or RadAsm the IDE.
One section will definitely work but will have some serious red flags, also my implementation above is far from right to the one section, see memory pages should have right protection flag, but the sections above are 512b each and they are location on one page, Windows had no problem running it.
Also found this strange thing that Windows is in few places are very forgiving for wrong/incorrect/invalid values, addresses and alignment, but mostly aggressive with zero tolerance.

Anyway big chunk of that part is from the snippet in the nasm forum, which is existed in few threads and used as template, so i used it, the strange thing is, that thread called solved didn't work on my Windows 10 and didn't generate valid 32bit exe, so i changed and fixed the parameters to x64 and one extra DLLs imports.
For analyzing the content of the EXE i used Interactive Disassembler from HexRays, they have free (and limited) version https://hex-rays.com/ida-free/ but it is powerful, yet it deceived me as fixed a lot of the errors without my permission, very useful to walk everything in EXE not only assembly but structures and headers.
Also if you not familiar with Ghidra https://ghidra-sre.org/ then you are missing a lot, you will love it, and love its decompiler, yes full decompiler.


Zitat:

Zitat von paule32.jk (Beitrag 1528800)
For your interesst:
in the Time, you present your Source Solution, I worked on a Compiler/Transpiler that is used AsmJit, wich you can use, to create Assembly Code with C++.
My Environment is MSYS2 MinGW32/64.

It emulate a POSIX BASH Shell, with powerful Tools.

I create a Bash Shell script, to compile, and link the Applications.
It comes with a Lexer/Parser (pc.exe) - that should read-up Pascal Syntax, and form a AsmJit Assembly file.
This Assembly file can then reverse create AsmJit Assembly. So you have Pascal scripts that will be transpile to Assembly. And when you have Assembly source file, it will transpiled back to AsmJit, so you can do things like execute, and/or code injections.

Feel free, and drop a message - if you have Questions.

That is very interesting indeed, and it is nice and useful, i am sure will enjoy digging in it, and will come back with any questions or just nagging.

Kas Ob. 1. Nov 2023 08:11

AW: NASM - Erstellung eines Win64-Bit Images für die Verwendung mit mehr als 2 Funcca
 
One more thing, NASM looks may or less more powerful than MASM, both have great and extremely useful macro system, so in theory adding a DLL and with a list of import could be to just adding string to a list passed to a macro (defined function), was going to read and test it but it will take lot of reading and i wasn't sure it was worth it, thought you want it once for one dll and few imports.
Building these three lists to add a DLL and it imports and align may be doable.

paule32.jk 1. Nov 2023 11:41

AW: NASM - Erstellung eines Win64-Bit Images für die Verwendung mit mehr als 2 Funcca
 
beside NASM there are many examples for YASM - which seems be compatible.
NASM is the netwide Assembler.

And I will see, how the macros can help, too.
But, Thank you for your Effort.


Alle Zeitangaben in WEZ +1. Es ist jetzt 15:04 Uhr.

Powered by vBulletin® Copyright ©2000 - 2024, Jelsoft Enterprises Ltd.
LinkBacks Enabled by vBSEO © 2011, Crawlability, Inc.
Delphi-PRAXiS (c) 2002 - 2023 by Daniel R. Wolf, 2024 by Thomas Breitkreuz