array1.asm

array1.asm
%define ARRAY_SIZE 100
%define NEW_LINE 10
segment .data
FirstMsg db "First 10 elements of array",0
Prompt db "Enter index of element to display: ",0
SecondMsg db "Element %d is %d", NEW_LINE,0
ThirdMsg db "Elemetns 20 through 29 of array",0
InputFOrmat db "%d",0
segment .bss
array resd ARRAY_SIZE
segment .text
extern _puts, _printf, _scanf, _dump_line
global _asm_main
global_main:
enter 4,0
push ebx
push esi
;배열을 100,99,98,97, ... 로 정의
mov ecx, ARRAY_SIZE
mov ebx, array
init_loop:
mov [ebx], ecx
add ebx, 4
loop init_loop
push dword FirstMsg ;FirstMsg 를 출력
call _puts
pop ecx
push dword 10
push dword array
call _print_array
add esp, 8
; prompt user for element index
Prompt_loop:
push dword Prompt
call _printf
pop ecx
lea eax, [ebp-4] ;eax=지역 더블워드의 주소
push eax
push dword InputFormat
call _scanf
add esp, 8
cmp eax, 1 ;eax=scanf의 리턴값
je InputOK
call _dump_line ;나머지 행을 덤프한 후 재시작
jmp Prompt_loop ;입력값이 올바르지 않다면 분기
InputOK:
mov esi, [ebp-4]
push dword [array+4*esi]
push esi
push dword SecondMsg ;원소값을 출력
call _printf
add esp, 12
push dword ThirdMsg ;원소 20-29의 값을 출력
call _puts
pop ecx
push dword 10
push dword array+20*4 ;array[20]의 주소
call _print_array
add esp, 8
pop esi
pop ebx
mov eax, 0
leave
ret
;
; _print_array 루틴
; C 호출 가능한 루틴으로, 더블워드 배열의 원소들을 부호 있는 정수로 출력한다.
; C 원형:
; void print_array(const int * a, int n);
; 인자:
; a-출력할 배열에 대한 포인터(스택의 ebp+8에 위치)
; n-출력할 정수의 개수 (스택의 ebp+12)에 위치
segment .data
OutputFormat db "%-5d %d", NEW_LINE,0
segment .text
global _print_array
_print_array:
enter 0,0
push esi
push ebx
xor esi, esi
mov ecx, [ebp+12]
mov ebx, [ebp+8]
print_loop:
push ecx
push dword [ebx+4*esi]
push esi
push dword OutputFormat
call _printf
add esp, 12
inc esi
pop ecx
loop print_loop
pop ebx
pop esi
leave
ret
array1c.c
#include <stdio.h>
int asm_main(void);
void dump_line(void);
int main()
{
int ret_status;
ret_status=asm_main();
return ret_status;
}
/*
*함수 dump_line
*입력 버퍼로부터 현재행에 남은 모든 문자(char)를 덤프한다.
*/
void dump_line()
{
int ch;
while((ch=getchar())!=EOF && ch!='\n'){
/* NULL BODY */
}
}