2

我正在尝试使用一些 Unix 系统调用自学一些 NASM x86 程序集。我正在尝试创建一个简单的 TCP 服务器,并且在 send() 命令之前我一直在运行代码。我可以通过 telnet 进行连接,但是一旦我的代码到达尝试向客户端发送响应的位置,就会出现段错误。

这是产生段错误的代码段:

; push on to stack for send
push    dword   0
push    dword   [start_len]
push    dword   [start]
push    dword   [socket]

; send something back
; THIS IS WHERE THE SEGFAULT OCCURS
mov eax,102
mov ebx,9 ; send is 9
mov ecx,esp
int 80h

如果有人想看的话,这里是完整的源代码。任何帮助将不胜感激!

; constants go here
section .data
    start: db 'Starting Socket...',0
    start_len: equ $-start

; variables go here
section .bss
    socket: resd   1 ; store the fd for the socket
    socket_address: resd    2 ; socket address

; starttttt
section .text
    global _start

open_socket:

    ; print we are starting
    mov eax,4
    mov ebx,1
    mov ecx,start
    mov edx,start_len
    int 80h

    ; push values to stack to make call
    ; values go in in opposite order, so when they are popped
    ; it is the correct order
    ; below is for a tcp socket
    push    dword   6
    push    dword   1
    push    dword   2

    ; make call to open socket
    mov eax,102 ; 102 is the call to open socket
    mov ebx,1 ; sub call, socket()
    mov ecx,esp
    int 80h

    ; store the file descriptor for the socket
    mov dword[socket],eax

    ; this is the socket address to bind to
    push    dword   0x00000000 ; localhost (127.0.0.1)
    push    dword   0x2823 ; port 9000
    push    word    2 ; AF_INET (IPv4)
    mov [socket_address],esp ; move to our socket address variable

    ; setup parameters for bind call bind(socket, socket_address, 16)
    push    dword  16
    push    dword   [socket_address]
    push    dword   [socket]

    ; call subcall for socket to bind
    mov eax,102; sys_socket 
    mov ebx,2 ; subcall 2 = bind()
    mov ecx,esp ; push vars from stack to params
    int 80h

    ; setup parameters for listen()
    push    byte    20
    push    dword   [socket]

    ; call listen()
    mov eax,102 ; socket call
    mov ebx,4 ; subcall listen()
    mov ecx,esp ; move stack as variables
    int 80h

    ; now we have to accept incoming connections...
    ; setup the call
    push    0
    push    0
    push    dword   [socket]

    ; call accept()
    mov eax,102
    mov ebx,5
    mov ecx,esp
    int 80h

    ; push on to stack for send
    push    dword   0
    push    dword   [start_len]
    push    dword   [start]
    push    dword   [socket]

    ; send something back
    ; THIS IS WHERE THE SEGFAULT OCCURS
    mov eax,102
    mov ebx,9 ; send is 9
    mov ecx,esp
    int 80h

; function to exit the program
exit:
    mov eax,1
    mov ebx,0
    int 80h

; main function to be called
_start:

    ; open it
    call open_socket
4

0 回答 0