1

My objective is to open a socket, connect to that socket on a port, and then whenever that socket sends data to me, I want to write it to stdout. My code works fine, but for some reason the string that is writing doesn't null terminate? I'm not so sure what the issue is and I have yet to find anything online about it.

#socket(2,1,0)
li      $t7, -6
nor     $t7, $t7, $zero
addi    $a0, $t7, -3
addi    $a1, $t7, -3
slti    $a2, $zero, -1
li      $v0, 4183
syscall 0x40404
sw      $v0, -4($sp)
#connect(3, &addr, 16)
lw      $a0, -4($sp)
li      $t7, -3
nor     $t7, $t7, $zero
sw      $t7,-32($sp)
lui     $t6,0x7a69
ori     $t6,$t6,0x7a69
sw      $t6, -28($sp)
lui     $t5, 0x7F00
ori     $t5, $t5, 0x1
sw      $t5, -26($sp)
addiu   $a1, $sp, -30
li      $t4, -17
nor     $a2, $t4, $zero
li      $v0, 4170
syscall 0x40404

#read(3, addr, 50)
nex:
    lw      $a0, -4($sp)
    addiu   $a1, $sp,-64
    li      $a2, 50
    addi    $a2, $a2, -1
    li      $v0, 4003
    syscall 0x40404
    beqz    $a3, next
    move    $a2,$v0
    negu    $a2,$v0
next:
    blez    $a2,nextt
    #write(1, addr, 50)
    li $a0, 1
    li $v0, 4004
    syscall 0x40404
    j nex
nextt:

Here is the strace of me writing a\n to the socket, and it writing a\n\0\0\0\0\0\0\0\0 to stdout.

socket(PF_INET, SOCK_STREAM, IPPROTO_IP) = 3
connect(3, {sa_family=AF_INET, sin_port=htons(31337), sin_addr=inet_addr("127.0.0.1")}, 16) = 0
read(3, "a\n", 49)                      = 2
write(1, "a\n\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"..., 49a
zi3▒ݤ) = 49

As you can see, it prints out some weird characters at the end. Thanks for any help!

1 Answers1

1

Notice in your strace output that your read syscall returns a value of 2 [in $v0].

Also notice that your write syscall has a length much greater than 2.

After your read syscall you have:

    move    $a2,$v0    # this reg has 2
    negu    $a2,$v0    # BUG: this changes it to -2 (0xFFFFFFFE)

The length for the write was interpreted as an unsigned number [and a very large one]

Change this to just [i.e. remove the negu]:

    move    $a2,$v0
Craig Estey
  • 30,627
  • 4
  • 24
  • 48
  • It's also worth noting that, "beqz $a3, next" should be taken out as it will cause a never ending loop. Thank you for this!! – Spencer Fuples Jun 07 '16 at 04:39
  • Yes, you are correct, and I _had_ noticed that. But, I wanted to solve your primary problem quickly [and I figured you find it yourself ;-)]. Also, I'd do a sweep and add return value checks on all your syscalls (e.g. -1=error, etc.). And, I'd put sidebar comments on each line that show intent. See my answer here http://stackoverflow.com/a/36560575/5382650 for an explanation of what I mean [and other asm tips] – Craig Estey Jun 07 '16 at 04:52
  • Okay, I don't know assembly too well and its great to know that at least someone knows about it. It's so hard to find information online for a specific problem – Spencer Fuples Jun 07 '16 at 04:59