# 開發紀錄(sandbox)
## Fibonacci 實作
recursive
```clike=
int fib(int n)
{
if (n == 0) return 0;
if (n == 1) return 1;
return fib(n - 1) + fib(n - 2);
}
```
用 moxie-none-moxiebox-gcc 產生組合語言程式碼
```
$ moxie-none-moxiebox-gcc -S fib_recursive.c
$ cat fib_recursive.s
.file "fib_recursive.c"
.text
.p2align 1
.global fib
.type fib, @function
fib:
push $sp, $r6
dec $sp, 24
sto.l 12($fp), $r0
ldo.l $r1, 12($fp)
xor $r0, $r0
cmp $r1, $r0
bne .L2
xor $r0, $r0
jmpa .L3
.L2:
ldo.l $r1, 12($fp)
ldi.l $r0, 1
cmp $r1, $r0
bne .L4
ldi.l $r0, 1
jmpa .L3
.L4:
ldo.l $r0, 12($fp)
dec $r0, --1
jsra fib
mov $r6, $r0
ldo.l $r0, 12($fp)
dec $r0, --2
jsra fib
mov $r1, $r6
add $r1, $r0
mov $r0, $r1
.L3:
mov $r12, $fp
dec $r12, 4
pop $r12, $r6
ret
.size fib, .-fib
.ident "GCC: (crosstool-NG crosstool-ng-1.23.0-215-g2196112) 7.2.0"
```
用 sandbox 執行程式
```
$ src/sandbox -e tests/fib_recursive
ep 00001000
ro 00000f6c-00001832 elf0
ro 00001834-00001950 elf1
rw 00001a50-0000201c elf2
rw 0000301c-0001301c stack
ro 0001401c-000140dc mapdesc
Sim exception 7 (Bus error)
```
iterative
```clike=
int fib(int n)
{
if (n == 0) return 0;
int prevPrev = 0;
int prev = 1;
int result = 0;
while (n > 0)
{
n--;
result = prev + prevPrev;
prevPrev = prev;
prev = result;
}
return result;
}
```
用 moxie-none-moxiebox-gcc 產生組合語言程式碼
```
$ moxie-none-moxiebox-gcc -S fib_iterative.c
$ cat fib_iterative.s
.file "fib_iterative.c"
.text
.p2align 1
.global fib
.type fib, @function
fib:
dec $sp, 12
sto.l 12($fp), $r0
ldo.l $r1, 12($fp)
xor $r0, $r0
cmp $r1, $r0
bne .L2
xor $r0, $r0
ret
.L2:
xor $r0, $r0
sto.l -4($fp), $r0
ldi.l $r0, 1
sto.l -8($fp), $r0
xor $r0, $r0
sto.l -12($fp), $r0
jmpa .L4
.L5:
ldo.l $r0, 12($fp)
dec $r0, --1
sto.l 12($fp), $r0
ldo.l $r1, -8($fp)
ldo.l $r0, -4($fp)
mov $r2, $r1
add $r2, $r0
mov $r0, $r2
sto.l -12($fp), $r0
ldo.l $r0, -8($fp)
sto.l -4($fp), $r0
ldo.l $r0, -12($fp)
sto.l -8($fp), $r0
.L4:
ldo.l $r1, 12($fp)
xor $r0, $r0
cmp $r1, $r0
bgt .L5
ldo.l $r0, -12($fp)
ret
.size fib, .-fib
.ident "GCC: (crosstool-NG crosstool-ng-1.23.0-215-g2196112) 7.2.0"
```