.global _start
_start:
mov 0ドルx1000,%edx
mov %edx,%eax
neg %eax
and %eax,%esp
mov %esp,%ecx
xor %ebx,%ebx
mov 3,ドル%eax
int 0ドルx80
add %edx,%esp
mov %ecx,%edi
mov $label00,%ebp
jmp parse_eax_load_constants
label00:
push %eax
inc %edi
mov $label01,%ebp
jmp parse_eax
label01:
mov %edi,%ebp
mov %esi,(%edi)
dec %edi
pop %edx
add %edx,%eax # finally
print_eax: # %edi: where to print %eax
xor %edx,%edx
div %esi
or %cl,%dl
mov %dl,(%edi)
dec %edi
test %eax,%eax
jnz print_eax
mov %ebp,%edx
sub %edi,%edx
inc %edi
mov %edi,%ecx
xor %ebx,%ebx
inc %ebx
mov 4,ドル%eax
int 0ドルx80
mov %ebx,%eax
int 0ドルx80
parse_eax_load_constants:
mov 10,ドル%esi
mov 0ドルx30,%ecx
parse_eax: # %edi: the string to parse
xor %eax,%eax
movb (%edi),%al
mov %edi,%ebx
inc %ebx
cmpb 0ドルx2d,%al
cmovz %ebx,%edi
setz %bl
push %ebx
mov (%edi),%al
xor %ebx,%ebx
xor %cl,%al
parse_eax_loop:
inc %edi
movb (%edi),%bl
xor %cl,%bl
cmp %esi,%ebx
jae parse_eax_end
mul %esi
add %ebx,%eax
jmp parse_eax_loop
parse_eax_end:
pop %ebx
mov %eax,%edx
neg %edx
test %bl,%bl
cmovnz %edx,%eax
jmp *%ebp
-
4\$\begingroup\$ You have to provide some context to the code, otherwise you won't get appropriate reviews. Why did you write it this way? \$\endgroup\$Roland Illig– Roland Illig2017年04月24日 04:56:33 +00:00Commented Apr 24, 2017 at 4:56
-
\$\begingroup\$ @RolandIllig I wrote this assembly as an exercise; and also to learn i386 assembly(from a x86_64 background) \$\endgroup\$user69874– user698742017年04月24日 05:37:05 +00:00Commented Apr 24, 2017 at 5:37
2 Answers 2
You are asking for a code review, and my first bit of feedback is: COMMENTS.
Please, reading raw assembler is a challenge. Start by a comment block at the top that describes the purpose of the code, then consider line-by-line comments, something like this: https://codereview.stackexchange.com/a/156947/110050
-
\$\begingroup\$ I had the exact same reaction when I saw the code, ++ \$\endgroup\$Phrancis– Phrancis2017年04月24日 04:37:02 +00:00Commented Apr 24, 2017 at 4:37
Reusing the constant 1 for both STDOUT_FILENO
and SYS_EXIT
is confusing to the human reader. You should prefer to write clear code instead of using these tricks.
Same for the jmp *%ebp
.
-
\$\begingroup\$ I definitely won't be using these "tricks" in a compiled language, but here there is no compiler to simplify human-readable code. I'm trading readability for performance here. The same goes with the jump, since there are only single-depth call stack the register is used for performance(avoids memory access). As an added bonus, this code is impervious to Remote Code Execution(RCE) via return pointers on the stack. \$\endgroup\$user69874– user698742017年04月24日 05:41:45 +00:00Commented Apr 24, 2017 at 5:41