Architecture / ISA
Beginner
QtSpim / SPIM / MARS
QtSpim / MARS 시뮬레이터 MIPS syscall 입출력(I/O) 및 서비스 코드 가이드MIPS Syscall I/O and Service Code Guide for QtSpim and MARS Simulators
MIPS 시뮬레이터(QtSpim, SPIM, MARS) 환경에서 시스템 콜($v0)을 이용한 정수·문자열 콘솔 출력, 사용자 입력 수신, 힙 메모리 할당 및 프로그램 종료 구현 방법입니다.Implementing console integer/string output, user input reading, heap allocation, and clean program termination using system calls ($v0) in MIPS simulators (QtSpim, SPIM, MARS).
#MIPS #Assembly #QtSpim #Syscall #IO
핵심 개념MIPS 시뮬레이터(QtSpim, MARS 등)에서 화면 출력이나 키보드 입력 같은 운영체제 I/O 서비스를 요청할 때는
$v0 레지스터에 서비스 번호를 적재하고 필요한 인자를 $a0, $a1 등에 배치한 후 syscall 명령어를 호출합니다.Key ConceptTo request operating system I/O services such as console printing or keyboard input in MIPS simulators (QtSpim, MARS), load the service code into register
$v0, place the required arguments in $a0 and $a1, and execute the syscall instruction.1. 주요 Syscall 서비스 코드 일람표1. Primary Syscall Service Code Reference
좌우로 밀어서 표 전체 내용을 확인하세요
| 서비스 ($v0) | 기능 | 입력 인자 | 출력/반환값 |
|---|---|---|---|
| 1 | Print Integer | $a0 = 출력할 정수 | - |
| 4 | Print String | $a0 = null 종단 문자열 주소 | - |
| 5 | Read Integer | - | $v0 = 입력받은 정수 |
| 8 | Read String | $a0 = 버퍼 주소, $a1 = 최대 길이 | 버퍼에 문자열 저장 |
| 9 | Sbrk (Heap 할당) | $a0 = 할당할 바이트 수 | $v0 = 할당된 힙 메모리 주소 |
| 10 | Exit (프로그램 종료) | - | 시뮬레이터 실행 중단 |
| 11 | Print Character | $a0 = ASCII 문자 코드 | - |
Swipe horizontally to view the full table
| Service ($v0) | Function | Input Arguments | Output / Return Value |
|---|---|---|---|
| 1 | Print Integer | $a0 = integer to print | - |
| 4 | Print String | $a0 = address of null-terminated string | - |
| 5 | Read Integer | - | $v0 = integer read from console |
| 8 | Read String | $a0 = buffer address, $a1 = max length | Writes string into buffer |
| 9 | Sbrk (Heap Allocate) | $a0 = number of bytes to allocate | $v0 = address of allocated heap block |
| 10 | Exit (Terminate) | - | Halts simulator execution |
| 11 | Print Character | $a0 = ASCII character code | - |
2. 사용자 입력 및 출력 종합 어셈블리 예제2. Complete User Input and Output Assembly Example
.data
prompt: .asciiz "정수를 입력하세요: "
result_msg: .asciiz "입력한 정수의 두 배는: "
newline: .asciiz "\n"
.text
.globl main
main:
# 1. 안내 문자열 출력 (Service 4: print_string)
li $v0, 4
la $a0, prompt
syscall
# 2. 사용자 정수 입력 받기 (Service 5: read_int)
li $v0, 5
syscall
move $t0, $v0 # 입력받은 값을 $t0에 저장
# 3. 연산 수행 (2배 곱하기)
sll $t1, $t0, 1 # $t1 = $t0 * 2 (좌측 시프트 1비트)
# 4. 결과 안내 문자열 출력
li $v0, 4
la $a0, result_msg
syscall
# 5. 연산 결과 정수 출력 (Service 1: print_int)
li $v0, 1
move $a0, $t1 # 출력할 값을 $a0에 배치
syscall
# 6. 줄바꿈 출력
li $v0, 4
la $a0, newline
syscall
# 7. 프로그램 안전 종료 (Service 10: exit)
li $v0, 10
syscall
.data
prompt: .asciiz "Enter an integer: "
result_msg: .asciiz "Double the input integer is: "
newline: .asciiz "\n"
.text
.globl main
main:
# 1. Print prompt string (Service 4: print_string)
li $v0, 4
la $a0, prompt
syscall
# 2. Read integer from user (Service 5: read_int)
li $v0, 5
syscall
move $t0, $v0 # Store input value in $t0
# 3. Perform arithmetic (multiply by 2)
sll $t1, $t0, 1 # $t1 = $t0 * 2 (logical left shift by 1 bit)
# 4. Print result label string
li $v0, 4
la $a0, result_msg
syscall
# 5. Print computed integer result (Service 1: print_int)
li $v0, 1
move $a0, $t1 # Place output integer in $a0
syscall
# 6. Print newline
li $v0, 4
la $a0, newline
syscall
# 7. Terminate program cleanly (Service 10: exit)
li $v0, 10
syscall
3. 실무 적용 및 주의사항3. Practical Considerations and Caveats
exit(서비스 10) 누락 주의:main라벨 끝에서syscall 10을 호출하지 않으면 PC 카운터가 아래쪽 메모리 영역으로 계속 진행하여 정의되지 않은 명령어(Invalid Instruction) 예외가 발생합니다.- 문자열 버퍼 오버플로우 방지: Service 8(
read_string) 사용 시$a1에 반드시 버퍼의 최대 바이트 크기(종단\0포함)를 지정해야 인접한.data변수가 덮어써지는 현상을 막을 수 있습니다. .asciiz와.ascii구분: Service 4(print_string)는 널 종단 문자(\0)를 만날 때까지 메모리를 읽으므로, 문자열 선언 시 널 문자를 자동 추가하는.asciiz지시어를 사용해야 합니다.
- Do Not Omit
exit(Service 10): Failing to invokesyscallwith$v0 = 10at the end ofmaincauses the program counter (PC) to fall through into unallocated memory, triggering an Invalid Instruction exception. - Prevent String Buffer Overflow: When calling Service 8 (
read_string), always pass the maximum buffer capacity (including the trailing\0) in$a1so user input does not overwrite adjacent.datavariables. - Distinguish
.asciizfrom.ascii: Because Service 4 (print_string) reads memory until it encounters a null byte (\0), declare string literals with.asciizso the null terminator is appended automatically.
시뮬레이터의 syscall 인터페이스는 레지스터 번호와 인자 전달 규칙이 고정되어 있으므로, 입출력 전후로 $v0와 $a0 값이 의도치 않게 변경되지 않았는지 확인하는 습관이 중요합니다.
Because simulator syscall operations rely on fixed register assignments, always verify that $v0 and $a0 are explicitly loaded before each system call.