| 1 | # sha1 |
| 2 | |
| 3 | [SHA-1](https://en.wikipedia.org/wiki/SHA-1) in `avo`. |
| 4 | |
| 5 | Compare to the [`crypto/sha1`](https://github.com/golang/go/blob/204a8f55dc2e0ac8d27a781dab0da609b98560da/src/crypto/sha1/sha1block_amd64.s#L16-L225) assembly. |
| 6 | |
| 7 | [embedmd]:# (asm.go /func main/ /^}/) |
| 8 | ```go |
| 9 | func main() { |
| 10 | TEXT("block", 0, "func(h *[5]uint32, m []byte)") |
| 11 | Doc("block SHA-1 hashes the 64-byte message m into the running state h.") |
| 12 | h := Mem{Base: Load(Param("h"), GP64())} |
| 13 | m := Mem{Base: Load(Param("m").Base(), GP64())} |
| 14 | |
| 15 | // Store message values on the stack. |
| 16 | w := AllocLocal(64) |
| 17 | W := func(r int) Mem { return w.Offset((r % 16) * 4) } |
| 18 | |
| 19 | Comment("Load initial hash.") |
| 20 | hash := [5]Register{GP32(), GP32(), GP32(), GP32(), GP32()} |
| 21 | for i, r := range hash { |
| 22 | MOVL(h.Offset(4*i), r) |
| 23 | } |
| 24 | |
| 25 | Comment("Initialize registers.") |
| 26 | a, b, c, d, e := GP32(), GP32(), GP32(), GP32(), GP32() |
| 27 | for i, r := range []Register{a, b, c, d, e} { |
| 28 | MOVL(hash[i], r) |
| 29 | } |
| 30 | |
| 31 | // Generate round updates. |
| 32 | quarter := []struct { |
| 33 | F func(Register, Register, Register) Register |
| 34 | K uint32 |
| 35 | }{ |
| 36 | {choose, 0x5a827999}, |
| 37 | {xor, 0x6ed9eba1}, |
| 38 | {majority, 0x8f1bbcdc}, |
| 39 | {xor, 0xca62c1d6}, |
| 40 | } |
| 41 | |
| 42 | for r := 0; r < 80; r++ { |
| 43 | Commentf("Round %d.", r) |
| 44 | q := quarter[r/20] |
| 45 | |
| 46 | // Load message value. |
| 47 | u := GP32() |
| 48 | if r < 16 { |
| 49 | MOVL(m.Offset(4*r), u) |
| 50 | BSWAPL(u) |
| 51 | } else { |
| 52 | MOVL(W(r-3), u) |
| 53 | XORL(W(r-8), u) |
| 54 | XORL(W(r-14), u) |
| 55 | XORL(W(r-16), u) |
| 56 | ROLL(U8(1), u) |
| 57 | } |
| 58 | MOVL(u, W(r)) |
| 59 | |
| 60 | // Compute the next state register. |
| 61 | t := GP32() |
| 62 | MOVL(a, t) |
| 63 | ROLL(U8(5), t) |
| 64 | ADDL(q.F(b, c, d), t) |
| 65 | ADDL(e, t) |
| 66 | ADDL(U32(q.K), t) |
| 67 | ADDL(u, t) |
| 68 | |
| 69 | // Update registers. |
| 70 | ROLL(Imm(30), b) |
| 71 | a, b, c, d, e = t, a, b, c, d |
| 72 | } |
| 73 | |
| 74 | Comment("Final add.") |
| 75 | for i, r := range []Register{a, b, c, d, e} { |
| 76 | ADDL(r, hash[i]) |
| 77 | } |
| 78 | |
| 79 | Comment("Store results back.") |
| 80 | for i, r := range hash { |
| 81 | MOVL(r, h.Offset(4*i)) |
| 82 | } |
| 83 | RET() |
| 84 | |
| 85 | Generate() |
| 86 | } |
| 87 | ``` |