1 # Example reading commandline arguments: compute length of first arg. 2 # 3 # To run: 4 # $ subx translate ex9.subx ex9 5 # $ subx run ex9 abc de fghi 6 # Expected result: 7 # $ echo $? 8 # 3 # length of 'abc' 9 # 10 # At the start of a SubX program: 11 # argc: *ESP 12 # argv[0]: *(ESP+4) 13 # argv[1]: *(ESP+8) 14 # ... 15 # Locals start from ESP-4 downwards. 16 17 == code 18 # instruction effective address operand displacement immediate 19 # op subop mod rm32 base index scale r32 20 # 1-3 bytes 3 bits 2 bits 3 bits 3 bits 3 bits 2 bits 2 bits 0/1/2/4 bytes 0/1/2/4 bytes 21 # var s = argv[1] (EBX) 22 8b/copy 1/mod/*+disp8 4/rm32/sib 4/base/ESP 4/index/none 3/r32/EBX 8/disp8 . # copy *(ESP+8) to EBX 23 # call ascii_length(EBX) 24 # prepare call 25 55/push . . . . . . . . # push EBP 26 89/copy 3/mod/direct 5/rm32/EBP . . . 4/r32/ESP . . # copy ESP to EBP 27 # push args 28 53/push . . . . . . . . # push EBX 29 # call 30 e8/call . . . . . . ascii_length/disp32 31 # discard args 32 5a/pop . . . . . . . . # pop into EDX 33 # clean up after call 34 89/copy 3/mod/direct 4/rm32/ESP . . . 5/r32/EBP . . # copy EBP to ESP 35 5d/pop . . . . . . . . # pop to EBP 36 37 # exit(EAX) 38 89/copy 3/mod/direct 3/rm32/EBX . . . 0/r32/EAX . . # copy EAX to EBX 39 b8/copy . . . . . . . 1/imm32/exit # copy 1 to EAX 40 cd/syscall . . . . . . . 0x80/imm8 # int 80h 41 42 ascii_length: # (s) 43 # initialize s (EDX) 44 8b/copy 1/mod/*+disp8 4/rm32/sib 4/base/ESP 4/index/none 2/r32/EDX 4/disp8 # copy *(ESP+4) to EDX 45 # var result = 0 (EAX) 46 b8/copy . . . . . . . 0/imm32 # copy 1 to EAX 47 $al_loop: 48 # var c = *s (ECX) 49 8a/copy 0/mod/* 2/rm32/EDX . . . 1/r32/ECX . . # copy byte at *EDX to lower byte of ECX 50 # if c == '\0' break 51 81 7/subop/compare 3/mod/direct 1/rm32/ECX . . . . . 0/imm32 # compare ECX with 0 52 74/jump-if-zero . . . . . . . $al_ret/disp8 # jump if equal 53 # ++s 54 81 0/subop/add 3/mod/direct 2/rm32/EDX . . . . . 1/imm32 # add 1 to EDX 55 # ++result 56 81 0/subop/add 3/mod/direct 0/rm32/EAX . . . . . 1/imm32 # add 1 to EAX 57 # loop 58 eb/jump . . . . . . . $al_loop/disp8 # jump $al_loop 59 $al_ret: 60 # return (result in EAX) 61 c3/return