__mulsi3
をStep9の
lib.c
に実装してみることにした。
で、まずはkozos.c
のthread_run
のアドレス計算部分を元に戻して、gcc -S kozos.c
でアセンブラを出力。
該当部分は次のようになっている。
mov.w @(-2,r6),r2 mov.w #40,r1 mov.w r2,r0 jsr @___mulhi3 mov.w r0,r2 mov.w #_threads,r3 add.w r3,r2
r1とr0に2バイトの値を入れて __mulsi3
をコールしてr0に2バイトの値を返すらしい。(実はここにあるのは __mulhi3
で __mulsi3
じゃないのに後で気が付いた。いつから __mulhi3
になったのかはわからない。)
なので__mulsi3
は int __mulsi3(int a, int b)
として定義すればいいんだと思った。
で、lib.h
に次のように定義した。
int __mulsi3(int a, int b);
で、lib.c
に次のように実装した。
int __mulsi3(int a, int b) { int res = 0; int i; if (b > 0) { for (i = 0; i < b; i++) { res += a; } } else if (b < 0) { for (i = 0; i < -b; i++) { res -= a; } } else { return 0; } puts("a="); putxval(a, 0); puts(", b="); putxval(b, 0); puts(", res="); putxval(res, 0); puts("\n"); return res; }
最後のputs
文はデバッグのためのメッセージ。
これで、ビルドするとリンクできた。
(何で__mulhi3
を実装せず、__mulsi3
を実装しただけでリンクエラーにならないのかは不明。)
これで実行したログが以下。
kzload> run starting from entry point: ffffc020 kozos boot succeed! a=0, b=38, res=0 a=0, b=38, res=0 a=1, b=38, res=38 a=0, b=38, res=0 a=1, b=38, res=38 a=2, b=38, res=70 a=0, b=38, res=0 a=1, b=38, res=38 a=2, b=38, res=70 a=3, b=38, res=a8 test09_1 started. test09_1 sleep in. test09_2 started. test09_2 sleep in. test09_3 started. test09_3 wakeup in (test09_1). test09_1 sleep out. test09_1 chpri in. test09_3 wakeup out. test09_3 wakeup in (test09_2). test09_2 sleep out. test09_2 chpri in. test09_1 chpri out. test09_1 wait in. test09_3 wakeup out. test09_3 wait in. test09_2 chpri out. test09_2 wait in. test09_1 wait out. test09_1 trap in. test09_1 DOWN. test09_1 EXIT. test09_3 wait out. test09_3 exit in. test09_3 EXIT. test09_2 wait out. test09_2 exit. test09_2 EXIT. ~. Disconnected.
ちゃんと動いているみたい。
ログを見るとaとbを今の実装と逆に扱った方が良さそう。
ところで__mulhi3
は何なの?
lib.c
に定義した __mulsi3
を __mulhi3
にリネームすると undefined reference to `___mulsi3'
のリンクエラーになる。
追記:ログをよく見ると sizeof(kz_thread)
が0x38(56)になっていて、アセンブラリストの#40と全然違う。単純に sizeof(kz_thread)
を手計算してみたら 52(0x34)なのでアラインメントを考えると0x38でいいのかも。
筆者の坂井です。
乗算が使えるようになるとなにかと便利ですよね。勝手ながら、当ブログを「KOZOS友の会」のほうで紹介させていただきました。
12ステップ本ですが、GWの祝日に「もくもく会」というイベントを行います。場所は神奈川なのですが、よければぜひ参加をご検討ください。
http://atnd.org/events/15186
__mulsi3と__mulhi3の違いなどよくわかっていない部分もありますが、坂井さんのご判断でご紹介していただいてけっこうです。
「もくもく会」お誘いいただいてありがとうございます。
以前から「もくもく会」には参加したいと思っていましたが、私、千葉の外房なのでちょっと遠いです。