# Arm + GNU Toolchain
## 預期目標
* 驗證 [Introduction to ARM Architecture](https://docs.google.com/presentation/d/1cFBRICktpVQAOLzE5eDKD-OM4ckJuncFsn39Wg8aLZI/edit#slide=id.p14) 簡報內容
* 學習 GNU Toolchain
* 使用 QEMU 作為指令集模擬器
## 預先準備動作
* 在自己的電腦中,安裝 [Lubuntu](http://lubuntu.net/) 16.04 作業系統 (版本太舊的話,後續操作可能會失敗)
* 安裝相關開發工具
```shell
sudo apt-get update
sudo apt-get install build-essential git-core
sudo apt-get install gcc-arm-linux-gnueabihf g++-arm-linux-gnueabihf
sudo apt-get install qemu-user qemu-system-arm
```
或者取得 Linaro 提供的 [GNU Toolchain 執行檔](https://releases.linaro.org/components/toolchain/binaries/latest/arm-linux-gnueabihf/)。
* 關於 GNU/Linux 指令,請參閱 [鳥哥的 Linux 私房菜](http://linux.vbird.org/)
* 本系列課程全程使用 GNU/Linux,全世界有十幾億台裝置內建 Linux 系統,學習 Linux 是相當划算的投資!
* [熟悉 Git 和 GitHub 操作](http://wiki.csie.ncku.edu.tw/github)
## 範例程式碼操作
* 取得 [Introduction to ARM Architecture](https://docs.google.com/presentation/d/1cFBRICktpVQAOLzE5eDKD-OM4ckJuncFsn39Wg8aLZI/edit#slide=id.p14) 簡報對應的程式碼
```shell
$ git clone https://github.com/embedded2015/arm-lecture.git
```
* 確認 [arm-lecture](https://github.com/embedded2015/arm-lecture.git) 目錄已正確由 git 建立,接著切換工作目錄,並且編譯 ARM 版本的 “Hello World” 程式
```
cd arm-lecture
cd hello && make qemu
```
* 預期將看到以下輸出
```
arm-linux-gnueabihf-as -c -o hello.o hello.s
arm-linux-gnueabihf-ld -o hello hello.o
qemu-arm ./hello
Hello, world!
```
* 若沒有特別指明,後續操作都在 [arm-lecture](https://github.com/embedded2015/arm-lecture.git) 目錄之下,以下指令可以從 `hello` 目錄返回
```
cd ..
```
## 對照測試簡報中的範例程式碼
* 參閱 [Introduction to ARM Architecture](https://docs.google.com/presentation/d/1cFBRICktpVQAOLzE5eDKD-OM4ckJuncFsn39Wg8aLZI/edit#slide=id.p14) 簡報內容
* Example 1 (Page 31)
cd example1
make default qemu
* 預期輸出: `0`
* 修改 `example1.c`,將其中的 `return 0` 改為 `return c`,之後再 `make qemu`,即可知道 `add(a,b)` 的輸出結果
* 將 example1.c 中的 add(a,b) 改為 div(a,b),並對照簡報 Page 40-41,在 Makefile 的 `CFLAGS` 加上`-mcpu=cortex-a15`, 可發現生成的 ARM 機械碼使用了 `sdiv` 指令
* Example 2 (Page 34)
cd example2
make default qemu
* 預期輸出:
a * b is 140
a * b + c is 143
c - a * b is -137
* Example 3 (Page 45)
cd example3
make default qemu
* 預期輸出
a/2 / b/2 is 0
* Example 4 (Page 50)
cd example4
make default qemu
* 預期輸出
a * b is 664237569
* Example 5 (Page 55)
cd example5
make default qemu
* 預期輸出
a & b is 17
Before operation, apsr was 20030010
After operation, apsr was 60030010
* Example 6 (Page 62)
cd example6
make default qemu
* 預期輸出
The address of a is 0xf6fff0ac
The value of b is now 10
## 作業要求
* 參閱 [Introduction to ARM Architecture](https://docs.google.com/presentation/d/1cFBRICktpVQAOLzE5eDKD-OM4ckJuncFsn39Wg8aLZI/edit#slide=id.p14) 簡報內容
* Lab-1: 實做 [Fibonacci 數列](http://zh.wikipedia.org/zh-tw/%E6%96%90%E6%B3%A2%E9%82%A3%E5%A5%91%E6%95%B0%E5%88%97),使用 ARM 組合語言
* 必須實做遞迴和非遞迴的版本,分別對應 `lab-1` 和 `lab-1i` 目錄,請直接修改這兩個目錄中的程式碼,不需要建立新目錄
* 可參考張家榮同學的[精美筆記](https://embedded2015.hackpad.com/ep/pad/static/c0m3ff7P1X0)
> 請問有非 dropbox 的版本嗎?
## 延伸閱讀
* [Thumb2 conditional code 以及程式開發心得](http://www.slideshare.net/hirokiht/arm-developement), 竹內宏輝