test.py 12 KB
Newer Older
1
#!/usr/bin/python3
Igor Zhirkov's avatar
init  
Igor Zhirkov committed
2

Nikita Akatyev's avatar
Nikita Akatyev committed
3 4
__unittest = True

Igor Zhirkov's avatar
init  
Igor Zhirkov committed
5 6
import subprocess
import re
Nikita Akatyev's avatar
Nikita Akatyev committed
7
import unittest
Nikita Akatyev's avatar
Nikita Akatyev committed
8
import xmlrunner
Igor Zhirkov's avatar
init  
Igor Zhirkov committed
9 10 11 12 13
from subprocess import CalledProcessError, Popen, PIPE

#-------helpers---------------

def starts_uint( s ):
14
    matches = re.findall('^\d+', s)
Igor Zhirkov's avatar
init  
Igor Zhirkov committed
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
    if matches:
        return (int(matches[0]), len(matches[0]))
    else:
        return (0, 0)

def starts_int( s ):
    matches = re.findall('^-?\d+', s)
    if matches:
        return (int(matches[0]), len(matches[0]))
    else:
        return (0, 0)

def unsigned_reinterpret(x):
    if x < 0:
        return x + 2**64
    else:
        return x

def first_or_empty( s ):
    sp = s.split()
35
    if sp == [] :
Igor Zhirkov's avatar
init  
Igor Zhirkov committed
36 37 38 39 40 41
        return ''
    else:
        return sp[0]

#-----------------------------

42 43
before_all="""
%macro call 1
Igor Zhirkov's avatar
init  
Igor Zhirkov committed
44 45 46 47 48 49 50
mov rax, -1
push rbx
push rbp
push r12 
push r13 
push r14 
push r15 
51
call %1
Igor Zhirkov's avatar
init  
Igor Zhirkov committed
52
cmp r15, [rsp] 
53
jne convention_error
Igor Zhirkov's avatar
init  
Igor Zhirkov committed
54 55
pop r15
cmp r14, [rsp] 
56
jne convention_error
Igor Zhirkov's avatar
init  
Igor Zhirkov committed
57 58
pop r14
cmp r13, [rsp] 
59
jne convention_error
Igor Zhirkov's avatar
init  
Igor Zhirkov committed
60 61
pop r13
cmp r12, [rsp] 
62
jne convention_error
Igor Zhirkov's avatar
init  
Igor Zhirkov committed
63 64
pop r12
cmp rbp, [rsp] 
65
jne convention_error
Igor Zhirkov's avatar
init  
Igor Zhirkov committed
66 67
pop rbp
cmp rbx, [rsp] 
68
jne convention_error
Igor Zhirkov's avatar
init  
Igor Zhirkov committed
69
pop rbx
70 71 72 73 74 75 76 77
mov rdi, -1
mov rsi, -1
mov rcx, -1
mov r8, -1
mov r9, -1
mov r10, -1
mov r11, -1
%endmacro
Igor Zhirkov's avatar
init  
Igor Zhirkov committed
78

79
%include "lib.inc"
Igor Zhirkov's avatar
init  
Igor Zhirkov committed
80

81 82 83 84
global _start

section .text
convention_error:
Igor Zhirkov's avatar
init  
Igor Zhirkov committed
85 86 87
    mov rax, 1
    mov rdi, 2
    mov rsi, err_calling_convention
88
    mov rdx, err_calling_convention.end - err_calling_convention
Igor Zhirkov's avatar
init  
Igor Zhirkov committed
89 90 91 92
    syscall
    mov rax, 60
    mov rdi, -41
    syscall
93

Igor Zhirkov's avatar
init  
Igor Zhirkov committed
94
section .data
95 96
    err_calling_convention: db "You did not respect the calling convention! Check that you handled caller-saved and callee-saved registers correctly", 10
    .end:
Igor Zhirkov's avatar
init  
Igor Zhirkov committed
97
"""
Nikita Akatyev's avatar
Nikita Akatyev committed
98 99 100 101 102 103 104 105 106 107 108

class IOLibraryTest(unittest.TestCase):
    def compile(self, fname, text):
        f = open( fname + '.asm', 'w')
        f.write( text )
        f.close()

        self.assertEqual(subprocess.call( ['nasm', '-f', 'elf64', fname + '.asm', '-o', fname+'.o'] ), 0, 'failed to compile')
        self.assertEqual(subprocess.call( ['ld', '-o' , fname, fname+'.o'] ), 0, 'failed to link')

    def launch(self, fname, input):
109
        output = b''
Nikita Akatyev's avatar
Nikita Akatyev committed
110 111
        try:
            p = Popen(['./'+fname], shell=None, stdin=PIPE, stdout=PIPE)
112
            (output, _) = p.communicate(input.encode())
Nikita Akatyev's avatar
Nikita Akatyev committed
113
            self.assertNotEqual(p.returncode, -11, 'segmentation fault')
114
            return (output.decode(), p.returncode)
Nikita Akatyev's avatar
Nikita Akatyev committed
115
        except CalledProcessError as exc:
Nikita Akatyev's avatar
Nikita Akatyev committed
116
            self.assertNotEqual(exc.returncode, -11, 'segmentation fault')
117
            return (exc.output.decode(), exc.returncode)
Nikita Akatyev's avatar
Nikita Akatyev committed
118 119

    def perform(self, fname, text, input):
120
        self.compile(fname, before_all + text)
Nikita Akatyev's avatar
Nikita Akatyev committed
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160
        return self.launch(fname, input)



    def test_string_length(self):
        inputs = ['asdkbasdka', 'qwe qweqe qe', '']
        for input in inputs:
            text = """
section .data
str: db '""" + input + """', 0

section .text
_start:
    mov rdi, str
    call string_length
    mov rdi, rax
    mov rax, 60
    syscall
"""
            (output, code) = self.perform('string_length', text, input)
            self.assertEqual(code, len(input), 'string_length(%s) returned wrong length: %d' % (repr(input), code))



    def test_print_string(self):
        inputs = ['ashdb asdhabs dahb', ' ', '']
        for input in inputs:
            text = """
section .data
str: db '""" + input + """', 0

section .text
_start:
    mov rdi, str
    call print_string
    xor rdi, rdi
    mov rax, 60
    syscall
"""
            (output, code) = self.perform('print_string', text, input)
161
            self.assertEqual(output, input, 'print_string(%s) printed wrong string: %s' % (repr(input), repr(output)))
Nikita Akatyev's avatar
Nikita Akatyev committed
162 163 164 165 166 167 168 169 170



    def test_string_copy(self):
        inputs = ['ashdb asdhabs dahb', ' ', '']
        for input in inputs:
            text = """
section .data
arg1: db '""" + input + """', 0
171
arg2: times """ + str(len(input) + 1) + """ db  66
Nikita Akatyev's avatar
Nikita Akatyev committed
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186

section .text
_start:
    mov rdi, arg1
    mov rsi, arg2
    mov rdx, """ + str(len(input) + 1) + """
    call string_copy

    mov rdi, arg2 
    call print_string
    mov rax, 60
    xor rdi, rdi
    syscall
"""
            (output, code) = self.perform('string_copy', text, input)
187
            self.assertEqual(output, input, 'string_copy(%s) put wrong string into buffer: %s' % (repr(input), repr(output)))
Nikita Akatyev's avatar
Nikita Akatyev committed
188 189 190 191 192 193 194 195 196 197 198 199



    def test_string_copy_too_long(self):
        inputs = ['ashdb asdhabs dahb', ' ', '']
        for input in inputs:
            text = """
section .rodata
err_too_long_msg: db "string is too long", 10, 0

section .data
arg1: db '""" + input + """', 0
200
arg2: times """ + str(len(input)//2) + """ db  66
Nikita Akatyev's avatar
Nikita Akatyev committed
201 202 203 204 205

section .text
_start:
    mov rdi, arg1
    mov rsi, arg2
206
    mov rdx, """ + str(len(input)//2) + """
Nikita Akatyev's avatar
Nikita Akatyev committed
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
    call string_copy
    test rax, rax
    jnz .good
    mov rdi, err_too_long_msg 
    call print_string
    jmp _exit
    .good:
    mov rdi, arg2 
    call print_string
_exit:
    mov rax, 60
    xor rdi, rdi
    syscall
"""
            (output, code) = self.perform('string_copy_too_long', text, input)
222
            self.assertNotEqual(output.find('too long'), -1, 'string_copy(%s) should have failed, but returned: %s' % (repr(input), repr(output)))
Nikita Akatyev's avatar
Nikita Akatyev committed
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238



    def test_print_char(self):
        inputs = ['a', ' ', 'c']
        for input in inputs:
            text = """
section .text
_start:
    mov rdi, '""" + input + """'
    call print_char
    mov rax, 60
    xor rdi, rdi
    syscall
"""
            (output, code) = self.perform('print_char', text, input)
239
            self.assertEqual(output, input, 'print_char(%s) printed wrong char: %s' % (repr(input), repr(output)))
Nikita Akatyev's avatar
Nikita Akatyev committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256



    def test_print_uint(self):
        inputs = ['-1', '12345234121', '0', '12312312', '123123']
        for input in inputs:
            text = """
section .text
_start:
    mov rdi, """ + input + """
    call print_uint
    mov rax, 60
    xor rdi, rdi
    syscall
"""
            (output, code) = self.perform('print_uint', text, input)
            uinput = str(unsigned_reinterpret(int(input)))
257
            self.assertEqual(output, uinput, 'print_uint(%s) printed wrong number: %s, expected: %s' % (repr(input), repr(output), repr(uinput)))
Nikita Akatyev's avatar
Nikita Akatyev committed
258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273



    def test_print_int(self):
        inputs = ['-1', '-12345234121', '0', '123412312', '123123']
        for input in inputs:
            text = """
section .text
_start:
    mov rdi, """ + input + """
    call print_int
    mov rax, 60
    xor rdi, rdi
    syscall
"""
            (output, code) = self.perform('print_int', text, input)
274
            self.assertEqual(output, input, 'print_int(%s) printed wrong number: %s' % (repr(input), repr(output)))
Nikita Akatyev's avatar
Nikita Akatyev committed
275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318



    def test_read_char(self):
        inputs = ['-1', '-1234asdasd5234121', '', '   ', '\t   ', 'hey ya ye ya', 'hello world' ]
        for input in inputs:
            text = """
section .text
_start:
    call read_char
    mov rdi, rax
    mov rax, 60
    syscall
"""
            (output, code) = self.perform('read_char', text, input)
            if input == "":
                self.assertEqual(code, 0, 'read_char with empty input should return 0')
            else:
                self.assertEqual(code, ord(input[0]), 'read_char(%d) returned incorrect char: %d' % (ord(input[0]), code))



    def test_read_word(self):
        inputs = ['-1'] # , '-1234asdasd5234121', '', '   ', '\t   ', 'hey ya ye ya', 'hello world' ],

        for input in inputs:
            text = """
section .data
word_buf: times 20 db 0xca

section .text
_start:
    mov rdi, word_buf
    mov rsi, 20 
    call read_word
    mov rdi, rax
    call print_string

    mov rax, 60
    xor rdi, rdi
    syscall
"""
            (output, code) = self.perform('read_word', text, input)
            input_word = first_or_empty(input)
319
            self.assertEqual(output, input_word, 'read_word(%s) put incorrect word in the buffer: %s, expected: %s' % (repr(input), repr(output), repr(input_word)))
Nikita Akatyev's avatar
Nikita Akatyev committed
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391



    def test_read_word_length(self):
        inputs = ['-1', '-1234asdasd5234121', '', '   ', '\t   ', '\t   123', 'hey ya ye ya', 'hello world' ]
        for input in inputs:
            text = """
section .data
word_buf: times 20 db 0xca

section .text
_start:
    mov rdi, word_buf
    mov rsi, 20 
    call read_word
    mov rax, 60
    mov rdi, rdx
    syscall
"""
            (output, code) = self.perform('read_word_length', text, input)
            input_word = first_or_empty(input)
            self.assertEqual(code, len(input_word), 'read_word(%s) returned incorrect length: %d, expected: %d' % (repr(input), code, len(input_word)))



    def test_read_word_too_long(self):
        inputs = [ 'asdbaskdbaksvbaskvhbashvbasdasdads wewe', 'short' ]
        for input in inputs:
            text = """
section .data
stub: times 5 db 0xca
word_buf: times 20 db 0xca

section .text
_start:
    mov rdi, word_buf
    mov rsi, 20 
    call read_word
    mov rdi, rax
    mov rax, 60
    syscall
"""
            (output, code) = self.perform('read_word_too_long', text, input)
            input_word = first_or_empty(input)
            if len(input_word) > 19:
                self.assertEqual(code, 0, 'read_word(%s) overflows buffer, but does not fail' % repr(input))
            else:
                self.assertNotEqual(code, 0, 'read_word(%s) does not overflow buffer, but fails' % repr(input))



    def test_parse_uint(self):
        inputs = ["0", "1234567890987654321hehehey", "1" ]
        for input in inputs:
            text = """
section .data
input: db '""" + input  + """', 0

section .text
_start:
    mov rdi, input
    call parse_uint
    push rdx
    mov rdi, rax
    call print_uint
    mov rax, 60
    pop rdi
    syscall
"""
            (output, code) = self.perform('parse_uint', text, input)
            (input_num, input_len) = starts_uint(input)

392
            self.assertEqual(output, str(input_num), 'parse_uint(%s) parsed wrong number: %s, expected: %s' % (repr(input), repr(output), repr(str(input_num))))
Nikita Akatyev's avatar
Nikita Akatyev committed
393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418
            self.assertEqual(code, input_len, 'parse_uint(%s) returned wrong length: %d, expected: %d' % (repr(input), code, input_len))



    def test_parse_int(self):
        inputs = ["0", "1234567890987654321hehehey", "-1dasda", "-eedea", "-123123123", "1" ]
        for input in inputs:
            text = """
section .data
input: db '""" + input  + """', 0

section .text
_start:
    mov rdi, input
    call parse_int
    push rdx
    mov rdi, rax
    call print_int
    mov rax, 60
    pop rdi
    syscall
"""
            (output, code) = self.perform('parse_int', text, input)
            (input_num, input_len) = starts_int(input)

            if input_len == 0:
419
                self.assertEqual(output, '0', 'parse_int(%s) should have failed, but parsed %s' % (repr(input), output))
Nikita Akatyev's avatar
Nikita Akatyev committed
420
            else:
421
                self.assertEqual(output, str(input_num), 'parse_int(%s) parsed wrong number: %s, expected: %s' % (repr(input), repr(output), repr(str(input_num))))
Nikita Akatyev's avatar
Nikita Akatyev committed
422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
                self.assertEqual(code, input_len, 'parse_int(%s) returned wrong length: %d, expected: %d' % (repr(input), code, input_len))



    def test_string_equals(self):
        inputs = ['ashdb asdhabs dahb', ' ', '', "asd" ]
        for input in inputs:
            text = """
section .data
str1: db '""" + input + """',0
str2: db '""" + input + """',0

section .text
_start:
    mov rdi, str1
    mov rsi, str2
    call string_equals
    mov rdi, rax
    mov rax, 60
    syscall
"""
            (output, code) = self.perform('string_equals', text, input)
            self.assertEqual(code, 1, 'string_equals(%s, %s) should return 1' % (repr(input), repr(input)))



    def test_string_not_equals(self):
        inputs = ['ashdb asdhabs dahb', ' ', '', "asd" ]
        for input in inputs:
            text = """
section .data
str1: db '""" + input + """',0
str2: db '""" + input + """!!',0

section .text
_start:
    mov rdi, str1
    mov rsi, str2
    call string_equals
    mov rdi, rax
    mov rax, 60
    syscall
"""
            (output, code) = self.perform('string_not_equals', text, input)
            self.assertEqual(code, 0, 'string_equals(%s, %s!!) should return 0' % (repr(input), repr(input)))



Igor Zhirkov's avatar
init  
Igor Zhirkov committed
470
if __name__ == "__main__":
Nikita Akatyev's avatar
Nikita Akatyev committed
471 472
    with open('report.xml', 'w') as report:
        unittest.main(testRunner=xmlrunner.XMLTestRunner(output=report), failfast=False, buffer=False, catchbreak=False)