From 8528da672cc093d4dd06732819abc1f7b6b5a46e Mon Sep 17 00:00:00 2001 From: Russ Cox Date: Mon, 8 Sep 2014 00:08:51 -0400 Subject: build: move package sources from src/pkg to src Preparation was in CL 134570043. This CL contains only the effect of 'hg mv src/pkg/* src'. For more about the move, see golang.org/s/go14nopkg. --- src/pkg/archive/tar/common.go | 305 - src/pkg/archive/tar/example_test.go | 79 - src/pkg/archive/tar/reader.go | 820 -- src/pkg/archive/tar/reader_test.go | 743 -- src/pkg/archive/tar/stat_atim.go | 20 - src/pkg/archive/tar/stat_atimespec.go | 20 - src/pkg/archive/tar/stat_unix.go | 32 - src/pkg/archive/tar/tar_test.go | 284 - src/pkg/archive/tar/testdata/gnu.tar | Bin 3072 -> 0 bytes src/pkg/archive/tar/testdata/nil-uid.tar | Bin 1024 -> 0 bytes src/pkg/archive/tar/testdata/pax.tar | Bin 10240 -> 0 bytes src/pkg/archive/tar/testdata/small.txt | 1 - src/pkg/archive/tar/testdata/small2.txt | 1 - src/pkg/archive/tar/testdata/sparse-formats.tar | Bin 17920 -> 0 bytes src/pkg/archive/tar/testdata/star.tar | Bin 3072 -> 0 bytes src/pkg/archive/tar/testdata/ustar.tar | Bin 2048 -> 0 bytes src/pkg/archive/tar/testdata/v7.tar | Bin 3584 -> 0 bytes src/pkg/archive/tar/testdata/writer-big-long.tar | Bin 4096 -> 0 bytes src/pkg/archive/tar/testdata/writer-big.tar | Bin 4096 -> 0 bytes src/pkg/archive/tar/testdata/writer.tar | Bin 3584 -> 0 bytes src/pkg/archive/tar/testdata/xattrs.tar | Bin 5120 -> 0 bytes src/pkg/archive/tar/writer.go | 396 - src/pkg/archive/tar/writer_test.go | 491 -- src/pkg/archive/zip/example_test.go | 75 - src/pkg/archive/zip/reader.go | 453 - src/pkg/archive/zip/reader_test.go | 533 -- src/pkg/archive/zip/register.go | 110 - src/pkg/archive/zip/struct.go | 313 - .../archive/zip/testdata/crc32-not-streamed.zip | Bin 314 -> 0 bytes src/pkg/archive/zip/testdata/dd.zip | Bin 154 -> 0 bytes .../archive/zip/testdata/go-no-datadesc-sig.zip | Bin 330 -> 0 bytes .../archive/zip/testdata/go-with-datadesc-sig.zip | Bin 242 -> 0 bytes src/pkg/archive/zip/testdata/gophercolor16x16.png | Bin 785 -> 0 bytes src/pkg/archive/zip/testdata/readme.notzip | Bin 1905 -> 0 bytes src/pkg/archive/zip/testdata/readme.zip | Bin 1885 -> 0 bytes src/pkg/archive/zip/testdata/symlink.zip | Bin 173 -> 0 bytes .../archive/zip/testdata/test-trailing-junk.zip | Bin 1184 -> 0 bytes src/pkg/archive/zip/testdata/test.zip | Bin 1170 -> 0 bytes src/pkg/archive/zip/testdata/unix.zip | Bin 620 -> 0 bytes src/pkg/archive/zip/testdata/winxp.zip | Bin 412 -> 0 bytes src/pkg/archive/zip/testdata/zip64-2.zip | Bin 266 -> 0 bytes src/pkg/archive/zip/testdata/zip64.zip | Bin 242 -> 0 bytes src/pkg/archive/zip/writer.go | 357 - src/pkg/archive/zip/writer_test.go | 164 - src/pkg/archive/zip/zip_test.go | 395 - src/pkg/bufio/bufio.go | 698 -- src/pkg/bufio/bufio_test.go | 1426 ---- src/pkg/bufio/example_test.go | 82 - src/pkg/bufio/export_test.go | 27 - src/pkg/bufio/scan.go | 344 - src/pkg/bufio/scan_test.go | 421 - src/pkg/builtin/builtin.go | 256 - src/pkg/bytes/buffer.go | 412 - src/pkg/bytes/buffer_test.go | 527 -- src/pkg/bytes/bytes.go | 701 -- src/pkg/bytes/bytes.s | 5 - src/pkg/bytes/bytes_decl.go | 24 - src/pkg/bytes/bytes_test.go | 1240 --- src/pkg/bytes/compare_test.go | 208 - src/pkg/bytes/equal_test.go | 47 - src/pkg/bytes/example_test.go | 85 - src/pkg/bytes/export_test.go | 13 - src/pkg/bytes/reader.go | 144 - src/pkg/bytes/reader_test.go | 246 - src/pkg/compress/bzip2/bit_reader.go | 90 - src/pkg/compress/bzip2/bzip2.go | 501 -- src/pkg/compress/bzip2/bzip2_test.go | 419 - src/pkg/compress/bzip2/huffman.go | 251 - src/pkg/compress/bzip2/move_to_front.go | 53 - .../bzip2/testdata/Mark.Twain-Tom.Sawyer.txt.bz2 | Bin 124744 -> 0 bytes src/pkg/compress/bzip2/testdata/e.txt.bz2 | Bin 43149 -> 0 bytes src/pkg/compress/flate/copy.go | 32 - src/pkg/compress/flate/copy_test.go | 54 - src/pkg/compress/flate/deflate.go | 571 -- src/pkg/compress/flate/deflate_test.go | 490 -- src/pkg/compress/flate/fixedhuff.go | 78 - src/pkg/compress/flate/flate_test.go | 62 - src/pkg/compress/flate/gen.go | 190 - src/pkg/compress/flate/huffman_bit_writer.go | 517 -- src/pkg/compress/flate/huffman_code.go | 323 - src/pkg/compress/flate/inflate.go | 710 -- src/pkg/compress/flate/reader_test.go | 96 - src/pkg/compress/flate/reverse_bits.go | 48 - src/pkg/compress/flate/token.go | 102 - src/pkg/compress/flate/writer_test.go | 60 - src/pkg/compress/gzip/gunzip.go | 255 - src/pkg/compress/gzip/gunzip_test.go | 369 - src/pkg/compress/gzip/gzip.go | 272 - src/pkg/compress/gzip/gzip_test.go | 231 - src/pkg/compress/gzip/testdata/issue6550.gz | Bin 65536 -> 0 bytes src/pkg/compress/lzw/reader.go | 257 - src/pkg/compress/lzw/reader_test.go | 152 - src/pkg/compress/lzw/writer.go | 262 - src/pkg/compress/lzw/writer_test.go | 144 - .../compress/testdata/Mark.Twain-Tom.Sawyer.txt | 8858 -------------------- src/pkg/compress/testdata/e.txt | 1 - src/pkg/compress/testdata/pi.txt | 1 - src/pkg/compress/zlib/example_test.go | 37 - src/pkg/compress/zlib/reader.go | 132 - src/pkg/compress/zlib/reader_test.go | 127 - src/pkg/compress/zlib/writer.go | 198 - src/pkg/compress/zlib/writer_test.go | 205 - src/pkg/container/heap/example_intheap_test.go | 47 - src/pkg/container/heap/example_pq_test.go | 97 - src/pkg/container/heap/heap.go | 117 - src/pkg/container/heap/heap_test.go | 213 - src/pkg/container/list/example_test.go | 30 - src/pkg/container/list/list.go | 216 - src/pkg/container/list/list_test.go | 343 - src/pkg/container/ring/ring.go | 141 - src/pkg/container/ring/ring_test.go | 228 - src/pkg/crypto/aes/aes_test.go | 421 - src/pkg/crypto/aes/asm_amd64.s | 289 - src/pkg/crypto/aes/block.go | 176 - src/pkg/crypto/aes/cipher.go | 66 - src/pkg/crypto/aes/cipher_asm.go | 48 - src/pkg/crypto/aes/cipher_generic.go | 19 - src/pkg/crypto/aes/const.go | 358 - src/pkg/crypto/cipher/benchmark_test.go | 139 - src/pkg/crypto/cipher/cbc.go | 133 - src/pkg/crypto/cipher/cbc_aes_test.go | 104 - src/pkg/crypto/cipher/cfb.go | 72 - src/pkg/crypto/cipher/cfb_test.go | 113 - src/pkg/crypto/cipher/cipher.go | 53 - src/pkg/crypto/cipher/cipher_test.go | 36 - src/pkg/crypto/cipher/common_test.go | 28 - src/pkg/crypto/cipher/ctr.go | 76 - src/pkg/crypto/cipher/ctr_aes_test.go | 102 - src/pkg/crypto/cipher/example_test.go | 283 - src/pkg/crypto/cipher/gcm.go | 343 - src/pkg/crypto/cipher/gcm_test.go | 159 - src/pkg/crypto/cipher/io.go | 55 - src/pkg/crypto/cipher/ofb.go | 66 - src/pkg/crypto/cipher/ofb_test.go | 102 - src/pkg/crypto/cipher/xor.go | 84 - src/pkg/crypto/cipher/xor_test.go | 28 - src/pkg/crypto/crypto.go | 126 - src/pkg/crypto/des/block.go | 223 - src/pkg/crypto/des/cipher.go | 73 - src/pkg/crypto/des/const.go | 139 - src/pkg/crypto/des/des_test.go | 1566 ---- src/pkg/crypto/des/example_test.go | 25 - src/pkg/crypto/dsa/dsa.go | 278 - src/pkg/crypto/dsa/dsa_test.go | 85 - src/pkg/crypto/ecdsa/ecdsa.go | 189 - src/pkg/crypto/ecdsa/ecdsa_test.go | 191 - src/pkg/crypto/ecdsa/testdata/SigVer.rsp.bz2 | Bin 95485 -> 0 bytes src/pkg/crypto/elliptic/elliptic.go | 373 - src/pkg/crypto/elliptic/elliptic_test.go | 458 - src/pkg/crypto/elliptic/p224.go | 765 -- src/pkg/crypto/elliptic/p224_test.go | 47 - src/pkg/crypto/elliptic/p256.go | 1186 --- src/pkg/crypto/hmac/hmac.go | 102 - src/pkg/crypto/hmac/hmac_test.go | 570 -- src/pkg/crypto/md5/example_test.go | 25 - src/pkg/crypto/md5/gen.go | 331 - src/pkg/crypto/md5/md5.go | 136 - src/pkg/crypto/md5/md5_test.go | 163 - src/pkg/crypto/md5/md5block.go | 265 - src/pkg/crypto/md5/md5block_386.s | 182 - src/pkg/crypto/md5/md5block_amd64.s | 179 - src/pkg/crypto/md5/md5block_amd64p32.s | 184 - src/pkg/crypto/md5/md5block_arm.s | 299 - src/pkg/crypto/md5/md5block_decl.go | 11 - src/pkg/crypto/md5/md5block_generic.go | 9 - src/pkg/crypto/rand/example_test.go | 28 - src/pkg/crypto/rand/rand.go | 21 - src/pkg/crypto/rand/rand_linux.go | 39 - src/pkg/crypto/rand/rand_test.go | 43 - src/pkg/crypto/rand/rand_unix.go | 147 - src/pkg/crypto/rand/rand_windows.go | 47 - src/pkg/crypto/rand/util.go | 136 - src/pkg/crypto/rand/util_test.go | 65 - src/pkg/crypto/rc4/rc4.go | 69 - src/pkg/crypto/rc4/rc4_386.s | 53 - src/pkg/crypto/rc4/rc4_amd64.s | 179 - src/pkg/crypto/rc4/rc4_amd64p32.s | 192 - src/pkg/crypto/rc4/rc4_arm.s | 62 - src/pkg/crypto/rc4/rc4_asm.go | 18 - src/pkg/crypto/rc4/rc4_ref.go | 13 - src/pkg/crypto/rc4/rc4_test.go | 173 - src/pkg/crypto/rsa/pkcs1v15.go | 292 - src/pkg/crypto/rsa/pkcs1v15_test.go | 271 - src/pkg/crypto/rsa/pss.go | 297 - src/pkg/crypto/rsa/pss_test.go | 249 - src/pkg/crypto/rsa/rsa.go | 557 -- src/pkg/crypto/rsa/rsa_test.go | 392 - src/pkg/crypto/rsa/testdata/pss-vect.txt.bz2 | Bin 28526 -> 0 bytes src/pkg/crypto/sha1/example_test.go | 25 - src/pkg/crypto/sha1/sha1.go | 130 - src/pkg/crypto/sha1/sha1_test.go | 129 - src/pkg/crypto/sha1/sha1block.go | 90 - src/pkg/crypto/sha1/sha1block_386.s | 233 - src/pkg/crypto/sha1/sha1block_amd64.s | 216 - src/pkg/crypto/sha1/sha1block_amd64p32.s | 216 - src/pkg/crypto/sha1/sha1block_arm.s | 217 - src/pkg/crypto/sha1/sha1block_decl.go | 11 - src/pkg/crypto/sha1/sha1block_generic.go | 9 - src/pkg/crypto/sha256/sha256.go | 193 - src/pkg/crypto/sha256/sha256_test.go | 176 - src/pkg/crypto/sha256/sha256block.go | 128 - src/pkg/crypto/sha256/sha256block_386.s | 283 - src/pkg/crypto/sha256/sha256block_amd64.s | 256 - src/pkg/crypto/sha256/sha256block_decl.go | 11 - src/pkg/crypto/sha512/sha512.go | 198 - src/pkg/crypto/sha512/sha512_test.go | 176 - src/pkg/crypto/sha512/sha512block.go | 144 - src/pkg/crypto/sha512/sha512block_amd64.s | 273 - src/pkg/crypto/sha512/sha512block_decl.go | 11 - src/pkg/crypto/subtle/constant_time.go | 73 - src/pkg/crypto/subtle/constant_time_test.go | 127 - src/pkg/crypto/tls/alert.go | 77 - src/pkg/crypto/tls/cipher_suites.go | 270 - src/pkg/crypto/tls/common.go | 621 -- src/pkg/crypto/tls/conn.go | 1030 --- src/pkg/crypto/tls/conn_test.go | 118 - src/pkg/crypto/tls/example_test.go | 57 - src/pkg/crypto/tls/generate_cert.go | 161 - src/pkg/crypto/tls/handshake_client.go | 638 -- src/pkg/crypto/tls/handshake_client_test.go | 490 -- src/pkg/crypto/tls/handshake_messages.go | 1438 ---- src/pkg/crypto/tls/handshake_messages_test.go | 251 - src/pkg/crypto/tls/handshake_server.go | 669 -- src/pkg/crypto/tls/handshake_server_test.go | 819 -- src/pkg/crypto/tls/handshake_test.go | 167 - src/pkg/crypto/tls/key_agreement.go | 413 - src/pkg/crypto/tls/prf.go | 291 - src/pkg/crypto/tls/prf_test.go | 126 - .../testdata/Client-TLSv10-ClientCert-ECDSA-ECDSA | 129 - .../testdata/Client-TLSv10-ClientCert-ECDSA-RSA | 125 - .../testdata/Client-TLSv10-ClientCert-RSA-ECDSA | 128 - .../tls/testdata/Client-TLSv10-ClientCert-RSA-RSA | 124 - .../tls/testdata/Client-TLSv10-ECDHE-ECDSA-AES | 87 - .../tls/testdata/Client-TLSv10-ECDHE-RSA-AES | 97 - src/pkg/crypto/tls/testdata/Client-TLSv10-RSA-RC4 | 83 - .../tls/testdata/Client-TLSv11-ECDHE-ECDSA-AES | 89 - .../tls/testdata/Client-TLSv11-ECDHE-RSA-AES | 99 - src/pkg/crypto/tls/testdata/Client-TLSv11-RSA-RC4 | 83 - src/pkg/crypto/tls/testdata/Client-TLSv12-ALPN | 97 - .../crypto/tls/testdata/Client-TLSv12-ALPN-NoMatch | 95 - .../testdata/Client-TLSv12-ClientCert-ECDSA-ECDSA | 134 - .../testdata/Client-TLSv12-ClientCert-ECDSA-RSA | 127 - .../testdata/Client-TLSv12-ClientCert-RSA-ECDSA | 133 - .../tls/testdata/Client-TLSv12-ClientCert-RSA-RSA | 126 - .../tls/testdata/Client-TLSv12-ECDHE-ECDSA-AES | 89 - .../tls/testdata/Client-TLSv12-ECDHE-ECDSA-AES-GCM | 84 - .../tls/testdata/Client-TLSv12-ECDHE-RSA-AES | 99 - src/pkg/crypto/tls/testdata/Client-TLSv12-RSA-RC4 | 83 - src/pkg/crypto/tls/testdata/Server-SSLv3-RSA-3DES | 83 - src/pkg/crypto/tls/testdata/Server-SSLv3-RSA-AES | 84 - src/pkg/crypto/tls/testdata/Server-SSLv3-RSA-RC4 | 79 - .../tls/testdata/Server-TLSv10-ECDHE-ECDSA-AES | 84 - src/pkg/crypto/tls/testdata/Server-TLSv10-RSA-3DES | 79 - src/pkg/crypto/tls/testdata/Server-TLSv10-RSA-AES | 82 - src/pkg/crypto/tls/testdata/Server-TLSv10-RSA-RC4 | 76 - src/pkg/crypto/tls/testdata/Server-TLSv11-RSA-RC4 | 76 - src/pkg/crypto/tls/testdata/Server-TLSv12-ALPN | 122 - .../crypto/tls/testdata/Server-TLSv12-ALPN-NoMatch | 121 - .../Server-TLSv12-CipherSuiteCertPreferenceECDSA | 91 - .../Server-TLSv12-CipherSuiteCertPreferenceRSA | 101 - .../Server-TLSv12-ClientAuthRequestedAndECDSAGiven | 122 - .../Server-TLSv12-ClientAuthRequestedAndGiven | 121 - .../Server-TLSv12-ClientAuthRequestedNotGiven | 81 - .../tls/testdata/Server-TLSv12-ECDHE-ECDSA-AES | 89 - .../crypto/tls/testdata/Server-TLSv12-IssueTicket | 87 - src/pkg/crypto/tls/testdata/Server-TLSv12-RSA-3DES | 83 - src/pkg/crypto/tls/testdata/Server-TLSv12-RSA-AES | 87 - .../crypto/tls/testdata/Server-TLSv12-RSA-AES-GCM | 93 - src/pkg/crypto/tls/testdata/Server-TLSv12-RSA-RC4 | 79 - src/pkg/crypto/tls/testdata/Server-TLSv12-Resume | 36 - src/pkg/crypto/tls/testdata/Server-TLSv12-SNI | 76 - src/pkg/crypto/tls/ticket.go | 182 - src/pkg/crypto/tls/tls.go | 275 - src/pkg/crypto/tls/tls_test.go | 282 - src/pkg/crypto/x509/cert_pool.go | 116 - src/pkg/crypto/x509/example_test.go | 91 - src/pkg/crypto/x509/pem_decrypt.go | 233 - src/pkg/crypto/x509/pem_decrypt_test.go | 223 - src/pkg/crypto/x509/pkcs1.go | 122 - src/pkg/crypto/x509/pkcs8.go | 54 - src/pkg/crypto/x509/pkcs8_test.go | 28 - src/pkg/crypto/x509/pkix/pkix.go | 178 - src/pkg/crypto/x509/root.go | 17 - src/pkg/crypto/x509/root_cgo_darwin.go | 79 - src/pkg/crypto/x509/root_darwin.go | 23 - src/pkg/crypto/x509/root_darwin_test.go | 50 - src/pkg/crypto/x509/root_nocgo_darwin.go | 11 - src/pkg/crypto/x509/root_plan9.go | 33 - src/pkg/crypto/x509/root_unix.go | 37 - src/pkg/crypto/x509/root_windows.go | 229 - src/pkg/crypto/x509/sec1.go | 83 - src/pkg/crypto/x509/sec1_test.go | 30 - src/pkg/crypto/x509/verify.go | 476 -- src/pkg/crypto/x509/verify_test.go | 1123 --- src/pkg/crypto/x509/x509.go | 1903 ----- src/pkg/crypto/x509/x509_test.go | 953 --- src/pkg/crypto/x509/x509_test_import.go | 53 - src/pkg/database/sql/convert.go | 299 - src/pkg/database/sql/convert_test.go | 348 - src/pkg/database/sql/doc.txt | 46 - src/pkg/database/sql/driver/driver.go | 211 - src/pkg/database/sql/driver/types.go | 252 - src/pkg/database/sql/driver/types_test.go | 65 - src/pkg/database/sql/example_test.go | 46 - src/pkg/database/sql/fakedb_test.go | 805 -- src/pkg/database/sql/sql.go | 1723 ---- src/pkg/database/sql/sql_test.go | 1956 ----- src/pkg/debug/dwarf/buf.go | 181 - src/pkg/debug/dwarf/const.go | 454 - src/pkg/debug/dwarf/entry.go | 401 - src/pkg/debug/dwarf/open.go | 87 - src/pkg/debug/dwarf/testdata/typedef.c | 85 - src/pkg/debug/dwarf/testdata/typedef.elf | Bin 12448 -> 0 bytes src/pkg/debug/dwarf/testdata/typedef.elf4 | Bin 9496 -> 0 bytes src/pkg/debug/dwarf/testdata/typedef.macho | Bin 5024 -> 0 bytes src/pkg/debug/dwarf/type.go | 685 -- src/pkg/debug/dwarf/type_test.go | 122 - src/pkg/debug/dwarf/typeunit.go | 166 - src/pkg/debug/dwarf/unit.go | 90 - src/pkg/debug/elf/elf.go | 1773 ---- src/pkg/debug/elf/elf_test.go | 49 - src/pkg/debug/elf/file.go | 945 --- src/pkg/debug/elf/file_test.go | 345 - src/pkg/debug/elf/symbols_test.go | 834 -- src/pkg/debug/elf/testdata/gcc-386-freebsd-exec | Bin 5742 -> 0 bytes src/pkg/debug/elf/testdata/gcc-amd64-linux-exec | Bin 8844 -> 0 bytes .../testdata/gcc-amd64-openbsd-debug-with-rela.obj | Bin 6544 -> 0 bytes .../elf/testdata/go-relocation-test-clang-x86.obj | Bin 1900 -> 0 bytes .../testdata/go-relocation-test-gcc424-x86-64.obj | Bin 3088 -> 0 bytes .../testdata/go-relocation-test-gcc441-x86-64.obj | Bin 2936 -> 0 bytes .../elf/testdata/go-relocation-test-gcc441-x86.obj | Bin 1884 -> 0 bytes .../testdata/go-relocation-test-gcc482-aarch64.obj | Bin 3392 -> 0 bytes src/pkg/debug/elf/testdata/hello-world-core.gz | Bin 12678 -> 0 bytes src/pkg/debug/elf/testdata/hello.c | 7 - src/pkg/debug/goobj/read.go | 666 -- src/pkg/debug/goobj/read_test.go | 28 - src/pkg/debug/gosym/pclinetest.asm | 58 - src/pkg/debug/gosym/pclinetest.h | 9 - src/pkg/debug/gosym/pclntab.go | 453 - src/pkg/debug/gosym/pclntab_test.go | 274 - src/pkg/debug/gosym/symtab.go | 710 -- src/pkg/debug/macho/fat.go | 146 - src/pkg/debug/macho/file.go | 524 -- src/pkg/debug/macho/file_test.go | 210 - src/pkg/debug/macho/macho.go | 316 - .../macho/testdata/fat-gcc-386-amd64-darwin-exec | Bin 28992 -> 0 bytes src/pkg/debug/macho/testdata/gcc-386-darwin-exec | Bin 12588 -> 0 bytes src/pkg/debug/macho/testdata/gcc-amd64-darwin-exec | Bin 8512 -> 0 bytes .../macho/testdata/gcc-amd64-darwin-exec-debug | Bin 4540 -> 0 bytes src/pkg/debug/macho/testdata/hello.c | 8 - src/pkg/debug/pe/file.go | 390 - src/pkg/debug/pe/file_test.go | 243 - src/pkg/debug/pe/pe.go | 134 - src/pkg/debug/pe/testdata/gcc-386-mingw-exec | Bin 29941 -> 0 bytes src/pkg/debug/pe/testdata/gcc-386-mingw-obj | Bin 2372 -> 0 bytes src/pkg/debug/pe/testdata/gcc-amd64-mingw-exec | Bin 273083 -> 0 bytes src/pkg/debug/pe/testdata/gcc-amd64-mingw-obj | Bin 736 -> 0 bytes src/pkg/debug/pe/testdata/hello.c | 8 - src/pkg/debug/plan9obj/file.go | 328 - src/pkg/debug/plan9obj/file_test.go | 81 - src/pkg/debug/plan9obj/plan9obj.go | 36 - src/pkg/debug/plan9obj/testdata/386-plan9-exec | Bin 37232 -> 0 bytes src/pkg/debug/plan9obj/testdata/amd64-plan9-exec | Bin 34279 -> 0 bytes src/pkg/debug/plan9obj/testdata/hello.c | 8 - src/pkg/encoding/ascii85/ascii85.go | 310 - src/pkg/encoding/ascii85/ascii85_test.go | 210 - src/pkg/encoding/asn1/asn1.go | 918 -- src/pkg/encoding/asn1/asn1_test.go | 814 -- src/pkg/encoding/asn1/common.go | 163 - src/pkg/encoding/asn1/marshal.go | 646 -- src/pkg/encoding/asn1/marshal_test.go | 164 - src/pkg/encoding/base32/base32.go | 426 - src/pkg/encoding/base32/base32_test.go | 302 - src/pkg/encoding/base32/example_test.go | 45 - src/pkg/encoding/base64/base64.go | 391 - src/pkg/encoding/base64/base64_test.go | 360 - src/pkg/encoding/base64/example_test.go | 45 - src/pkg/encoding/binary/binary.go | 639 -- src/pkg/encoding/binary/binary_test.go | 397 - src/pkg/encoding/binary/example_test.go | 52 - src/pkg/encoding/binary/varint.go | 133 - src/pkg/encoding/binary/varint_test.go | 168 - src/pkg/encoding/csv/reader.go | 337 - src/pkg/encoding/csv/reader_test.go | 284 - src/pkg/encoding/csv/writer.go | 127 - src/pkg/encoding/csv/writer_test.go | 74 - src/pkg/encoding/encoding.go | 48 - src/pkg/encoding/gob/codec_test.go | 1469 ---- src/pkg/encoding/gob/debug.go | 705 -- src/pkg/encoding/gob/decode.go | 1146 --- src/pkg/encoding/gob/decoder.go | 237 - src/pkg/encoding/gob/doc.go | 386 - src/pkg/encoding/gob/dump.go | 29 - src/pkg/encoding/gob/encode.go | 661 -- src/pkg/encoding/gob/encoder.go | 253 - src/pkg/encoding/gob/encoder_test.go | 934 --- src/pkg/encoding/gob/error.go | 43 - src/pkg/encoding/gob/example_encdec_test.go | 61 - src/pkg/encoding/gob/example_interface_test.go | 81 - src/pkg/encoding/gob/example_test.go | 60 - src/pkg/encoding/gob/gobencdec_test.go | 798 -- src/pkg/encoding/gob/timing_test.go | 133 - src/pkg/encoding/gob/type.go | 893 -- src/pkg/encoding/gob/type_test.go | 222 - src/pkg/encoding/hex/hex.go | 216 - src/pkg/encoding/hex/hex_test.go | 153 - src/pkg/encoding/json/bench_test.go | 189 - src/pkg/encoding/json/decode.go | 1050 --- src/pkg/encoding/json/decode_test.go | 1356 --- src/pkg/encoding/json/encode.go | 1175 --- src/pkg/encoding/json/encode_test.go | 480 -- src/pkg/encoding/json/example_test.go | 161 - src/pkg/encoding/json/fold.go | 143 - src/pkg/encoding/json/fold_test.go | 116 - src/pkg/encoding/json/indent.go | 137 - src/pkg/encoding/json/scanner.go | 623 -- src/pkg/encoding/json/scanner_test.go | 315 - src/pkg/encoding/json/stream.go | 200 - src/pkg/encoding/json/stream_test.go | 206 - src/pkg/encoding/json/tagkey_test.go | 115 - src/pkg/encoding/json/tags.go | 44 - src/pkg/encoding/json/tags_test.go | 28 - src/pkg/encoding/json/testdata/code.json.gz | Bin 120432 -> 0 bytes src/pkg/encoding/pem/pem.go | 277 - src/pkg/encoding/pem/pem_test.go | 404 - src/pkg/encoding/xml/atom_test.go | 56 - src/pkg/encoding/xml/example_test.go | 151 - src/pkg/encoding/xml/marshal.go | 938 --- src/pkg/encoding/xml/marshal_test.go | 1266 --- src/pkg/encoding/xml/read.go | 692 -- src/pkg/encoding/xml/read_test.go | 714 -- src/pkg/encoding/xml/typeinfo.go | 363 - src/pkg/encoding/xml/xml.go | 1946 ----- src/pkg/encoding/xml/xml_test.go | 749 -- src/pkg/errors/errors.go | 20 - src/pkg/errors/errors_test.go | 53 - src/pkg/errors/example_test.go | 34 - src/pkg/expvar/expvar.go | 336 - src/pkg/expvar/expvar_test.go | 167 - src/pkg/flag/example_test.go | 83 - src/pkg/flag/export_test.go | 17 - src/pkg/flag/flag.go | 854 -- src/pkg/flag/flag_test.go | 369 - src/pkg/fmt/doc.go | 272 - src/pkg/fmt/export_test.go | 7 - src/pkg/fmt/fmt_test.go | 1182 --- src/pkg/fmt/format.go | 492 -- src/pkg/fmt/print.go | 1205 --- src/pkg/fmt/scan.go | 1169 --- src/pkg/fmt/scan_test.go | 992 --- src/pkg/fmt/stringer_test.go | 61 - src/pkg/go/ast/ast.go | 995 --- src/pkg/go/ast/ast_test.go | 50 - src/pkg/go/ast/commentmap.go | 332 - src/pkg/go/ast/commentmap_test.go | 143 - src/pkg/go/ast/example_test.go | 210 - src/pkg/go/ast/filter.go | 466 - src/pkg/go/ast/filter_test.go | 86 - src/pkg/go/ast/import.go | 196 - src/pkg/go/ast/print.go | 251 - src/pkg/go/ast/print_test.go | 97 - src/pkg/go/ast/resolve.go | 174 - src/pkg/go/ast/scope.go | 162 - src/pkg/go/ast/walk.go | 386 - src/pkg/go/build/build.go | 1364 --- src/pkg/go/build/build_test.go | 205 - src/pkg/go/build/deps_test.go | 443 - src/pkg/go/build/doc.go | 140 - src/pkg/go/build/read.go | 238 - src/pkg/go/build/read_test.go | 226 - src/pkg/go/build/syslist.go | 8 - src/pkg/go/build/syslist_test.go | 62 - src/pkg/go/build/testdata/other/file/file.go | 5 - src/pkg/go/build/testdata/other/main.go | 11 - src/pkg/go/doc/Makefile | 7 - src/pkg/go/doc/comment.go | 480 -- src/pkg/go/doc/comment_test.go | 207 - src/pkg/go/doc/doc.go | 111 - src/pkg/go/doc/doc_test.go | 146 - src/pkg/go/doc/example.go | 355 - src/pkg/go/doc/example_test.go | 191 - src/pkg/go/doc/exports.go | 199 - src/pkg/go/doc/filter.go | 105 - src/pkg/go/doc/headscan.go | 114 - src/pkg/go/doc/reader.go | 853 -- src/pkg/go/doc/synopsis.go | 82 - src/pkg/go/doc/synopsis_test.go | 51 - src/pkg/go/doc/testdata/a.0.golden | 52 - src/pkg/go/doc/testdata/a.1.golden | 52 - src/pkg/go/doc/testdata/a.2.golden | 52 - src/pkg/go/doc/testdata/a0.go | 40 - src/pkg/go/doc/testdata/a1.go | 12 - src/pkg/go/doc/testdata/b.0.golden | 71 - src/pkg/go/doc/testdata/b.1.golden | 83 - src/pkg/go/doc/testdata/b.2.golden | 71 - src/pkg/go/doc/testdata/b.go | 58 - src/pkg/go/doc/testdata/benchmark.go | 293 - src/pkg/go/doc/testdata/bugpara.0.golden | 20 - src/pkg/go/doc/testdata/bugpara.1.golden | 20 - src/pkg/go/doc/testdata/bugpara.2.golden | 20 - src/pkg/go/doc/testdata/bugpara.go | 5 - src/pkg/go/doc/testdata/c.0.golden | 48 - src/pkg/go/doc/testdata/c.1.golden | 48 - src/pkg/go/doc/testdata/c.2.golden | 48 - src/pkg/go/doc/testdata/c.go | 62 - src/pkg/go/doc/testdata/d.0.golden | 104 - src/pkg/go/doc/testdata/d.1.golden | 104 - src/pkg/go/doc/testdata/d.2.golden | 104 - src/pkg/go/doc/testdata/d1.go | 57 - src/pkg/go/doc/testdata/d2.go | 45 - src/pkg/go/doc/testdata/e.0.golden | 109 - src/pkg/go/doc/testdata/e.1.golden | 144 - src/pkg/go/doc/testdata/e.2.golden | 130 - src/pkg/go/doc/testdata/e.go | 147 - src/pkg/go/doc/testdata/error1.0.golden | 30 - src/pkg/go/doc/testdata/error1.1.golden | 32 - src/pkg/go/doc/testdata/error1.2.golden | 30 - src/pkg/go/doc/testdata/error1.go | 24 - src/pkg/go/doc/testdata/error2.0.golden | 27 - src/pkg/go/doc/testdata/error2.1.golden | 37 - src/pkg/go/doc/testdata/error2.2.golden | 27 - src/pkg/go/doc/testdata/error2.go | 29 - src/pkg/go/doc/testdata/example.go | 81 - src/pkg/go/doc/testdata/f.0.golden | 13 - src/pkg/go/doc/testdata/f.1.golden | 16 - src/pkg/go/doc/testdata/f.2.golden | 13 - src/pkg/go/doc/testdata/f.go | 14 - src/pkg/go/doc/testdata/template.txt | 68 - src/pkg/go/doc/testdata/testing.0.golden | 156 - src/pkg/go/doc/testdata/testing.1.golden | 298 - src/pkg/go/doc/testdata/testing.2.golden | 156 - src/pkg/go/doc/testdata/testing.go | 404 - src/pkg/go/format/format.go | 199 - src/pkg/go/format/format_test.go | 124 - src/pkg/go/parser/error_test.go | 182 - src/pkg/go/parser/example_test.go | 34 - src/pkg/go/parser/interface.go | 198 - src/pkg/go/parser/parser.go | 2460 ------ src/pkg/go/parser/parser_test.go | 449 - src/pkg/go/parser/performance_test.go | 30 - src/pkg/go/parser/short_test.go | 103 - src/pkg/go/parser/testdata/commas.src | 19 - src/pkg/go/parser/testdata/issue3106.src | 46 - src/pkg/go/printer/example_test.go | 67 - src/pkg/go/printer/nodes.go | 1602 ---- src/pkg/go/printer/performance_test.go | 58 - src/pkg/go/printer/printer.go | 1292 --- src/pkg/go/printer/printer_test.go | 562 -- src/pkg/go/printer/testdata/comments.golden | 643 -- src/pkg/go/printer/testdata/comments.input | 648 -- src/pkg/go/printer/testdata/comments.x | 56 - src/pkg/go/printer/testdata/comments2.golden | 105 - src/pkg/go/printer/testdata/comments2.input | 105 - src/pkg/go/printer/testdata/declarations.golden | 955 --- src/pkg/go/printer/testdata/declarations.input | 967 --- src/pkg/go/printer/testdata/empty.golden | 5 - src/pkg/go/printer/testdata/empty.input | 5 - src/pkg/go/printer/testdata/expressions.golden | 681 -- src/pkg/go/printer/testdata/expressions.input | 710 -- src/pkg/go/printer/testdata/expressions.raw | 681 -- src/pkg/go/printer/testdata/linebreaks.golden | 275 - src/pkg/go/printer/testdata/linebreaks.input | 271 - src/pkg/go/printer/testdata/parser.go | 2153 ----- src/pkg/go/printer/testdata/slow.golden | 85 - src/pkg/go/printer/testdata/slow.input | 85 - src/pkg/go/printer/testdata/statements.golden | 644 -- src/pkg/go/printer/testdata/statements.input | 555 -- src/pkg/go/scanner/errors.go | 126 - src/pkg/go/scanner/example_test.go | 46 - src/pkg/go/scanner/scanner.go | 760 -- src/pkg/go/scanner/scanner_test.go | 775 -- src/pkg/go/token/position.go | 485 -- src/pkg/go/token/position_test.go | 297 - src/pkg/go/token/serialize.go | 56 - src/pkg/go/token/serialize_test.go | 111 - src/pkg/go/token/token.go | 308 - src/pkg/hash/adler32/adler32.go | 78 - src/pkg/hash/adler32/adler32_test.go | 105 - src/pkg/hash/crc32/crc32.go | 135 - src/pkg/hash/crc32/crc32_amd64.s | 64 - src/pkg/hash/crc32/crc32_amd64p32.s | 64 - src/pkg/hash/crc32/crc32_amd64x.go | 27 - src/pkg/hash/crc32/crc32_generic.go | 14 - src/pkg/hash/crc32/crc32_test.go | 99 - src/pkg/hash/crc64/crc64.go | 87 - src/pkg/hash/crc64/crc64_test.go | 81 - src/pkg/hash/fnv/fnv.go | 131 - src/pkg/hash/fnv/fnv_test.go | 165 - src/pkg/hash/hash.go | 43 - src/pkg/hash/test_cases.txt | 31 - src/pkg/hash/test_gen.awk | 14 - src/pkg/html/entity.go | 2253 ----- src/pkg/html/entity_test.go | 29 - src/pkg/html/escape.go | 250 - src/pkg/html/escape_test.go | 115 - src/pkg/html/template/attr.go | 175 - src/pkg/html/template/clone_test.go | 188 - src/pkg/html/template/content.go | 136 - src/pkg/html/template/content_test.go | 280 - src/pkg/html/template/context.go | 339 - src/pkg/html/template/css.go | 268 - src/pkg/html/template/css_test.go | 281 - src/pkg/html/template/doc.go | 191 - src/pkg/html/template/error.go | 205 - src/pkg/html/template/escape.go | 807 -- src/pkg/html/template/escape_test.go | 1697 ---- src/pkg/html/template/html.go | 257 - src/pkg/html/template/html_test.go | 94 - src/pkg/html/template/js.go | 362 - src/pkg/html/template/js_test.go | 401 - src/pkg/html/template/template.go | 389 - src/pkg/html/template/transition.go | 550 -- src/pkg/html/template/url.go | 105 - src/pkg/html/template/url_test.go | 112 - src/pkg/image/color/color.go | 297 - src/pkg/image/color/palette/gen.go | 121 - src/pkg/image/color/palette/generate.go | 8 - src/pkg/image/color/palette/palette.go | 503 -- src/pkg/image/color/ycbcr.go | 99 - src/pkg/image/color/ycbcr_test.go | 33 - src/pkg/image/decode_example_test.go | 140 - src/pkg/image/decode_test.go | 120 - src/pkg/image/draw/bench_test.go | 206 - src/pkg/image/draw/clip_test.go | 193 - src/pkg/image/draw/draw.go | 673 -- src/pkg/image/draw/draw_test.go | 429 - src/pkg/image/format.go | 100 - src/pkg/image/geom.go | 234 - src/pkg/image/gif/reader.go | 460 - src/pkg/image/gif/reader_test.go | 201 - src/pkg/image/gif/writer.go | 323 - src/pkg/image/gif/writer_test.go | 204 - src/pkg/image/image.go | 936 --- src/pkg/image/image_test.go | 113 - src/pkg/image/jpeg/dct_test.go | 299 - src/pkg/image/jpeg/fdct.go | 190 - src/pkg/image/jpeg/huffman.go | 244 - src/pkg/image/jpeg/idct.go | 192 - src/pkg/image/jpeg/reader.go | 524 -- src/pkg/image/jpeg/reader_test.go | 224 - src/pkg/image/jpeg/scan.go | 436 - src/pkg/image/jpeg/writer.go | 614 -- src/pkg/image/jpeg/writer_test.go | 232 - src/pkg/image/names.go | 52 - src/pkg/image/png/paeth.go | 71 - src/pkg/image/png/paeth_test.go | 91 - src/pkg/image/png/reader.go | 820 -- src/pkg/image/png/reader_test.go | 362 - src/pkg/image/png/testdata/benchGray.png | Bin 14709 -> 0 bytes src/pkg/image/png/testdata/benchNRGBA-gradient.png | Bin 58831 -> 0 bytes src/pkg/image/png/testdata/benchNRGBA-opaque.png | Bin 44237 -> 0 bytes src/pkg/image/png/testdata/benchPaletted.png | Bin 13397 -> 0 bytes src/pkg/image/png/testdata/benchRGB-interlace.png | Bin 47483 -> 0 bytes src/pkg/image/png/testdata/benchRGB.png | Bin 39571 -> 0 bytes src/pkg/image/png/testdata/invalid-crc32.png | Bin 1289 -> 0 bytes src/pkg/image/png/testdata/invalid-noend.png | Bin 1277 -> 0 bytes src/pkg/image/png/testdata/invalid-trunc.png | Bin 1288 -> 0 bytes src/pkg/image/png/testdata/invalid-zlib.png | Bin 1289 -> 0 bytes src/pkg/image/png/testdata/pngsuite/README | 21 - .../image/png/testdata/pngsuite/README.original | 85 - .../image/png/testdata/pngsuite/basn0g01-30.png | Bin 162 -> 0 bytes .../image/png/testdata/pngsuite/basn0g01-30.sng | 39 - src/pkg/image/png/testdata/pngsuite/basn0g01.png | Bin 164 -> 0 bytes src/pkg/image/png/testdata/pngsuite/basn0g01.sng | 41 - .../image/png/testdata/pngsuite/basn0g02-29.png | Bin 110 -> 0 bytes .../image/png/testdata/pngsuite/basn0g02-29.sng | 38 - src/pkg/image/png/testdata/pngsuite/basn0g02.png | Bin 104 -> 0 bytes src/pkg/image/png/testdata/pngsuite/basn0g02.sng | 41 - .../image/png/testdata/pngsuite/basn0g04-31.png | Bin 153 -> 0 bytes .../image/png/testdata/pngsuite/basn0g04-31.sng | 40 - src/pkg/image/png/testdata/pngsuite/basn0g04.png | Bin 145 -> 0 bytes src/pkg/image/png/testdata/pngsuite/basn0g04.sng | 41 - src/pkg/image/png/testdata/pngsuite/basn0g08.png | Bin 138 -> 0 bytes src/pkg/image/png/testdata/pngsuite/basn0g08.sng | 41 - src/pkg/image/png/testdata/pngsuite/basn0g16.png | Bin 167 -> 0 bytes src/pkg/image/png/testdata/pngsuite/basn0g16.sng | 41 - src/pkg/image/png/testdata/pngsuite/basn2c08.png | Bin 145 -> 0 bytes src/pkg/image/png/testdata/pngsuite/basn2c08.sng | 41 - src/pkg/image/png/testdata/pngsuite/basn2c16.png | Bin 302 -> 0 bytes src/pkg/image/png/testdata/pngsuite/basn2c16.sng | 41 - src/pkg/image/png/testdata/pngsuite/basn3p01.png | Bin 112 -> 0 bytes src/pkg/image/png/testdata/pngsuite/basn3p01.sng | 45 - src/pkg/image/png/testdata/pngsuite/basn3p02.png | Bin 146 -> 0 bytes src/pkg/image/png/testdata/pngsuite/basn3p02.sng | 47 - .../image/png/testdata/pngsuite/basn3p04-31i.png | Bin 358 -> 0 bytes .../image/png/testdata/pngsuite/basn3p04-31i.sng | 57 - src/pkg/image/png/testdata/pngsuite/basn3p04.png | Bin 216 -> 0 bytes src/pkg/image/png/testdata/pngsuite/basn3p04.sng | 58 - .../image/png/testdata/pngsuite/basn3p08-trns.png | Bin 1538 -> 0 bytes .../image/png/testdata/pngsuite/basn3p08-trns.sng | 301 - src/pkg/image/png/testdata/pngsuite/basn3p08.png | Bin 1286 -> 0 bytes src/pkg/image/png/testdata/pngsuite/basn3p08.sng | 299 - src/pkg/image/png/testdata/pngsuite/basn4a08.png | Bin 126 -> 0 bytes src/pkg/image/png/testdata/pngsuite/basn4a08.sng | 41 - src/pkg/image/png/testdata/pngsuite/basn4a16.png | Bin 2206 -> 0 bytes src/pkg/image/png/testdata/pngsuite/basn4a16.sng | 41 - src/pkg/image/png/testdata/pngsuite/basn6a08.png | Bin 184 -> 0 bytes src/pkg/image/png/testdata/pngsuite/basn6a08.sng | 41 - src/pkg/image/png/testdata/pngsuite/basn6a16.png | Bin 3435 -> 0 bytes src/pkg/image/png/testdata/pngsuite/basn6a16.sng | 41 - src/pkg/image/png/writer.go | 530 -- src/pkg/image/png/writer_test.go | 210 - src/pkg/image/testdata/video-001.5bpp.gif | Bin 6214 -> 0 bytes src/pkg/image/testdata/video-001.gif | Bin 13106 -> 0 bytes src/pkg/image/testdata/video-001.interlaced.gif | Bin 14142 -> 0 bytes src/pkg/image/testdata/video-001.jpeg | Bin 21459 -> 0 bytes src/pkg/image/testdata/video-001.png | Bin 29228 -> 0 bytes src/pkg/image/testdata/video-001.progressive.jpeg | Bin 20732 -> 0 bytes src/pkg/image/testdata/video-001.q50.420.jpeg | Bin 3407 -> 0 bytes .../testdata/video-001.q50.420.progressive.jpeg | Bin 3279 -> 0 bytes src/pkg/image/testdata/video-001.q50.422.jpeg | Bin 3608 -> 0 bytes .../testdata/video-001.q50.422.progressive.jpeg | Bin 3506 -> 0 bytes src/pkg/image/testdata/video-001.q50.440.jpeg | Bin 3662 -> 0 bytes .../testdata/video-001.q50.440.progressive.jpeg | Bin 3529 -> 0 bytes src/pkg/image/testdata/video-001.q50.444.jpeg | Bin 4032 -> 0 bytes .../testdata/video-001.q50.444.progressive.jpeg | Bin 3935 -> 0 bytes .../video-001.separate.dc.progression.jpeg | Bin 14288 -> 0 bytes ...eo-001.separate.dc.progression.progressive.jpeg | Bin 14312 -> 0 bytes src/pkg/image/testdata/video-005.gray.gif | Bin 14505 -> 0 bytes src/pkg/image/testdata/video-005.gray.jpeg | Bin 5618 -> 0 bytes src/pkg/image/testdata/video-005.gray.png | Bin 14974 -> 0 bytes src/pkg/image/testdata/video-005.gray.q50.2x2.jpeg | Bin 2782 -> 0 bytes .../video-005.gray.q50.2x2.progressive.jpeg | Bin 2699 -> 0 bytes src/pkg/image/testdata/video-005.gray.q50.jpeg | Bin 2782 -> 0 bytes .../testdata/video-005.gray.q50.progressive.jpeg | Bin 2699 -> 0 bytes src/pkg/image/ycbcr.go | 157 - src/pkg/image/ycbcr_test.go | 107 - src/pkg/index/suffixarray/qsufsort.go | 168 - src/pkg/index/suffixarray/suffixarray.go | 307 - src/pkg/index/suffixarray/suffixarray_test.go | 304 - src/pkg/internal/syscall/getrandom_linux.go | 56 - src/pkg/io/io.go | 499 -- src/pkg/io/io_test.go | 341 - src/pkg/io/ioutil/ioutil.go | 165 - src/pkg/io/ioutil/ioutil_test.go | 95 - src/pkg/io/ioutil/tempfile.go | 95 - src/pkg/io/ioutil/tempfile_test.go | 53 - src/pkg/io/multi.go | 61 - src/pkg/io/multi_test.go | 115 - src/pkg/io/pipe.go | 193 - src/pkg/io/pipe_test.go | 302 - src/pkg/log/example_test.go | 21 - src/pkg/log/log.go | 322 - src/pkg/log/log_test.go | 119 - src/pkg/log/syslog/syslog.go | 319 - src/pkg/log/syslog/syslog_plan9.go | 8 - src/pkg/log/syslog/syslog_test.go | 358 - src/pkg/log/syslog/syslog_unix.go | 31 - src/pkg/log/syslog/syslog_windows.go | 8 - src/pkg/math/abs.go | 22 - src/pkg/math/abs_386.s | 12 - src/pkg/math/abs_amd64.s | 14 - src/pkg/math/abs_amd64p32.s | 5 - src/pkg/math/abs_arm.s | 13 - src/pkg/math/acosh.go | 60 - src/pkg/math/all_test.go | 2992 ------- src/pkg/math/asin.go | 55 - src/pkg/math/asin_386.s | 30 - src/pkg/math/asin_amd64.s | 11 - src/pkg/math/asin_amd64p32.s | 5 - src/pkg/math/asin_arm.s | 11 - src/pkg/math/asinh.go | 69 - src/pkg/math/atan.go | 105 - src/pkg/math/atan2.go | 71 - src/pkg/math/atan2_386.s | 13 - src/pkg/math/atan2_amd64.s | 8 - src/pkg/math/atan2_amd64p32.s | 5 - src/pkg/math/atan2_arm.s | 8 - src/pkg/math/atan_386.s | 13 - src/pkg/math/atan_amd64.s | 8 - src/pkg/math/atan_amd64p32.s | 5 - src/pkg/math/atan_arm.s | 8 - src/pkg/math/atanh.go | 77 - src/pkg/math/big/arith.go | 240 - src/pkg/math/big/arith_386.s | 278 - src/pkg/math/big/arith_amd64.s | 401 - src/pkg/math/big/arith_amd64p32.s | 41 - src/pkg/math/big/arith_arm.s | 300 - src/pkg/math/big/arith_decl.go | 19 - src/pkg/math/big/arith_test.go | 456 - src/pkg/math/big/calibrate_test.go | 88 - src/pkg/math/big/example_test.go | 51 - src/pkg/math/big/gcd_test.go | 47 - src/pkg/math/big/hilbert_test.go | 160 - src/pkg/math/big/int.go | 1024 --- src/pkg/math/big/int_test.go | 1601 ---- src/pkg/math/big/nat.go | 1508 ---- src/pkg/math/big/nat_test.go | 771 -- src/pkg/math/big/rat.go | 713 -- src/pkg/math/big/rat_test.go | 1159 --- src/pkg/math/bits.go | 59 - src/pkg/math/cbrt.go | 76 - src/pkg/math/cmplx/abs.go | 12 - src/pkg/math/cmplx/asin.go | 170 - src/pkg/math/cmplx/cmath_test.go | 866 -- src/pkg/math/cmplx/conj.go | 8 - src/pkg/math/cmplx/exp.go | 55 - src/pkg/math/cmplx/isinf.go | 21 - src/pkg/math/cmplx/isnan.go | 25 - src/pkg/math/cmplx/log.go | 64 - src/pkg/math/cmplx/phase.go | 11 - src/pkg/math/cmplx/polar.go | 12 - src/pkg/math/cmplx/pow.go | 78 - src/pkg/math/cmplx/rect.go | 13 - src/pkg/math/cmplx/sin.go | 132 - src/pkg/math/cmplx/sqrt.go | 104 - src/pkg/math/cmplx/tan.go | 184 - src/pkg/math/const.go | 51 - src/pkg/math/copysign.go | 12 - src/pkg/math/dim.go | 72 - src/pkg/math/dim_386.s | 14 - src/pkg/math/dim_amd64.s | 144 - src/pkg/math/dim_amd64p32.s | 5 - src/pkg/math/dim_arm.s | 14 - src/pkg/math/erf.go | 335 - src/pkg/math/exp.go | 191 - src/pkg/math/exp2_386.s | 40 - src/pkg/math/exp2_amd64.s | 8 - src/pkg/math/exp2_amd64p32.s | 5 - src/pkg/math/exp2_arm.s | 8 - src/pkg/math/exp_386.s | 41 - src/pkg/math/exp_amd64.s | 114 - src/pkg/math/exp_amd64p32.s | 5 - src/pkg/math/exp_arm.s | 8 - src/pkg/math/expm1.go | 237 - src/pkg/math/expm1_386.s | 57 - src/pkg/math/expm1_amd64.s | 8 - src/pkg/math/expm1_amd64p32.s | 5 - src/pkg/math/expm1_arm.s | 8 - src/pkg/math/export_test.go | 11 - src/pkg/math/floor.go | 56 - src/pkg/math/floor_386.s | 46 - src/pkg/math/floor_amd64.s | 76 - src/pkg/math/floor_amd64p32.s | 5 - src/pkg/math/floor_arm.s | 14 - src/pkg/math/frexp.go | 33 - src/pkg/math/frexp_386.s | 25 - src/pkg/math/frexp_amd64.s | 8 - src/pkg/math/frexp_amd64p32.s | 5 - src/pkg/math/frexp_arm.s | 8 - src/pkg/math/gamma.go | 202 - src/pkg/math/hypot.go | 43 - src/pkg/math/hypot_386.s | 59 - src/pkg/math/hypot_amd64.s | 52 - src/pkg/math/hypot_amd64p32.s | 5 - src/pkg/math/hypot_arm.s | 8 - src/pkg/math/j0.go | 429 - src/pkg/math/j1.go | 422 - src/pkg/math/jn.go | 306 - src/pkg/math/ldexp.go | 45 - src/pkg/math/ldexp_386.s | 14 - src/pkg/math/ldexp_amd64.s | 8 - src/pkg/math/ldexp_amd64p32.s | 5 - src/pkg/math/ldexp_arm.s | 8 - src/pkg/math/lgamma.go | 365 - src/pkg/math/log.go | 123 - src/pkg/math/log10.go | 22 - src/pkg/math/log10_386.s | 21 - src/pkg/math/log10_amd64.s | 11 - src/pkg/math/log10_amd64p32.s | 5 - src/pkg/math/log10_arm.s | 11 - src/pkg/math/log1p.go | 200 - src/pkg/math/log1p_386.s | 27 - src/pkg/math/log1p_amd64.s | 8 - src/pkg/math/log1p_amd64p32.s | 5 - src/pkg/math/log1p_arm.s | 8 - src/pkg/math/log_386.s | 13 - src/pkg/math/log_amd64.s | 111 - src/pkg/math/log_amd64p32.s | 5 - src/pkg/math/log_arm.s | 8 - src/pkg/math/logb.go | 50 - src/pkg/math/mod.go | 50 - src/pkg/math/mod_386.s | 17 - src/pkg/math/mod_amd64.s | 8 - src/pkg/math/mod_amd64p32.s | 5 - src/pkg/math/mod_arm.s | 8 - src/pkg/math/modf.go | 34 - src/pkg/math/modf_386.s | 21 - src/pkg/math/modf_amd64.s | 8 - src/pkg/math/modf_amd64p32.s | 5 - src/pkg/math/modf_arm.s | 8 - src/pkg/math/nextafter.go | 47 - src/pkg/math/pow.go | 137 - src/pkg/math/pow10.go | 40 - src/pkg/math/rand/example_test.go | 97 - src/pkg/math/rand/exp.go | 222 - src/pkg/math/rand/normal.go | 157 - src/pkg/math/rand/rand.go | 246 - src/pkg/math/rand/rand_test.go | 398 - src/pkg/math/rand/regress_test.go | 355 - src/pkg/math/rand/rng.go | 246 - src/pkg/math/rand/zipf.go | 75 - src/pkg/math/remainder.go | 85 - src/pkg/math/remainder_386.s | 17 - src/pkg/math/remainder_amd64.s | 8 - src/pkg/math/remainder_amd64p32.s | 5 - src/pkg/math/remainder_arm.s | 8 - src/pkg/math/signbit.go | 10 - src/pkg/math/sin.go | 224 - src/pkg/math/sin_386.s | 47 - src/pkg/math/sin_amd64.s | 11 - src/pkg/math/sin_amd64p32.s | 5 - src/pkg/math/sin_arm.s | 11 - src/pkg/math/sincos.go | 69 - src/pkg/math/sincos_386.s | 28 - src/pkg/math/sincos_amd64.s | 145 - src/pkg/math/sincos_amd64p32.s | 5 - src/pkg/math/sincos_arm.s | 8 - src/pkg/math/sinh.go | 77 - src/pkg/math/sqrt.go | 143 - src/pkg/math/sqrt_386.s | 12 - src/pkg/math/sqrt_amd64.s | 11 - src/pkg/math/sqrt_amd64p32.s | 5 - src/pkg/math/sqrt_arm.s | 12 - src/pkg/math/tan.go | 130 - src/pkg/math/tan_386.s | 28 - src/pkg/math/tan_amd64.s | 8 - src/pkg/math/tan_amd64p32.s | 5 - src/pkg/math/tan_arm.s | 8 - src/pkg/math/tanh.go | 97 - src/pkg/math/unsafe.go | 21 - src/pkg/mime/grammar.go | 32 - src/pkg/mime/mediatype.go | 358 - src/pkg/mime/mediatype_test.go | 306 - src/pkg/mime/multipart/example_test.go | 53 - src/pkg/mime/multipart/formdata.go | 157 - src/pkg/mime/multipart/formdata_test.go | 90 - src/pkg/mime/multipart/multipart.go | 348 - src/pkg/mime/multipart/multipart_test.go | 634 -- src/pkg/mime/multipart/quotedprintable.go | 118 - src/pkg/mime/multipart/quotedprintable_test.go | 204 - src/pkg/mime/multipart/testdata/nested-mime | 29 - src/pkg/mime/multipart/writer.go | 184 - src/pkg/mime/multipart/writer_test.go | 128 - src/pkg/mime/testdata/test.types | 8 - src/pkg/mime/testdata/test.types.plan9 | 8 - src/pkg/mime/type.go | 121 - src/pkg/mime/type_plan9.go | 53 - src/pkg/mime/type_test.go | 54 - src/pkg/mime/type_unix.go | 60 - src/pkg/mime/type_windows.go | 63 - src/pkg/net/cgo_android.go | 14 - src/pkg/net/cgo_bsd.go | 17 - src/pkg/net/cgo_linux.go | 22 - src/pkg/net/cgo_netbsd.go | 16 - src/pkg/net/cgo_openbsd.go | 16 - src/pkg/net/cgo_stub.go | 25 - src/pkg/net/cgo_unix.go | 164 - src/pkg/net/cgo_unix_test.go | 24 - src/pkg/net/conn_test.go | 124 - src/pkg/net/dial.go | 302 - src/pkg/net/dial_gen.go | 46 - src/pkg/net/dial_gen_test.go | 11 - src/pkg/net/dial_test.go | 536 -- src/pkg/net/dialgoogle_test.go | 209 - src/pkg/net/dnsclient.go | 249 - src/pkg/net/dnsclient_test.go | 69 - src/pkg/net/dnsclient_unix.go | 423 - src/pkg/net/dnsclient_unix_test.go | 246 - src/pkg/net/dnsconfig_unix.go | 96 - src/pkg/net/dnsconfig_unix_test.go | 69 - src/pkg/net/dnsmsg.go | 887 -- src/pkg/net/dnsmsg_test.go | 113 - src/pkg/net/dnsname_test.go | 83 - src/pkg/net/empty.c | 8 - src/pkg/net/example_test.go | 36 - src/pkg/net/fd_mutex.go | 184 - src/pkg/net/fd_mutex_test.go | 195 - src/pkg/net/fd_plan9.go | 232 - src/pkg/net/fd_poll_nacl.go | 94 - src/pkg/net/fd_poll_runtime.go | 144 - src/pkg/net/fd_unix.go | 518 -- src/pkg/net/fd_unix_test.go | 58 - src/pkg/net/fd_windows.go | 644 -- src/pkg/net/file_plan9.go | 157 - src/pkg/net/file_test.go | 205 - src/pkg/net/file_unix.go | 139 - src/pkg/net/file_windows.go | 37 - src/pkg/net/hosts.go | 86 - src/pkg/net/hosts_test.go | 81 - src/pkg/net/http/cgi/child.go | 206 - src/pkg/net/http/cgi/child_test.go | 131 - src/pkg/net/http/cgi/host.go | 377 - src/pkg/net/http/cgi/host_test.go | 461 - src/pkg/net/http/cgi/matryoshka_test.go | 228 - src/pkg/net/http/cgi/plan9_test.go | 18 - src/pkg/net/http/cgi/posix_test.go | 21 - src/pkg/net/http/cgi/testdata/test.cgi | 91 - src/pkg/net/http/client.go | 487 -- src/pkg/net/http/client_test.go | 1038 --- src/pkg/net/http/cookie.go | 363 - src/pkg/net/http/cookie_test.go | 380 - src/pkg/net/http/cookiejar/jar.go | 497 -- src/pkg/net/http/cookiejar/jar_test.go | 1267 --- src/pkg/net/http/cookiejar/punycode.go | 159 - src/pkg/net/http/cookiejar/punycode_test.go | 161 - src/pkg/net/http/doc.go | 80 - src/pkg/net/http/example_test.go | 88 - src/pkg/net/http/export_test.go | 78 - src/pkg/net/http/fcgi/child.go | 305 - src/pkg/net/http/fcgi/fcgi.go | 274 - src/pkg/net/http/fcgi/fcgi_test.go | 150 - src/pkg/net/http/filetransport.go | 123 - src/pkg/net/http/filetransport_test.go | 65 - src/pkg/net/http/fs.go | 552 -- src/pkg/net/http/fs_test.go | 880 -- src/pkg/net/http/header.go | 211 - src/pkg/net/http/header_test.go | 212 - src/pkg/net/http/httptest/example_test.go | 50 - src/pkg/net/http/httptest/recorder.go | 72 - src/pkg/net/http/httptest/recorder_test.go | 90 - src/pkg/net/http/httptest/server.go | 228 - src/pkg/net/http/httptest/server_test.go | 29 - src/pkg/net/http/httputil/dump.go | 276 - src/pkg/net/http/httputil/dump_test.go | 263 - src/pkg/net/http/httputil/httputil.go | 39 - src/pkg/net/http/httputil/persist.go | 429 - src/pkg/net/http/httputil/reverseproxy.go | 225 - src/pkg/net/http/httputil/reverseproxy_test.go | 213 - src/pkg/net/http/internal/chunked.go | 202 - src/pkg/net/http/internal/chunked_test.go | 156 - src/pkg/net/http/jar.go | 27 - src/pkg/net/http/lex.go | 96 - src/pkg/net/http/lex_test.go | 31 - src/pkg/net/http/npn_test.go | 118 - src/pkg/net/http/pprof/pprof.go | 205 - src/pkg/net/http/proxy_test.go | 81 - src/pkg/net/http/race.go | 11 - src/pkg/net/http/range_test.go | 79 - src/pkg/net/http/readrequest_test.go | 358 - src/pkg/net/http/request.go | 920 -- src/pkg/net/http/request_test.go | 680 -- src/pkg/net/http/requestwrite_test.go | 623 -- src/pkg/net/http/response.go | 291 - src/pkg/net/http/response_test.go | 646 -- src/pkg/net/http/responsewrite_test.go | 226 - src/pkg/net/http/serve_test.go | 2944 ------- src/pkg/net/http/server.go | 2051 ----- src/pkg/net/http/sniff.go | 214 - src/pkg/net/http/sniff_test.go | 171 - src/pkg/net/http/status.go | 120 - src/pkg/net/http/testdata/file | 1 - src/pkg/net/http/testdata/index.html | 1 - src/pkg/net/http/testdata/style.css | 1 - src/pkg/net/http/transfer.go | 737 -- src/pkg/net/http/transfer_test.go | 64 - src/pkg/net/http/transport.go | 1242 --- src/pkg/net/http/transport_test.go | 2211 ----- src/pkg/net/http/triv.go | 141 - src/pkg/net/http/z_last_test.go | 97 - src/pkg/net/interface.go | 126 - src/pkg/net/interface_bsd.go | 182 - src/pkg/net/interface_bsd_test.go | 52 - src/pkg/net/interface_darwin.go | 63 - src/pkg/net/interface_dragonfly.go | 12 - src/pkg/net/interface_freebsd.go | 63 - src/pkg/net/interface_linux.go | 271 - src/pkg/net/interface_linux_test.go | 102 - src/pkg/net/interface_netbsd.go | 12 - src/pkg/net/interface_openbsd.go | 12 - src/pkg/net/interface_stub.go | 27 - src/pkg/net/interface_test.go | 211 - src/pkg/net/interface_unix_test.go | 151 - src/pkg/net/interface_windows.go | 158 - src/pkg/net/ip.go | 689 -- src/pkg/net/ip_test.go | 465 - src/pkg/net/ipraw_test.go | 289 - src/pkg/net/iprawsock.go | 54 - src/pkg/net/iprawsock_plan9.go | 82 - src/pkg/net/iprawsock_posix.go | 227 - src/pkg/net/ipsock.go | 318 - src/pkg/net/ipsock_plan9.go | 228 - src/pkg/net/ipsock_posix.go | 177 - src/pkg/net/ipsock_test.go | 193 - src/pkg/net/lookup.go | 137 - src/pkg/net/lookup_plan9.go | 297 - src/pkg/net/lookup_test.go | 231 - src/pkg/net/lookup_unix.go | 168 - src/pkg/net/lookup_windows.go | 381 - src/pkg/net/lookup_windows_test.go | 243 - src/pkg/net/mac.go | 86 - src/pkg/net/mac_test.go | 66 - src/pkg/net/mail/message.go | 545 -- src/pkg/net/mail/message_test.go | 304 - src/pkg/net/mockicmp_test.go | 116 - src/pkg/net/mockserver_test.go | 82 - src/pkg/net/multicast_test.go | 188 - src/pkg/net/net.go | 426 - src/pkg/net/net_test.go | 263 - src/pkg/net/net_windows_test.go | 148 - src/pkg/net/netgo_unix_test.go | 24 - src/pkg/net/packetconn_test.go | 186 - src/pkg/net/parse.go | 247 - src/pkg/net/parse_test.go | 53 - src/pkg/net/pipe.go | 67 - src/pkg/net/pipe_test.go | 56 - src/pkg/net/port.go | 24 - src/pkg/net/port_test.go | 53 - src/pkg/net/port_unix.go | 73 - src/pkg/net/protoconn_test.go | 386 - src/pkg/net/race.go | 31 - src/pkg/net/race0.go | 26 - src/pkg/net/rpc/client.go | 317 - src/pkg/net/rpc/client_test.go | 36 - src/pkg/net/rpc/debug.go | 93 - src/pkg/net/rpc/jsonrpc/all_test.go | 296 - src/pkg/net/rpc/jsonrpc/client.go | 123 - src/pkg/net/rpc/jsonrpc/server.go | 134 - src/pkg/net/rpc/server.go | 686 -- src/pkg/net/rpc/server_test.go | 683 -- src/pkg/net/sendfile_dragonfly.go | 103 - src/pkg/net/sendfile_freebsd.go | 103 - src/pkg/net/sendfile_linux.go | 76 - src/pkg/net/sendfile_stub.go | 13 - src/pkg/net/sendfile_windows.go | 55 - src/pkg/net/server_test.go | 461 - src/pkg/net/singleflight.go | 53 - src/pkg/net/smtp/auth.go | 107 - src/pkg/net/smtp/example_test.go | 61 - src/pkg/net/smtp/smtp.go | 357 - src/pkg/net/smtp/smtp_test.go | 694 -- src/pkg/net/sock_bsd.go | 37 - src/pkg/net/sock_cloexec.go | 78 - src/pkg/net/sock_linux.go | 31 - src/pkg/net/sock_plan9.go | 10 - src/pkg/net/sock_posix.go | 216 - src/pkg/net/sock_solaris.go | 13 - src/pkg/net/sock_windows.go | 24 - src/pkg/net/sockopt_bsd.go | 54 - src/pkg/net/sockopt_linux.go | 32 - src/pkg/net/sockopt_plan9.go | 13 - src/pkg/net/sockopt_posix.go | 141 - src/pkg/net/sockopt_solaris.go | 32 - src/pkg/net/sockopt_windows.go | 38 - src/pkg/net/sockoptip_bsd.go | 34 - src/pkg/net/sockoptip_linux.go | 31 - src/pkg/net/sockoptip_posix.go | 57 - src/pkg/net/sockoptip_stub.go | 39 - src/pkg/net/sockoptip_windows.go | 33 - src/pkg/net/sys_cloexec.go | 54 - src/pkg/net/tcp_test.go | 611 -- src/pkg/net/tcpsock.go | 54 - src/pkg/net/tcpsock_plan9.go | 198 - src/pkg/net/tcpsock_posix.go | 299 - src/pkg/net/tcpsockopt_darwin.go | 27 - src/pkg/net/tcpsockopt_dragonfly.go | 29 - src/pkg/net/tcpsockopt_openbsd.go | 27 - src/pkg/net/tcpsockopt_plan9.go | 18 - src/pkg/net/tcpsockopt_posix.go | 20 - src/pkg/net/tcpsockopt_solaris.go | 27 - src/pkg/net/tcpsockopt_unix.go | 31 - src/pkg/net/tcpsockopt_windows.go | 34 - src/pkg/net/testdata/domain-resolv.conf | 5 - src/pkg/net/testdata/empty-resolv.conf | 1 - src/pkg/net/testdata/hosts | 12 - src/pkg/net/testdata/hosts_singleline | 1 - src/pkg/net/testdata/igmp | 24 - src/pkg/net/testdata/igmp6 | 18 - src/pkg/net/testdata/resolv.conf | 8 - src/pkg/net/testdata/search-resolv.conf | 5 - src/pkg/net/textproto/header.go | 43 - src/pkg/net/textproto/pipeline.go | 117 - src/pkg/net/textproto/reader.go | 637 -- src/pkg/net/textproto/reader_test.go | 337 - src/pkg/net/textproto/textproto.go | 154 - src/pkg/net/textproto/writer.go | 118 - src/pkg/net/textproto/writer_test.go | 35 - src/pkg/net/timeout_test.go | 747 -- src/pkg/net/udp_test.go | 257 - src/pkg/net/udpsock.go | 54 - src/pkg/net/udpsock_plan9.go | 203 - src/pkg/net/udpsock_posix.go | 268 - src/pkg/net/unicast_posix_test.go | 466 - src/pkg/net/unix_test.go | 333 - src/pkg/net/unixsock.go | 43 - src/pkg/net/unixsock_plan9.go | 143 - src/pkg/net/unixsock_posix.go | 362 - src/pkg/net/url/example_test.go | 41 - src/pkg/net/url/url.go | 701 -- src/pkg/net/url/url_test.go | 961 --- src/pkg/net/z_last_test.go | 37 - src/pkg/os/dir_plan9.go | 73 - src/pkg/os/dir_unix.go | 58 - src/pkg/os/dir_windows.go | 14 - src/pkg/os/doc.go | 135 - src/pkg/os/env.go | 103 - src/pkg/os/env_test.go | 70 - src/pkg/os/env_unix_test.go | 30 - src/pkg/os/error.go | 65 - src/pkg/os/error_plan9.go | 53 - src/pkg/os/error_test.go | 132 - src/pkg/os/error_unix.go | 45 - src/pkg/os/error_windows.go | 45 - src/pkg/os/error_windows_test.go | 47 - src/pkg/os/exec.go | 70 - src/pkg/os/exec/example_test.go | 75 - src/pkg/os/exec/exec.go | 493 -- src/pkg/os/exec/exec_test.go | 726 -- src/pkg/os/exec/lp_plan9.go | 53 - src/pkg/os/exec/lp_test.go | 33 - src/pkg/os/exec/lp_unix.go | 60 - src/pkg/os/exec/lp_unix_test.go | 55 - src/pkg/os/exec/lp_windows.go | 123 - src/pkg/os/exec/lp_windows_test.go | 573 -- src/pkg/os/exec_plan9.go | 137 - src/pkg/os/exec_posix.go | 134 - src/pkg/os/exec_unix.go | 73 - src/pkg/os/exec_windows.go | 115 - src/pkg/os/export_test.go | 10 - src/pkg/os/file.go | 257 - src/pkg/os/file_plan9.go | 468 -- src/pkg/os/file_posix.go | 149 - src/pkg/os/file_unix.go | 338 - src/pkg/os/file_windows.go | 595 -- src/pkg/os/getwd.go | 123 - src/pkg/os/getwd_darwin.go | 15 - src/pkg/os/os_test.go | 1405 ---- src/pkg/os/os_unix_test.go | 76 - src/pkg/os/os_windows_test.go | 81 - src/pkg/os/path.go | 123 - src/pkg/os/path_plan9.go | 15 - src/pkg/os/path_test.go | 220 - src/pkg/os/path_unix.go | 17 - src/pkg/os/path_windows.go | 16 - src/pkg/os/pipe_bsd.go | 28 - src/pkg/os/pipe_linux.go | 33 - src/pkg/os/proc.go | 36 - src/pkg/os/signal/example_test.go | 23 - src/pkg/os/signal/sig.s | 23 - src/pkg/os/signal/signal.go | 131 - src/pkg/os/signal/signal_stub.go | 17 - src/pkg/os/signal/signal_test.go | 208 - src/pkg/os/signal/signal_unix.go | 53 - src/pkg/os/signal/signal_windows_test.go | 103 - src/pkg/os/stat_darwin.go | 61 - src/pkg/os/stat_dragonfly.go | 61 - src/pkg/os/stat_freebsd.go | 61 - src/pkg/os/stat_linux.go | 61 - src/pkg/os/stat_nacl.go | 62 - src/pkg/os/stat_netbsd.go | 61 - src/pkg/os/stat_openbsd.go | 61 - src/pkg/os/stat_plan9.go | 110 - src/pkg/os/stat_solaris.go | 61 - src/pkg/os/stat_windows.go | 170 - src/pkg/os/str.go | 22 - src/pkg/os/sys_bsd.go | 20 - src/pkg/os/sys_darwin.go | 31 - src/pkg/os/sys_freebsd.go | 23 - src/pkg/os/sys_linux.go | 26 - src/pkg/os/sys_nacl.go | 9 - src/pkg/os/sys_plan9.go | 26 - src/pkg/os/sys_solaris.go | 11 - src/pkg/os/sys_unix.go | 11 - src/pkg/os/sys_windows.go | 15 - src/pkg/os/types.go | 118 - src/pkg/os/types_notwin.go | 25 - src/pkg/os/types_windows.go | 107 - src/pkg/os/user/lookup.go | 22 - src/pkg/os/user/lookup_plan9.go | 46 - src/pkg/os/user/lookup_stubs.go | 28 - src/pkg/os/user/lookup_unix.go | 112 - src/pkg/os/user/lookup_windows.go | 149 - src/pkg/os/user/user.go | 43 - src/pkg/os/user/user_test.go | 89 - src/pkg/path/example_test.go | 63 - src/pkg/path/filepath/example_unix_test.go | 39 - src/pkg/path/filepath/export_test.go | 7 - src/pkg/path/filepath/match.go | 309 - src/pkg/path/filepath/match_test.go | 211 - src/pkg/path/filepath/path.go | 464 - src/pkg/path/filepath/path_plan9.go | 34 - src/pkg/path/filepath/path_test.go | 1028 --- src/pkg/path/filepath/path_unix.go | 36 - src/pkg/path/filepath/path_windows.go | 110 - src/pkg/path/filepath/path_windows_test.go | 113 - src/pkg/path/filepath/symlink.go | 72 - src/pkg/path/filepath/symlink_unix.go | 7 - src/pkg/path/filepath/symlink_windows.go | 74 - src/pkg/path/match.go | 209 - src/pkg/path/match_test.go | 79 - src/pkg/path/path.go | 210 - src/pkg/path/path_test.go | 241 - src/pkg/reflect/all_test.go | 3862 --------- src/pkg/reflect/asm_386.s | 27 - src/pkg/reflect/asm_amd64.s | 27 - src/pkg/reflect/asm_amd64p32.s | 27 - src/pkg/reflect/asm_arm.s | 27 - src/pkg/reflect/deepequal.go | 145 - src/pkg/reflect/example_test.go | 66 - src/pkg/reflect/export_test.go | 19 - src/pkg/reflect/makefunc.go | 120 - src/pkg/reflect/set_test.go | 211 - src/pkg/reflect/tostring_test.go | 95 - src/pkg/reflect/type.go | 1824 ---- src/pkg/reflect/value.go | 2718 ------ src/pkg/regexp/all_test.go | 648 -- src/pkg/regexp/example_test.go | 148 - src/pkg/regexp/exec.go | 452 - src/pkg/regexp/exec2_test.go | 20 - src/pkg/regexp/exec_test.go | 715 -- src/pkg/regexp/find_test.go | 498 -- src/pkg/regexp/onepass.go | 581 -- src/pkg/regexp/onepass_test.go | 208 - src/pkg/regexp/regexp.go | 1120 --- src/pkg/regexp/syntax/compile.go | 289 - src/pkg/regexp/syntax/doc.go | 131 - src/pkg/regexp/syntax/make_perl_groups.pl | 107 - src/pkg/regexp/syntax/parse.go | 1863 ---- src/pkg/regexp/syntax/parse_test.go | 559 -- src/pkg/regexp/syntax/perl_groups.go | 134 - src/pkg/regexp/syntax/prog.go | 345 - src/pkg/regexp/syntax/prog_test.go | 114 - src/pkg/regexp/syntax/regexp.go | 319 - src/pkg/regexp/syntax/simplify.go | 151 - src/pkg/regexp/syntax/simplify_test.go | 151 - src/pkg/regexp/testdata/README | 23 - src/pkg/regexp/testdata/basic.dat | 221 - src/pkg/regexp/testdata/nullsubexpr.dat | 79 - src/pkg/regexp/testdata/re2-exhaustive.txt.bz2 | Bin 394016 -> 0 bytes src/pkg/regexp/testdata/re2-search.txt | 3667 -------- src/pkg/regexp/testdata/repetition.dat | 163 - src/pkg/regexp/testdata/testregex.c | 2286 ----- src/pkg/runtime/Makefile | 5 - src/pkg/runtime/alg.go | 352 - src/pkg/runtime/append_test.go | 190 - src/pkg/runtime/arch_386.go | 12 - src/pkg/runtime/arch_386.h | 17 - src/pkg/runtime/arch_amd64.go | 12 - src/pkg/runtime/arch_amd64.h | 25 - src/pkg/runtime/arch_amd64p32.go | 12 - src/pkg/runtime/arch_amd64p32.h | 17 - src/pkg/runtime/arch_arm.go | 12 - src/pkg/runtime/arch_arm.h | 17 - src/pkg/runtime/asm_386.s | 2292 ----- src/pkg/runtime/asm_amd64.s | 2343 ------ src/pkg/runtime/asm_amd64p32.s | 1227 --- src/pkg/runtime/asm_arm.s | 1309 --- src/pkg/runtime/atomic.go | 51 - src/pkg/runtime/atomic_386.c | 46 - src/pkg/runtime/atomic_amd64x.c | 29 - src/pkg/runtime/atomic_arm.go | 155 - src/pkg/runtime/cgo/asm_386.s | 31 - src/pkg/runtime/cgo/asm_amd64.s | 47 - src/pkg/runtime/cgo/asm_arm.s | 24 - src/pkg/runtime/cgo/asm_nacl_amd64p32.s | 13 - src/pkg/runtime/cgo/callbacks.c | 102 - src/pkg/runtime/cgo/cgo.go | 33 - src/pkg/runtime/cgo/dragonfly.c | 13 - src/pkg/runtime/cgo/freebsd.c | 13 - src/pkg/runtime/cgo/gcc_386.S | 45 - src/pkg/runtime/cgo/gcc_amd64.S | 48 - src/pkg/runtime/cgo/gcc_android.c | 31 - src/pkg/runtime/cgo/gcc_android_arm.c | 43 - src/pkg/runtime/cgo/gcc_arm.S | 45 - src/pkg/runtime/cgo/gcc_darwin_386.c | 155 - src/pkg/runtime/cgo/gcc_darwin_amd64.c | 126 - src/pkg/runtime/cgo/gcc_dragonfly_386.c | 77 - src/pkg/runtime/cgo/gcc_dragonfly_amd64.c | 77 - src/pkg/runtime/cgo/gcc_fatalf.c | 23 - src/pkg/runtime/cgo/gcc_freebsd_386.c | 77 - src/pkg/runtime/cgo/gcc_freebsd_amd64.c | 77 - src/pkg/runtime/cgo/gcc_freebsd_arm.c | 89 - src/pkg/runtime/cgo/gcc_linux_386.c | 79 - src/pkg/runtime/cgo/gcc_linux_amd64.c | 74 - src/pkg/runtime/cgo/gcc_linux_arm.c | 80 - src/pkg/runtime/cgo/gcc_netbsd_386.c | 76 - src/pkg/runtime/cgo/gcc_netbsd_amd64.c | 77 - src/pkg/runtime/cgo/gcc_netbsd_arm.c | 73 - src/pkg/runtime/cgo/gcc_openbsd_386.c | 165 - src/pkg/runtime/cgo/gcc_openbsd_amd64.c | 166 - src/pkg/runtime/cgo/gcc_setenv.c | 16 - src/pkg/runtime/cgo/gcc_util.c | 47 - src/pkg/runtime/cgo/gcc_windows_386.c | 61 - src/pkg/runtime/cgo/gcc_windows_amd64.c | 61 - src/pkg/runtime/cgo/iscgo.c | 15 - src/pkg/runtime/cgo/libcgo.h | 65 - src/pkg/runtime/cgo/netbsd.c | 13 - src/pkg/runtime/cgo/openbsd.c | 21 - src/pkg/runtime/cgo/setenv.c | 10 - src/pkg/runtime/cgocall.go | 270 - src/pkg/runtime/cgocall.h | 13 - src/pkg/runtime/chan.go | 644 -- src/pkg/runtime/chan.h | 68 - src/pkg/runtime/chan_test.go | 791 -- src/pkg/runtime/closure_test.go | 53 - src/pkg/runtime/compiler.go | 13 - src/pkg/runtime/complex.go | 52 - src/pkg/runtime/complex_test.go | 67 - src/pkg/runtime/cpuprof.go | 425 - src/pkg/runtime/crash_cgo_test.go | 119 - src/pkg/runtime/crash_test.go | 382 - src/pkg/runtime/debug.go | 56 - src/pkg/runtime/debug/debug.c | 9 - src/pkg/runtime/debug/garbage.go | 147 - src/pkg/runtime/debug/garbage_test.go | 102 - src/pkg/runtime/debug/heapdump_test.go | 33 - src/pkg/runtime/debug/stack.go | 98 - src/pkg/runtime/debug/stack_test.go | 62 - src/pkg/runtime/debug/stubs.go | 20 - src/pkg/runtime/debug/stubs.s | 21 - src/pkg/runtime/defs.c | 15 - src/pkg/runtime/defs1_linux.go | 37 - src/pkg/runtime/defs2_linux.go | 146 - src/pkg/runtime/defs_android_arm.h | 3 - src/pkg/runtime/defs_arm_linux.go | 124 - src/pkg/runtime/defs_darwin.go | 179 - src/pkg/runtime/defs_darwin_386.h | 392 - src/pkg/runtime/defs_darwin_amd64.h | 395 - src/pkg/runtime/defs_dragonfly.go | 126 - src/pkg/runtime/defs_dragonfly_386.h | 198 - src/pkg/runtime/defs_dragonfly_amd64.h | 208 - src/pkg/runtime/defs_freebsd.go | 133 - src/pkg/runtime/defs_freebsd_386.h | 213 - src/pkg/runtime/defs_freebsd_amd64.h | 224 - src/pkg/runtime/defs_freebsd_arm.h | 186 - src/pkg/runtime/defs_linux.go | 124 - src/pkg/runtime/defs_linux_386.h | 211 - src/pkg/runtime/defs_linux_amd64.h | 254 - src/pkg/runtime/defs_linux_arm.h | 168 - src/pkg/runtime/defs_nacl_386.h | 63 - src/pkg/runtime/defs_nacl_amd64p32.h | 90 - src/pkg/runtime/defs_nacl_arm.h | 70 - src/pkg/runtime/defs_netbsd.go | 125 - src/pkg/runtime/defs_netbsd_386.go | 41 - src/pkg/runtime/defs_netbsd_386.h | 182 - src/pkg/runtime/defs_netbsd_amd64.go | 48 - src/pkg/runtime/defs_netbsd_amd64.h | 194 - src/pkg/runtime/defs_netbsd_arm.go | 39 - src/pkg/runtime/defs_netbsd_arm.h | 184 - src/pkg/runtime/defs_openbsd.go | 121 - src/pkg/runtime/defs_openbsd_386.h | 168 - src/pkg/runtime/defs_openbsd_amd64.h | 179 - src/pkg/runtime/defs_plan9_386.h | 26 - src/pkg/runtime/defs_plan9_amd64.h | 34 - src/pkg/runtime/defs_solaris.go | 156 - src/pkg/runtime/defs_solaris_amd64.go | 48 - src/pkg/runtime/defs_solaris_amd64.h | 254 - src/pkg/runtime/defs_windows.go | 70 - src/pkg/runtime/defs_windows_386.h | 113 - src/pkg/runtime/defs_windows_amd64.h | 128 - src/pkg/runtime/env_plan9.go | 52 - src/pkg/runtime/env_posix.go | 52 - src/pkg/runtime/error.go | 129 - src/pkg/runtime/export_futex_test.go | 10 - src/pkg/runtime/export_test.go | 163 - src/pkg/runtime/extern.go | 155 - src/pkg/runtime/float.c | 10 - src/pkg/runtime/funcdata.h | 37 - src/pkg/runtime/futex_test.go | 77 - src/pkg/runtime/gc_test.go | 292 - src/pkg/runtime/gcinfo_test.go | 193 - src/pkg/runtime/hash_test.go | 572 -- src/pkg/runtime/hashmap.go | 944 --- src/pkg/runtime/hashmap_fast.go | 379 - src/pkg/runtime/heapdump.c | 854 -- src/pkg/runtime/iface.go | 439 - src/pkg/runtime/iface_test.go | 138 - src/pkg/runtime/lfstack.c | 87 - src/pkg/runtime/lfstack_test.go | 136 - src/pkg/runtime/lock_futex.go | 205 - src/pkg/runtime/lock_sema.go | 270 - src/pkg/runtime/malloc.c | 439 - src/pkg/runtime/malloc.go | 814 -- src/pkg/runtime/malloc.h | 618 -- src/pkg/runtime/malloc_test.go | 189 - src/pkg/runtime/map_test.go | 477 -- src/pkg/runtime/mapspeed_test.go | 300 - src/pkg/runtime/mcache.c | 115 - src/pkg/runtime/mcentral.c | 214 - src/pkg/runtime/mem.go | 72 - src/pkg/runtime/mem_darwin.c | 82 - src/pkg/runtime/mem_dragonfly.c | 105 - src/pkg/runtime/mem_freebsd.c | 100 - src/pkg/runtime/mem_linux.c | 162 - src/pkg/runtime/mem_nacl.c | 120 - src/pkg/runtime/mem_netbsd.c | 100 - src/pkg/runtime/mem_openbsd.c | 100 - src/pkg/runtime/mem_plan9.c | 120 - src/pkg/runtime/mem_solaris.c | 101 - src/pkg/runtime/mem_windows.c | 120 - src/pkg/runtime/memclr_386.s | 128 - src/pkg/runtime/memclr_amd64.s | 117 - src/pkg/runtime/memclr_arm.s | 87 - src/pkg/runtime/memclr_plan9_386.s | 51 - src/pkg/runtime/memclr_plan9_amd64.s | 21 - src/pkg/runtime/memmove_386.s | 176 - src/pkg/runtime/memmove_amd64.s | 252 - src/pkg/runtime/memmove_arm.s | 261 - src/pkg/runtime/memmove_linux_amd64_test.go | 61 - src/pkg/runtime/memmove_nacl_amd64p32.s | 46 - src/pkg/runtime/memmove_plan9_386.s | 128 - src/pkg/runtime/memmove_plan9_amd64.s | 127 - src/pkg/runtime/memmove_test.go | 295 - src/pkg/runtime/mfinal_test.go | 239 - src/pkg/runtime/mfixalloc.c | 64 - src/pkg/runtime/mgc0.c | 1910 ----- src/pkg/runtime/mgc0.go | 70 - src/pkg/runtime/mgc0.h | 78 - src/pkg/runtime/mheap.c | 885 -- src/pkg/runtime/mknacl.sh | 15 - src/pkg/runtime/mprof.go | 660 -- src/pkg/runtime/msize.c | 184 - src/pkg/runtime/netpoll.go | 455 - src/pkg/runtime/netpoll_epoll.go | 97 - src/pkg/runtime/netpoll_kqueue.go | 101 - src/pkg/runtime/netpoll_nacl.go | 26 - src/pkg/runtime/netpoll_solaris.c | 264 - src/pkg/runtime/netpoll_stub.c | 18 - src/pkg/runtime/netpoll_windows.c | 163 - src/pkg/runtime/noasm_arm.go | 54 - src/pkg/runtime/norace_test.go | 46 - src/pkg/runtime/os_android.c | 16 - src/pkg/runtime/os_android.h | 1 - src/pkg/runtime/os_darwin.c | 595 -- src/pkg/runtime/os_darwin.go | 26 - src/pkg/runtime/os_darwin.h | 43 - src/pkg/runtime/os_dragonfly.c | 340 - src/pkg/runtime/os_dragonfly.go | 20 - src/pkg/runtime/os_dragonfly.h | 30 - src/pkg/runtime/os_freebsd.c | 348 - src/pkg/runtime/os_freebsd.go | 19 - src/pkg/runtime/os_freebsd.h | 29 - src/pkg/runtime/os_freebsd_arm.c | 24 - src/pkg/runtime/os_linux.c | 370 - src/pkg/runtime/os_linux.go | 19 - src/pkg/runtime/os_linux.h | 41 - src/pkg/runtime/os_linux_386.c | 38 - src/pkg/runtime/os_linux_arm.c | 80 - src/pkg/runtime/os_nacl.c | 325 - src/pkg/runtime/os_nacl.go | 30 - src/pkg/runtime/os_nacl.h | 162 - src/pkg/runtime/os_nacl_arm.c | 24 - src/pkg/runtime/os_netbsd.c | 396 - src/pkg/runtime/os_netbsd.go | 22 - src/pkg/runtime/os_netbsd.h | 31 - src/pkg/runtime/os_netbsd_386.c | 17 - src/pkg/runtime/os_netbsd_amd64.c | 18 - src/pkg/runtime/os_netbsd_arm.c | 34 - src/pkg/runtime/os_openbsd.c | 348 - src/pkg/runtime/os_openbsd.go | 19 - src/pkg/runtime/os_openbsd.h | 26 - src/pkg/runtime/os_plan9.c | 437 - src/pkg/runtime/os_plan9.go | 34 - src/pkg/runtime/os_plan9.h | 92 - src/pkg/runtime/os_plan9_386.c | 150 - src/pkg/runtime/os_plan9_amd64.c | 158 - src/pkg/runtime/os_solaris.c | 582 -- src/pkg/runtime/os_solaris.go | 101 - src/pkg/runtime/os_solaris.h | 55 - src/pkg/runtime/os_windows.c | 619 -- src/pkg/runtime/os_windows.go | 33 - src/pkg/runtime/os_windows.h | 42 - src/pkg/runtime/os_windows_386.c | 138 - src/pkg/runtime/os_windows_386.go | 11 - src/pkg/runtime/os_windows_amd64.c | 144 - src/pkg/runtime/os_windows_amd64.go | 11 - src/pkg/runtime/panic.c | 219 - src/pkg/runtime/panic.go | 216 - src/pkg/runtime/panic1.go | 209 - src/pkg/runtime/parfor.c | 238 - src/pkg/runtime/parfor_test.go | 139 - src/pkg/runtime/pprof/pprof.go | 673 -- src/pkg/runtime/pprof/pprof_test.go | 452 - src/pkg/runtime/print1.go | 341 - src/pkg/runtime/proc.c | 3663 -------- src/pkg/runtime/proc.go | 123 - src/pkg/runtime/proc_test.go | 480 -- src/pkg/runtime/race.c | 314 - src/pkg/runtime/race.go | 125 - src/pkg/runtime/race.h | 34 - src/pkg/runtime/race/README | 12 - src/pkg/runtime/race/doc.go | 9 - src/pkg/runtime/race/output_test.go | 156 - src/pkg/runtime/race/race.go | 15 - src/pkg/runtime/race/race_darwin_amd64.syso | Bin 278328 -> 0 bytes src/pkg/runtime/race/race_freebsd_amd64.syso | Bin 294224 -> 0 bytes src/pkg/runtime/race/race_linux_amd64.syso | Bin 298064 -> 0 bytes src/pkg/runtime/race/race_test.go | 172 - src/pkg/runtime/race/race_windows_amd64.syso | Bin 292311 -> 0 bytes src/pkg/runtime/race/testdata/atomic_test.go | 288 - src/pkg/runtime/race/testdata/cgo_test.go | 20 - src/pkg/runtime/race/testdata/cgo_test_main.go | 30 - src/pkg/runtime/race/testdata/chan_test.go | 659 -- src/pkg/runtime/race/testdata/comp_test.go | 186 - src/pkg/runtime/race/testdata/finalizer_test.go | 67 - src/pkg/runtime/race/testdata/io_test.go | 69 - src/pkg/runtime/race/testdata/map_test.go | 333 - src/pkg/runtime/race/testdata/mop_test.go | 1957 ----- src/pkg/runtime/race/testdata/mutex_test.go | 138 - src/pkg/runtime/race/testdata/regression_test.go | 194 - src/pkg/runtime/race/testdata/rwmutex_test.go | 134 - src/pkg/runtime/race/testdata/select_test.go | 286 - src/pkg/runtime/race/testdata/slice_test.go | 485 -- src/pkg/runtime/race/testdata/sync_test.go | 216 - src/pkg/runtime/race/testdata/waitgroup_test.go | 352 - src/pkg/runtime/race0.go | 37 - src/pkg/runtime/race_amd64.s | 383 - src/pkg/runtime/rdebug.go | 37 - src/pkg/runtime/rt0_android_arm.s | 11 - src/pkg/runtime/rt0_darwin_386.s | 16 - src/pkg/runtime/rt0_darwin_amd64.s | 15 - src/pkg/runtime/rt0_dragonfly_386.s | 16 - src/pkg/runtime/rt0_dragonfly_amd64.s | 15 - src/pkg/runtime/rt0_freebsd_386.s | 16 - src/pkg/runtime/rt0_freebsd_amd64.s | 15 - src/pkg/runtime/rt0_freebsd_arm.s | 18 - src/pkg/runtime/rt0_linux_386.s | 25 - src/pkg/runtime/rt0_linux_amd64.s | 15 - src/pkg/runtime/rt0_linux_arm.s | 91 - src/pkg/runtime/rt0_nacl_386.s | 22 - src/pkg/runtime/rt0_nacl_amd64p32.s | 30 - src/pkg/runtime/rt0_nacl_arm.s | 20 - src/pkg/runtime/rt0_netbsd_386.s | 16 - src/pkg/runtime/rt0_netbsd_amd64.s | 15 - src/pkg/runtime/rt0_netbsd_arm.s | 13 - src/pkg/runtime/rt0_openbsd_386.s | 16 - src/pkg/runtime/rt0_openbsd_amd64.s | 15 - src/pkg/runtime/rt0_plan9_386.s | 23 - src/pkg/runtime/rt0_plan9_amd64.s | 21 - src/pkg/runtime/rt0_solaris_amd64.s | 18 - src/pkg/runtime/rt0_windows_386.s | 20 - src/pkg/runtime/rt0_windows_amd64.s | 19 - src/pkg/runtime/rune.go | 219 - src/pkg/runtime/runtime-gdb.py | 478 -- src/pkg/runtime/runtime.c | 391 - src/pkg/runtime/runtime.go | 37 - src/pkg/runtime/runtime.h | 1079 --- src/pkg/runtime/runtime_linux_test.go | 29 - src/pkg/runtime/runtime_test.go | 243 - src/pkg/runtime/runtime_unix_test.go | 56 - src/pkg/runtime/select.go | 636 -- src/pkg/runtime/sema.go | 266 - src/pkg/runtime/signal.c | 25 - src/pkg/runtime/signal_386.c | 122 - src/pkg/runtime/signal_amd64x.c | 156 - src/pkg/runtime/signal_android_386.h | 1 - src/pkg/runtime/signal_android_arm.h | 1 - src/pkg/runtime/signal_arm.c | 121 - src/pkg/runtime/signal_darwin_386.h | 23 - src/pkg/runtime/signal_darwin_amd64.h | 31 - src/pkg/runtime/signal_dragonfly_386.h | 23 - src/pkg/runtime/signal_dragonfly_amd64.h | 31 - src/pkg/runtime/signal_freebsd_386.h | 23 - src/pkg/runtime/signal_freebsd_amd64.h | 31 - src/pkg/runtime/signal_freebsd_arm.h | 28 - src/pkg/runtime/signal_linux_386.h | 24 - src/pkg/runtime/signal_linux_amd64.h | 32 - src/pkg/runtime/signal_linux_arm.h | 28 - src/pkg/runtime/signal_nacl_386.h | 23 - src/pkg/runtime/signal_nacl_amd64p32.h | 31 - src/pkg/runtime/signal_nacl_arm.h | 28 - src/pkg/runtime/signal_netbsd_386.h | 23 - src/pkg/runtime/signal_netbsd_amd64.h | 31 - src/pkg/runtime/signal_netbsd_arm.h | 30 - src/pkg/runtime/signal_openbsd_386.h | 23 - src/pkg/runtime/signal_openbsd_amd64.h | 31 - src/pkg/runtime/signal_solaris_amd64.h | 31 - src/pkg/runtime/signal_unix.c | 119 - src/pkg/runtime/signal_unix.go | 13 - src/pkg/runtime/signal_unix.h | 14 - src/pkg/runtime/signals_android.h | 1 - src/pkg/runtime/signals_darwin.h | 50 - src/pkg/runtime/signals_dragonfly.h | 51 - src/pkg/runtime/signals_freebsd.h | 51 - src/pkg/runtime/signals_linux.h | 83 - src/pkg/runtime/signals_nacl.h | 50 - src/pkg/runtime/signals_netbsd.h | 51 - src/pkg/runtime/signals_openbsd.h | 51 - src/pkg/runtime/signals_plan9.h | 60 - src/pkg/runtime/signals_solaris.h | 94 - src/pkg/runtime/signals_windows.h | 3 - src/pkg/runtime/sigqueue.go | 173 - src/pkg/runtime/slice.go | 139 - src/pkg/runtime/softfloat64.go | 498 -- src/pkg/runtime/softfloat64_test.go | 198 - src/pkg/runtime/softfloat_arm.c | 687 -- src/pkg/runtime/sqrt.go | 150 - src/pkg/runtime/stack.c | 1128 --- src/pkg/runtime/stack.go | 13 - src/pkg/runtime/stack.h | 119 - src/pkg/runtime/stack_gen_test.go | 1473 ---- src/pkg/runtime/stack_test.go | 367 - src/pkg/runtime/string.c | 288 - src/pkg/runtime/string.go | 241 - src/pkg/runtime/string_test.go | 147 - src/pkg/runtime/stubs.go | 240 - src/pkg/runtime/symtab.go | 292 - src/pkg/runtime/symtab_test.go | 47 - src/pkg/runtime/sys_arm.c | 35 - src/pkg/runtime/sys_darwin_386.s | 541 -- src/pkg/runtime/sys_darwin_amd64.s | 505 -- src/pkg/runtime/sys_dragonfly_386.s | 381 - src/pkg/runtime/sys_dragonfly_amd64.s | 344 - src/pkg/runtime/sys_freebsd_386.s | 391 - src/pkg/runtime/sys_freebsd_amd64.s | 357 - src/pkg/runtime/sys_freebsd_arm.s | 382 - src/pkg/runtime/sys_linux_386.s | 489 -- src/pkg/runtime/sys_linux_amd64.s | 410 - src/pkg/runtime/sys_linux_arm.s | 461 - src/pkg/runtime/sys_nacl_386.s | 363 - src/pkg/runtime/sys_nacl_amd64p32.s | 459 - src/pkg/runtime/sys_nacl_arm.s | 320 - src/pkg/runtime/sys_netbsd_386.s | 384 - src/pkg/runtime/sys_netbsd_amd64.s | 358 - src/pkg/runtime/sys_netbsd_arm.s | 351 - src/pkg/runtime/sys_openbsd_386.s | 398 - src/pkg/runtime/sys_openbsd_amd64.s | 350 - src/pkg/runtime/sys_plan9_386.s | 258 - src/pkg/runtime/sys_plan9_amd64.s | 260 - src/pkg/runtime/sys_solaris_amd64.s | 349 - src/pkg/runtime/sys_windows_386.s | 380 - src/pkg/runtime/sys_windows_amd64.s | 407 - src/pkg/runtime/sys_x86.c | 57 - src/pkg/runtime/syscall_nacl.h | 71 - src/pkg/runtime/syscall_solaris.c | 23 - src/pkg/runtime/syscall_solaris.go | 322 - src/pkg/runtime/syscall_windows.c | 166 - src/pkg/runtime/syscall_windows.go | 88 - src/pkg/runtime/syscall_windows_test.go | 451 - src/pkg/runtime/thunk.s | 150 - src/pkg/runtime/thunk_solaris_amd64.s | 88 - src/pkg/runtime/time.go | 266 - src/pkg/runtime/tls_arm.s | 65 - src/pkg/runtime/traceback.go | 639 -- src/pkg/runtime/traceback_windows.go | 63 - src/pkg/runtime/type.h | 113 - src/pkg/runtime/typekind.go | 44 - src/pkg/runtime/typekind.h | 41 - src/pkg/runtime/vdso_linux_amd64.c | 366 - src/pkg/runtime/vlop_386.s | 56 - src/pkg/runtime/vlop_arm.s | 317 - src/pkg/runtime/vlop_arm_test.go | 70 - src/pkg/runtime/vlrt.c | 914 -- src/pkg/runtime/vlrt.go | 258 - src/pkg/sort/example_interface_test.go | 44 - src/pkg/sort/example_keys_test.go | 96 - src/pkg/sort/example_multi_test.go | 131 - src/pkg/sort/example_test.go | 24 - src/pkg/sort/example_wrapper_test.go | 77 - src/pkg/sort/export_test.go | 9 - src/pkg/sort/search.go | 112 - src/pkg/sort/search_test.go | 161 - src/pkg/sort/sort.go | 474 -- src/pkg/sort/sort_test.go | 553 -- src/pkg/strconv/atob.go | 35 - src/pkg/strconv/atob_test.go | 91 - src/pkg/strconv/atof.go | 540 -- src/pkg/strconv/atof_test.go | 430 - src/pkg/strconv/atoi.go | 198 - src/pkg/strconv/atoi_test.go | 326 - src/pkg/strconv/decimal.go | 378 - src/pkg/strconv/decimal_test.go | 127 - src/pkg/strconv/extfloat.go | 668 -- src/pkg/strconv/fp_test.go | 144 - src/pkg/strconv/ftoa.go | 475 -- src/pkg/strconv/ftoa_test.go | 240 - src/pkg/strconv/internal_test.go | 19 - src/pkg/strconv/isprint.go | 624 -- src/pkg/strconv/itoa.go | 131 - src/pkg/strconv/itoa_test.go | 160 - src/pkg/strconv/makeisprint.go | 187 - src/pkg/strconv/quote.go | 455 - src/pkg/strconv/quote_example_test.go | 35 - src/pkg/strconv/quote_test.go | 266 - src/pkg/strconv/strconv_test.go | 57 - src/pkg/strconv/testdata/testfp.txt | 181 - src/pkg/strings/example_test.go | 225 - src/pkg/strings/export_test.go | 45 - src/pkg/strings/reader.go | 144 - src/pkg/strings/reader_test.go | 159 - src/pkg/strings/replace.go | 518 -- src/pkg/strings/replace_test.go | 542 -- src/pkg/strings/search.go | 124 - src/pkg/strings/search_test.go | 90 - src/pkg/strings/strings.go | 765 -- src/pkg/strings/strings.s | 5 - src/pkg/strings/strings_decl.go | 8 - src/pkg/strings/strings_test.go | 1204 --- src/pkg/sync/atomic/64bit_arm.go | 46 - src/pkg/sync/atomic/asm_386.s | 214 - src/pkg/sync/atomic/asm_amd64.s | 146 - src/pkg/sync/atomic/asm_amd64p32.s | 159 - src/pkg/sync/atomic/asm_arm.s | 197 - src/pkg/sync/atomic/asm_freebsd_arm.s | 109 - src/pkg/sync/atomic/asm_linux_arm.s | 216 - src/pkg/sync/atomic/asm_nacl_arm.s | 109 - src/pkg/sync/atomic/asm_netbsd_arm.s | 109 - src/pkg/sync/atomic/atomic_linux_arm_test.go | 14 - src/pkg/sync/atomic/atomic_test.go | 1509 ---- src/pkg/sync/atomic/doc.go | 149 - src/pkg/sync/atomic/export_linux_arm_test.go | 9 - src/pkg/sync/atomic/race.s | 8 - src/pkg/sync/cond.go | 118 - src/pkg/sync/cond_test.go | 255 - src/pkg/sync/example_test.go | 59 - src/pkg/sync/export_test.go | 9 - src/pkg/sync/mutex.go | 109 - src/pkg/sync/mutex_test.go | 136 - src/pkg/sync/once.go | 43 - src/pkg/sync/once_test.go | 70 - src/pkg/sync/pool.go | 223 - src/pkg/sync/pool_test.go | 151 - src/pkg/sync/race.go | 42 - src/pkg/sync/race0.go | 34 - src/pkg/sync/runtime.go | 40 - src/pkg/sync/runtime_sema_test.go | 72 - src/pkg/sync/rwmutex.go | 136 - src/pkg/sync/rwmutex_test.go | 254 - src/pkg/sync/waitgroup.go | 137 - src/pkg/sync/waitgroup_test.go | 148 - src/pkg/syscall/asm_darwin_386.s | 142 - src/pkg/syscall/asm_darwin_amd64.s | 106 - src/pkg/syscall/asm_dragonfly_386.s | 139 - src/pkg/syscall/asm_dragonfly_amd64.s | 133 - src/pkg/syscall/asm_freebsd_386.s | 142 - src/pkg/syscall/asm_freebsd_amd64.s | 141 - src/pkg/syscall/asm_freebsd_arm.s | 129 - src/pkg/syscall/asm_linux_386.s | 186 - src/pkg/syscall/asm_linux_amd64.s | 126 - src/pkg/syscall/asm_linux_arm.s | 158 - src/pkg/syscall/asm_nacl_386.s | 43 - src/pkg/syscall/asm_nacl_amd64p32.s | 41 - src/pkg/syscall/asm_nacl_arm.s | 43 - src/pkg/syscall/asm_netbsd_386.s | 142 - src/pkg/syscall/asm_netbsd_amd64.s | 135 - src/pkg/syscall/asm_netbsd_arm.s | 126 - src/pkg/syscall/asm_openbsd_386.s | 142 - src/pkg/syscall/asm_openbsd_amd64.s | 135 - src/pkg/syscall/asm_plan9_386.s | 164 - src/pkg/syscall/asm_plan9_amd64.s | 162 - src/pkg/syscall/asm_solaris_amd64.s | 81 - src/pkg/syscall/asm_windows.s | 13 - src/pkg/syscall/bpf_bsd.go | 169 - src/pkg/syscall/creds_test.go | 113 - src/pkg/syscall/dir_plan9.go | 212 - src/pkg/syscall/dll_windows.go | 279 - src/pkg/syscall/env_plan9.go | 142 - src/pkg/syscall/env_unix.go | 119 - src/pkg/syscall/env_windows.go | 82 - src/pkg/syscall/exec_bsd.go | 247 - src/pkg/syscall/exec_linux.go | 262 - src/pkg/syscall/exec_plan9.go | 650 -- src/pkg/syscall/exec_solaris.go | 243 - src/pkg/syscall/exec_unix.go | 261 - src/pkg/syscall/exec_windows.go | 340 - src/pkg/syscall/fd_nacl.go | 326 - src/pkg/syscall/flock.go | 22 - src/pkg/syscall/flock_linux_32bit.go | 13 - src/pkg/syscall/fs_nacl.go | 832 -- src/pkg/syscall/lsf_linux.go | 78 - src/pkg/syscall/mkall.sh | 263 - src/pkg/syscall/mkall_windows.bat | 15 - src/pkg/syscall/mkerrors.sh | 433 - src/pkg/syscall/mksyscall.pl | 313 - src/pkg/syscall/mksyscall_solaris.pl | 279 - src/pkg/syscall/mksyscall_windows.go | 698 -- src/pkg/syscall/mksysctl_openbsd.pl | 257 - src/pkg/syscall/mksysnum_darwin.pl | 32 - src/pkg/syscall/mksysnum_dragonfly.pl | 43 - src/pkg/syscall/mksysnum_freebsd.pl | 56 - src/pkg/syscall/mksysnum_linux.pl | 38 - src/pkg/syscall/mksysnum_netbsd.pl | 51 - src/pkg/syscall/mksysnum_openbsd.pl | 43 - src/pkg/syscall/mksysnum_plan9.sh | 25 - src/pkg/syscall/mmap_unix_test.go | 22 - src/pkg/syscall/net_nacl.go | 913 -- src/pkg/syscall/netlink_linux.go | 178 - src/pkg/syscall/race.go | 30 - src/pkg/syscall/race0.go | 25 - src/pkg/syscall/route_bsd.go | 224 - src/pkg/syscall/route_darwin.go | 61 - src/pkg/syscall/route_dragonfly.go | 72 - src/pkg/syscall/route_freebsd.go | 78 - src/pkg/syscall/route_freebsd_32bit.go | 24 - src/pkg/syscall/route_freebsd_64bit.go | 14 - src/pkg/syscall/route_netbsd.go | 35 - src/pkg/syscall/route_openbsd.go | 35 - src/pkg/syscall/security_windows.go | 384 - src/pkg/syscall/so_solaris.go | 260 - src/pkg/syscall/sockcmsg_linux.go | 36 - src/pkg/syscall/sockcmsg_unix.go | 103 - src/pkg/syscall/srpc_nacl.go | 822 -- src/pkg/syscall/str.go | 20 - src/pkg/syscall/syscall.go | 88 - src/pkg/syscall/syscall_bsd.go | 588 -- src/pkg/syscall/syscall_bsd_test.go | 34 - src/pkg/syscall/syscall_darwin.go | 508 -- src/pkg/syscall/syscall_darwin_386.go | 70 - src/pkg/syscall/syscall_darwin_amd64.go | 70 - src/pkg/syscall/syscall_dragonfly.go | 408 - src/pkg/syscall/syscall_dragonfly_386.go | 58 - src/pkg/syscall/syscall_dragonfly_amd64.go | 58 - src/pkg/syscall/syscall_freebsd.go | 430 - src/pkg/syscall/syscall_freebsd_386.go | 58 - src/pkg/syscall/syscall_freebsd_amd64.go | 58 - src/pkg/syscall/syscall_freebsd_arm.go | 58 - src/pkg/syscall/syscall_linux.go | 1038 --- src/pkg/syscall/syscall_linux_386.go | 355 - src/pkg/syscall/syscall_linux_amd64.go | 114 - src/pkg/syscall/syscall_linux_arm.go | 195 - src/pkg/syscall/syscall_nacl.go | 311 - src/pkg/syscall/syscall_nacl_386.go | 32 - src/pkg/syscall/syscall_nacl_amd64p32.go | 32 - src/pkg/syscall/syscall_nacl_arm.go | 32 - src/pkg/syscall/syscall_netbsd.go | 489 -- src/pkg/syscall/syscall_netbsd_386.go | 42 - src/pkg/syscall/syscall_netbsd_amd64.go | 42 - src/pkg/syscall/syscall_netbsd_arm.go | 42 - src/pkg/syscall/syscall_no_getwd.go | 11 - src/pkg/syscall/syscall_openbsd.go | 299 - src/pkg/syscall/syscall_openbsd_386.go | 42 - src/pkg/syscall/syscall_openbsd_amd64.go | 42 - src/pkg/syscall/syscall_plan9.go | 339 - src/pkg/syscall/syscall_solaris.go | 523 -- src/pkg/syscall/syscall_solaris_amd64.go | 37 - src/pkg/syscall/syscall_test.go | 30 - src/pkg/syscall/syscall_unix.go | 299 - src/pkg/syscall/syscall_unix_test.go | 314 - src/pkg/syscall/syscall_windows.go | 1013 --- src/pkg/syscall/syscall_windows_386.go | 5 - src/pkg/syscall/syscall_windows_amd64.go | 5 - src/pkg/syscall/syscall_windows_test.go | 72 - src/pkg/syscall/tables_nacl.go | 324 - src/pkg/syscall/time_nacl_386.s | 11 - src/pkg/syscall/time_nacl_amd64p32.s | 11 - src/pkg/syscall/time_nacl_arm.s | 11 - src/pkg/syscall/types_darwin.go | 243 - src/pkg/syscall/types_dragonfly.go | 242 - src/pkg/syscall/types_freebsd.go | 342 - src/pkg/syscall/types_linux.go | 484 -- src/pkg/syscall/types_netbsd.go | 232 - src/pkg/syscall/types_openbsd.go | 244 - src/pkg/syscall/types_plan9.c | 115 - src/pkg/syscall/types_solaris.go | 222 - src/pkg/syscall/unzip_nacl.go | 685 -- src/pkg/syscall/zerrors_darwin_386.go | 1421 ---- src/pkg/syscall/zerrors_darwin_amd64.go | 1421 ---- src/pkg/syscall/zerrors_dragonfly_386.go | 1526 ---- src/pkg/syscall/zerrors_dragonfly_amd64.go | 1526 ---- src/pkg/syscall/zerrors_freebsd_386.go | 1715 ---- src/pkg/syscall/zerrors_freebsd_amd64.go | 1716 ---- src/pkg/syscall/zerrors_freebsd_arm.go | 1715 ---- src/pkg/syscall/zerrors_linux_386.go | 1544 ---- src/pkg/syscall/zerrors_linux_amd64.go | 1545 ---- src/pkg/syscall/zerrors_linux_arm.go | 1558 ---- src/pkg/syscall/zerrors_netbsd_386.go | 1708 ---- src/pkg/syscall/zerrors_netbsd_amd64.go | 1698 ---- src/pkg/syscall/zerrors_netbsd_arm.go | 1684 ---- src/pkg/syscall/zerrors_openbsd_386.go | 1580 ---- src/pkg/syscall/zerrors_openbsd_amd64.go | 1579 ---- src/pkg/syscall/zerrors_plan9_386.go | 48 - src/pkg/syscall/zerrors_plan9_amd64.go | 48 - src/pkg/syscall/zerrors_solaris_amd64.go | 1414 ---- src/pkg/syscall/zerrors_windows.go | 283 - src/pkg/syscall/zerrors_windows_386.go | 5 - src/pkg/syscall/zerrors_windows_amd64.go | 5 - src/pkg/syscall/zsyscall_darwin_386.go | 1387 --- src/pkg/syscall/zsyscall_darwin_amd64.go | 1387 --- src/pkg/syscall/zsyscall_dragonfly_386.go | 1287 --- src/pkg/syscall/zsyscall_dragonfly_amd64.go | 1287 --- src/pkg/syscall/zsyscall_freebsd_386.go | 1298 --- src/pkg/syscall/zsyscall_freebsd_amd64.go | 1298 --- src/pkg/syscall/zsyscall_freebsd_arm.go | 1298 --- src/pkg/syscall/zsyscall_linux_386.go | 1717 ---- src/pkg/syscall/zsyscall_linux_amd64.go | 1910 ----- src/pkg/syscall/zsyscall_linux_arm.go | 1865 ----- src/pkg/syscall/zsyscall_nacl_386.go | 63 - src/pkg/syscall/zsyscall_nacl_amd64p32.go | 63 - src/pkg/syscall/zsyscall_nacl_arm.go | 63 - src/pkg/syscall/zsyscall_netbsd_386.go | 1224 --- src/pkg/syscall/zsyscall_netbsd_amd64.go | 1224 --- src/pkg/syscall/zsyscall_netbsd_arm.go | 1224 --- src/pkg/syscall/zsyscall_openbsd_386.go | 1262 --- src/pkg/syscall/zsyscall_openbsd_amd64.go | 1262 --- src/pkg/syscall/zsyscall_plan9_386.go | 282 - src/pkg/syscall/zsyscall_plan9_amd64.go | 282 - src/pkg/syscall/zsyscall_solaris_amd64.go | 883 -- src/pkg/syscall/zsyscall_windows.go | 1846 ---- src/pkg/syscall/zsysctl_openbsd.go | 270 - src/pkg/syscall/zsysnum_darwin_386.go | 360 - src/pkg/syscall/zsysnum_darwin_amd64.go | 360 - src/pkg/syscall/zsysnum_dragonfly_386.go | 302 - src/pkg/syscall/zsysnum_dragonfly_amd64.go | 302 - src/pkg/syscall/zsysnum_freebsd_386.go | 348 - src/pkg/syscall/zsysnum_freebsd_amd64.go | 348 - src/pkg/syscall/zsysnum_freebsd_arm.go | 348 - src/pkg/syscall/zsysnum_linux_386.go | 345 - src/pkg/syscall/zsysnum_linux_amd64.go | 310 - src/pkg/syscall/zsysnum_linux_arm.go | 354 - src/pkg/syscall/zsysnum_netbsd_386.go | 271 - src/pkg/syscall/zsysnum_netbsd_amd64.go | 271 - src/pkg/syscall/zsysnum_netbsd_arm.go | 271 - src/pkg/syscall/zsysnum_openbsd_386.go | 205 - src/pkg/syscall/zsysnum_openbsd_amd64.go | 205 - src/pkg/syscall/zsysnum_plan9_386.go | 49 - src/pkg/syscall/zsysnum_plan9_amd64.go | 49 - src/pkg/syscall/zsysnum_solaris_amd64.go | 11 - src/pkg/syscall/zsysnum_windows_386.go | 3 - src/pkg/syscall/zsysnum_windows_amd64.go | 3 - src/pkg/syscall/ztypes_darwin_386.go | 446 - src/pkg/syscall/ztypes_darwin_amd64.go | 456 - src/pkg/syscall/ztypes_dragonfly_386.go | 435 - src/pkg/syscall/ztypes_dragonfly_amd64.go | 441 - src/pkg/syscall/ztypes_freebsd_386.go | 492 -- src/pkg/syscall/ztypes_freebsd_amd64.go | 495 -- src/pkg/syscall/ztypes_freebsd_arm.go | 495 -- src/pkg/syscall/ztypes_linux_386.go | 690 -- src/pkg/syscall/ztypes_linux_amd64.go | 708 -- src/pkg/syscall/ztypes_linux_arm.go | 679 -- src/pkg/syscall/ztypes_netbsd_386.go | 394 - src/pkg/syscall/ztypes_netbsd_amd64.go | 401 - src/pkg/syscall/ztypes_netbsd_arm.go | 399 - src/pkg/syscall/ztypes_openbsd_386.go | 439 - src/pkg/syscall/ztypes_openbsd_amd64.go | 446 - src/pkg/syscall/ztypes_plan9_386.go | 75 - src/pkg/syscall/ztypes_plan9_amd64.go | 75 - src/pkg/syscall/ztypes_solaris_amd64.go | 365 - src/pkg/syscall/ztypes_windows.go | 1104 --- src/pkg/syscall/ztypes_windows_386.go | 22 - src/pkg/syscall/ztypes_windows_amd64.go | 22 - src/pkg/testing/allocs.go | 45 - src/pkg/testing/benchmark.go | 446 - src/pkg/testing/benchmark_test.go | 113 - src/pkg/testing/cover.go | 109 - src/pkg/testing/example.go | 100 - src/pkg/testing/export_test.go | 10 - src/pkg/testing/iotest/logger.go | 54 - src/pkg/testing/iotest/reader.go | 88 - src/pkg/testing/iotest/writer.go | 35 - src/pkg/testing/quick/quick.go | 358 - src/pkg/testing/quick/quick_test.go | 249 - src/pkg/testing/testing.go | 662 -- src/pkg/text/scanner/scanner.go | 693 -- src/pkg/text/scanner/scanner_test.go | 618 -- src/pkg/text/tabwriter/example_test.go | 38 - src/pkg/text/tabwriter/tabwriter.go | 558 -- src/pkg/text/tabwriter/tabwriter_test.go | 652 -- src/pkg/text/template/doc.go | 405 - src/pkg/text/template/example_test.go | 71 - src/pkg/text/template/examplefiles_test.go | 182 - src/pkg/text/template/examplefunc_test.go | 54 - src/pkg/text/template/exec.go | 842 -- src/pkg/text/template/exec_test.go | 994 --- src/pkg/text/template/funcs.go | 580 -- src/pkg/text/template/helper.go | 108 - src/pkg/text/template/multi_test.go | 292 - src/pkg/text/template/parse/lex.go | 551 -- src/pkg/text/template/parse/lex_test.go | 465 - src/pkg/text/template/parse/node.go | 834 -- src/pkg/text/template/parse/parse.go | 677 -- src/pkg/text/template/parse/parse_test.go | 423 - src/pkg/text/template/template.go | 217 - src/pkg/text/template/testdata/file1.tmpl | 2 - src/pkg/text/template/testdata/file2.tmpl | 2 - src/pkg/text/template/testdata/tmpl1.tmpl | 3 - src/pkg/text/template/testdata/tmpl2.tmpl | 3 - src/pkg/time/example_test.go | 160 - src/pkg/time/export_test.go | 24 - src/pkg/time/export_windows_test.go | 10 - src/pkg/time/format.go | 1248 --- src/pkg/time/format_test.go | 518 -- src/pkg/time/genzabbrs.go | 159 - src/pkg/time/internal_test.go | 59 - src/pkg/time/sleep.go | 123 - src/pkg/time/sleep_test.go | 409 - src/pkg/time/sys_plan9.go | 76 - src/pkg/time/sys_unix.go | 76 - src/pkg/time/sys_windows.go | 73 - src/pkg/time/tick.go | 56 - src/pkg/time/tick_test.go | 78 - src/pkg/time/time.go | 1198 --- src/pkg/time/time_test.go | 1081 --- src/pkg/time/zoneinfo.go | 287 - src/pkg/time/zoneinfo_abbrs_windows.go | 116 - src/pkg/time/zoneinfo_plan9.go | 160 - src/pkg/time/zoneinfo_read.go | 343 - src/pkg/time/zoneinfo_test.go | 63 - src/pkg/time/zoneinfo_unix.go | 84 - src/pkg/time/zoneinfo_windows.go | 272 - src/pkg/time/zoneinfo_windows_test.go | 35 - src/pkg/unicode/casetables.go | 20 - src/pkg/unicode/digit.go | 13 - src/pkg/unicode/digit_test.go | 126 - src/pkg/unicode/graphic.go | 144 - src/pkg/unicode/graphic_test.go | 122 - src/pkg/unicode/letter.go | 357 - src/pkg/unicode/letter_test.go | 535 -- src/pkg/unicode/maketables.go | 1376 --- src/pkg/unicode/script_test.go | 287 - src/pkg/unicode/tables.go | 7029 ---------------- src/pkg/unicode/utf16/export_test.go | 11 - src/pkg/unicode/utf16/utf16.go | 108 - src/pkg/unicode/utf16/utf16_test.go | 149 - src/pkg/unicode/utf8/example_test.go | 196 - src/pkg/unicode/utf8/utf8.go | 435 - src/pkg/unicode/utf8/utf8_test.go | 444 - src/pkg/unsafe/unsafe.go | 37 - 2097 files changed, 511731 deletions(-) delete mode 100644 src/pkg/archive/tar/common.go delete mode 100644 src/pkg/archive/tar/example_test.go delete mode 100644 src/pkg/archive/tar/reader.go delete mode 100644 src/pkg/archive/tar/reader_test.go delete mode 100644 src/pkg/archive/tar/stat_atim.go delete mode 100644 src/pkg/archive/tar/stat_atimespec.go delete mode 100644 src/pkg/archive/tar/stat_unix.go delete mode 100644 src/pkg/archive/tar/tar_test.go delete mode 100644 src/pkg/archive/tar/testdata/gnu.tar delete mode 100644 src/pkg/archive/tar/testdata/nil-uid.tar delete mode 100644 src/pkg/archive/tar/testdata/pax.tar delete mode 100644 src/pkg/archive/tar/testdata/small.txt delete mode 100644 src/pkg/archive/tar/testdata/small2.txt delete mode 100644 src/pkg/archive/tar/testdata/sparse-formats.tar delete mode 100644 src/pkg/archive/tar/testdata/star.tar delete mode 100644 src/pkg/archive/tar/testdata/ustar.tar delete mode 100644 src/pkg/archive/tar/testdata/v7.tar delete mode 100644 src/pkg/archive/tar/testdata/writer-big-long.tar delete mode 100644 src/pkg/archive/tar/testdata/writer-big.tar delete mode 100644 src/pkg/archive/tar/testdata/writer.tar delete mode 100644 src/pkg/archive/tar/testdata/xattrs.tar delete mode 100644 src/pkg/archive/tar/writer.go delete mode 100644 src/pkg/archive/tar/writer_test.go delete mode 100644 src/pkg/archive/zip/example_test.go delete mode 100644 src/pkg/archive/zip/reader.go delete mode 100644 src/pkg/archive/zip/reader_test.go delete mode 100644 src/pkg/archive/zip/register.go delete mode 100644 src/pkg/archive/zip/struct.go delete mode 100644 src/pkg/archive/zip/testdata/crc32-not-streamed.zip delete mode 100644 src/pkg/archive/zip/testdata/dd.zip delete mode 100644 src/pkg/archive/zip/testdata/go-no-datadesc-sig.zip delete mode 100644 src/pkg/archive/zip/testdata/go-with-datadesc-sig.zip delete mode 100644 src/pkg/archive/zip/testdata/gophercolor16x16.png delete mode 100644 src/pkg/archive/zip/testdata/readme.notzip delete mode 100644 src/pkg/archive/zip/testdata/readme.zip delete mode 100644 src/pkg/archive/zip/testdata/symlink.zip delete mode 100644 src/pkg/archive/zip/testdata/test-trailing-junk.zip delete mode 100644 src/pkg/archive/zip/testdata/test.zip delete mode 100644 src/pkg/archive/zip/testdata/unix.zip delete mode 100644 src/pkg/archive/zip/testdata/winxp.zip delete mode 100644 src/pkg/archive/zip/testdata/zip64-2.zip delete mode 100644 src/pkg/archive/zip/testdata/zip64.zip delete mode 100644 src/pkg/archive/zip/writer.go delete mode 100644 src/pkg/archive/zip/writer_test.go delete mode 100644 src/pkg/archive/zip/zip_test.go delete mode 100644 src/pkg/bufio/bufio.go delete mode 100644 src/pkg/bufio/bufio_test.go delete mode 100644 src/pkg/bufio/example_test.go delete mode 100644 src/pkg/bufio/export_test.go delete mode 100644 src/pkg/bufio/scan.go delete mode 100644 src/pkg/bufio/scan_test.go delete mode 100644 src/pkg/builtin/builtin.go delete mode 100644 src/pkg/bytes/buffer.go delete mode 100644 src/pkg/bytes/buffer_test.go delete mode 100644 src/pkg/bytes/bytes.go delete mode 100644 src/pkg/bytes/bytes.s delete mode 100644 src/pkg/bytes/bytes_decl.go delete mode 100644 src/pkg/bytes/bytes_test.go delete mode 100644 src/pkg/bytes/compare_test.go delete mode 100644 src/pkg/bytes/equal_test.go delete mode 100644 src/pkg/bytes/example_test.go delete mode 100644 src/pkg/bytes/export_test.go delete mode 100644 src/pkg/bytes/reader.go delete mode 100644 src/pkg/bytes/reader_test.go delete mode 100644 src/pkg/compress/bzip2/bit_reader.go delete mode 100644 src/pkg/compress/bzip2/bzip2.go delete mode 100644 src/pkg/compress/bzip2/bzip2_test.go delete mode 100644 src/pkg/compress/bzip2/huffman.go delete mode 100644 src/pkg/compress/bzip2/move_to_front.go delete mode 100644 src/pkg/compress/bzip2/testdata/Mark.Twain-Tom.Sawyer.txt.bz2 delete mode 100644 src/pkg/compress/bzip2/testdata/e.txt.bz2 delete mode 100644 src/pkg/compress/flate/copy.go delete mode 100644 src/pkg/compress/flate/copy_test.go delete mode 100644 src/pkg/compress/flate/deflate.go delete mode 100644 src/pkg/compress/flate/deflate_test.go delete mode 100644 src/pkg/compress/flate/fixedhuff.go delete mode 100644 src/pkg/compress/flate/flate_test.go delete mode 100644 src/pkg/compress/flate/gen.go delete mode 100644 src/pkg/compress/flate/huffman_bit_writer.go delete mode 100644 src/pkg/compress/flate/huffman_code.go delete mode 100644 src/pkg/compress/flate/inflate.go delete mode 100644 src/pkg/compress/flate/reader_test.go delete mode 100644 src/pkg/compress/flate/reverse_bits.go delete mode 100644 src/pkg/compress/flate/token.go delete mode 100644 src/pkg/compress/flate/writer_test.go delete mode 100644 src/pkg/compress/gzip/gunzip.go delete mode 100644 src/pkg/compress/gzip/gunzip_test.go delete mode 100644 src/pkg/compress/gzip/gzip.go delete mode 100644 src/pkg/compress/gzip/gzip_test.go delete mode 100644 src/pkg/compress/gzip/testdata/issue6550.gz delete mode 100644 src/pkg/compress/lzw/reader.go delete mode 100644 src/pkg/compress/lzw/reader_test.go delete mode 100644 src/pkg/compress/lzw/writer.go delete mode 100644 src/pkg/compress/lzw/writer_test.go delete mode 100644 src/pkg/compress/testdata/Mark.Twain-Tom.Sawyer.txt delete mode 100644 src/pkg/compress/testdata/e.txt delete mode 100644 src/pkg/compress/testdata/pi.txt delete mode 100644 src/pkg/compress/zlib/example_test.go delete mode 100644 src/pkg/compress/zlib/reader.go delete mode 100644 src/pkg/compress/zlib/reader_test.go delete mode 100644 src/pkg/compress/zlib/writer.go delete mode 100644 src/pkg/compress/zlib/writer_test.go delete mode 100644 src/pkg/container/heap/example_intheap_test.go delete mode 100644 src/pkg/container/heap/example_pq_test.go delete mode 100644 src/pkg/container/heap/heap.go delete mode 100644 src/pkg/container/heap/heap_test.go delete mode 100644 src/pkg/container/list/example_test.go delete mode 100644 src/pkg/container/list/list.go delete mode 100644 src/pkg/container/list/list_test.go delete mode 100644 src/pkg/container/ring/ring.go delete mode 100644 src/pkg/container/ring/ring_test.go delete mode 100644 src/pkg/crypto/aes/aes_test.go delete mode 100644 src/pkg/crypto/aes/asm_amd64.s delete mode 100644 src/pkg/crypto/aes/block.go delete mode 100644 src/pkg/crypto/aes/cipher.go delete mode 100644 src/pkg/crypto/aes/cipher_asm.go delete mode 100644 src/pkg/crypto/aes/cipher_generic.go delete mode 100644 src/pkg/crypto/aes/const.go delete mode 100644 src/pkg/crypto/cipher/benchmark_test.go delete mode 100644 src/pkg/crypto/cipher/cbc.go delete mode 100644 src/pkg/crypto/cipher/cbc_aes_test.go delete mode 100644 src/pkg/crypto/cipher/cfb.go delete mode 100644 src/pkg/crypto/cipher/cfb_test.go delete mode 100644 src/pkg/crypto/cipher/cipher.go delete mode 100644 src/pkg/crypto/cipher/cipher_test.go delete mode 100644 src/pkg/crypto/cipher/common_test.go delete mode 100644 src/pkg/crypto/cipher/ctr.go delete mode 100644 src/pkg/crypto/cipher/ctr_aes_test.go delete mode 100644 src/pkg/crypto/cipher/example_test.go delete mode 100644 src/pkg/crypto/cipher/gcm.go delete mode 100644 src/pkg/crypto/cipher/gcm_test.go delete mode 100644 src/pkg/crypto/cipher/io.go delete mode 100644 src/pkg/crypto/cipher/ofb.go delete mode 100644 src/pkg/crypto/cipher/ofb_test.go delete mode 100644 src/pkg/crypto/cipher/xor.go delete mode 100644 src/pkg/crypto/cipher/xor_test.go delete mode 100644 src/pkg/crypto/crypto.go delete mode 100644 src/pkg/crypto/des/block.go delete mode 100644 src/pkg/crypto/des/cipher.go delete mode 100644 src/pkg/crypto/des/const.go delete mode 100644 src/pkg/crypto/des/des_test.go delete mode 100644 src/pkg/crypto/des/example_test.go delete mode 100644 src/pkg/crypto/dsa/dsa.go delete mode 100644 src/pkg/crypto/dsa/dsa_test.go delete mode 100644 src/pkg/crypto/ecdsa/ecdsa.go delete mode 100644 src/pkg/crypto/ecdsa/ecdsa_test.go delete mode 100644 src/pkg/crypto/ecdsa/testdata/SigVer.rsp.bz2 delete mode 100644 src/pkg/crypto/elliptic/elliptic.go delete mode 100644 src/pkg/crypto/elliptic/elliptic_test.go delete mode 100644 src/pkg/crypto/elliptic/p224.go delete mode 100644 src/pkg/crypto/elliptic/p224_test.go delete mode 100644 src/pkg/crypto/elliptic/p256.go delete mode 100644 src/pkg/crypto/hmac/hmac.go delete mode 100644 src/pkg/crypto/hmac/hmac_test.go delete mode 100644 src/pkg/crypto/md5/example_test.go delete mode 100644 src/pkg/crypto/md5/gen.go delete mode 100644 src/pkg/crypto/md5/md5.go delete mode 100644 src/pkg/crypto/md5/md5_test.go delete mode 100644 src/pkg/crypto/md5/md5block.go delete mode 100644 src/pkg/crypto/md5/md5block_386.s delete mode 100644 src/pkg/crypto/md5/md5block_amd64.s delete mode 100644 src/pkg/crypto/md5/md5block_amd64p32.s delete mode 100644 src/pkg/crypto/md5/md5block_arm.s delete mode 100644 src/pkg/crypto/md5/md5block_decl.go delete mode 100644 src/pkg/crypto/md5/md5block_generic.go delete mode 100644 src/pkg/crypto/rand/example_test.go delete mode 100644 src/pkg/crypto/rand/rand.go delete mode 100644 src/pkg/crypto/rand/rand_linux.go delete mode 100644 src/pkg/crypto/rand/rand_test.go delete mode 100644 src/pkg/crypto/rand/rand_unix.go delete mode 100644 src/pkg/crypto/rand/rand_windows.go delete mode 100644 src/pkg/crypto/rand/util.go delete mode 100644 src/pkg/crypto/rand/util_test.go delete mode 100644 src/pkg/crypto/rc4/rc4.go delete mode 100644 src/pkg/crypto/rc4/rc4_386.s delete mode 100644 src/pkg/crypto/rc4/rc4_amd64.s delete mode 100644 src/pkg/crypto/rc4/rc4_amd64p32.s delete mode 100644 src/pkg/crypto/rc4/rc4_arm.s delete mode 100644 src/pkg/crypto/rc4/rc4_asm.go delete mode 100644 src/pkg/crypto/rc4/rc4_ref.go delete mode 100644 src/pkg/crypto/rc4/rc4_test.go delete mode 100644 src/pkg/crypto/rsa/pkcs1v15.go delete mode 100644 src/pkg/crypto/rsa/pkcs1v15_test.go delete mode 100644 src/pkg/crypto/rsa/pss.go delete mode 100644 src/pkg/crypto/rsa/pss_test.go delete mode 100644 src/pkg/crypto/rsa/rsa.go delete mode 100644 src/pkg/crypto/rsa/rsa_test.go delete mode 100644 src/pkg/crypto/rsa/testdata/pss-vect.txt.bz2 delete mode 100644 src/pkg/crypto/sha1/example_test.go delete mode 100644 src/pkg/crypto/sha1/sha1.go delete mode 100644 src/pkg/crypto/sha1/sha1_test.go delete mode 100644 src/pkg/crypto/sha1/sha1block.go delete mode 100644 src/pkg/crypto/sha1/sha1block_386.s delete mode 100644 src/pkg/crypto/sha1/sha1block_amd64.s delete mode 100644 src/pkg/crypto/sha1/sha1block_amd64p32.s delete mode 100644 src/pkg/crypto/sha1/sha1block_arm.s delete mode 100644 src/pkg/crypto/sha1/sha1block_decl.go delete mode 100644 src/pkg/crypto/sha1/sha1block_generic.go delete mode 100644 src/pkg/crypto/sha256/sha256.go delete mode 100644 src/pkg/crypto/sha256/sha256_test.go delete mode 100644 src/pkg/crypto/sha256/sha256block.go delete mode 100644 src/pkg/crypto/sha256/sha256block_386.s delete mode 100644 src/pkg/crypto/sha256/sha256block_amd64.s delete mode 100644 src/pkg/crypto/sha256/sha256block_decl.go delete mode 100644 src/pkg/crypto/sha512/sha512.go delete mode 100644 src/pkg/crypto/sha512/sha512_test.go delete mode 100644 src/pkg/crypto/sha512/sha512block.go delete mode 100644 src/pkg/crypto/sha512/sha512block_amd64.s delete mode 100644 src/pkg/crypto/sha512/sha512block_decl.go delete mode 100644 src/pkg/crypto/subtle/constant_time.go delete mode 100644 src/pkg/crypto/subtle/constant_time_test.go delete mode 100644 src/pkg/crypto/tls/alert.go delete mode 100644 src/pkg/crypto/tls/cipher_suites.go delete mode 100644 src/pkg/crypto/tls/common.go delete mode 100644 src/pkg/crypto/tls/conn.go delete mode 100644 src/pkg/crypto/tls/conn_test.go delete mode 100644 src/pkg/crypto/tls/example_test.go delete mode 100644 src/pkg/crypto/tls/generate_cert.go delete mode 100644 src/pkg/crypto/tls/handshake_client.go delete mode 100644 src/pkg/crypto/tls/handshake_client_test.go delete mode 100644 src/pkg/crypto/tls/handshake_messages.go delete mode 100644 src/pkg/crypto/tls/handshake_messages_test.go delete mode 100644 src/pkg/crypto/tls/handshake_server.go delete mode 100644 src/pkg/crypto/tls/handshake_server_test.go delete mode 100644 src/pkg/crypto/tls/handshake_test.go delete mode 100644 src/pkg/crypto/tls/key_agreement.go delete mode 100644 src/pkg/crypto/tls/prf.go delete mode 100644 src/pkg/crypto/tls/prf_test.go delete mode 100644 src/pkg/crypto/tls/testdata/Client-TLSv10-ClientCert-ECDSA-ECDSA delete mode 100644 src/pkg/crypto/tls/testdata/Client-TLSv10-ClientCert-ECDSA-RSA delete mode 100644 src/pkg/crypto/tls/testdata/Client-TLSv10-ClientCert-RSA-ECDSA delete mode 100644 src/pkg/crypto/tls/testdata/Client-TLSv10-ClientCert-RSA-RSA delete mode 100644 src/pkg/crypto/tls/testdata/Client-TLSv10-ECDHE-ECDSA-AES delete mode 100644 src/pkg/crypto/tls/testdata/Client-TLSv10-ECDHE-RSA-AES delete mode 100644 src/pkg/crypto/tls/testdata/Client-TLSv10-RSA-RC4 delete mode 100644 src/pkg/crypto/tls/testdata/Client-TLSv11-ECDHE-ECDSA-AES delete mode 100644 src/pkg/crypto/tls/testdata/Client-TLSv11-ECDHE-RSA-AES delete mode 100644 src/pkg/crypto/tls/testdata/Client-TLSv11-RSA-RC4 delete mode 100644 src/pkg/crypto/tls/testdata/Client-TLSv12-ALPN delete mode 100644 src/pkg/crypto/tls/testdata/Client-TLSv12-ALPN-NoMatch delete mode 100644 src/pkg/crypto/tls/testdata/Client-TLSv12-ClientCert-ECDSA-ECDSA delete mode 100644 src/pkg/crypto/tls/testdata/Client-TLSv12-ClientCert-ECDSA-RSA delete mode 100644 src/pkg/crypto/tls/testdata/Client-TLSv12-ClientCert-RSA-ECDSA delete mode 100644 src/pkg/crypto/tls/testdata/Client-TLSv12-ClientCert-RSA-RSA delete mode 100644 src/pkg/crypto/tls/testdata/Client-TLSv12-ECDHE-ECDSA-AES delete mode 100644 src/pkg/crypto/tls/testdata/Client-TLSv12-ECDHE-ECDSA-AES-GCM delete mode 100644 src/pkg/crypto/tls/testdata/Client-TLSv12-ECDHE-RSA-AES delete mode 100644 src/pkg/crypto/tls/testdata/Client-TLSv12-RSA-RC4 delete mode 100644 src/pkg/crypto/tls/testdata/Server-SSLv3-RSA-3DES delete mode 100644 src/pkg/crypto/tls/testdata/Server-SSLv3-RSA-AES delete mode 100644 src/pkg/crypto/tls/testdata/Server-SSLv3-RSA-RC4 delete mode 100644 src/pkg/crypto/tls/testdata/Server-TLSv10-ECDHE-ECDSA-AES delete mode 100644 src/pkg/crypto/tls/testdata/Server-TLSv10-RSA-3DES delete mode 100644 src/pkg/crypto/tls/testdata/Server-TLSv10-RSA-AES delete mode 100644 src/pkg/crypto/tls/testdata/Server-TLSv10-RSA-RC4 delete mode 100644 src/pkg/crypto/tls/testdata/Server-TLSv11-RSA-RC4 delete mode 100644 src/pkg/crypto/tls/testdata/Server-TLSv12-ALPN delete mode 100644 src/pkg/crypto/tls/testdata/Server-TLSv12-ALPN-NoMatch delete mode 100644 src/pkg/crypto/tls/testdata/Server-TLSv12-CipherSuiteCertPreferenceECDSA delete mode 100644 src/pkg/crypto/tls/testdata/Server-TLSv12-CipherSuiteCertPreferenceRSA delete mode 100644 src/pkg/crypto/tls/testdata/Server-TLSv12-ClientAuthRequestedAndECDSAGiven delete mode 100644 src/pkg/crypto/tls/testdata/Server-TLSv12-ClientAuthRequestedAndGiven delete mode 100644 src/pkg/crypto/tls/testdata/Server-TLSv12-ClientAuthRequestedNotGiven delete mode 100644 src/pkg/crypto/tls/testdata/Server-TLSv12-ECDHE-ECDSA-AES delete mode 100644 src/pkg/crypto/tls/testdata/Server-TLSv12-IssueTicket delete mode 100644 src/pkg/crypto/tls/testdata/Server-TLSv12-RSA-3DES delete mode 100644 src/pkg/crypto/tls/testdata/Server-TLSv12-RSA-AES delete mode 100644 src/pkg/crypto/tls/testdata/Server-TLSv12-RSA-AES-GCM delete mode 100644 src/pkg/crypto/tls/testdata/Server-TLSv12-RSA-RC4 delete mode 100644 src/pkg/crypto/tls/testdata/Server-TLSv12-Resume delete mode 100644 src/pkg/crypto/tls/testdata/Server-TLSv12-SNI delete mode 100644 src/pkg/crypto/tls/ticket.go delete mode 100644 src/pkg/crypto/tls/tls.go delete mode 100644 src/pkg/crypto/tls/tls_test.go delete mode 100644 src/pkg/crypto/x509/cert_pool.go delete mode 100644 src/pkg/crypto/x509/example_test.go delete mode 100644 src/pkg/crypto/x509/pem_decrypt.go delete mode 100644 src/pkg/crypto/x509/pem_decrypt_test.go delete mode 100644 src/pkg/crypto/x509/pkcs1.go delete mode 100644 src/pkg/crypto/x509/pkcs8.go delete mode 100644 src/pkg/crypto/x509/pkcs8_test.go delete mode 100644 src/pkg/crypto/x509/pkix/pkix.go delete mode 100644 src/pkg/crypto/x509/root.go delete mode 100644 src/pkg/crypto/x509/root_cgo_darwin.go delete mode 100644 src/pkg/crypto/x509/root_darwin.go delete mode 100644 src/pkg/crypto/x509/root_darwin_test.go delete mode 100644 src/pkg/crypto/x509/root_nocgo_darwin.go delete mode 100644 src/pkg/crypto/x509/root_plan9.go delete mode 100644 src/pkg/crypto/x509/root_unix.go delete mode 100644 src/pkg/crypto/x509/root_windows.go delete mode 100644 src/pkg/crypto/x509/sec1.go delete mode 100644 src/pkg/crypto/x509/sec1_test.go delete mode 100644 src/pkg/crypto/x509/verify.go delete mode 100644 src/pkg/crypto/x509/verify_test.go delete mode 100644 src/pkg/crypto/x509/x509.go delete mode 100644 src/pkg/crypto/x509/x509_test.go delete mode 100644 src/pkg/crypto/x509/x509_test_import.go delete mode 100644 src/pkg/database/sql/convert.go delete mode 100644 src/pkg/database/sql/convert_test.go delete mode 100644 src/pkg/database/sql/doc.txt delete mode 100644 src/pkg/database/sql/driver/driver.go delete mode 100644 src/pkg/database/sql/driver/types.go delete mode 100644 src/pkg/database/sql/driver/types_test.go delete mode 100644 src/pkg/database/sql/example_test.go delete mode 100644 src/pkg/database/sql/fakedb_test.go delete mode 100644 src/pkg/database/sql/sql.go delete mode 100644 src/pkg/database/sql/sql_test.go delete mode 100644 src/pkg/debug/dwarf/buf.go delete mode 100644 src/pkg/debug/dwarf/const.go delete mode 100644 src/pkg/debug/dwarf/entry.go delete mode 100644 src/pkg/debug/dwarf/open.go delete mode 100644 src/pkg/debug/dwarf/testdata/typedef.c delete mode 100755 src/pkg/debug/dwarf/testdata/typedef.elf delete mode 100644 src/pkg/debug/dwarf/testdata/typedef.elf4 delete mode 100644 src/pkg/debug/dwarf/testdata/typedef.macho delete mode 100644 src/pkg/debug/dwarf/type.go delete mode 100644 src/pkg/debug/dwarf/type_test.go delete mode 100644 src/pkg/debug/dwarf/typeunit.go delete mode 100644 src/pkg/debug/dwarf/unit.go delete mode 100644 src/pkg/debug/elf/elf.go delete mode 100644 src/pkg/debug/elf/elf_test.go delete mode 100644 src/pkg/debug/elf/file.go delete mode 100644 src/pkg/debug/elf/file_test.go delete mode 100644 src/pkg/debug/elf/symbols_test.go delete mode 100755 src/pkg/debug/elf/testdata/gcc-386-freebsd-exec delete mode 100755 src/pkg/debug/elf/testdata/gcc-amd64-linux-exec delete mode 100644 src/pkg/debug/elf/testdata/gcc-amd64-openbsd-debug-with-rela.obj delete mode 100644 src/pkg/debug/elf/testdata/go-relocation-test-clang-x86.obj delete mode 100644 src/pkg/debug/elf/testdata/go-relocation-test-gcc424-x86-64.obj delete mode 100644 src/pkg/debug/elf/testdata/go-relocation-test-gcc441-x86-64.obj delete mode 100644 src/pkg/debug/elf/testdata/go-relocation-test-gcc441-x86.obj delete mode 100644 src/pkg/debug/elf/testdata/go-relocation-test-gcc482-aarch64.obj delete mode 100644 src/pkg/debug/elf/testdata/hello-world-core.gz delete mode 100644 src/pkg/debug/elf/testdata/hello.c delete mode 100644 src/pkg/debug/goobj/read.go delete mode 100644 src/pkg/debug/goobj/read_test.go delete mode 100644 src/pkg/debug/gosym/pclinetest.asm delete mode 100644 src/pkg/debug/gosym/pclinetest.h delete mode 100644 src/pkg/debug/gosym/pclntab.go delete mode 100644 src/pkg/debug/gosym/pclntab_test.go delete mode 100644 src/pkg/debug/gosym/symtab.go delete mode 100644 src/pkg/debug/macho/fat.go delete mode 100644 src/pkg/debug/macho/file.go delete mode 100644 src/pkg/debug/macho/file_test.go delete mode 100644 src/pkg/debug/macho/macho.go delete mode 100644 src/pkg/debug/macho/testdata/fat-gcc-386-amd64-darwin-exec delete mode 100755 src/pkg/debug/macho/testdata/gcc-386-darwin-exec delete mode 100755 src/pkg/debug/macho/testdata/gcc-amd64-darwin-exec delete mode 100644 src/pkg/debug/macho/testdata/gcc-amd64-darwin-exec-debug delete mode 100644 src/pkg/debug/macho/testdata/hello.c delete mode 100644 src/pkg/debug/pe/file.go delete mode 100644 src/pkg/debug/pe/file_test.go delete mode 100644 src/pkg/debug/pe/pe.go delete mode 100644 src/pkg/debug/pe/testdata/gcc-386-mingw-exec delete mode 100644 src/pkg/debug/pe/testdata/gcc-386-mingw-obj delete mode 100644 src/pkg/debug/pe/testdata/gcc-amd64-mingw-exec delete mode 100644 src/pkg/debug/pe/testdata/gcc-amd64-mingw-obj delete mode 100644 src/pkg/debug/pe/testdata/hello.c delete mode 100644 src/pkg/debug/plan9obj/file.go delete mode 100644 src/pkg/debug/plan9obj/file_test.go delete mode 100644 src/pkg/debug/plan9obj/plan9obj.go delete mode 100755 src/pkg/debug/plan9obj/testdata/386-plan9-exec delete mode 100755 src/pkg/debug/plan9obj/testdata/amd64-plan9-exec delete mode 100644 src/pkg/debug/plan9obj/testdata/hello.c delete mode 100644 src/pkg/encoding/ascii85/ascii85.go delete mode 100644 src/pkg/encoding/ascii85/ascii85_test.go delete mode 100644 src/pkg/encoding/asn1/asn1.go delete mode 100644 src/pkg/encoding/asn1/asn1_test.go delete mode 100644 src/pkg/encoding/asn1/common.go delete mode 100644 src/pkg/encoding/asn1/marshal.go delete mode 100644 src/pkg/encoding/asn1/marshal_test.go delete mode 100644 src/pkg/encoding/base32/base32.go delete mode 100644 src/pkg/encoding/base32/base32_test.go delete mode 100644 src/pkg/encoding/base32/example_test.go delete mode 100644 src/pkg/encoding/base64/base64.go delete mode 100644 src/pkg/encoding/base64/base64_test.go delete mode 100644 src/pkg/encoding/base64/example_test.go delete mode 100644 src/pkg/encoding/binary/binary.go delete mode 100644 src/pkg/encoding/binary/binary_test.go delete mode 100644 src/pkg/encoding/binary/example_test.go delete mode 100644 src/pkg/encoding/binary/varint.go delete mode 100644 src/pkg/encoding/binary/varint_test.go delete mode 100644 src/pkg/encoding/csv/reader.go delete mode 100644 src/pkg/encoding/csv/reader_test.go delete mode 100644 src/pkg/encoding/csv/writer.go delete mode 100644 src/pkg/encoding/csv/writer_test.go delete mode 100644 src/pkg/encoding/encoding.go delete mode 100644 src/pkg/encoding/gob/codec_test.go delete mode 100644 src/pkg/encoding/gob/debug.go delete mode 100644 src/pkg/encoding/gob/decode.go delete mode 100644 src/pkg/encoding/gob/decoder.go delete mode 100644 src/pkg/encoding/gob/doc.go delete mode 100644 src/pkg/encoding/gob/dump.go delete mode 100644 src/pkg/encoding/gob/encode.go delete mode 100644 src/pkg/encoding/gob/encoder.go delete mode 100644 src/pkg/encoding/gob/encoder_test.go delete mode 100644 src/pkg/encoding/gob/error.go delete mode 100644 src/pkg/encoding/gob/example_encdec_test.go delete mode 100644 src/pkg/encoding/gob/example_interface_test.go delete mode 100644 src/pkg/encoding/gob/example_test.go delete mode 100644 src/pkg/encoding/gob/gobencdec_test.go delete mode 100644 src/pkg/encoding/gob/timing_test.go delete mode 100644 src/pkg/encoding/gob/type.go delete mode 100644 src/pkg/encoding/gob/type_test.go delete mode 100644 src/pkg/encoding/hex/hex.go delete mode 100644 src/pkg/encoding/hex/hex_test.go delete mode 100644 src/pkg/encoding/json/bench_test.go delete mode 100644 src/pkg/encoding/json/decode.go delete mode 100644 src/pkg/encoding/json/decode_test.go delete mode 100644 src/pkg/encoding/json/encode.go delete mode 100644 src/pkg/encoding/json/encode_test.go delete mode 100644 src/pkg/encoding/json/example_test.go delete mode 100644 src/pkg/encoding/json/fold.go delete mode 100644 src/pkg/encoding/json/fold_test.go delete mode 100644 src/pkg/encoding/json/indent.go delete mode 100644 src/pkg/encoding/json/scanner.go delete mode 100644 src/pkg/encoding/json/scanner_test.go delete mode 100644 src/pkg/encoding/json/stream.go delete mode 100644 src/pkg/encoding/json/stream_test.go delete mode 100644 src/pkg/encoding/json/tagkey_test.go delete mode 100644 src/pkg/encoding/json/tags.go delete mode 100644 src/pkg/encoding/json/tags_test.go delete mode 100644 src/pkg/encoding/json/testdata/code.json.gz delete mode 100644 src/pkg/encoding/pem/pem.go delete mode 100644 src/pkg/encoding/pem/pem_test.go delete mode 100644 src/pkg/encoding/xml/atom_test.go delete mode 100644 src/pkg/encoding/xml/example_test.go delete mode 100644 src/pkg/encoding/xml/marshal.go delete mode 100644 src/pkg/encoding/xml/marshal_test.go delete mode 100644 src/pkg/encoding/xml/read.go delete mode 100644 src/pkg/encoding/xml/read_test.go delete mode 100644 src/pkg/encoding/xml/typeinfo.go delete mode 100644 src/pkg/encoding/xml/xml.go delete mode 100644 src/pkg/encoding/xml/xml_test.go delete mode 100644 src/pkg/errors/errors.go delete mode 100644 src/pkg/errors/errors_test.go delete mode 100644 src/pkg/errors/example_test.go delete mode 100644 src/pkg/expvar/expvar.go delete mode 100644 src/pkg/expvar/expvar_test.go delete mode 100644 src/pkg/flag/example_test.go delete mode 100644 src/pkg/flag/export_test.go delete mode 100644 src/pkg/flag/flag.go delete mode 100644 src/pkg/flag/flag_test.go delete mode 100644 src/pkg/fmt/doc.go delete mode 100644 src/pkg/fmt/export_test.go delete mode 100644 src/pkg/fmt/fmt_test.go delete mode 100644 src/pkg/fmt/format.go delete mode 100644 src/pkg/fmt/print.go delete mode 100644 src/pkg/fmt/scan.go delete mode 100644 src/pkg/fmt/scan_test.go delete mode 100644 src/pkg/fmt/stringer_test.go delete mode 100644 src/pkg/go/ast/ast.go delete mode 100644 src/pkg/go/ast/ast_test.go delete mode 100644 src/pkg/go/ast/commentmap.go delete mode 100644 src/pkg/go/ast/commentmap_test.go delete mode 100644 src/pkg/go/ast/example_test.go delete mode 100644 src/pkg/go/ast/filter.go delete mode 100644 src/pkg/go/ast/filter_test.go delete mode 100644 src/pkg/go/ast/import.go delete mode 100644 src/pkg/go/ast/print.go delete mode 100644 src/pkg/go/ast/print_test.go delete mode 100644 src/pkg/go/ast/resolve.go delete mode 100644 src/pkg/go/ast/scope.go delete mode 100644 src/pkg/go/ast/walk.go delete mode 100644 src/pkg/go/build/build.go delete mode 100644 src/pkg/go/build/build_test.go delete mode 100644 src/pkg/go/build/deps_test.go delete mode 100644 src/pkg/go/build/doc.go delete mode 100644 src/pkg/go/build/read.go delete mode 100644 src/pkg/go/build/read_test.go delete mode 100644 src/pkg/go/build/syslist.go delete mode 100644 src/pkg/go/build/syslist_test.go delete mode 100644 src/pkg/go/build/testdata/other/file/file.go delete mode 100644 src/pkg/go/build/testdata/other/main.go delete mode 100644 src/pkg/go/doc/Makefile delete mode 100644 src/pkg/go/doc/comment.go delete mode 100644 src/pkg/go/doc/comment_test.go delete mode 100644 src/pkg/go/doc/doc.go delete mode 100644 src/pkg/go/doc/doc_test.go delete mode 100644 src/pkg/go/doc/example.go delete mode 100644 src/pkg/go/doc/example_test.go delete mode 100644 src/pkg/go/doc/exports.go delete mode 100644 src/pkg/go/doc/filter.go delete mode 100644 src/pkg/go/doc/headscan.go delete mode 100644 src/pkg/go/doc/reader.go delete mode 100644 src/pkg/go/doc/synopsis.go delete mode 100644 src/pkg/go/doc/synopsis_test.go delete mode 100644 src/pkg/go/doc/testdata/a.0.golden delete mode 100644 src/pkg/go/doc/testdata/a.1.golden delete mode 100644 src/pkg/go/doc/testdata/a.2.golden delete mode 100644 src/pkg/go/doc/testdata/a0.go delete mode 100644 src/pkg/go/doc/testdata/a1.go delete mode 100644 src/pkg/go/doc/testdata/b.0.golden delete mode 100644 src/pkg/go/doc/testdata/b.1.golden delete mode 100644 src/pkg/go/doc/testdata/b.2.golden delete mode 100644 src/pkg/go/doc/testdata/b.go delete mode 100644 src/pkg/go/doc/testdata/benchmark.go delete mode 100644 src/pkg/go/doc/testdata/bugpara.0.golden delete mode 100644 src/pkg/go/doc/testdata/bugpara.1.golden delete mode 100644 src/pkg/go/doc/testdata/bugpara.2.golden delete mode 100644 src/pkg/go/doc/testdata/bugpara.go delete mode 100644 src/pkg/go/doc/testdata/c.0.golden delete mode 100644 src/pkg/go/doc/testdata/c.1.golden delete mode 100644 src/pkg/go/doc/testdata/c.2.golden delete mode 100644 src/pkg/go/doc/testdata/c.go delete mode 100644 src/pkg/go/doc/testdata/d.0.golden delete mode 100644 src/pkg/go/doc/testdata/d.1.golden delete mode 100644 src/pkg/go/doc/testdata/d.2.golden delete mode 100644 src/pkg/go/doc/testdata/d1.go delete mode 100644 src/pkg/go/doc/testdata/d2.go delete mode 100644 src/pkg/go/doc/testdata/e.0.golden delete mode 100644 src/pkg/go/doc/testdata/e.1.golden delete mode 100644 src/pkg/go/doc/testdata/e.2.golden delete mode 100644 src/pkg/go/doc/testdata/e.go delete mode 100644 src/pkg/go/doc/testdata/error1.0.golden delete mode 100644 src/pkg/go/doc/testdata/error1.1.golden delete mode 100644 src/pkg/go/doc/testdata/error1.2.golden delete mode 100644 src/pkg/go/doc/testdata/error1.go delete mode 100644 src/pkg/go/doc/testdata/error2.0.golden delete mode 100644 src/pkg/go/doc/testdata/error2.1.golden delete mode 100644 src/pkg/go/doc/testdata/error2.2.golden delete mode 100644 src/pkg/go/doc/testdata/error2.go delete mode 100644 src/pkg/go/doc/testdata/example.go delete mode 100644 src/pkg/go/doc/testdata/f.0.golden delete mode 100644 src/pkg/go/doc/testdata/f.1.golden delete mode 100644 src/pkg/go/doc/testdata/f.2.golden delete mode 100644 src/pkg/go/doc/testdata/f.go delete mode 100644 src/pkg/go/doc/testdata/template.txt delete mode 100644 src/pkg/go/doc/testdata/testing.0.golden delete mode 100644 src/pkg/go/doc/testdata/testing.1.golden delete mode 100644 src/pkg/go/doc/testdata/testing.2.golden delete mode 100644 src/pkg/go/doc/testdata/testing.go delete mode 100644 src/pkg/go/format/format.go delete mode 100644 src/pkg/go/format/format_test.go delete mode 100644 src/pkg/go/parser/error_test.go delete mode 100644 src/pkg/go/parser/example_test.go delete mode 100644 src/pkg/go/parser/interface.go delete mode 100644 src/pkg/go/parser/parser.go delete mode 100644 src/pkg/go/parser/parser_test.go delete mode 100644 src/pkg/go/parser/performance_test.go delete mode 100644 src/pkg/go/parser/short_test.go delete mode 100644 src/pkg/go/parser/testdata/commas.src delete mode 100644 src/pkg/go/parser/testdata/issue3106.src delete mode 100644 src/pkg/go/printer/example_test.go delete mode 100644 src/pkg/go/printer/nodes.go delete mode 100644 src/pkg/go/printer/performance_test.go delete mode 100644 src/pkg/go/printer/printer.go delete mode 100644 src/pkg/go/printer/printer_test.go delete mode 100644 src/pkg/go/printer/testdata/comments.golden delete mode 100644 src/pkg/go/printer/testdata/comments.input delete mode 100644 src/pkg/go/printer/testdata/comments.x delete mode 100644 src/pkg/go/printer/testdata/comments2.golden delete mode 100644 src/pkg/go/printer/testdata/comments2.input delete mode 100644 src/pkg/go/printer/testdata/declarations.golden delete mode 100644 src/pkg/go/printer/testdata/declarations.input delete mode 100644 src/pkg/go/printer/testdata/empty.golden delete mode 100644 src/pkg/go/printer/testdata/empty.input delete mode 100644 src/pkg/go/printer/testdata/expressions.golden delete mode 100644 src/pkg/go/printer/testdata/expressions.input delete mode 100644 src/pkg/go/printer/testdata/expressions.raw delete mode 100644 src/pkg/go/printer/testdata/linebreaks.golden delete mode 100644 src/pkg/go/printer/testdata/linebreaks.input delete mode 100644 src/pkg/go/printer/testdata/parser.go delete mode 100644 src/pkg/go/printer/testdata/slow.golden delete mode 100644 src/pkg/go/printer/testdata/slow.input delete mode 100644 src/pkg/go/printer/testdata/statements.golden delete mode 100644 src/pkg/go/printer/testdata/statements.input delete mode 100644 src/pkg/go/scanner/errors.go delete mode 100644 src/pkg/go/scanner/example_test.go delete mode 100644 src/pkg/go/scanner/scanner.go delete mode 100644 src/pkg/go/scanner/scanner_test.go delete mode 100644 src/pkg/go/token/position.go delete mode 100644 src/pkg/go/token/position_test.go delete mode 100644 src/pkg/go/token/serialize.go delete mode 100644 src/pkg/go/token/serialize_test.go delete mode 100644 src/pkg/go/token/token.go delete mode 100644 src/pkg/hash/adler32/adler32.go delete mode 100644 src/pkg/hash/adler32/adler32_test.go delete mode 100644 src/pkg/hash/crc32/crc32.go delete mode 100644 src/pkg/hash/crc32/crc32_amd64.s delete mode 100644 src/pkg/hash/crc32/crc32_amd64p32.s delete mode 100644 src/pkg/hash/crc32/crc32_amd64x.go delete mode 100644 src/pkg/hash/crc32/crc32_generic.go delete mode 100644 src/pkg/hash/crc32/crc32_test.go delete mode 100644 src/pkg/hash/crc64/crc64.go delete mode 100644 src/pkg/hash/crc64/crc64_test.go delete mode 100644 src/pkg/hash/fnv/fnv.go delete mode 100644 src/pkg/hash/fnv/fnv_test.go delete mode 100644 src/pkg/hash/hash.go delete mode 100644 src/pkg/hash/test_cases.txt delete mode 100644 src/pkg/hash/test_gen.awk delete mode 100644 src/pkg/html/entity.go delete mode 100644 src/pkg/html/entity_test.go delete mode 100644 src/pkg/html/escape.go delete mode 100644 src/pkg/html/escape_test.go delete mode 100644 src/pkg/html/template/attr.go delete mode 100644 src/pkg/html/template/clone_test.go delete mode 100644 src/pkg/html/template/content.go delete mode 100644 src/pkg/html/template/content_test.go delete mode 100644 src/pkg/html/template/context.go delete mode 100644 src/pkg/html/template/css.go delete mode 100644 src/pkg/html/template/css_test.go delete mode 100644 src/pkg/html/template/doc.go delete mode 100644 src/pkg/html/template/error.go delete mode 100644 src/pkg/html/template/escape.go delete mode 100644 src/pkg/html/template/escape_test.go delete mode 100644 src/pkg/html/template/html.go delete mode 100644 src/pkg/html/template/html_test.go delete mode 100644 src/pkg/html/template/js.go delete mode 100644 src/pkg/html/template/js_test.go delete mode 100644 src/pkg/html/template/template.go delete mode 100644 src/pkg/html/template/transition.go delete mode 100644 src/pkg/html/template/url.go delete mode 100644 src/pkg/html/template/url_test.go delete mode 100644 src/pkg/image/color/color.go delete mode 100644 src/pkg/image/color/palette/gen.go delete mode 100644 src/pkg/image/color/palette/generate.go delete mode 100644 src/pkg/image/color/palette/palette.go delete mode 100644 src/pkg/image/color/ycbcr.go delete mode 100644 src/pkg/image/color/ycbcr_test.go delete mode 100644 src/pkg/image/decode_example_test.go delete mode 100644 src/pkg/image/decode_test.go delete mode 100644 src/pkg/image/draw/bench_test.go delete mode 100644 src/pkg/image/draw/clip_test.go delete mode 100644 src/pkg/image/draw/draw.go delete mode 100644 src/pkg/image/draw/draw_test.go delete mode 100644 src/pkg/image/format.go delete mode 100644 src/pkg/image/geom.go delete mode 100644 src/pkg/image/gif/reader.go delete mode 100644 src/pkg/image/gif/reader_test.go delete mode 100644 src/pkg/image/gif/writer.go delete mode 100644 src/pkg/image/gif/writer_test.go delete mode 100644 src/pkg/image/image.go delete mode 100644 src/pkg/image/image_test.go delete mode 100644 src/pkg/image/jpeg/dct_test.go delete mode 100644 src/pkg/image/jpeg/fdct.go delete mode 100644 src/pkg/image/jpeg/huffman.go delete mode 100644 src/pkg/image/jpeg/idct.go delete mode 100644 src/pkg/image/jpeg/reader.go delete mode 100644 src/pkg/image/jpeg/reader_test.go delete mode 100644 src/pkg/image/jpeg/scan.go delete mode 100644 src/pkg/image/jpeg/writer.go delete mode 100644 src/pkg/image/jpeg/writer_test.go delete mode 100644 src/pkg/image/names.go delete mode 100644 src/pkg/image/png/paeth.go delete mode 100644 src/pkg/image/png/paeth_test.go delete mode 100644 src/pkg/image/png/reader.go delete mode 100644 src/pkg/image/png/reader_test.go delete mode 100644 src/pkg/image/png/testdata/benchGray.png delete mode 100644 src/pkg/image/png/testdata/benchNRGBA-gradient.png delete mode 100644 src/pkg/image/png/testdata/benchNRGBA-opaque.png delete mode 100644 src/pkg/image/png/testdata/benchPaletted.png delete mode 100644 src/pkg/image/png/testdata/benchRGB-interlace.png delete mode 100644 src/pkg/image/png/testdata/benchRGB.png delete mode 100644 src/pkg/image/png/testdata/invalid-crc32.png delete mode 100644 src/pkg/image/png/testdata/invalid-noend.png delete mode 100644 src/pkg/image/png/testdata/invalid-trunc.png delete mode 100644 src/pkg/image/png/testdata/invalid-zlib.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/README delete mode 100644 src/pkg/image/png/testdata/pngsuite/README.original delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn0g01-30.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn0g01-30.sng delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn0g01.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn0g01.sng delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn0g02-29.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn0g02-29.sng delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn0g02.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn0g02.sng delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn0g04-31.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn0g04-31.sng delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn0g04.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn0g04.sng delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn0g08.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn0g08.sng delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn0g16.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn0g16.sng delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn2c08.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn2c08.sng delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn2c16.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn2c16.sng delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn3p01.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn3p01.sng delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn3p02.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn3p02.sng delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn3p04-31i.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn3p04-31i.sng delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn3p04.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn3p04.sng delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn3p08-trns.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn3p08-trns.sng delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn3p08.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn3p08.sng delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn4a08.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn4a08.sng delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn4a16.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn4a16.sng delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn6a08.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn6a08.sng delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn6a16.png delete mode 100644 src/pkg/image/png/testdata/pngsuite/basn6a16.sng delete mode 100644 src/pkg/image/png/writer.go delete mode 100644 src/pkg/image/png/writer_test.go delete mode 100644 src/pkg/image/testdata/video-001.5bpp.gif delete mode 100644 src/pkg/image/testdata/video-001.gif delete mode 100644 src/pkg/image/testdata/video-001.interlaced.gif delete mode 100644 src/pkg/image/testdata/video-001.jpeg delete mode 100644 src/pkg/image/testdata/video-001.png delete mode 100644 src/pkg/image/testdata/video-001.progressive.jpeg delete mode 100644 src/pkg/image/testdata/video-001.q50.420.jpeg delete mode 100644 src/pkg/image/testdata/video-001.q50.420.progressive.jpeg delete mode 100644 src/pkg/image/testdata/video-001.q50.422.jpeg delete mode 100644 src/pkg/image/testdata/video-001.q50.422.progressive.jpeg delete mode 100644 src/pkg/image/testdata/video-001.q50.440.jpeg delete mode 100644 src/pkg/image/testdata/video-001.q50.440.progressive.jpeg delete mode 100644 src/pkg/image/testdata/video-001.q50.444.jpeg delete mode 100644 src/pkg/image/testdata/video-001.q50.444.progressive.jpeg delete mode 100644 src/pkg/image/testdata/video-001.separate.dc.progression.jpeg delete mode 100644 src/pkg/image/testdata/video-001.separate.dc.progression.progressive.jpeg delete mode 100644 src/pkg/image/testdata/video-005.gray.gif delete mode 100644 src/pkg/image/testdata/video-005.gray.jpeg delete mode 100644 src/pkg/image/testdata/video-005.gray.png delete mode 100644 src/pkg/image/testdata/video-005.gray.q50.2x2.jpeg delete mode 100644 src/pkg/image/testdata/video-005.gray.q50.2x2.progressive.jpeg delete mode 100644 src/pkg/image/testdata/video-005.gray.q50.jpeg delete mode 100644 src/pkg/image/testdata/video-005.gray.q50.progressive.jpeg delete mode 100644 src/pkg/image/ycbcr.go delete mode 100644 src/pkg/image/ycbcr_test.go delete mode 100644 src/pkg/index/suffixarray/qsufsort.go delete mode 100644 src/pkg/index/suffixarray/suffixarray.go delete mode 100644 src/pkg/index/suffixarray/suffixarray_test.go delete mode 100644 src/pkg/internal/syscall/getrandom_linux.go delete mode 100644 src/pkg/io/io.go delete mode 100644 src/pkg/io/io_test.go delete mode 100644 src/pkg/io/ioutil/ioutil.go delete mode 100644 src/pkg/io/ioutil/ioutil_test.go delete mode 100644 src/pkg/io/ioutil/tempfile.go delete mode 100644 src/pkg/io/ioutil/tempfile_test.go delete mode 100644 src/pkg/io/multi.go delete mode 100644 src/pkg/io/multi_test.go delete mode 100644 src/pkg/io/pipe.go delete mode 100644 src/pkg/io/pipe_test.go delete mode 100644 src/pkg/log/example_test.go delete mode 100644 src/pkg/log/log.go delete mode 100644 src/pkg/log/log_test.go delete mode 100644 src/pkg/log/syslog/syslog.go delete mode 100644 src/pkg/log/syslog/syslog_plan9.go delete mode 100644 src/pkg/log/syslog/syslog_test.go delete mode 100644 src/pkg/log/syslog/syslog_unix.go delete mode 100644 src/pkg/log/syslog/syslog_windows.go delete mode 100644 src/pkg/math/abs.go delete mode 100644 src/pkg/math/abs_386.s delete mode 100644 src/pkg/math/abs_amd64.s delete mode 100644 src/pkg/math/abs_amd64p32.s delete mode 100644 src/pkg/math/abs_arm.s delete mode 100644 src/pkg/math/acosh.go delete mode 100644 src/pkg/math/all_test.go delete mode 100644 src/pkg/math/asin.go delete mode 100644 src/pkg/math/asin_386.s delete mode 100644 src/pkg/math/asin_amd64.s delete mode 100644 src/pkg/math/asin_amd64p32.s delete mode 100644 src/pkg/math/asin_arm.s delete mode 100644 src/pkg/math/asinh.go delete mode 100644 src/pkg/math/atan.go delete mode 100644 src/pkg/math/atan2.go delete mode 100644 src/pkg/math/atan2_386.s delete mode 100644 src/pkg/math/atan2_amd64.s delete mode 100644 src/pkg/math/atan2_amd64p32.s delete mode 100644 src/pkg/math/atan2_arm.s delete mode 100644 src/pkg/math/atan_386.s delete mode 100644 src/pkg/math/atan_amd64.s delete mode 100644 src/pkg/math/atan_amd64p32.s delete mode 100644 src/pkg/math/atan_arm.s delete mode 100644 src/pkg/math/atanh.go delete mode 100644 src/pkg/math/big/arith.go delete mode 100644 src/pkg/math/big/arith_386.s delete mode 100644 src/pkg/math/big/arith_amd64.s delete mode 100644 src/pkg/math/big/arith_amd64p32.s delete mode 100644 src/pkg/math/big/arith_arm.s delete mode 100644 src/pkg/math/big/arith_decl.go delete mode 100644 src/pkg/math/big/arith_test.go delete mode 100644 src/pkg/math/big/calibrate_test.go delete mode 100644 src/pkg/math/big/example_test.go delete mode 100644 src/pkg/math/big/gcd_test.go delete mode 100644 src/pkg/math/big/hilbert_test.go delete mode 100644 src/pkg/math/big/int.go delete mode 100644 src/pkg/math/big/int_test.go delete mode 100644 src/pkg/math/big/nat.go delete mode 100644 src/pkg/math/big/nat_test.go delete mode 100644 src/pkg/math/big/rat.go delete mode 100644 src/pkg/math/big/rat_test.go delete mode 100644 src/pkg/math/bits.go delete mode 100644 src/pkg/math/cbrt.go delete mode 100644 src/pkg/math/cmplx/abs.go delete mode 100644 src/pkg/math/cmplx/asin.go delete mode 100644 src/pkg/math/cmplx/cmath_test.go delete mode 100644 src/pkg/math/cmplx/conj.go delete mode 100644 src/pkg/math/cmplx/exp.go delete mode 100644 src/pkg/math/cmplx/isinf.go delete mode 100644 src/pkg/math/cmplx/isnan.go delete mode 100644 src/pkg/math/cmplx/log.go delete mode 100644 src/pkg/math/cmplx/phase.go delete mode 100644 src/pkg/math/cmplx/polar.go delete mode 100644 src/pkg/math/cmplx/pow.go delete mode 100644 src/pkg/math/cmplx/rect.go delete mode 100644 src/pkg/math/cmplx/sin.go delete mode 100644 src/pkg/math/cmplx/sqrt.go delete mode 100644 src/pkg/math/cmplx/tan.go delete mode 100644 src/pkg/math/const.go delete mode 100644 src/pkg/math/copysign.go delete mode 100644 src/pkg/math/dim.go delete mode 100644 src/pkg/math/dim_386.s delete mode 100644 src/pkg/math/dim_amd64.s delete mode 100644 src/pkg/math/dim_amd64p32.s delete mode 100644 src/pkg/math/dim_arm.s delete mode 100644 src/pkg/math/erf.go delete mode 100644 src/pkg/math/exp.go delete mode 100644 src/pkg/math/exp2_386.s delete mode 100644 src/pkg/math/exp2_amd64.s delete mode 100644 src/pkg/math/exp2_amd64p32.s delete mode 100644 src/pkg/math/exp2_arm.s delete mode 100644 src/pkg/math/exp_386.s delete mode 100644 src/pkg/math/exp_amd64.s delete mode 100644 src/pkg/math/exp_amd64p32.s delete mode 100644 src/pkg/math/exp_arm.s delete mode 100644 src/pkg/math/expm1.go delete mode 100644 src/pkg/math/expm1_386.s delete mode 100644 src/pkg/math/expm1_amd64.s delete mode 100644 src/pkg/math/expm1_amd64p32.s delete mode 100644 src/pkg/math/expm1_arm.s delete mode 100644 src/pkg/math/export_test.go delete mode 100644 src/pkg/math/floor.go delete mode 100644 src/pkg/math/floor_386.s delete mode 100644 src/pkg/math/floor_amd64.s delete mode 100644 src/pkg/math/floor_amd64p32.s delete mode 100644 src/pkg/math/floor_arm.s delete mode 100644 src/pkg/math/frexp.go delete mode 100644 src/pkg/math/frexp_386.s delete mode 100644 src/pkg/math/frexp_amd64.s delete mode 100644 src/pkg/math/frexp_amd64p32.s delete mode 100644 src/pkg/math/frexp_arm.s delete mode 100644 src/pkg/math/gamma.go delete mode 100644 src/pkg/math/hypot.go delete mode 100644 src/pkg/math/hypot_386.s delete mode 100644 src/pkg/math/hypot_amd64.s delete mode 100644 src/pkg/math/hypot_amd64p32.s delete mode 100644 src/pkg/math/hypot_arm.s delete mode 100644 src/pkg/math/j0.go delete mode 100644 src/pkg/math/j1.go delete mode 100644 src/pkg/math/jn.go delete mode 100644 src/pkg/math/ldexp.go delete mode 100644 src/pkg/math/ldexp_386.s delete mode 100644 src/pkg/math/ldexp_amd64.s delete mode 100644 src/pkg/math/ldexp_amd64p32.s delete mode 100644 src/pkg/math/ldexp_arm.s delete mode 100644 src/pkg/math/lgamma.go delete mode 100644 src/pkg/math/log.go delete mode 100644 src/pkg/math/log10.go delete mode 100644 src/pkg/math/log10_386.s delete mode 100644 src/pkg/math/log10_amd64.s delete mode 100644 src/pkg/math/log10_amd64p32.s delete mode 100644 src/pkg/math/log10_arm.s delete mode 100644 src/pkg/math/log1p.go delete mode 100644 src/pkg/math/log1p_386.s delete mode 100644 src/pkg/math/log1p_amd64.s delete mode 100644 src/pkg/math/log1p_amd64p32.s delete mode 100644 src/pkg/math/log1p_arm.s delete mode 100644 src/pkg/math/log_386.s delete mode 100644 src/pkg/math/log_amd64.s delete mode 100644 src/pkg/math/log_amd64p32.s delete mode 100644 src/pkg/math/log_arm.s delete mode 100644 src/pkg/math/logb.go delete mode 100644 src/pkg/math/mod.go delete mode 100644 src/pkg/math/mod_386.s delete mode 100644 src/pkg/math/mod_amd64.s delete mode 100644 src/pkg/math/mod_amd64p32.s delete mode 100644 src/pkg/math/mod_arm.s delete mode 100644 src/pkg/math/modf.go delete mode 100644 src/pkg/math/modf_386.s delete mode 100644 src/pkg/math/modf_amd64.s delete mode 100644 src/pkg/math/modf_amd64p32.s delete mode 100644 src/pkg/math/modf_arm.s delete mode 100644 src/pkg/math/nextafter.go delete mode 100644 src/pkg/math/pow.go delete mode 100644 src/pkg/math/pow10.go delete mode 100644 src/pkg/math/rand/example_test.go delete mode 100644 src/pkg/math/rand/exp.go delete mode 100644 src/pkg/math/rand/normal.go delete mode 100644 src/pkg/math/rand/rand.go delete mode 100644 src/pkg/math/rand/rand_test.go delete mode 100644 src/pkg/math/rand/regress_test.go delete mode 100644 src/pkg/math/rand/rng.go delete mode 100644 src/pkg/math/rand/zipf.go delete mode 100644 src/pkg/math/remainder.go delete mode 100644 src/pkg/math/remainder_386.s delete mode 100644 src/pkg/math/remainder_amd64.s delete mode 100644 src/pkg/math/remainder_amd64p32.s delete mode 100644 src/pkg/math/remainder_arm.s delete mode 100644 src/pkg/math/signbit.go delete mode 100644 src/pkg/math/sin.go delete mode 100644 src/pkg/math/sin_386.s delete mode 100644 src/pkg/math/sin_amd64.s delete mode 100644 src/pkg/math/sin_amd64p32.s delete mode 100644 src/pkg/math/sin_arm.s delete mode 100644 src/pkg/math/sincos.go delete mode 100644 src/pkg/math/sincos_386.s delete mode 100644 src/pkg/math/sincos_amd64.s delete mode 100644 src/pkg/math/sincos_amd64p32.s delete mode 100644 src/pkg/math/sincos_arm.s delete mode 100644 src/pkg/math/sinh.go delete mode 100644 src/pkg/math/sqrt.go delete mode 100644 src/pkg/math/sqrt_386.s delete mode 100644 src/pkg/math/sqrt_amd64.s delete mode 100644 src/pkg/math/sqrt_amd64p32.s delete mode 100644 src/pkg/math/sqrt_arm.s delete mode 100644 src/pkg/math/tan.go delete mode 100644 src/pkg/math/tan_386.s delete mode 100644 src/pkg/math/tan_amd64.s delete mode 100644 src/pkg/math/tan_amd64p32.s delete mode 100644 src/pkg/math/tan_arm.s delete mode 100644 src/pkg/math/tanh.go delete mode 100644 src/pkg/math/unsafe.go delete mode 100644 src/pkg/mime/grammar.go delete mode 100644 src/pkg/mime/mediatype.go delete mode 100644 src/pkg/mime/mediatype_test.go delete mode 100644 src/pkg/mime/multipart/example_test.go delete mode 100644 src/pkg/mime/multipart/formdata.go delete mode 100644 src/pkg/mime/multipart/formdata_test.go delete mode 100644 src/pkg/mime/multipart/multipart.go delete mode 100644 src/pkg/mime/multipart/multipart_test.go delete mode 100644 src/pkg/mime/multipart/quotedprintable.go delete mode 100644 src/pkg/mime/multipart/quotedprintable_test.go delete mode 100644 src/pkg/mime/multipart/testdata/nested-mime delete mode 100644 src/pkg/mime/multipart/writer.go delete mode 100644 src/pkg/mime/multipart/writer_test.go delete mode 100644 src/pkg/mime/testdata/test.types delete mode 100644 src/pkg/mime/testdata/test.types.plan9 delete mode 100644 src/pkg/mime/type.go delete mode 100644 src/pkg/mime/type_plan9.go delete mode 100644 src/pkg/mime/type_test.go delete mode 100644 src/pkg/mime/type_unix.go delete mode 100644 src/pkg/mime/type_windows.go delete mode 100644 src/pkg/net/cgo_android.go delete mode 100644 src/pkg/net/cgo_bsd.go delete mode 100644 src/pkg/net/cgo_linux.go delete mode 100644 src/pkg/net/cgo_netbsd.go delete mode 100644 src/pkg/net/cgo_openbsd.go delete mode 100644 src/pkg/net/cgo_stub.go delete mode 100644 src/pkg/net/cgo_unix.go delete mode 100644 src/pkg/net/cgo_unix_test.go delete mode 100644 src/pkg/net/conn_test.go delete mode 100644 src/pkg/net/dial.go delete mode 100644 src/pkg/net/dial_gen.go delete mode 100644 src/pkg/net/dial_gen_test.go delete mode 100644 src/pkg/net/dial_test.go delete mode 100644 src/pkg/net/dialgoogle_test.go delete mode 100644 src/pkg/net/dnsclient.go delete mode 100644 src/pkg/net/dnsclient_test.go delete mode 100644 src/pkg/net/dnsclient_unix.go delete mode 100644 src/pkg/net/dnsclient_unix_test.go delete mode 100644 src/pkg/net/dnsconfig_unix.go delete mode 100644 src/pkg/net/dnsconfig_unix_test.go delete mode 100644 src/pkg/net/dnsmsg.go delete mode 100644 src/pkg/net/dnsmsg_test.go delete mode 100644 src/pkg/net/dnsname_test.go delete mode 100644 src/pkg/net/empty.c delete mode 100644 src/pkg/net/example_test.go delete mode 100644 src/pkg/net/fd_mutex.go delete mode 100644 src/pkg/net/fd_mutex_test.go delete mode 100644 src/pkg/net/fd_plan9.go delete mode 100644 src/pkg/net/fd_poll_nacl.go delete mode 100644 src/pkg/net/fd_poll_runtime.go delete mode 100644 src/pkg/net/fd_unix.go delete mode 100644 src/pkg/net/fd_unix_test.go delete mode 100644 src/pkg/net/fd_windows.go delete mode 100644 src/pkg/net/file_plan9.go delete mode 100644 src/pkg/net/file_test.go delete mode 100644 src/pkg/net/file_unix.go delete mode 100644 src/pkg/net/file_windows.go delete mode 100644 src/pkg/net/hosts.go delete mode 100644 src/pkg/net/hosts_test.go delete mode 100644 src/pkg/net/http/cgi/child.go delete mode 100644 src/pkg/net/http/cgi/child_test.go delete mode 100644 src/pkg/net/http/cgi/host.go delete mode 100644 src/pkg/net/http/cgi/host_test.go delete mode 100644 src/pkg/net/http/cgi/matryoshka_test.go delete mode 100644 src/pkg/net/http/cgi/plan9_test.go delete mode 100644 src/pkg/net/http/cgi/posix_test.go delete mode 100755 src/pkg/net/http/cgi/testdata/test.cgi delete mode 100644 src/pkg/net/http/client.go delete mode 100644 src/pkg/net/http/client_test.go delete mode 100644 src/pkg/net/http/cookie.go delete mode 100644 src/pkg/net/http/cookie_test.go delete mode 100644 src/pkg/net/http/cookiejar/jar.go delete mode 100644 src/pkg/net/http/cookiejar/jar_test.go delete mode 100644 src/pkg/net/http/cookiejar/punycode.go delete mode 100644 src/pkg/net/http/cookiejar/punycode_test.go delete mode 100644 src/pkg/net/http/doc.go delete mode 100644 src/pkg/net/http/example_test.go delete mode 100644 src/pkg/net/http/export_test.go delete mode 100644 src/pkg/net/http/fcgi/child.go delete mode 100644 src/pkg/net/http/fcgi/fcgi.go delete mode 100644 src/pkg/net/http/fcgi/fcgi_test.go delete mode 100644 src/pkg/net/http/filetransport.go delete mode 100644 src/pkg/net/http/filetransport_test.go delete mode 100644 src/pkg/net/http/fs.go delete mode 100644 src/pkg/net/http/fs_test.go delete mode 100644 src/pkg/net/http/header.go delete mode 100644 src/pkg/net/http/header_test.go delete mode 100644 src/pkg/net/http/httptest/example_test.go delete mode 100644 src/pkg/net/http/httptest/recorder.go delete mode 100644 src/pkg/net/http/httptest/recorder_test.go delete mode 100644 src/pkg/net/http/httptest/server.go delete mode 100644 src/pkg/net/http/httptest/server_test.go delete mode 100644 src/pkg/net/http/httputil/dump.go delete mode 100644 src/pkg/net/http/httputil/dump_test.go delete mode 100644 src/pkg/net/http/httputil/httputil.go delete mode 100644 src/pkg/net/http/httputil/persist.go delete mode 100644 src/pkg/net/http/httputil/reverseproxy.go delete mode 100644 src/pkg/net/http/httputil/reverseproxy_test.go delete mode 100644 src/pkg/net/http/internal/chunked.go delete mode 100644 src/pkg/net/http/internal/chunked_test.go delete mode 100644 src/pkg/net/http/jar.go delete mode 100644 src/pkg/net/http/lex.go delete mode 100644 src/pkg/net/http/lex_test.go delete mode 100644 src/pkg/net/http/npn_test.go delete mode 100644 src/pkg/net/http/pprof/pprof.go delete mode 100644 src/pkg/net/http/proxy_test.go delete mode 100644 src/pkg/net/http/race.go delete mode 100644 src/pkg/net/http/range_test.go delete mode 100644 src/pkg/net/http/readrequest_test.go delete mode 100644 src/pkg/net/http/request.go delete mode 100644 src/pkg/net/http/request_test.go delete mode 100644 src/pkg/net/http/requestwrite_test.go delete mode 100644 src/pkg/net/http/response.go delete mode 100644 src/pkg/net/http/response_test.go delete mode 100644 src/pkg/net/http/responsewrite_test.go delete mode 100644 src/pkg/net/http/serve_test.go delete mode 100644 src/pkg/net/http/server.go delete mode 100644 src/pkg/net/http/sniff.go delete mode 100644 src/pkg/net/http/sniff_test.go delete mode 100644 src/pkg/net/http/status.go delete mode 100644 src/pkg/net/http/testdata/file delete mode 100644 src/pkg/net/http/testdata/index.html delete mode 100644 src/pkg/net/http/testdata/style.css delete mode 100644 src/pkg/net/http/transfer.go delete mode 100644 src/pkg/net/http/transfer_test.go delete mode 100644 src/pkg/net/http/transport.go delete mode 100644 src/pkg/net/http/transport_test.go delete mode 100644 src/pkg/net/http/triv.go delete mode 100644 src/pkg/net/http/z_last_test.go delete mode 100644 src/pkg/net/interface.go delete mode 100644 src/pkg/net/interface_bsd.go delete mode 100644 src/pkg/net/interface_bsd_test.go delete mode 100644 src/pkg/net/interface_darwin.go delete mode 100644 src/pkg/net/interface_dragonfly.go delete mode 100644 src/pkg/net/interface_freebsd.go delete mode 100644 src/pkg/net/interface_linux.go delete mode 100644 src/pkg/net/interface_linux_test.go delete mode 100644 src/pkg/net/interface_netbsd.go delete mode 100644 src/pkg/net/interface_openbsd.go delete mode 100644 src/pkg/net/interface_stub.go delete mode 100644 src/pkg/net/interface_test.go delete mode 100644 src/pkg/net/interface_unix_test.go delete mode 100644 src/pkg/net/interface_windows.go delete mode 100644 src/pkg/net/ip.go delete mode 100644 src/pkg/net/ip_test.go delete mode 100644 src/pkg/net/ipraw_test.go delete mode 100644 src/pkg/net/iprawsock.go delete mode 100644 src/pkg/net/iprawsock_plan9.go delete mode 100644 src/pkg/net/iprawsock_posix.go delete mode 100644 src/pkg/net/ipsock.go delete mode 100644 src/pkg/net/ipsock_plan9.go delete mode 100644 src/pkg/net/ipsock_posix.go delete mode 100644 src/pkg/net/ipsock_test.go delete mode 100644 src/pkg/net/lookup.go delete mode 100644 src/pkg/net/lookup_plan9.go delete mode 100644 src/pkg/net/lookup_test.go delete mode 100644 src/pkg/net/lookup_unix.go delete mode 100644 src/pkg/net/lookup_windows.go delete mode 100644 src/pkg/net/lookup_windows_test.go delete mode 100644 src/pkg/net/mac.go delete mode 100644 src/pkg/net/mac_test.go delete mode 100644 src/pkg/net/mail/message.go delete mode 100644 src/pkg/net/mail/message_test.go delete mode 100644 src/pkg/net/mockicmp_test.go delete mode 100644 src/pkg/net/mockserver_test.go delete mode 100644 src/pkg/net/multicast_test.go delete mode 100644 src/pkg/net/net.go delete mode 100644 src/pkg/net/net_test.go delete mode 100644 src/pkg/net/net_windows_test.go delete mode 100644 src/pkg/net/netgo_unix_test.go delete mode 100644 src/pkg/net/packetconn_test.go delete mode 100644 src/pkg/net/parse.go delete mode 100644 src/pkg/net/parse_test.go delete mode 100644 src/pkg/net/pipe.go delete mode 100644 src/pkg/net/pipe_test.go delete mode 100644 src/pkg/net/port.go delete mode 100644 src/pkg/net/port_test.go delete mode 100644 src/pkg/net/port_unix.go delete mode 100644 src/pkg/net/protoconn_test.go delete mode 100644 src/pkg/net/race.go delete mode 100644 src/pkg/net/race0.go delete mode 100644 src/pkg/net/rpc/client.go delete mode 100644 src/pkg/net/rpc/client_test.go delete mode 100644 src/pkg/net/rpc/debug.go delete mode 100644 src/pkg/net/rpc/jsonrpc/all_test.go delete mode 100644 src/pkg/net/rpc/jsonrpc/client.go delete mode 100644 src/pkg/net/rpc/jsonrpc/server.go delete mode 100644 src/pkg/net/rpc/server.go delete mode 100644 src/pkg/net/rpc/server_test.go delete mode 100644 src/pkg/net/sendfile_dragonfly.go delete mode 100644 src/pkg/net/sendfile_freebsd.go delete mode 100644 src/pkg/net/sendfile_linux.go delete mode 100644 src/pkg/net/sendfile_stub.go delete mode 100644 src/pkg/net/sendfile_windows.go delete mode 100644 src/pkg/net/server_test.go delete mode 100644 src/pkg/net/singleflight.go delete mode 100644 src/pkg/net/smtp/auth.go delete mode 100644 src/pkg/net/smtp/example_test.go delete mode 100644 src/pkg/net/smtp/smtp.go delete mode 100644 src/pkg/net/smtp/smtp_test.go delete mode 100644 src/pkg/net/sock_bsd.go delete mode 100644 src/pkg/net/sock_cloexec.go delete mode 100644 src/pkg/net/sock_linux.go delete mode 100644 src/pkg/net/sock_plan9.go delete mode 100644 src/pkg/net/sock_posix.go delete mode 100644 src/pkg/net/sock_solaris.go delete mode 100644 src/pkg/net/sock_windows.go delete mode 100644 src/pkg/net/sockopt_bsd.go delete mode 100644 src/pkg/net/sockopt_linux.go delete mode 100644 src/pkg/net/sockopt_plan9.go delete mode 100644 src/pkg/net/sockopt_posix.go delete mode 100644 src/pkg/net/sockopt_solaris.go delete mode 100644 src/pkg/net/sockopt_windows.go delete mode 100644 src/pkg/net/sockoptip_bsd.go delete mode 100644 src/pkg/net/sockoptip_linux.go delete mode 100644 src/pkg/net/sockoptip_posix.go delete mode 100644 src/pkg/net/sockoptip_stub.go delete mode 100644 src/pkg/net/sockoptip_windows.go delete mode 100644 src/pkg/net/sys_cloexec.go delete mode 100644 src/pkg/net/tcp_test.go delete mode 100644 src/pkg/net/tcpsock.go delete mode 100644 src/pkg/net/tcpsock_plan9.go delete mode 100644 src/pkg/net/tcpsock_posix.go delete mode 100644 src/pkg/net/tcpsockopt_darwin.go delete mode 100644 src/pkg/net/tcpsockopt_dragonfly.go delete mode 100644 src/pkg/net/tcpsockopt_openbsd.go delete mode 100644 src/pkg/net/tcpsockopt_plan9.go delete mode 100644 src/pkg/net/tcpsockopt_posix.go delete mode 100644 src/pkg/net/tcpsockopt_solaris.go delete mode 100644 src/pkg/net/tcpsockopt_unix.go delete mode 100644 src/pkg/net/tcpsockopt_windows.go delete mode 100644 src/pkg/net/testdata/domain-resolv.conf delete mode 100644 src/pkg/net/testdata/empty-resolv.conf delete mode 100644 src/pkg/net/testdata/hosts delete mode 100644 src/pkg/net/testdata/hosts_singleline delete mode 100644 src/pkg/net/testdata/igmp delete mode 100644 src/pkg/net/testdata/igmp6 delete mode 100644 src/pkg/net/testdata/resolv.conf delete mode 100644 src/pkg/net/testdata/search-resolv.conf delete mode 100644 src/pkg/net/textproto/header.go delete mode 100644 src/pkg/net/textproto/pipeline.go delete mode 100644 src/pkg/net/textproto/reader.go delete mode 100644 src/pkg/net/textproto/reader_test.go delete mode 100644 src/pkg/net/textproto/textproto.go delete mode 100644 src/pkg/net/textproto/writer.go delete mode 100644 src/pkg/net/textproto/writer_test.go delete mode 100644 src/pkg/net/timeout_test.go delete mode 100644 src/pkg/net/udp_test.go delete mode 100644 src/pkg/net/udpsock.go delete mode 100644 src/pkg/net/udpsock_plan9.go delete mode 100644 src/pkg/net/udpsock_posix.go delete mode 100644 src/pkg/net/unicast_posix_test.go delete mode 100644 src/pkg/net/unix_test.go delete mode 100644 src/pkg/net/unixsock.go delete mode 100644 src/pkg/net/unixsock_plan9.go delete mode 100644 src/pkg/net/unixsock_posix.go delete mode 100644 src/pkg/net/url/example_test.go delete mode 100644 src/pkg/net/url/url.go delete mode 100644 src/pkg/net/url/url_test.go delete mode 100644 src/pkg/net/z_last_test.go delete mode 100644 src/pkg/os/dir_plan9.go delete mode 100644 src/pkg/os/dir_unix.go delete mode 100644 src/pkg/os/dir_windows.go delete mode 100644 src/pkg/os/doc.go delete mode 100644 src/pkg/os/env.go delete mode 100644 src/pkg/os/env_test.go delete mode 100644 src/pkg/os/env_unix_test.go delete mode 100644 src/pkg/os/error.go delete mode 100644 src/pkg/os/error_plan9.go delete mode 100644 src/pkg/os/error_test.go delete mode 100644 src/pkg/os/error_unix.go delete mode 100644 src/pkg/os/error_windows.go delete mode 100644 src/pkg/os/error_windows_test.go delete mode 100644 src/pkg/os/exec.go delete mode 100644 src/pkg/os/exec/example_test.go delete mode 100644 src/pkg/os/exec/exec.go delete mode 100644 src/pkg/os/exec/exec_test.go delete mode 100644 src/pkg/os/exec/lp_plan9.go delete mode 100644 src/pkg/os/exec/lp_test.go delete mode 100644 src/pkg/os/exec/lp_unix.go delete mode 100644 src/pkg/os/exec/lp_unix_test.go delete mode 100644 src/pkg/os/exec/lp_windows.go delete mode 100644 src/pkg/os/exec/lp_windows_test.go delete mode 100644 src/pkg/os/exec_plan9.go delete mode 100644 src/pkg/os/exec_posix.go delete mode 100644 src/pkg/os/exec_unix.go delete mode 100644 src/pkg/os/exec_windows.go delete mode 100644 src/pkg/os/export_test.go delete mode 100644 src/pkg/os/file.go delete mode 100644 src/pkg/os/file_plan9.go delete mode 100644 src/pkg/os/file_posix.go delete mode 100644 src/pkg/os/file_unix.go delete mode 100644 src/pkg/os/file_windows.go delete mode 100644 src/pkg/os/getwd.go delete mode 100644 src/pkg/os/getwd_darwin.go delete mode 100644 src/pkg/os/os_test.go delete mode 100644 src/pkg/os/os_unix_test.go delete mode 100644 src/pkg/os/os_windows_test.go delete mode 100644 src/pkg/os/path.go delete mode 100644 src/pkg/os/path_plan9.go delete mode 100644 src/pkg/os/path_test.go delete mode 100644 src/pkg/os/path_unix.go delete mode 100644 src/pkg/os/path_windows.go delete mode 100644 src/pkg/os/pipe_bsd.go delete mode 100644 src/pkg/os/pipe_linux.go delete mode 100644 src/pkg/os/proc.go delete mode 100644 src/pkg/os/signal/example_test.go delete mode 100644 src/pkg/os/signal/sig.s delete mode 100644 src/pkg/os/signal/signal.go delete mode 100644 src/pkg/os/signal/signal_stub.go delete mode 100644 src/pkg/os/signal/signal_test.go delete mode 100644 src/pkg/os/signal/signal_unix.go delete mode 100644 src/pkg/os/signal/signal_windows_test.go delete mode 100644 src/pkg/os/stat_darwin.go delete mode 100644 src/pkg/os/stat_dragonfly.go delete mode 100644 src/pkg/os/stat_freebsd.go delete mode 100644 src/pkg/os/stat_linux.go delete mode 100644 src/pkg/os/stat_nacl.go delete mode 100644 src/pkg/os/stat_netbsd.go delete mode 100644 src/pkg/os/stat_openbsd.go delete mode 100644 src/pkg/os/stat_plan9.go delete mode 100644 src/pkg/os/stat_solaris.go delete mode 100644 src/pkg/os/stat_windows.go delete mode 100644 src/pkg/os/str.go delete mode 100644 src/pkg/os/sys_bsd.go delete mode 100644 src/pkg/os/sys_darwin.go delete mode 100644 src/pkg/os/sys_freebsd.go delete mode 100644 src/pkg/os/sys_linux.go delete mode 100644 src/pkg/os/sys_nacl.go delete mode 100644 src/pkg/os/sys_plan9.go delete mode 100644 src/pkg/os/sys_solaris.go delete mode 100644 src/pkg/os/sys_unix.go delete mode 100644 src/pkg/os/sys_windows.go delete mode 100644 src/pkg/os/types.go delete mode 100644 src/pkg/os/types_notwin.go delete mode 100644 src/pkg/os/types_windows.go delete mode 100644 src/pkg/os/user/lookup.go delete mode 100644 src/pkg/os/user/lookup_plan9.go delete mode 100644 src/pkg/os/user/lookup_stubs.go delete mode 100644 src/pkg/os/user/lookup_unix.go delete mode 100644 src/pkg/os/user/lookup_windows.go delete mode 100644 src/pkg/os/user/user.go delete mode 100644 src/pkg/os/user/user_test.go delete mode 100644 src/pkg/path/example_test.go delete mode 100644 src/pkg/path/filepath/example_unix_test.go delete mode 100644 src/pkg/path/filepath/export_test.go delete mode 100644 src/pkg/path/filepath/match.go delete mode 100644 src/pkg/path/filepath/match_test.go delete mode 100644 src/pkg/path/filepath/path.go delete mode 100644 src/pkg/path/filepath/path_plan9.go delete mode 100644 src/pkg/path/filepath/path_test.go delete mode 100644 src/pkg/path/filepath/path_unix.go delete mode 100644 src/pkg/path/filepath/path_windows.go delete mode 100644 src/pkg/path/filepath/path_windows_test.go delete mode 100644 src/pkg/path/filepath/symlink.go delete mode 100644 src/pkg/path/filepath/symlink_unix.go delete mode 100644 src/pkg/path/filepath/symlink_windows.go delete mode 100644 src/pkg/path/match.go delete mode 100644 src/pkg/path/match_test.go delete mode 100644 src/pkg/path/path.go delete mode 100644 src/pkg/path/path_test.go delete mode 100644 src/pkg/reflect/all_test.go delete mode 100644 src/pkg/reflect/asm_386.s delete mode 100644 src/pkg/reflect/asm_amd64.s delete mode 100644 src/pkg/reflect/asm_amd64p32.s delete mode 100644 src/pkg/reflect/asm_arm.s delete mode 100644 src/pkg/reflect/deepequal.go delete mode 100644 src/pkg/reflect/example_test.go delete mode 100644 src/pkg/reflect/export_test.go delete mode 100644 src/pkg/reflect/makefunc.go delete mode 100644 src/pkg/reflect/set_test.go delete mode 100644 src/pkg/reflect/tostring_test.go delete mode 100644 src/pkg/reflect/type.go delete mode 100644 src/pkg/reflect/value.go delete mode 100644 src/pkg/regexp/all_test.go delete mode 100644 src/pkg/regexp/example_test.go delete mode 100644 src/pkg/regexp/exec.go delete mode 100644 src/pkg/regexp/exec2_test.go delete mode 100644 src/pkg/regexp/exec_test.go delete mode 100644 src/pkg/regexp/find_test.go delete mode 100644 src/pkg/regexp/onepass.go delete mode 100644 src/pkg/regexp/onepass_test.go delete mode 100644 src/pkg/regexp/regexp.go delete mode 100644 src/pkg/regexp/syntax/compile.go delete mode 100644 src/pkg/regexp/syntax/doc.go delete mode 100755 src/pkg/regexp/syntax/make_perl_groups.pl delete mode 100644 src/pkg/regexp/syntax/parse.go delete mode 100644 src/pkg/regexp/syntax/parse_test.go delete mode 100644 src/pkg/regexp/syntax/perl_groups.go delete mode 100644 src/pkg/regexp/syntax/prog.go delete mode 100644 src/pkg/regexp/syntax/prog_test.go delete mode 100644 src/pkg/regexp/syntax/regexp.go delete mode 100644 src/pkg/regexp/syntax/simplify.go delete mode 100644 src/pkg/regexp/syntax/simplify_test.go delete mode 100644 src/pkg/regexp/testdata/README delete mode 100644 src/pkg/regexp/testdata/basic.dat delete mode 100644 src/pkg/regexp/testdata/nullsubexpr.dat delete mode 100644 src/pkg/regexp/testdata/re2-exhaustive.txt.bz2 delete mode 100644 src/pkg/regexp/testdata/re2-search.txt delete mode 100644 src/pkg/regexp/testdata/repetition.dat delete mode 100644 src/pkg/regexp/testdata/testregex.c delete mode 100644 src/pkg/runtime/Makefile delete mode 100644 src/pkg/runtime/alg.go delete mode 100644 src/pkg/runtime/append_test.go delete mode 100644 src/pkg/runtime/arch_386.go delete mode 100644 src/pkg/runtime/arch_386.h delete mode 100644 src/pkg/runtime/arch_amd64.go delete mode 100644 src/pkg/runtime/arch_amd64.h delete mode 100644 src/pkg/runtime/arch_amd64p32.go delete mode 100644 src/pkg/runtime/arch_amd64p32.h delete mode 100644 src/pkg/runtime/arch_arm.go delete mode 100644 src/pkg/runtime/arch_arm.h delete mode 100644 src/pkg/runtime/asm_386.s delete mode 100644 src/pkg/runtime/asm_amd64.s delete mode 100644 src/pkg/runtime/asm_amd64p32.s delete mode 100644 src/pkg/runtime/asm_arm.s delete mode 100644 src/pkg/runtime/atomic.go delete mode 100644 src/pkg/runtime/atomic_386.c delete mode 100644 src/pkg/runtime/atomic_amd64x.c delete mode 100644 src/pkg/runtime/atomic_arm.go delete mode 100644 src/pkg/runtime/cgo/asm_386.s delete mode 100644 src/pkg/runtime/cgo/asm_amd64.s delete mode 100644 src/pkg/runtime/cgo/asm_arm.s delete mode 100644 src/pkg/runtime/cgo/asm_nacl_amd64p32.s delete mode 100644 src/pkg/runtime/cgo/callbacks.c delete mode 100644 src/pkg/runtime/cgo/cgo.go delete mode 100644 src/pkg/runtime/cgo/dragonfly.c delete mode 100644 src/pkg/runtime/cgo/freebsd.c delete mode 100644 src/pkg/runtime/cgo/gcc_386.S delete mode 100644 src/pkg/runtime/cgo/gcc_amd64.S delete mode 100644 src/pkg/runtime/cgo/gcc_android.c delete mode 100644 src/pkg/runtime/cgo/gcc_android_arm.c delete mode 100644 src/pkg/runtime/cgo/gcc_arm.S delete mode 100644 src/pkg/runtime/cgo/gcc_darwin_386.c delete mode 100644 src/pkg/runtime/cgo/gcc_darwin_amd64.c delete mode 100644 src/pkg/runtime/cgo/gcc_dragonfly_386.c delete mode 100644 src/pkg/runtime/cgo/gcc_dragonfly_amd64.c delete mode 100644 src/pkg/runtime/cgo/gcc_fatalf.c delete mode 100644 src/pkg/runtime/cgo/gcc_freebsd_386.c delete mode 100644 src/pkg/runtime/cgo/gcc_freebsd_amd64.c delete mode 100644 src/pkg/runtime/cgo/gcc_freebsd_arm.c delete mode 100644 src/pkg/runtime/cgo/gcc_linux_386.c delete mode 100644 src/pkg/runtime/cgo/gcc_linux_amd64.c delete mode 100644 src/pkg/runtime/cgo/gcc_linux_arm.c delete mode 100644 src/pkg/runtime/cgo/gcc_netbsd_386.c delete mode 100644 src/pkg/runtime/cgo/gcc_netbsd_amd64.c delete mode 100644 src/pkg/runtime/cgo/gcc_netbsd_arm.c delete mode 100644 src/pkg/runtime/cgo/gcc_openbsd_386.c delete mode 100644 src/pkg/runtime/cgo/gcc_openbsd_amd64.c delete mode 100644 src/pkg/runtime/cgo/gcc_setenv.c delete mode 100644 src/pkg/runtime/cgo/gcc_util.c delete mode 100644 src/pkg/runtime/cgo/gcc_windows_386.c delete mode 100644 src/pkg/runtime/cgo/gcc_windows_amd64.c delete mode 100644 src/pkg/runtime/cgo/iscgo.c delete mode 100644 src/pkg/runtime/cgo/libcgo.h delete mode 100644 src/pkg/runtime/cgo/netbsd.c delete mode 100644 src/pkg/runtime/cgo/openbsd.c delete mode 100644 src/pkg/runtime/cgo/setenv.c delete mode 100644 src/pkg/runtime/cgocall.go delete mode 100644 src/pkg/runtime/cgocall.h delete mode 100644 src/pkg/runtime/chan.go delete mode 100644 src/pkg/runtime/chan.h delete mode 100644 src/pkg/runtime/chan_test.go delete mode 100644 src/pkg/runtime/closure_test.go delete mode 100644 src/pkg/runtime/compiler.go delete mode 100644 src/pkg/runtime/complex.go delete mode 100644 src/pkg/runtime/complex_test.go delete mode 100644 src/pkg/runtime/cpuprof.go delete mode 100644 src/pkg/runtime/crash_cgo_test.go delete mode 100644 src/pkg/runtime/crash_test.go delete mode 100644 src/pkg/runtime/debug.go delete mode 100644 src/pkg/runtime/debug/debug.c delete mode 100644 src/pkg/runtime/debug/garbage.go delete mode 100644 src/pkg/runtime/debug/garbage_test.go delete mode 100644 src/pkg/runtime/debug/heapdump_test.go delete mode 100644 src/pkg/runtime/debug/stack.go delete mode 100644 src/pkg/runtime/debug/stack_test.go delete mode 100644 src/pkg/runtime/debug/stubs.go delete mode 100644 src/pkg/runtime/debug/stubs.s delete mode 100644 src/pkg/runtime/defs.c delete mode 100644 src/pkg/runtime/defs1_linux.go delete mode 100644 src/pkg/runtime/defs2_linux.go delete mode 100644 src/pkg/runtime/defs_android_arm.h delete mode 100644 src/pkg/runtime/defs_arm_linux.go delete mode 100644 src/pkg/runtime/defs_darwin.go delete mode 100644 src/pkg/runtime/defs_darwin_386.h delete mode 100644 src/pkg/runtime/defs_darwin_amd64.h delete mode 100644 src/pkg/runtime/defs_dragonfly.go delete mode 100644 src/pkg/runtime/defs_dragonfly_386.h delete mode 100644 src/pkg/runtime/defs_dragonfly_amd64.h delete mode 100644 src/pkg/runtime/defs_freebsd.go delete mode 100644 src/pkg/runtime/defs_freebsd_386.h delete mode 100644 src/pkg/runtime/defs_freebsd_amd64.h delete mode 100644 src/pkg/runtime/defs_freebsd_arm.h delete mode 100644 src/pkg/runtime/defs_linux.go delete mode 100644 src/pkg/runtime/defs_linux_386.h delete mode 100644 src/pkg/runtime/defs_linux_amd64.h delete mode 100644 src/pkg/runtime/defs_linux_arm.h delete mode 100644 src/pkg/runtime/defs_nacl_386.h delete mode 100644 src/pkg/runtime/defs_nacl_amd64p32.h delete mode 100644 src/pkg/runtime/defs_nacl_arm.h delete mode 100644 src/pkg/runtime/defs_netbsd.go delete mode 100644 src/pkg/runtime/defs_netbsd_386.go delete mode 100644 src/pkg/runtime/defs_netbsd_386.h delete mode 100644 src/pkg/runtime/defs_netbsd_amd64.go delete mode 100644 src/pkg/runtime/defs_netbsd_amd64.h delete mode 100644 src/pkg/runtime/defs_netbsd_arm.go delete mode 100644 src/pkg/runtime/defs_netbsd_arm.h delete mode 100644 src/pkg/runtime/defs_openbsd.go delete mode 100644 src/pkg/runtime/defs_openbsd_386.h delete mode 100644 src/pkg/runtime/defs_openbsd_amd64.h delete mode 100644 src/pkg/runtime/defs_plan9_386.h delete mode 100644 src/pkg/runtime/defs_plan9_amd64.h delete mode 100644 src/pkg/runtime/defs_solaris.go delete mode 100644 src/pkg/runtime/defs_solaris_amd64.go delete mode 100644 src/pkg/runtime/defs_solaris_amd64.h delete mode 100644 src/pkg/runtime/defs_windows.go delete mode 100644 src/pkg/runtime/defs_windows_386.h delete mode 100644 src/pkg/runtime/defs_windows_amd64.h delete mode 100644 src/pkg/runtime/env_plan9.go delete mode 100644 src/pkg/runtime/env_posix.go delete mode 100644 src/pkg/runtime/error.go delete mode 100644 src/pkg/runtime/export_futex_test.go delete mode 100644 src/pkg/runtime/export_test.go delete mode 100644 src/pkg/runtime/extern.go delete mode 100644 src/pkg/runtime/float.c delete mode 100644 src/pkg/runtime/funcdata.h delete mode 100644 src/pkg/runtime/futex_test.go delete mode 100644 src/pkg/runtime/gc_test.go delete mode 100644 src/pkg/runtime/gcinfo_test.go delete mode 100644 src/pkg/runtime/hash_test.go delete mode 100644 src/pkg/runtime/hashmap.go delete mode 100644 src/pkg/runtime/hashmap_fast.go delete mode 100644 src/pkg/runtime/heapdump.c delete mode 100644 src/pkg/runtime/iface.go delete mode 100644 src/pkg/runtime/iface_test.go delete mode 100644 src/pkg/runtime/lfstack.c delete mode 100644 src/pkg/runtime/lfstack_test.go delete mode 100644 src/pkg/runtime/lock_futex.go delete mode 100644 src/pkg/runtime/lock_sema.go delete mode 100644 src/pkg/runtime/malloc.c delete mode 100644 src/pkg/runtime/malloc.go delete mode 100644 src/pkg/runtime/malloc.h delete mode 100644 src/pkg/runtime/malloc_test.go delete mode 100644 src/pkg/runtime/map_test.go delete mode 100644 src/pkg/runtime/mapspeed_test.go delete mode 100644 src/pkg/runtime/mcache.c delete mode 100644 src/pkg/runtime/mcentral.c delete mode 100644 src/pkg/runtime/mem.go delete mode 100644 src/pkg/runtime/mem_darwin.c delete mode 100644 src/pkg/runtime/mem_dragonfly.c delete mode 100644 src/pkg/runtime/mem_freebsd.c delete mode 100644 src/pkg/runtime/mem_linux.c delete mode 100644 src/pkg/runtime/mem_nacl.c delete mode 100644 src/pkg/runtime/mem_netbsd.c delete mode 100644 src/pkg/runtime/mem_openbsd.c delete mode 100644 src/pkg/runtime/mem_plan9.c delete mode 100644 src/pkg/runtime/mem_solaris.c delete mode 100644 src/pkg/runtime/mem_windows.c delete mode 100644 src/pkg/runtime/memclr_386.s delete mode 100644 src/pkg/runtime/memclr_amd64.s delete mode 100644 src/pkg/runtime/memclr_arm.s delete mode 100644 src/pkg/runtime/memclr_plan9_386.s delete mode 100644 src/pkg/runtime/memclr_plan9_amd64.s delete mode 100644 src/pkg/runtime/memmove_386.s delete mode 100644 src/pkg/runtime/memmove_amd64.s delete mode 100644 src/pkg/runtime/memmove_arm.s delete mode 100644 src/pkg/runtime/memmove_linux_amd64_test.go delete mode 100644 src/pkg/runtime/memmove_nacl_amd64p32.s delete mode 100644 src/pkg/runtime/memmove_plan9_386.s delete mode 100644 src/pkg/runtime/memmove_plan9_amd64.s delete mode 100644 src/pkg/runtime/memmove_test.go delete mode 100644 src/pkg/runtime/mfinal_test.go delete mode 100644 src/pkg/runtime/mfixalloc.c delete mode 100644 src/pkg/runtime/mgc0.c delete mode 100644 src/pkg/runtime/mgc0.go delete mode 100644 src/pkg/runtime/mgc0.h delete mode 100644 src/pkg/runtime/mheap.c delete mode 100644 src/pkg/runtime/mknacl.sh delete mode 100644 src/pkg/runtime/mprof.go delete mode 100644 src/pkg/runtime/msize.c delete mode 100644 src/pkg/runtime/netpoll.go delete mode 100644 src/pkg/runtime/netpoll_epoll.go delete mode 100644 src/pkg/runtime/netpoll_kqueue.go delete mode 100644 src/pkg/runtime/netpoll_nacl.go delete mode 100644 src/pkg/runtime/netpoll_solaris.c delete mode 100644 src/pkg/runtime/netpoll_stub.c delete mode 100644 src/pkg/runtime/netpoll_windows.c delete mode 100644 src/pkg/runtime/noasm_arm.go delete mode 100644 src/pkg/runtime/norace_test.go delete mode 100644 src/pkg/runtime/os_android.c delete mode 100644 src/pkg/runtime/os_android.h delete mode 100644 src/pkg/runtime/os_darwin.c delete mode 100644 src/pkg/runtime/os_darwin.go delete mode 100644 src/pkg/runtime/os_darwin.h delete mode 100644 src/pkg/runtime/os_dragonfly.c delete mode 100644 src/pkg/runtime/os_dragonfly.go delete mode 100644 src/pkg/runtime/os_dragonfly.h delete mode 100644 src/pkg/runtime/os_freebsd.c delete mode 100644 src/pkg/runtime/os_freebsd.go delete mode 100644 src/pkg/runtime/os_freebsd.h delete mode 100644 src/pkg/runtime/os_freebsd_arm.c delete mode 100644 src/pkg/runtime/os_linux.c delete mode 100644 src/pkg/runtime/os_linux.go delete mode 100644 src/pkg/runtime/os_linux.h delete mode 100644 src/pkg/runtime/os_linux_386.c delete mode 100644 src/pkg/runtime/os_linux_arm.c delete mode 100644 src/pkg/runtime/os_nacl.c delete mode 100644 src/pkg/runtime/os_nacl.go delete mode 100644 src/pkg/runtime/os_nacl.h delete mode 100644 src/pkg/runtime/os_nacl_arm.c delete mode 100644 src/pkg/runtime/os_netbsd.c delete mode 100644 src/pkg/runtime/os_netbsd.go delete mode 100644 src/pkg/runtime/os_netbsd.h delete mode 100644 src/pkg/runtime/os_netbsd_386.c delete mode 100644 src/pkg/runtime/os_netbsd_amd64.c delete mode 100644 src/pkg/runtime/os_netbsd_arm.c delete mode 100644 src/pkg/runtime/os_openbsd.c delete mode 100644 src/pkg/runtime/os_openbsd.go delete mode 100644 src/pkg/runtime/os_openbsd.h delete mode 100644 src/pkg/runtime/os_plan9.c delete mode 100644 src/pkg/runtime/os_plan9.go delete mode 100644 src/pkg/runtime/os_plan9.h delete mode 100644 src/pkg/runtime/os_plan9_386.c delete mode 100644 src/pkg/runtime/os_plan9_amd64.c delete mode 100644 src/pkg/runtime/os_solaris.c delete mode 100644 src/pkg/runtime/os_solaris.go delete mode 100644 src/pkg/runtime/os_solaris.h delete mode 100644 src/pkg/runtime/os_windows.c delete mode 100644 src/pkg/runtime/os_windows.go delete mode 100644 src/pkg/runtime/os_windows.h delete mode 100644 src/pkg/runtime/os_windows_386.c delete mode 100644 src/pkg/runtime/os_windows_386.go delete mode 100644 src/pkg/runtime/os_windows_amd64.c delete mode 100644 src/pkg/runtime/os_windows_amd64.go delete mode 100644 src/pkg/runtime/panic.c delete mode 100644 src/pkg/runtime/panic.go delete mode 100644 src/pkg/runtime/panic1.go delete mode 100644 src/pkg/runtime/parfor.c delete mode 100644 src/pkg/runtime/parfor_test.go delete mode 100644 src/pkg/runtime/pprof/pprof.go delete mode 100644 src/pkg/runtime/pprof/pprof_test.go delete mode 100644 src/pkg/runtime/print1.go delete mode 100644 src/pkg/runtime/proc.c delete mode 100644 src/pkg/runtime/proc.go delete mode 100644 src/pkg/runtime/proc_test.go delete mode 100644 src/pkg/runtime/race.c delete mode 100644 src/pkg/runtime/race.go delete mode 100644 src/pkg/runtime/race.h delete mode 100644 src/pkg/runtime/race/README delete mode 100644 src/pkg/runtime/race/doc.go delete mode 100644 src/pkg/runtime/race/output_test.go delete mode 100644 src/pkg/runtime/race/race.go delete mode 100644 src/pkg/runtime/race/race_darwin_amd64.syso delete mode 100644 src/pkg/runtime/race/race_freebsd_amd64.syso delete mode 100644 src/pkg/runtime/race/race_linux_amd64.syso delete mode 100644 src/pkg/runtime/race/race_test.go delete mode 100644 src/pkg/runtime/race/race_windows_amd64.syso delete mode 100644 src/pkg/runtime/race/testdata/atomic_test.go delete mode 100644 src/pkg/runtime/race/testdata/cgo_test.go delete mode 100644 src/pkg/runtime/race/testdata/cgo_test_main.go delete mode 100644 src/pkg/runtime/race/testdata/chan_test.go delete mode 100644 src/pkg/runtime/race/testdata/comp_test.go delete mode 100644 src/pkg/runtime/race/testdata/finalizer_test.go delete mode 100644 src/pkg/runtime/race/testdata/io_test.go delete mode 100644 src/pkg/runtime/race/testdata/map_test.go delete mode 100644 src/pkg/runtime/race/testdata/mop_test.go delete mode 100644 src/pkg/runtime/race/testdata/mutex_test.go delete mode 100644 src/pkg/runtime/race/testdata/regression_test.go delete mode 100644 src/pkg/runtime/race/testdata/rwmutex_test.go delete mode 100644 src/pkg/runtime/race/testdata/select_test.go delete mode 100644 src/pkg/runtime/race/testdata/slice_test.go delete mode 100644 src/pkg/runtime/race/testdata/sync_test.go delete mode 100644 src/pkg/runtime/race/testdata/waitgroup_test.go delete mode 100644 src/pkg/runtime/race0.go delete mode 100644 src/pkg/runtime/race_amd64.s delete mode 100644 src/pkg/runtime/rdebug.go delete mode 100644 src/pkg/runtime/rt0_android_arm.s delete mode 100644 src/pkg/runtime/rt0_darwin_386.s delete mode 100644 src/pkg/runtime/rt0_darwin_amd64.s delete mode 100644 src/pkg/runtime/rt0_dragonfly_386.s delete mode 100644 src/pkg/runtime/rt0_dragonfly_amd64.s delete mode 100644 src/pkg/runtime/rt0_freebsd_386.s delete mode 100644 src/pkg/runtime/rt0_freebsd_amd64.s delete mode 100644 src/pkg/runtime/rt0_freebsd_arm.s delete mode 100644 src/pkg/runtime/rt0_linux_386.s delete mode 100644 src/pkg/runtime/rt0_linux_amd64.s delete mode 100644 src/pkg/runtime/rt0_linux_arm.s delete mode 100644 src/pkg/runtime/rt0_nacl_386.s delete mode 100644 src/pkg/runtime/rt0_nacl_amd64p32.s delete mode 100644 src/pkg/runtime/rt0_nacl_arm.s delete mode 100644 src/pkg/runtime/rt0_netbsd_386.s delete mode 100644 src/pkg/runtime/rt0_netbsd_amd64.s delete mode 100644 src/pkg/runtime/rt0_netbsd_arm.s delete mode 100644 src/pkg/runtime/rt0_openbsd_386.s delete mode 100644 src/pkg/runtime/rt0_openbsd_amd64.s delete mode 100644 src/pkg/runtime/rt0_plan9_386.s delete mode 100644 src/pkg/runtime/rt0_plan9_amd64.s delete mode 100644 src/pkg/runtime/rt0_solaris_amd64.s delete mode 100644 src/pkg/runtime/rt0_windows_386.s delete mode 100644 src/pkg/runtime/rt0_windows_amd64.s delete mode 100644 src/pkg/runtime/rune.go delete mode 100644 src/pkg/runtime/runtime-gdb.py delete mode 100644 src/pkg/runtime/runtime.c delete mode 100644 src/pkg/runtime/runtime.go delete mode 100644 src/pkg/runtime/runtime.h delete mode 100644 src/pkg/runtime/runtime_linux_test.go delete mode 100644 src/pkg/runtime/runtime_test.go delete mode 100644 src/pkg/runtime/runtime_unix_test.go delete mode 100644 src/pkg/runtime/select.go delete mode 100644 src/pkg/runtime/sema.go delete mode 100644 src/pkg/runtime/signal.c delete mode 100644 src/pkg/runtime/signal_386.c delete mode 100644 src/pkg/runtime/signal_amd64x.c delete mode 100644 src/pkg/runtime/signal_android_386.h delete mode 100644 src/pkg/runtime/signal_android_arm.h delete mode 100644 src/pkg/runtime/signal_arm.c delete mode 100644 src/pkg/runtime/signal_darwin_386.h delete mode 100644 src/pkg/runtime/signal_darwin_amd64.h delete mode 100644 src/pkg/runtime/signal_dragonfly_386.h delete mode 100644 src/pkg/runtime/signal_dragonfly_amd64.h delete mode 100644 src/pkg/runtime/signal_freebsd_386.h delete mode 100644 src/pkg/runtime/signal_freebsd_amd64.h delete mode 100644 src/pkg/runtime/signal_freebsd_arm.h delete mode 100644 src/pkg/runtime/signal_linux_386.h delete mode 100644 src/pkg/runtime/signal_linux_amd64.h delete mode 100644 src/pkg/runtime/signal_linux_arm.h delete mode 100644 src/pkg/runtime/signal_nacl_386.h delete mode 100644 src/pkg/runtime/signal_nacl_amd64p32.h delete mode 100644 src/pkg/runtime/signal_nacl_arm.h delete mode 100644 src/pkg/runtime/signal_netbsd_386.h delete mode 100644 src/pkg/runtime/signal_netbsd_amd64.h delete mode 100644 src/pkg/runtime/signal_netbsd_arm.h delete mode 100644 src/pkg/runtime/signal_openbsd_386.h delete mode 100644 src/pkg/runtime/signal_openbsd_amd64.h delete mode 100644 src/pkg/runtime/signal_solaris_amd64.h delete mode 100644 src/pkg/runtime/signal_unix.c delete mode 100644 src/pkg/runtime/signal_unix.go delete mode 100644 src/pkg/runtime/signal_unix.h delete mode 100644 src/pkg/runtime/signals_android.h delete mode 100644 src/pkg/runtime/signals_darwin.h delete mode 100644 src/pkg/runtime/signals_dragonfly.h delete mode 100644 src/pkg/runtime/signals_freebsd.h delete mode 100644 src/pkg/runtime/signals_linux.h delete mode 100644 src/pkg/runtime/signals_nacl.h delete mode 100644 src/pkg/runtime/signals_netbsd.h delete mode 100644 src/pkg/runtime/signals_openbsd.h delete mode 100644 src/pkg/runtime/signals_plan9.h delete mode 100644 src/pkg/runtime/signals_solaris.h delete mode 100644 src/pkg/runtime/signals_windows.h delete mode 100644 src/pkg/runtime/sigqueue.go delete mode 100644 src/pkg/runtime/slice.go delete mode 100644 src/pkg/runtime/softfloat64.go delete mode 100644 src/pkg/runtime/softfloat64_test.go delete mode 100644 src/pkg/runtime/softfloat_arm.c delete mode 100644 src/pkg/runtime/sqrt.go delete mode 100644 src/pkg/runtime/stack.c delete mode 100644 src/pkg/runtime/stack.go delete mode 100644 src/pkg/runtime/stack.h delete mode 100644 src/pkg/runtime/stack_gen_test.go delete mode 100644 src/pkg/runtime/stack_test.go delete mode 100644 src/pkg/runtime/string.c delete mode 100644 src/pkg/runtime/string.go delete mode 100644 src/pkg/runtime/string_test.go delete mode 100644 src/pkg/runtime/stubs.go delete mode 100644 src/pkg/runtime/symtab.go delete mode 100644 src/pkg/runtime/symtab_test.go delete mode 100644 src/pkg/runtime/sys_arm.c delete mode 100644 src/pkg/runtime/sys_darwin_386.s delete mode 100644 src/pkg/runtime/sys_darwin_amd64.s delete mode 100644 src/pkg/runtime/sys_dragonfly_386.s delete mode 100644 src/pkg/runtime/sys_dragonfly_amd64.s delete mode 100644 src/pkg/runtime/sys_freebsd_386.s delete mode 100644 src/pkg/runtime/sys_freebsd_amd64.s delete mode 100644 src/pkg/runtime/sys_freebsd_arm.s delete mode 100644 src/pkg/runtime/sys_linux_386.s delete mode 100644 src/pkg/runtime/sys_linux_amd64.s delete mode 100644 src/pkg/runtime/sys_linux_arm.s delete mode 100644 src/pkg/runtime/sys_nacl_386.s delete mode 100644 src/pkg/runtime/sys_nacl_amd64p32.s delete mode 100644 src/pkg/runtime/sys_nacl_arm.s delete mode 100644 src/pkg/runtime/sys_netbsd_386.s delete mode 100644 src/pkg/runtime/sys_netbsd_amd64.s delete mode 100644 src/pkg/runtime/sys_netbsd_arm.s delete mode 100644 src/pkg/runtime/sys_openbsd_386.s delete mode 100644 src/pkg/runtime/sys_openbsd_amd64.s delete mode 100644 src/pkg/runtime/sys_plan9_386.s delete mode 100644 src/pkg/runtime/sys_plan9_amd64.s delete mode 100644 src/pkg/runtime/sys_solaris_amd64.s delete mode 100644 src/pkg/runtime/sys_windows_386.s delete mode 100644 src/pkg/runtime/sys_windows_amd64.s delete mode 100644 src/pkg/runtime/sys_x86.c delete mode 100644 src/pkg/runtime/syscall_nacl.h delete mode 100644 src/pkg/runtime/syscall_solaris.c delete mode 100644 src/pkg/runtime/syscall_solaris.go delete mode 100644 src/pkg/runtime/syscall_windows.c delete mode 100644 src/pkg/runtime/syscall_windows.go delete mode 100644 src/pkg/runtime/syscall_windows_test.go delete mode 100644 src/pkg/runtime/thunk.s delete mode 100644 src/pkg/runtime/thunk_solaris_amd64.s delete mode 100644 src/pkg/runtime/time.go delete mode 100644 src/pkg/runtime/tls_arm.s delete mode 100644 src/pkg/runtime/traceback.go delete mode 100644 src/pkg/runtime/traceback_windows.go delete mode 100644 src/pkg/runtime/type.h delete mode 100644 src/pkg/runtime/typekind.go delete mode 100644 src/pkg/runtime/typekind.h delete mode 100644 src/pkg/runtime/vdso_linux_amd64.c delete mode 100644 src/pkg/runtime/vlop_386.s delete mode 100644 src/pkg/runtime/vlop_arm.s delete mode 100644 src/pkg/runtime/vlop_arm_test.go delete mode 100644 src/pkg/runtime/vlrt.c delete mode 100644 src/pkg/runtime/vlrt.go delete mode 100644 src/pkg/sort/example_interface_test.go delete mode 100644 src/pkg/sort/example_keys_test.go delete mode 100644 src/pkg/sort/example_multi_test.go delete mode 100644 src/pkg/sort/example_test.go delete mode 100644 src/pkg/sort/example_wrapper_test.go delete mode 100644 src/pkg/sort/export_test.go delete mode 100644 src/pkg/sort/search.go delete mode 100644 src/pkg/sort/search_test.go delete mode 100644 src/pkg/sort/sort.go delete mode 100644 src/pkg/sort/sort_test.go delete mode 100644 src/pkg/strconv/atob.go delete mode 100644 src/pkg/strconv/atob_test.go delete mode 100644 src/pkg/strconv/atof.go delete mode 100644 src/pkg/strconv/atof_test.go delete mode 100644 src/pkg/strconv/atoi.go delete mode 100644 src/pkg/strconv/atoi_test.go delete mode 100644 src/pkg/strconv/decimal.go delete mode 100644 src/pkg/strconv/decimal_test.go delete mode 100644 src/pkg/strconv/extfloat.go delete mode 100644 src/pkg/strconv/fp_test.go delete mode 100644 src/pkg/strconv/ftoa.go delete mode 100644 src/pkg/strconv/ftoa_test.go delete mode 100644 src/pkg/strconv/internal_test.go delete mode 100644 src/pkg/strconv/isprint.go delete mode 100644 src/pkg/strconv/itoa.go delete mode 100644 src/pkg/strconv/itoa_test.go delete mode 100644 src/pkg/strconv/makeisprint.go delete mode 100644 src/pkg/strconv/quote.go delete mode 100644 src/pkg/strconv/quote_example_test.go delete mode 100644 src/pkg/strconv/quote_test.go delete mode 100644 src/pkg/strconv/strconv_test.go delete mode 100644 src/pkg/strconv/testdata/testfp.txt delete mode 100644 src/pkg/strings/example_test.go delete mode 100644 src/pkg/strings/export_test.go delete mode 100644 src/pkg/strings/reader.go delete mode 100644 src/pkg/strings/reader_test.go delete mode 100644 src/pkg/strings/replace.go delete mode 100644 src/pkg/strings/replace_test.go delete mode 100644 src/pkg/strings/search.go delete mode 100644 src/pkg/strings/search_test.go delete mode 100644 src/pkg/strings/strings.go delete mode 100644 src/pkg/strings/strings.s delete mode 100644 src/pkg/strings/strings_decl.go delete mode 100644 src/pkg/strings/strings_test.go delete mode 100644 src/pkg/sync/atomic/64bit_arm.go delete mode 100644 src/pkg/sync/atomic/asm_386.s delete mode 100644 src/pkg/sync/atomic/asm_amd64.s delete mode 100644 src/pkg/sync/atomic/asm_amd64p32.s delete mode 100644 src/pkg/sync/atomic/asm_arm.s delete mode 100644 src/pkg/sync/atomic/asm_freebsd_arm.s delete mode 100644 src/pkg/sync/atomic/asm_linux_arm.s delete mode 100644 src/pkg/sync/atomic/asm_nacl_arm.s delete mode 100644 src/pkg/sync/atomic/asm_netbsd_arm.s delete mode 100644 src/pkg/sync/atomic/atomic_linux_arm_test.go delete mode 100644 src/pkg/sync/atomic/atomic_test.go delete mode 100644 src/pkg/sync/atomic/doc.go delete mode 100644 src/pkg/sync/atomic/export_linux_arm_test.go delete mode 100644 src/pkg/sync/atomic/race.s delete mode 100644 src/pkg/sync/cond.go delete mode 100644 src/pkg/sync/cond_test.go delete mode 100644 src/pkg/sync/example_test.go delete mode 100644 src/pkg/sync/export_test.go delete mode 100644 src/pkg/sync/mutex.go delete mode 100644 src/pkg/sync/mutex_test.go delete mode 100644 src/pkg/sync/once.go delete mode 100644 src/pkg/sync/once_test.go delete mode 100644 src/pkg/sync/pool.go delete mode 100644 src/pkg/sync/pool_test.go delete mode 100644 src/pkg/sync/race.go delete mode 100644 src/pkg/sync/race0.go delete mode 100644 src/pkg/sync/runtime.go delete mode 100644 src/pkg/sync/runtime_sema_test.go delete mode 100644 src/pkg/sync/rwmutex.go delete mode 100644 src/pkg/sync/rwmutex_test.go delete mode 100644 src/pkg/sync/waitgroup.go delete mode 100644 src/pkg/sync/waitgroup_test.go delete mode 100644 src/pkg/syscall/asm_darwin_386.s delete mode 100644 src/pkg/syscall/asm_darwin_amd64.s delete mode 100644 src/pkg/syscall/asm_dragonfly_386.s delete mode 100644 src/pkg/syscall/asm_dragonfly_amd64.s delete mode 100644 src/pkg/syscall/asm_freebsd_386.s delete mode 100644 src/pkg/syscall/asm_freebsd_amd64.s delete mode 100644 src/pkg/syscall/asm_freebsd_arm.s delete mode 100644 src/pkg/syscall/asm_linux_386.s delete mode 100644 src/pkg/syscall/asm_linux_amd64.s delete mode 100644 src/pkg/syscall/asm_linux_arm.s delete mode 100644 src/pkg/syscall/asm_nacl_386.s delete mode 100644 src/pkg/syscall/asm_nacl_amd64p32.s delete mode 100644 src/pkg/syscall/asm_nacl_arm.s delete mode 100644 src/pkg/syscall/asm_netbsd_386.s delete mode 100644 src/pkg/syscall/asm_netbsd_amd64.s delete mode 100644 src/pkg/syscall/asm_netbsd_arm.s delete mode 100644 src/pkg/syscall/asm_openbsd_386.s delete mode 100644 src/pkg/syscall/asm_openbsd_amd64.s delete mode 100644 src/pkg/syscall/asm_plan9_386.s delete mode 100644 src/pkg/syscall/asm_plan9_amd64.s delete mode 100644 src/pkg/syscall/asm_solaris_amd64.s delete mode 100644 src/pkg/syscall/asm_windows.s delete mode 100644 src/pkg/syscall/bpf_bsd.go delete mode 100644 src/pkg/syscall/creds_test.go delete mode 100644 src/pkg/syscall/dir_plan9.go delete mode 100644 src/pkg/syscall/dll_windows.go delete mode 100644 src/pkg/syscall/env_plan9.go delete mode 100644 src/pkg/syscall/env_unix.go delete mode 100644 src/pkg/syscall/env_windows.go delete mode 100644 src/pkg/syscall/exec_bsd.go delete mode 100644 src/pkg/syscall/exec_linux.go delete mode 100644 src/pkg/syscall/exec_plan9.go delete mode 100644 src/pkg/syscall/exec_solaris.go delete mode 100644 src/pkg/syscall/exec_unix.go delete mode 100644 src/pkg/syscall/exec_windows.go delete mode 100644 src/pkg/syscall/fd_nacl.go delete mode 100644 src/pkg/syscall/flock.go delete mode 100644 src/pkg/syscall/flock_linux_32bit.go delete mode 100644 src/pkg/syscall/fs_nacl.go delete mode 100644 src/pkg/syscall/lsf_linux.go delete mode 100755 src/pkg/syscall/mkall.sh delete mode 100644 src/pkg/syscall/mkall_windows.bat delete mode 100755 src/pkg/syscall/mkerrors.sh delete mode 100755 src/pkg/syscall/mksyscall.pl delete mode 100755 src/pkg/syscall/mksyscall_solaris.pl delete mode 100644 src/pkg/syscall/mksyscall_windows.go delete mode 100755 src/pkg/syscall/mksysctl_openbsd.pl delete mode 100755 src/pkg/syscall/mksysnum_darwin.pl delete mode 100755 src/pkg/syscall/mksysnum_dragonfly.pl delete mode 100755 src/pkg/syscall/mksysnum_freebsd.pl delete mode 100755 src/pkg/syscall/mksysnum_linux.pl delete mode 100755 src/pkg/syscall/mksysnum_netbsd.pl delete mode 100755 src/pkg/syscall/mksysnum_openbsd.pl delete mode 100755 src/pkg/syscall/mksysnum_plan9.sh delete mode 100644 src/pkg/syscall/mmap_unix_test.go delete mode 100644 src/pkg/syscall/net_nacl.go delete mode 100644 src/pkg/syscall/netlink_linux.go delete mode 100644 src/pkg/syscall/race.go delete mode 100644 src/pkg/syscall/race0.go delete mode 100644 src/pkg/syscall/route_bsd.go delete mode 100644 src/pkg/syscall/route_darwin.go delete mode 100644 src/pkg/syscall/route_dragonfly.go delete mode 100644 src/pkg/syscall/route_freebsd.go delete mode 100644 src/pkg/syscall/route_freebsd_32bit.go delete mode 100644 src/pkg/syscall/route_freebsd_64bit.go delete mode 100644 src/pkg/syscall/route_netbsd.go delete mode 100644 src/pkg/syscall/route_openbsd.go delete mode 100644 src/pkg/syscall/security_windows.go delete mode 100644 src/pkg/syscall/so_solaris.go delete mode 100644 src/pkg/syscall/sockcmsg_linux.go delete mode 100644 src/pkg/syscall/sockcmsg_unix.go delete mode 100644 src/pkg/syscall/srpc_nacl.go delete mode 100644 src/pkg/syscall/str.go delete mode 100644 src/pkg/syscall/syscall.go delete mode 100644 src/pkg/syscall/syscall_bsd.go delete mode 100644 src/pkg/syscall/syscall_bsd_test.go delete mode 100644 src/pkg/syscall/syscall_darwin.go delete mode 100644 src/pkg/syscall/syscall_darwin_386.go delete mode 100644 src/pkg/syscall/syscall_darwin_amd64.go delete mode 100644 src/pkg/syscall/syscall_dragonfly.go delete mode 100644 src/pkg/syscall/syscall_dragonfly_386.go delete mode 100644 src/pkg/syscall/syscall_dragonfly_amd64.go delete mode 100644 src/pkg/syscall/syscall_freebsd.go delete mode 100644 src/pkg/syscall/syscall_freebsd_386.go delete mode 100644 src/pkg/syscall/syscall_freebsd_amd64.go delete mode 100644 src/pkg/syscall/syscall_freebsd_arm.go delete mode 100644 src/pkg/syscall/syscall_linux.go delete mode 100644 src/pkg/syscall/syscall_linux_386.go delete mode 100644 src/pkg/syscall/syscall_linux_amd64.go delete mode 100644 src/pkg/syscall/syscall_linux_arm.go delete mode 100644 src/pkg/syscall/syscall_nacl.go delete mode 100644 src/pkg/syscall/syscall_nacl_386.go delete mode 100644 src/pkg/syscall/syscall_nacl_amd64p32.go delete mode 100644 src/pkg/syscall/syscall_nacl_arm.go delete mode 100644 src/pkg/syscall/syscall_netbsd.go delete mode 100644 src/pkg/syscall/syscall_netbsd_386.go delete mode 100644 src/pkg/syscall/syscall_netbsd_amd64.go delete mode 100644 src/pkg/syscall/syscall_netbsd_arm.go delete mode 100644 src/pkg/syscall/syscall_no_getwd.go delete mode 100644 src/pkg/syscall/syscall_openbsd.go delete mode 100644 src/pkg/syscall/syscall_openbsd_386.go delete mode 100644 src/pkg/syscall/syscall_openbsd_amd64.go delete mode 100644 src/pkg/syscall/syscall_plan9.go delete mode 100644 src/pkg/syscall/syscall_solaris.go delete mode 100644 src/pkg/syscall/syscall_solaris_amd64.go delete mode 100644 src/pkg/syscall/syscall_test.go delete mode 100644 src/pkg/syscall/syscall_unix.go delete mode 100644 src/pkg/syscall/syscall_unix_test.go delete mode 100644 src/pkg/syscall/syscall_windows.go delete mode 100644 src/pkg/syscall/syscall_windows_386.go delete mode 100644 src/pkg/syscall/syscall_windows_amd64.go delete mode 100644 src/pkg/syscall/syscall_windows_test.go delete mode 100644 src/pkg/syscall/tables_nacl.go delete mode 100644 src/pkg/syscall/time_nacl_386.s delete mode 100644 src/pkg/syscall/time_nacl_amd64p32.s delete mode 100644 src/pkg/syscall/time_nacl_arm.s delete mode 100644 src/pkg/syscall/types_darwin.go delete mode 100644 src/pkg/syscall/types_dragonfly.go delete mode 100644 src/pkg/syscall/types_freebsd.go delete mode 100644 src/pkg/syscall/types_linux.go delete mode 100644 src/pkg/syscall/types_netbsd.go delete mode 100644 src/pkg/syscall/types_openbsd.go delete mode 100644 src/pkg/syscall/types_plan9.c delete mode 100644 src/pkg/syscall/types_solaris.go delete mode 100644 src/pkg/syscall/unzip_nacl.go delete mode 100644 src/pkg/syscall/zerrors_darwin_386.go delete mode 100644 src/pkg/syscall/zerrors_darwin_amd64.go delete mode 100644 src/pkg/syscall/zerrors_dragonfly_386.go delete mode 100644 src/pkg/syscall/zerrors_dragonfly_amd64.go delete mode 100644 src/pkg/syscall/zerrors_freebsd_386.go delete mode 100644 src/pkg/syscall/zerrors_freebsd_amd64.go delete mode 100644 src/pkg/syscall/zerrors_freebsd_arm.go delete mode 100644 src/pkg/syscall/zerrors_linux_386.go delete mode 100644 src/pkg/syscall/zerrors_linux_amd64.go delete mode 100644 src/pkg/syscall/zerrors_linux_arm.go delete mode 100644 src/pkg/syscall/zerrors_netbsd_386.go delete mode 100644 src/pkg/syscall/zerrors_netbsd_amd64.go delete mode 100644 src/pkg/syscall/zerrors_netbsd_arm.go delete mode 100644 src/pkg/syscall/zerrors_openbsd_386.go delete mode 100644 src/pkg/syscall/zerrors_openbsd_amd64.go delete mode 100644 src/pkg/syscall/zerrors_plan9_386.go delete mode 100644 src/pkg/syscall/zerrors_plan9_amd64.go delete mode 100644 src/pkg/syscall/zerrors_solaris_amd64.go delete mode 100644 src/pkg/syscall/zerrors_windows.go delete mode 100644 src/pkg/syscall/zerrors_windows_386.go delete mode 100644 src/pkg/syscall/zerrors_windows_amd64.go delete mode 100644 src/pkg/syscall/zsyscall_darwin_386.go delete mode 100644 src/pkg/syscall/zsyscall_darwin_amd64.go delete mode 100644 src/pkg/syscall/zsyscall_dragonfly_386.go delete mode 100644 src/pkg/syscall/zsyscall_dragonfly_amd64.go delete mode 100644 src/pkg/syscall/zsyscall_freebsd_386.go delete mode 100644 src/pkg/syscall/zsyscall_freebsd_amd64.go delete mode 100644 src/pkg/syscall/zsyscall_freebsd_arm.go delete mode 100644 src/pkg/syscall/zsyscall_linux_386.go delete mode 100644 src/pkg/syscall/zsyscall_linux_amd64.go delete mode 100644 src/pkg/syscall/zsyscall_linux_arm.go delete mode 100644 src/pkg/syscall/zsyscall_nacl_386.go delete mode 100644 src/pkg/syscall/zsyscall_nacl_amd64p32.go delete mode 100644 src/pkg/syscall/zsyscall_nacl_arm.go delete mode 100644 src/pkg/syscall/zsyscall_netbsd_386.go delete mode 100644 src/pkg/syscall/zsyscall_netbsd_amd64.go delete mode 100644 src/pkg/syscall/zsyscall_netbsd_arm.go delete mode 100644 src/pkg/syscall/zsyscall_openbsd_386.go delete mode 100644 src/pkg/syscall/zsyscall_openbsd_amd64.go delete mode 100644 src/pkg/syscall/zsyscall_plan9_386.go delete mode 100644 src/pkg/syscall/zsyscall_plan9_amd64.go delete mode 100644 src/pkg/syscall/zsyscall_solaris_amd64.go delete mode 100644 src/pkg/syscall/zsyscall_windows.go delete mode 100644 src/pkg/syscall/zsysctl_openbsd.go delete mode 100644 src/pkg/syscall/zsysnum_darwin_386.go delete mode 100644 src/pkg/syscall/zsysnum_darwin_amd64.go delete mode 100644 src/pkg/syscall/zsysnum_dragonfly_386.go delete mode 100644 src/pkg/syscall/zsysnum_dragonfly_amd64.go delete mode 100644 src/pkg/syscall/zsysnum_freebsd_386.go delete mode 100644 src/pkg/syscall/zsysnum_freebsd_amd64.go delete mode 100644 src/pkg/syscall/zsysnum_freebsd_arm.go delete mode 100644 src/pkg/syscall/zsysnum_linux_386.go delete mode 100644 src/pkg/syscall/zsysnum_linux_amd64.go delete mode 100644 src/pkg/syscall/zsysnum_linux_arm.go delete mode 100644 src/pkg/syscall/zsysnum_netbsd_386.go delete mode 100644 src/pkg/syscall/zsysnum_netbsd_amd64.go delete mode 100644 src/pkg/syscall/zsysnum_netbsd_arm.go delete mode 100644 src/pkg/syscall/zsysnum_openbsd_386.go delete mode 100644 src/pkg/syscall/zsysnum_openbsd_amd64.go delete mode 100644 src/pkg/syscall/zsysnum_plan9_386.go delete mode 100644 src/pkg/syscall/zsysnum_plan9_amd64.go delete mode 100644 src/pkg/syscall/zsysnum_solaris_amd64.go delete mode 100644 src/pkg/syscall/zsysnum_windows_386.go delete mode 100644 src/pkg/syscall/zsysnum_windows_amd64.go delete mode 100644 src/pkg/syscall/ztypes_darwin_386.go delete mode 100644 src/pkg/syscall/ztypes_darwin_amd64.go delete mode 100644 src/pkg/syscall/ztypes_dragonfly_386.go delete mode 100644 src/pkg/syscall/ztypes_dragonfly_amd64.go delete mode 100644 src/pkg/syscall/ztypes_freebsd_386.go delete mode 100644 src/pkg/syscall/ztypes_freebsd_amd64.go delete mode 100644 src/pkg/syscall/ztypes_freebsd_arm.go delete mode 100644 src/pkg/syscall/ztypes_linux_386.go delete mode 100644 src/pkg/syscall/ztypes_linux_amd64.go delete mode 100644 src/pkg/syscall/ztypes_linux_arm.go delete mode 100644 src/pkg/syscall/ztypes_netbsd_386.go delete mode 100644 src/pkg/syscall/ztypes_netbsd_amd64.go delete mode 100644 src/pkg/syscall/ztypes_netbsd_arm.go delete mode 100644 src/pkg/syscall/ztypes_openbsd_386.go delete mode 100644 src/pkg/syscall/ztypes_openbsd_amd64.go delete mode 100644 src/pkg/syscall/ztypes_plan9_386.go delete mode 100644 src/pkg/syscall/ztypes_plan9_amd64.go delete mode 100644 src/pkg/syscall/ztypes_solaris_amd64.go delete mode 100644 src/pkg/syscall/ztypes_windows.go delete mode 100644 src/pkg/syscall/ztypes_windows_386.go delete mode 100644 src/pkg/syscall/ztypes_windows_amd64.go delete mode 100644 src/pkg/testing/allocs.go delete mode 100644 src/pkg/testing/benchmark.go delete mode 100644 src/pkg/testing/benchmark_test.go delete mode 100644 src/pkg/testing/cover.go delete mode 100644 src/pkg/testing/example.go delete mode 100644 src/pkg/testing/export_test.go delete mode 100644 src/pkg/testing/iotest/logger.go delete mode 100644 src/pkg/testing/iotest/reader.go delete mode 100644 src/pkg/testing/iotest/writer.go delete mode 100644 src/pkg/testing/quick/quick.go delete mode 100644 src/pkg/testing/quick/quick_test.go delete mode 100644 src/pkg/testing/testing.go delete mode 100644 src/pkg/text/scanner/scanner.go delete mode 100644 src/pkg/text/scanner/scanner_test.go delete mode 100644 src/pkg/text/tabwriter/example_test.go delete mode 100644 src/pkg/text/tabwriter/tabwriter.go delete mode 100644 src/pkg/text/tabwriter/tabwriter_test.go delete mode 100644 src/pkg/text/template/doc.go delete mode 100644 src/pkg/text/template/example_test.go delete mode 100644 src/pkg/text/template/examplefiles_test.go delete mode 100644 src/pkg/text/template/examplefunc_test.go delete mode 100644 src/pkg/text/template/exec.go delete mode 100644 src/pkg/text/template/exec_test.go delete mode 100644 src/pkg/text/template/funcs.go delete mode 100644 src/pkg/text/template/helper.go delete mode 100644 src/pkg/text/template/multi_test.go delete mode 100644 src/pkg/text/template/parse/lex.go delete mode 100644 src/pkg/text/template/parse/lex_test.go delete mode 100644 src/pkg/text/template/parse/node.go delete mode 100644 src/pkg/text/template/parse/parse.go delete mode 100644 src/pkg/text/template/parse/parse_test.go delete mode 100644 src/pkg/text/template/template.go delete mode 100644 src/pkg/text/template/testdata/file1.tmpl delete mode 100644 src/pkg/text/template/testdata/file2.tmpl delete mode 100644 src/pkg/text/template/testdata/tmpl1.tmpl delete mode 100644 src/pkg/text/template/testdata/tmpl2.tmpl delete mode 100644 src/pkg/time/example_test.go delete mode 100644 src/pkg/time/export_test.go delete mode 100644 src/pkg/time/export_windows_test.go delete mode 100644 src/pkg/time/format.go delete mode 100644 src/pkg/time/format_test.go delete mode 100644 src/pkg/time/genzabbrs.go delete mode 100644 src/pkg/time/internal_test.go delete mode 100644 src/pkg/time/sleep.go delete mode 100644 src/pkg/time/sleep_test.go delete mode 100644 src/pkg/time/sys_plan9.go delete mode 100644 src/pkg/time/sys_unix.go delete mode 100644 src/pkg/time/sys_windows.go delete mode 100644 src/pkg/time/tick.go delete mode 100644 src/pkg/time/tick_test.go delete mode 100644 src/pkg/time/time.go delete mode 100644 src/pkg/time/time_test.go delete mode 100644 src/pkg/time/zoneinfo.go delete mode 100644 src/pkg/time/zoneinfo_abbrs_windows.go delete mode 100644 src/pkg/time/zoneinfo_plan9.go delete mode 100644 src/pkg/time/zoneinfo_read.go delete mode 100644 src/pkg/time/zoneinfo_test.go delete mode 100644 src/pkg/time/zoneinfo_unix.go delete mode 100644 src/pkg/time/zoneinfo_windows.go delete mode 100644 src/pkg/time/zoneinfo_windows_test.go delete mode 100644 src/pkg/unicode/casetables.go delete mode 100644 src/pkg/unicode/digit.go delete mode 100644 src/pkg/unicode/digit_test.go delete mode 100644 src/pkg/unicode/graphic.go delete mode 100644 src/pkg/unicode/graphic_test.go delete mode 100644 src/pkg/unicode/letter.go delete mode 100644 src/pkg/unicode/letter_test.go delete mode 100644 src/pkg/unicode/maketables.go delete mode 100644 src/pkg/unicode/script_test.go delete mode 100644 src/pkg/unicode/tables.go delete mode 100644 src/pkg/unicode/utf16/export_test.go delete mode 100644 src/pkg/unicode/utf16/utf16.go delete mode 100644 src/pkg/unicode/utf16/utf16_test.go delete mode 100644 src/pkg/unicode/utf8/example_test.go delete mode 100644 src/pkg/unicode/utf8/utf8.go delete mode 100644 src/pkg/unicode/utf8/utf8_test.go delete mode 100644 src/pkg/unsafe/unsafe.go (limited to 'src/pkg') diff --git a/src/pkg/archive/tar/common.go b/src/pkg/archive/tar/common.go deleted file mode 100644 index e363aa793..000000000 --- a/src/pkg/archive/tar/common.go +++ /dev/null @@ -1,305 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package tar implements access to tar archives. -// It aims to cover most of the variations, including those produced -// by GNU and BSD tars. -// -// References: -// http://www.freebsd.org/cgi/man.cgi?query=tar&sektion=5 -// http://www.gnu.org/software/tar/manual/html_node/Standard.html -// http://pubs.opengroup.org/onlinepubs/9699919799/utilities/pax.html -package tar - -import ( - "bytes" - "errors" - "fmt" - "os" - "path" - "time" -) - -const ( - blockSize = 512 - - // Types - TypeReg = '0' // regular file - TypeRegA = '\x00' // regular file - TypeLink = '1' // hard link - TypeSymlink = '2' // symbolic link - TypeChar = '3' // character device node - TypeBlock = '4' // block device node - TypeDir = '5' // directory - TypeFifo = '6' // fifo node - TypeCont = '7' // reserved - TypeXHeader = 'x' // extended header - TypeXGlobalHeader = 'g' // global extended header - TypeGNULongName = 'L' // Next file has a long name - TypeGNULongLink = 'K' // Next file symlinks to a file w/ a long name - TypeGNUSparse = 'S' // sparse file -) - -// A Header represents a single header in a tar archive. -// Some fields may not be populated. -type Header struct { - Name string // name of header file entry - Mode int64 // permission and mode bits - Uid int // user id of owner - Gid int // group id of owner - Size int64 // length in bytes - ModTime time.Time // modified time - Typeflag byte // type of header entry - Linkname string // target name of link - Uname string // user name of owner - Gname string // group name of owner - Devmajor int64 // major number of character or block device - Devminor int64 // minor number of character or block device - AccessTime time.Time // access time - ChangeTime time.Time // status change time - Xattrs map[string]string -} - -// File name constants from the tar spec. -const ( - fileNameSize = 100 // Maximum number of bytes in a standard tar name. - fileNamePrefixSize = 155 // Maximum number of ustar extension bytes. -) - -// FileInfo returns an os.FileInfo for the Header. -func (h *Header) FileInfo() os.FileInfo { - return headerFileInfo{h} -} - -// headerFileInfo implements os.FileInfo. -type headerFileInfo struct { - h *Header -} - -func (fi headerFileInfo) Size() int64 { return fi.h.Size } -func (fi headerFileInfo) IsDir() bool { return fi.Mode().IsDir() } -func (fi headerFileInfo) ModTime() time.Time { return fi.h.ModTime } -func (fi headerFileInfo) Sys() interface{} { return fi.h } - -// Name returns the base name of the file. -func (fi headerFileInfo) Name() string { - if fi.IsDir() { - return path.Base(path.Clean(fi.h.Name)) - } - return path.Base(fi.h.Name) -} - -// Mode returns the permission and mode bits for the headerFileInfo. -func (fi headerFileInfo) Mode() (mode os.FileMode) { - // Set file permission bits. - mode = os.FileMode(fi.h.Mode).Perm() - - // Set setuid, setgid and sticky bits. - if fi.h.Mode&c_ISUID != 0 { - // setuid - mode |= os.ModeSetuid - } - if fi.h.Mode&c_ISGID != 0 { - // setgid - mode |= os.ModeSetgid - } - if fi.h.Mode&c_ISVTX != 0 { - // sticky - mode |= os.ModeSticky - } - - // Set file mode bits. - // clear perm, setuid, setgid and sticky bits. - m := os.FileMode(fi.h.Mode) &^ 07777 - if m == c_ISDIR { - // directory - mode |= os.ModeDir - } - if m == c_ISFIFO { - // named pipe (FIFO) - mode |= os.ModeNamedPipe - } - if m == c_ISLNK { - // symbolic link - mode |= os.ModeSymlink - } - if m == c_ISBLK { - // device file - mode |= os.ModeDevice - } - if m == c_ISCHR { - // Unix character device - mode |= os.ModeDevice - mode |= os.ModeCharDevice - } - if m == c_ISSOCK { - // Unix domain socket - mode |= os.ModeSocket - } - - switch fi.h.Typeflag { - case TypeLink, TypeSymlink: - // hard link, symbolic link - mode |= os.ModeSymlink - case TypeChar: - // character device node - mode |= os.ModeDevice - mode |= os.ModeCharDevice - case TypeBlock: - // block device node - mode |= os.ModeDevice - case TypeDir: - // directory - mode |= os.ModeDir - case TypeFifo: - // fifo node - mode |= os.ModeNamedPipe - } - - return mode -} - -// sysStat, if non-nil, populates h from system-dependent fields of fi. -var sysStat func(fi os.FileInfo, h *Header) error - -// Mode constants from the tar spec. -const ( - c_ISUID = 04000 // Set uid - c_ISGID = 02000 // Set gid - c_ISVTX = 01000 // Save text (sticky bit) - c_ISDIR = 040000 // Directory - c_ISFIFO = 010000 // FIFO - c_ISREG = 0100000 // Regular file - c_ISLNK = 0120000 // Symbolic link - c_ISBLK = 060000 // Block special file - c_ISCHR = 020000 // Character special file - c_ISSOCK = 0140000 // Socket -) - -// Keywords for the PAX Extended Header -const ( - paxAtime = "atime" - paxCharset = "charset" - paxComment = "comment" - paxCtime = "ctime" // please note that ctime is not a valid pax header. - paxGid = "gid" - paxGname = "gname" - paxLinkpath = "linkpath" - paxMtime = "mtime" - paxPath = "path" - paxSize = "size" - paxUid = "uid" - paxUname = "uname" - paxXattr = "SCHILY.xattr." - paxNone = "" -) - -// FileInfoHeader creates a partially-populated Header from fi. -// If fi describes a symlink, FileInfoHeader records link as the link target. -// If fi describes a directory, a slash is appended to the name. -// Because os.FileInfo's Name method returns only the base name of -// the file it describes, it may be necessary to modify the Name field -// of the returned header to provide the full path name of the file. -func FileInfoHeader(fi os.FileInfo, link string) (*Header, error) { - if fi == nil { - return nil, errors.New("tar: FileInfo is nil") - } - fm := fi.Mode() - h := &Header{ - Name: fi.Name(), - ModTime: fi.ModTime(), - Mode: int64(fm.Perm()), // or'd with c_IS* constants later - } - switch { - case fm.IsRegular(): - h.Mode |= c_ISREG - h.Typeflag = TypeReg - h.Size = fi.Size() - case fi.IsDir(): - h.Typeflag = TypeDir - h.Mode |= c_ISDIR - h.Name += "/" - case fm&os.ModeSymlink != 0: - h.Typeflag = TypeSymlink - h.Mode |= c_ISLNK - h.Linkname = link - case fm&os.ModeDevice != 0: - if fm&os.ModeCharDevice != 0 { - h.Mode |= c_ISCHR - h.Typeflag = TypeChar - } else { - h.Mode |= c_ISBLK - h.Typeflag = TypeBlock - } - case fm&os.ModeNamedPipe != 0: - h.Typeflag = TypeFifo - h.Mode |= c_ISFIFO - case fm&os.ModeSocket != 0: - h.Mode |= c_ISSOCK - default: - return nil, fmt.Errorf("archive/tar: unknown file mode %v", fm) - } - if fm&os.ModeSetuid != 0 { - h.Mode |= c_ISUID - } - if fm&os.ModeSetgid != 0 { - h.Mode |= c_ISGID - } - if fm&os.ModeSticky != 0 { - h.Mode |= c_ISVTX - } - if sysStat != nil { - return h, sysStat(fi, h) - } - return h, nil -} - -var zeroBlock = make([]byte, blockSize) - -// POSIX specifies a sum of the unsigned byte values, but the Sun tar uses signed byte values. -// We compute and return both. -func checksum(header []byte) (unsigned int64, signed int64) { - for i := 0; i < len(header); i++ { - if i == 148 { - // The chksum field (header[148:156]) is special: it should be treated as space bytes. - unsigned += ' ' * 8 - signed += ' ' * 8 - i += 7 - continue - } - unsigned += int64(header[i]) - signed += int64(int8(header[i])) - } - return -} - -type slicer []byte - -func (sp *slicer) next(n int) (b []byte) { - s := *sp - b, *sp = s[0:n], s[n:] - return -} - -func isASCII(s string) bool { - for _, c := range s { - if c >= 0x80 { - return false - } - } - return true -} - -func toASCII(s string) string { - if isASCII(s) { - return s - } - var buf bytes.Buffer - for _, c := range s { - if c < 0x80 { - buf.WriteByte(byte(c)) - } - } - return buf.String() -} diff --git a/src/pkg/archive/tar/example_test.go b/src/pkg/archive/tar/example_test.go deleted file mode 100644 index 351eaa0e6..000000000 --- a/src/pkg/archive/tar/example_test.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tar_test - -import ( - "archive/tar" - "bytes" - "fmt" - "io" - "log" - "os" -) - -func Example() { - // Create a buffer to write our archive to. - buf := new(bytes.Buffer) - - // Create a new tar archive. - tw := tar.NewWriter(buf) - - // Add some files to the archive. - var files = []struct { - Name, Body string - }{ - {"readme.txt", "This archive contains some text files."}, - {"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"}, - {"todo.txt", "Get animal handling licence."}, - } - for _, file := range files { - hdr := &tar.Header{ - Name: file.Name, - Size: int64(len(file.Body)), - } - if err := tw.WriteHeader(hdr); err != nil { - log.Fatalln(err) - } - if _, err := tw.Write([]byte(file.Body)); err != nil { - log.Fatalln(err) - } - } - // Make sure to check the error on Close. - if err := tw.Close(); err != nil { - log.Fatalln(err) - } - - // Open the tar archive for reading. - r := bytes.NewReader(buf.Bytes()) - tr := tar.NewReader(r) - - // Iterate through the files in the archive. - for { - hdr, err := tr.Next() - if err == io.EOF { - // end of tar archive - break - } - if err != nil { - log.Fatalln(err) - } - fmt.Printf("Contents of %s:\n", hdr.Name) - if _, err := io.Copy(os.Stdout, tr); err != nil { - log.Fatalln(err) - } - fmt.Println() - } - - // Output: - // Contents of readme.txt: - // This archive contains some text files. - // Contents of gopher.txt: - // Gopher names: - // George - // Geoffrey - // Gonzo - // Contents of todo.txt: - // Get animal handling licence. -} diff --git a/src/pkg/archive/tar/reader.go b/src/pkg/archive/tar/reader.go deleted file mode 100644 index a27559d0f..000000000 --- a/src/pkg/archive/tar/reader.go +++ /dev/null @@ -1,820 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tar - -// TODO(dsymonds): -// - pax extensions - -import ( - "bytes" - "errors" - "io" - "io/ioutil" - "os" - "strconv" - "strings" - "time" -) - -var ( - ErrHeader = errors.New("archive/tar: invalid tar header") -) - -const maxNanoSecondIntSize = 9 - -// A Reader provides sequential access to the contents of a tar archive. -// A tar archive consists of a sequence of files. -// The Next method advances to the next file in the archive (including the first), -// and then it can be treated as an io.Reader to access the file's data. -type Reader struct { - r io.Reader - err error - pad int64 // amount of padding (ignored) after current file entry - curr numBytesReader // reader for current file entry - hdrBuff [blockSize]byte // buffer to use in readHeader -} - -// A numBytesReader is an io.Reader with a numBytes method, returning the number -// of bytes remaining in the underlying encoded data. -type numBytesReader interface { - io.Reader - numBytes() int64 -} - -// A regFileReader is a numBytesReader for reading file data from a tar archive. -type regFileReader struct { - r io.Reader // underlying reader - nb int64 // number of unread bytes for current file entry -} - -// A sparseFileReader is a numBytesReader for reading sparse file data from a tar archive. -type sparseFileReader struct { - rfr *regFileReader // reads the sparse-encoded file data - sp []sparseEntry // the sparse map for the file - pos int64 // keeps track of file position - tot int64 // total size of the file -} - -// Keywords for GNU sparse files in a PAX extended header -const ( - paxGNUSparseNumBlocks = "GNU.sparse.numblocks" - paxGNUSparseOffset = "GNU.sparse.offset" - paxGNUSparseNumBytes = "GNU.sparse.numbytes" - paxGNUSparseMap = "GNU.sparse.map" - paxGNUSparseName = "GNU.sparse.name" - paxGNUSparseMajor = "GNU.sparse.major" - paxGNUSparseMinor = "GNU.sparse.minor" - paxGNUSparseSize = "GNU.sparse.size" - paxGNUSparseRealSize = "GNU.sparse.realsize" -) - -// Keywords for old GNU sparse headers -const ( - oldGNUSparseMainHeaderOffset = 386 - oldGNUSparseMainHeaderIsExtendedOffset = 482 - oldGNUSparseMainHeaderNumEntries = 4 - oldGNUSparseExtendedHeaderIsExtendedOffset = 504 - oldGNUSparseExtendedHeaderNumEntries = 21 - oldGNUSparseOffsetSize = 12 - oldGNUSparseNumBytesSize = 12 -) - -// NewReader creates a new Reader reading from r. -func NewReader(r io.Reader) *Reader { return &Reader{r: r} } - -// Next advances to the next entry in the tar archive. -func (tr *Reader) Next() (*Header, error) { - var hdr *Header - if tr.err == nil { - tr.skipUnread() - } - if tr.err != nil { - return hdr, tr.err - } - hdr = tr.readHeader() - if hdr == nil { - return hdr, tr.err - } - // Check for PAX/GNU header. - switch hdr.Typeflag { - case TypeXHeader: - // PAX extended header - headers, err := parsePAX(tr) - if err != nil { - return nil, err - } - // We actually read the whole file, - // but this skips alignment padding - tr.skipUnread() - hdr = tr.readHeader() - mergePAX(hdr, headers) - - // Check for a PAX format sparse file - sp, err := tr.checkForGNUSparsePAXHeaders(hdr, headers) - if err != nil { - tr.err = err - return nil, err - } - if sp != nil { - // Current file is a PAX format GNU sparse file. - // Set the current file reader to a sparse file reader. - tr.curr = &sparseFileReader{rfr: tr.curr.(*regFileReader), sp: sp, tot: hdr.Size} - } - return hdr, nil - case TypeGNULongName: - // We have a GNU long name header. Its contents are the real file name. - realname, err := ioutil.ReadAll(tr) - if err != nil { - return nil, err - } - hdr, err := tr.Next() - hdr.Name = cString(realname) - return hdr, err - case TypeGNULongLink: - // We have a GNU long link header. - realname, err := ioutil.ReadAll(tr) - if err != nil { - return nil, err - } - hdr, err := tr.Next() - hdr.Linkname = cString(realname) - return hdr, err - } - return hdr, tr.err -} - -// checkForGNUSparsePAXHeaders checks the PAX headers for GNU sparse headers. If they are found, then -// this function reads the sparse map and returns it. Unknown sparse formats are ignored, causing the file to -// be treated as a regular file. -func (tr *Reader) checkForGNUSparsePAXHeaders(hdr *Header, headers map[string]string) ([]sparseEntry, error) { - var sparseFormat string - - // Check for sparse format indicators - major, majorOk := headers[paxGNUSparseMajor] - minor, minorOk := headers[paxGNUSparseMinor] - sparseName, sparseNameOk := headers[paxGNUSparseName] - _, sparseMapOk := headers[paxGNUSparseMap] - sparseSize, sparseSizeOk := headers[paxGNUSparseSize] - sparseRealSize, sparseRealSizeOk := headers[paxGNUSparseRealSize] - - // Identify which, if any, sparse format applies from which PAX headers are set - if majorOk && minorOk { - sparseFormat = major + "." + minor - } else if sparseNameOk && sparseMapOk { - sparseFormat = "0.1" - } else if sparseSizeOk { - sparseFormat = "0.0" - } else { - // Not a PAX format GNU sparse file. - return nil, nil - } - - // Check for unknown sparse format - if sparseFormat != "0.0" && sparseFormat != "0.1" && sparseFormat != "1.0" { - return nil, nil - } - - // Update hdr from GNU sparse PAX headers - if sparseNameOk { - hdr.Name = sparseName - } - if sparseSizeOk { - realSize, err := strconv.ParseInt(sparseSize, 10, 0) - if err != nil { - return nil, ErrHeader - } - hdr.Size = realSize - } else if sparseRealSizeOk { - realSize, err := strconv.ParseInt(sparseRealSize, 10, 0) - if err != nil { - return nil, ErrHeader - } - hdr.Size = realSize - } - - // Set up the sparse map, according to the particular sparse format in use - var sp []sparseEntry - var err error - switch sparseFormat { - case "0.0", "0.1": - sp, err = readGNUSparseMap0x1(headers) - case "1.0": - sp, err = readGNUSparseMap1x0(tr.curr) - } - return sp, err -} - -// mergePAX merges well known headers according to PAX standard. -// In general headers with the same name as those found -// in the header struct overwrite those found in the header -// struct with higher precision or longer values. Esp. useful -// for name and linkname fields. -func mergePAX(hdr *Header, headers map[string]string) error { - for k, v := range headers { - switch k { - case paxPath: - hdr.Name = v - case paxLinkpath: - hdr.Linkname = v - case paxGname: - hdr.Gname = v - case paxUname: - hdr.Uname = v - case paxUid: - uid, err := strconv.ParseInt(v, 10, 0) - if err != nil { - return err - } - hdr.Uid = int(uid) - case paxGid: - gid, err := strconv.ParseInt(v, 10, 0) - if err != nil { - return err - } - hdr.Gid = int(gid) - case paxAtime: - t, err := parsePAXTime(v) - if err != nil { - return err - } - hdr.AccessTime = t - case paxMtime: - t, err := parsePAXTime(v) - if err != nil { - return err - } - hdr.ModTime = t - case paxCtime: - t, err := parsePAXTime(v) - if err != nil { - return err - } - hdr.ChangeTime = t - case paxSize: - size, err := strconv.ParseInt(v, 10, 0) - if err != nil { - return err - } - hdr.Size = int64(size) - default: - if strings.HasPrefix(k, paxXattr) { - if hdr.Xattrs == nil { - hdr.Xattrs = make(map[string]string) - } - hdr.Xattrs[k[len(paxXattr):]] = v - } - } - } - return nil -} - -// parsePAXTime takes a string of the form %d.%d as described in -// the PAX specification. -func parsePAXTime(t string) (time.Time, error) { - buf := []byte(t) - pos := bytes.IndexByte(buf, '.') - var seconds, nanoseconds int64 - var err error - if pos == -1 { - seconds, err = strconv.ParseInt(t, 10, 0) - if err != nil { - return time.Time{}, err - } - } else { - seconds, err = strconv.ParseInt(string(buf[:pos]), 10, 0) - if err != nil { - return time.Time{}, err - } - nano_buf := string(buf[pos+1:]) - // Pad as needed before converting to a decimal. - // For example .030 -> .030000000 -> 30000000 nanoseconds - if len(nano_buf) < maxNanoSecondIntSize { - // Right pad - nano_buf += strings.Repeat("0", maxNanoSecondIntSize-len(nano_buf)) - } else if len(nano_buf) > maxNanoSecondIntSize { - // Right truncate - nano_buf = nano_buf[:maxNanoSecondIntSize] - } - nanoseconds, err = strconv.ParseInt(string(nano_buf), 10, 0) - if err != nil { - return time.Time{}, err - } - } - ts := time.Unix(seconds, nanoseconds) - return ts, nil -} - -// parsePAX parses PAX headers. -// If an extended header (type 'x') is invalid, ErrHeader is returned -func parsePAX(r io.Reader) (map[string]string, error) { - buf, err := ioutil.ReadAll(r) - if err != nil { - return nil, err - } - - // For GNU PAX sparse format 0.0 support. - // This function transforms the sparse format 0.0 headers into sparse format 0.1 headers. - var sparseMap bytes.Buffer - - headers := make(map[string]string) - // Each record is constructed as - // "%d %s=%s\n", length, keyword, value - for len(buf) > 0 { - // or the header was empty to start with. - var sp int - // The size field ends at the first space. - sp = bytes.IndexByte(buf, ' ') - if sp == -1 { - return nil, ErrHeader - } - // Parse the first token as a decimal integer. - n, err := strconv.ParseInt(string(buf[:sp]), 10, 0) - if err != nil { - return nil, ErrHeader - } - // Extract everything between the decimal and the n -1 on the - // beginning to eat the ' ', -1 on the end to skip the newline. - var record []byte - record, buf = buf[sp+1:n-1], buf[n:] - // The first equals is guaranteed to mark the end of the key. - // Everything else is value. - eq := bytes.IndexByte(record, '=') - if eq == -1 { - return nil, ErrHeader - } - key, value := record[:eq], record[eq+1:] - - keyStr := string(key) - if keyStr == paxGNUSparseOffset || keyStr == paxGNUSparseNumBytes { - // GNU sparse format 0.0 special key. Write to sparseMap instead of using the headers map. - sparseMap.Write(value) - sparseMap.Write([]byte{','}) - } else { - // Normal key. Set the value in the headers map. - headers[keyStr] = string(value) - } - } - if sparseMap.Len() != 0 { - // Add sparse info to headers, chopping off the extra comma - sparseMap.Truncate(sparseMap.Len() - 1) - headers[paxGNUSparseMap] = sparseMap.String() - } - return headers, nil -} - -// cString parses bytes as a NUL-terminated C-style string. -// If a NUL byte is not found then the whole slice is returned as a string. -func cString(b []byte) string { - n := 0 - for n < len(b) && b[n] != 0 { - n++ - } - return string(b[0:n]) -} - -func (tr *Reader) octal(b []byte) int64 { - // Check for binary format first. - if len(b) > 0 && b[0]&0x80 != 0 { - var x int64 - for i, c := range b { - if i == 0 { - c &= 0x7f // ignore signal bit in first byte - } - x = x<<8 | int64(c) - } - return x - } - - // Because unused fields are filled with NULs, we need - // to skip leading NULs. Fields may also be padded with - // spaces or NULs. - // So we remove leading and trailing NULs and spaces to - // be sure. - b = bytes.Trim(b, " \x00") - - if len(b) == 0 { - return 0 - } - x, err := strconv.ParseUint(cString(b), 8, 64) - if err != nil { - tr.err = err - } - return int64(x) -} - -// skipUnread skips any unread bytes in the existing file entry, as well as any alignment padding. -func (tr *Reader) skipUnread() { - nr := tr.numBytes() + tr.pad // number of bytes to skip - tr.curr, tr.pad = nil, 0 - if sr, ok := tr.r.(io.Seeker); ok { - if _, err := sr.Seek(nr, os.SEEK_CUR); err == nil { - return - } - } - _, tr.err = io.CopyN(ioutil.Discard, tr.r, nr) -} - -func (tr *Reader) verifyChecksum(header []byte) bool { - if tr.err != nil { - return false - } - - given := tr.octal(header[148:156]) - unsigned, signed := checksum(header) - return given == unsigned || given == signed -} - -func (tr *Reader) readHeader() *Header { - header := tr.hdrBuff[:] - copy(header, zeroBlock) - - if _, tr.err = io.ReadFull(tr.r, header); tr.err != nil { - return nil - } - - // Two blocks of zero bytes marks the end of the archive. - if bytes.Equal(header, zeroBlock[0:blockSize]) { - if _, tr.err = io.ReadFull(tr.r, header); tr.err != nil { - return nil - } - if bytes.Equal(header, zeroBlock[0:blockSize]) { - tr.err = io.EOF - } else { - tr.err = ErrHeader // zero block and then non-zero block - } - return nil - } - - if !tr.verifyChecksum(header) { - tr.err = ErrHeader - return nil - } - - // Unpack - hdr := new(Header) - s := slicer(header) - - hdr.Name = cString(s.next(100)) - hdr.Mode = tr.octal(s.next(8)) - hdr.Uid = int(tr.octal(s.next(8))) - hdr.Gid = int(tr.octal(s.next(8))) - hdr.Size = tr.octal(s.next(12)) - hdr.ModTime = time.Unix(tr.octal(s.next(12)), 0) - s.next(8) // chksum - hdr.Typeflag = s.next(1)[0] - hdr.Linkname = cString(s.next(100)) - - // The remainder of the header depends on the value of magic. - // The original (v7) version of tar had no explicit magic field, - // so its magic bytes, like the rest of the block, are NULs. - magic := string(s.next(8)) // contains version field as well. - var format string - switch { - case magic[:6] == "ustar\x00": // POSIX tar (1003.1-1988) - if string(header[508:512]) == "tar\x00" { - format = "star" - } else { - format = "posix" - } - case magic == "ustar \x00": // old GNU tar - format = "gnu" - } - - switch format { - case "posix", "gnu", "star": - hdr.Uname = cString(s.next(32)) - hdr.Gname = cString(s.next(32)) - devmajor := s.next(8) - devminor := s.next(8) - if hdr.Typeflag == TypeChar || hdr.Typeflag == TypeBlock { - hdr.Devmajor = tr.octal(devmajor) - hdr.Devminor = tr.octal(devminor) - } - var prefix string - switch format { - case "posix", "gnu": - prefix = cString(s.next(155)) - case "star": - prefix = cString(s.next(131)) - hdr.AccessTime = time.Unix(tr.octal(s.next(12)), 0) - hdr.ChangeTime = time.Unix(tr.octal(s.next(12)), 0) - } - if len(prefix) > 0 { - hdr.Name = prefix + "/" + hdr.Name - } - } - - if tr.err != nil { - tr.err = ErrHeader - return nil - } - - // Maximum value of hdr.Size is 64 GB (12 octal digits), - // so there's no risk of int64 overflowing. - nb := int64(hdr.Size) - tr.pad = -nb & (blockSize - 1) // blockSize is a power of two - - // Set the current file reader. - tr.curr = ®FileReader{r: tr.r, nb: nb} - - // Check for old GNU sparse format entry. - if hdr.Typeflag == TypeGNUSparse { - // Get the real size of the file. - hdr.Size = tr.octal(header[483:495]) - - // Read the sparse map. - sp := tr.readOldGNUSparseMap(header) - if tr.err != nil { - return nil - } - // Current file is a GNU sparse file. Update the current file reader. - tr.curr = &sparseFileReader{rfr: tr.curr.(*regFileReader), sp: sp, tot: hdr.Size} - } - - return hdr -} - -// A sparseEntry holds a single entry in a sparse file's sparse map. -// A sparse entry indicates the offset and size in a sparse file of a -// block of data. -type sparseEntry struct { - offset int64 - numBytes int64 -} - -// readOldGNUSparseMap reads the sparse map as stored in the old GNU sparse format. -// The sparse map is stored in the tar header if it's small enough. If it's larger than four entries, -// then one or more extension headers are used to store the rest of the sparse map. -func (tr *Reader) readOldGNUSparseMap(header []byte) []sparseEntry { - isExtended := header[oldGNUSparseMainHeaderIsExtendedOffset] != 0 - spCap := oldGNUSparseMainHeaderNumEntries - if isExtended { - spCap += oldGNUSparseExtendedHeaderNumEntries - } - sp := make([]sparseEntry, 0, spCap) - s := slicer(header[oldGNUSparseMainHeaderOffset:]) - - // Read the four entries from the main tar header - for i := 0; i < oldGNUSparseMainHeaderNumEntries; i++ { - offset := tr.octal(s.next(oldGNUSparseOffsetSize)) - numBytes := tr.octal(s.next(oldGNUSparseNumBytesSize)) - if tr.err != nil { - tr.err = ErrHeader - return nil - } - if offset == 0 && numBytes == 0 { - break - } - sp = append(sp, sparseEntry{offset: offset, numBytes: numBytes}) - } - - for isExtended { - // There are more entries. Read an extension header and parse its entries. - sparseHeader := make([]byte, blockSize) - if _, tr.err = io.ReadFull(tr.r, sparseHeader); tr.err != nil { - return nil - } - isExtended = sparseHeader[oldGNUSparseExtendedHeaderIsExtendedOffset] != 0 - s = slicer(sparseHeader) - for i := 0; i < oldGNUSparseExtendedHeaderNumEntries; i++ { - offset := tr.octal(s.next(oldGNUSparseOffsetSize)) - numBytes := tr.octal(s.next(oldGNUSparseNumBytesSize)) - if tr.err != nil { - tr.err = ErrHeader - return nil - } - if offset == 0 && numBytes == 0 { - break - } - sp = append(sp, sparseEntry{offset: offset, numBytes: numBytes}) - } - } - return sp -} - -// readGNUSparseMap1x0 reads the sparse map as stored in GNU's PAX sparse format version 1.0. -// The sparse map is stored just before the file data and padded out to the nearest block boundary. -func readGNUSparseMap1x0(r io.Reader) ([]sparseEntry, error) { - buf := make([]byte, 2*blockSize) - sparseHeader := buf[:blockSize] - - // readDecimal is a helper function to read a decimal integer from the sparse map - // while making sure to read from the file in blocks of size blockSize - readDecimal := func() (int64, error) { - // Look for newline - nl := bytes.IndexByte(sparseHeader, '\n') - if nl == -1 { - if len(sparseHeader) >= blockSize { - // This is an error - return 0, ErrHeader - } - oldLen := len(sparseHeader) - newLen := oldLen + blockSize - if cap(sparseHeader) < newLen { - // There's more header, but we need to make room for the next block - copy(buf, sparseHeader) - sparseHeader = buf[:newLen] - } else { - // There's more header, and we can just reslice - sparseHeader = sparseHeader[:newLen] - } - - // Now that sparseHeader is large enough, read next block - if _, err := io.ReadFull(r, sparseHeader[oldLen:newLen]); err != nil { - return 0, err - } - - // Look for a newline in the new data - nl = bytes.IndexByte(sparseHeader[oldLen:newLen], '\n') - if nl == -1 { - // This is an error - return 0, ErrHeader - } - nl += oldLen // We want the position from the beginning - } - // Now that we've found a newline, read a number - n, err := strconv.ParseInt(string(sparseHeader[:nl]), 10, 0) - if err != nil { - return 0, ErrHeader - } - - // Update sparseHeader to consume this number - sparseHeader = sparseHeader[nl+1:] - return n, nil - } - - // Read the first block - if _, err := io.ReadFull(r, sparseHeader); err != nil { - return nil, err - } - - // The first line contains the number of entries - numEntries, err := readDecimal() - if err != nil { - return nil, err - } - - // Read all the entries - sp := make([]sparseEntry, 0, numEntries) - for i := int64(0); i < numEntries; i++ { - // Read the offset - offset, err := readDecimal() - if err != nil { - return nil, err - } - // Read numBytes - numBytes, err := readDecimal() - if err != nil { - return nil, err - } - - sp = append(sp, sparseEntry{offset: offset, numBytes: numBytes}) - } - - return sp, nil -} - -// readGNUSparseMap0x1 reads the sparse map as stored in GNU's PAX sparse format version 0.1. -// The sparse map is stored in the PAX headers. -func readGNUSparseMap0x1(headers map[string]string) ([]sparseEntry, error) { - // Get number of entries - numEntriesStr, ok := headers[paxGNUSparseNumBlocks] - if !ok { - return nil, ErrHeader - } - numEntries, err := strconv.ParseInt(numEntriesStr, 10, 0) - if err != nil { - return nil, ErrHeader - } - - sparseMap := strings.Split(headers[paxGNUSparseMap], ",") - - // There should be two numbers in sparseMap for each entry - if int64(len(sparseMap)) != 2*numEntries { - return nil, ErrHeader - } - - // Loop through the entries in the sparse map - sp := make([]sparseEntry, 0, numEntries) - for i := int64(0); i < numEntries; i++ { - offset, err := strconv.ParseInt(sparseMap[2*i], 10, 0) - if err != nil { - return nil, ErrHeader - } - numBytes, err := strconv.ParseInt(sparseMap[2*i+1], 10, 0) - if err != nil { - return nil, ErrHeader - } - sp = append(sp, sparseEntry{offset: offset, numBytes: numBytes}) - } - - return sp, nil -} - -// numBytes returns the number of bytes left to read in the current file's entry -// in the tar archive, or 0 if there is no current file. -func (tr *Reader) numBytes() int64 { - if tr.curr == nil { - // No current file, so no bytes - return 0 - } - return tr.curr.numBytes() -} - -// Read reads from the current entry in the tar archive. -// It returns 0, io.EOF when it reaches the end of that entry, -// until Next is called to advance to the next entry. -func (tr *Reader) Read(b []byte) (n int, err error) { - if tr.curr == nil { - return 0, io.EOF - } - n, err = tr.curr.Read(b) - if err != nil && err != io.EOF { - tr.err = err - } - return -} - -func (rfr *regFileReader) Read(b []byte) (n int, err error) { - if rfr.nb == 0 { - // file consumed - return 0, io.EOF - } - if int64(len(b)) > rfr.nb { - b = b[0:rfr.nb] - } - n, err = rfr.r.Read(b) - rfr.nb -= int64(n) - - if err == io.EOF && rfr.nb > 0 { - err = io.ErrUnexpectedEOF - } - return -} - -// numBytes returns the number of bytes left to read in the file's data in the tar archive. -func (rfr *regFileReader) numBytes() int64 { - return rfr.nb -} - -// readHole reads a sparse file hole ending at offset toOffset -func (sfr *sparseFileReader) readHole(b []byte, toOffset int64) int { - n64 := toOffset - sfr.pos - if n64 > int64(len(b)) { - n64 = int64(len(b)) - } - n := int(n64) - for i := 0; i < n; i++ { - b[i] = 0 - } - sfr.pos += n64 - return n -} - -// Read reads the sparse file data in expanded form. -func (sfr *sparseFileReader) Read(b []byte) (n int, err error) { - if len(sfr.sp) == 0 { - // No more data fragments to read from. - if sfr.pos < sfr.tot { - // We're in the last hole - n = sfr.readHole(b, sfr.tot) - return - } - // Otherwise, we're at the end of the file - return 0, io.EOF - } - if sfr.pos < sfr.sp[0].offset { - // We're in a hole - n = sfr.readHole(b, sfr.sp[0].offset) - return - } - - // We're not in a hole, so we'll read from the next data fragment - posInFragment := sfr.pos - sfr.sp[0].offset - bytesLeft := sfr.sp[0].numBytes - posInFragment - if int64(len(b)) > bytesLeft { - b = b[0:bytesLeft] - } - - n, err = sfr.rfr.Read(b) - sfr.pos += int64(n) - - if int64(n) == bytesLeft { - // We're done with this fragment - sfr.sp = sfr.sp[1:] - } - - if err == io.EOF && sfr.pos < sfr.tot { - // We reached the end of the last fragment's data, but there's a final hole - err = nil - } - return -} - -// numBytes returns the number of bytes left to read in the sparse file's -// sparse-encoded data in the tar archive. -func (sfr *sparseFileReader) numBytes() int64 { - return sfr.rfr.nb -} diff --git a/src/pkg/archive/tar/reader_test.go b/src/pkg/archive/tar/reader_test.go deleted file mode 100644 index 9601ffe45..000000000 --- a/src/pkg/archive/tar/reader_test.go +++ /dev/null @@ -1,743 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tar - -import ( - "bytes" - "crypto/md5" - "fmt" - "io" - "io/ioutil" - "os" - "reflect" - "strings" - "testing" - "time" -) - -type untarTest struct { - file string - headers []*Header - cksums []string -} - -var gnuTarTest = &untarTest{ - file: "testdata/gnu.tar", - headers: []*Header{ - { - Name: "small.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 5, - ModTime: time.Unix(1244428340, 0), - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - }, - { - Name: "small2.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 11, - ModTime: time.Unix(1244436044, 0), - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - }, - }, - cksums: []string{ - "e38b27eaccb4391bdec553a7f3ae6b2f", - "c65bd2e50a56a2138bf1716f2fd56fe9", - }, -} - -var sparseTarTest = &untarTest{ - file: "testdata/sparse-formats.tar", - headers: []*Header{ - { - Name: "sparse-gnu", - Mode: 420, - Uid: 1000, - Gid: 1000, - Size: 200, - ModTime: time.Unix(1392395740, 0), - Typeflag: 0x53, - Linkname: "", - Uname: "david", - Gname: "david", - Devmajor: 0, - Devminor: 0, - }, - { - Name: "sparse-posix-0.0", - Mode: 420, - Uid: 1000, - Gid: 1000, - Size: 200, - ModTime: time.Unix(1392342187, 0), - Typeflag: 0x30, - Linkname: "", - Uname: "david", - Gname: "david", - Devmajor: 0, - Devminor: 0, - }, - { - Name: "sparse-posix-0.1", - Mode: 420, - Uid: 1000, - Gid: 1000, - Size: 200, - ModTime: time.Unix(1392340456, 0), - Typeflag: 0x30, - Linkname: "", - Uname: "david", - Gname: "david", - Devmajor: 0, - Devminor: 0, - }, - { - Name: "sparse-posix-1.0", - Mode: 420, - Uid: 1000, - Gid: 1000, - Size: 200, - ModTime: time.Unix(1392337404, 0), - Typeflag: 0x30, - Linkname: "", - Uname: "david", - Gname: "david", - Devmajor: 0, - Devminor: 0, - }, - { - Name: "end", - Mode: 420, - Uid: 1000, - Gid: 1000, - Size: 4, - ModTime: time.Unix(1392398319, 0), - Typeflag: 0x30, - Linkname: "", - Uname: "david", - Gname: "david", - Devmajor: 0, - Devminor: 0, - }, - }, - cksums: []string{ - "6f53234398c2449fe67c1812d993012f", - "6f53234398c2449fe67c1812d993012f", - "6f53234398c2449fe67c1812d993012f", - "6f53234398c2449fe67c1812d993012f", - "b0061974914468de549a2af8ced10316", - }, -} - -var untarTests = []*untarTest{ - gnuTarTest, - sparseTarTest, - { - file: "testdata/star.tar", - headers: []*Header{ - { - Name: "small.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 5, - ModTime: time.Unix(1244592783, 0), - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - AccessTime: time.Unix(1244592783, 0), - ChangeTime: time.Unix(1244592783, 0), - }, - { - Name: "small2.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 11, - ModTime: time.Unix(1244592783, 0), - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - AccessTime: time.Unix(1244592783, 0), - ChangeTime: time.Unix(1244592783, 0), - }, - }, - }, - { - file: "testdata/v7.tar", - headers: []*Header{ - { - Name: "small.txt", - Mode: 0444, - Uid: 73025, - Gid: 5000, - Size: 5, - ModTime: time.Unix(1244593104, 0), - Typeflag: '\x00', - }, - { - Name: "small2.txt", - Mode: 0444, - Uid: 73025, - Gid: 5000, - Size: 11, - ModTime: time.Unix(1244593104, 0), - Typeflag: '\x00', - }, - }, - }, - { - file: "testdata/pax.tar", - headers: []*Header{ - { - Name: "a/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100", - Mode: 0664, - Uid: 1000, - Gid: 1000, - Uname: "shane", - Gname: "shane", - Size: 7, - ModTime: time.Unix(1350244992, 23960108), - ChangeTime: time.Unix(1350244992, 23960108), - AccessTime: time.Unix(1350244992, 23960108), - Typeflag: TypeReg, - }, - { - Name: "a/b", - Mode: 0777, - Uid: 1000, - Gid: 1000, - Uname: "shane", - Gname: "shane", - Size: 0, - ModTime: time.Unix(1350266320, 910238425), - ChangeTime: time.Unix(1350266320, 910238425), - AccessTime: time.Unix(1350266320, 910238425), - Typeflag: TypeSymlink, - Linkname: "123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100", - }, - }, - }, - { - file: "testdata/nil-uid.tar", // golang.org/issue/5290 - headers: []*Header{ - { - Name: "P1050238.JPG.log", - Mode: 0664, - Uid: 0, - Gid: 0, - Size: 14, - ModTime: time.Unix(1365454838, 0), - Typeflag: TypeReg, - Linkname: "", - Uname: "eyefi", - Gname: "eyefi", - Devmajor: 0, - Devminor: 0, - }, - }, - }, - { - file: "testdata/xattrs.tar", - headers: []*Header{ - { - Name: "small.txt", - Mode: 0644, - Uid: 1000, - Gid: 10, - Size: 5, - ModTime: time.Unix(1386065770, 448252320), - Typeflag: '0', - Uname: "alex", - Gname: "wheel", - AccessTime: time.Unix(1389782991, 419875220), - ChangeTime: time.Unix(1389782956, 794414986), - Xattrs: map[string]string{ - "user.key": "value", - "user.key2": "value2", - // Interestingly, selinux encodes the terminating null inside the xattr - "security.selinux": "unconfined_u:object_r:default_t:s0\x00", - }, - }, - { - Name: "small2.txt", - Mode: 0644, - Uid: 1000, - Gid: 10, - Size: 11, - ModTime: time.Unix(1386065770, 449252304), - Typeflag: '0', - Uname: "alex", - Gname: "wheel", - AccessTime: time.Unix(1389782991, 419875220), - ChangeTime: time.Unix(1386065770, 449252304), - Xattrs: map[string]string{ - "security.selinux": "unconfined_u:object_r:default_t:s0\x00", - }, - }, - }, - }, -} - -func TestReader(t *testing.T) { -testLoop: - for i, test := range untarTests { - f, err := os.Open(test.file) - if err != nil { - t.Errorf("test %d: Unexpected error: %v", i, err) - continue - } - defer f.Close() - tr := NewReader(f) - for j, header := range test.headers { - hdr, err := tr.Next() - if err != nil || hdr == nil { - t.Errorf("test %d, entry %d: Didn't get entry: %v", i, j, err) - f.Close() - continue testLoop - } - if !reflect.DeepEqual(*hdr, *header) { - t.Errorf("test %d, entry %d: Incorrect header:\nhave %+v\nwant %+v", - i, j, *hdr, *header) - } - } - hdr, err := tr.Next() - if err == io.EOF { - continue testLoop - } - if hdr != nil || err != nil { - t.Errorf("test %d: Unexpected entry or error: hdr=%v err=%v", i, hdr, err) - } - } -} - -func TestPartialRead(t *testing.T) { - f, err := os.Open("testdata/gnu.tar") - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - defer f.Close() - - tr := NewReader(f) - - // Read the first four bytes; Next() should skip the last byte. - hdr, err := tr.Next() - if err != nil || hdr == nil { - t.Fatalf("Didn't get first file: %v", err) - } - buf := make([]byte, 4) - if _, err := io.ReadFull(tr, buf); err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if expected := []byte("Kilt"); !bytes.Equal(buf, expected) { - t.Errorf("Contents = %v, want %v", buf, expected) - } - - // Second file - hdr, err = tr.Next() - if err != nil || hdr == nil { - t.Fatalf("Didn't get second file: %v", err) - } - buf = make([]byte, 6) - if _, err := io.ReadFull(tr, buf); err != nil { - t.Fatalf("Unexpected error: %v", err) - } - if expected := []byte("Google"); !bytes.Equal(buf, expected) { - t.Errorf("Contents = %v, want %v", buf, expected) - } -} - -func TestIncrementalRead(t *testing.T) { - test := gnuTarTest - f, err := os.Open(test.file) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - defer f.Close() - - tr := NewReader(f) - - headers := test.headers - cksums := test.cksums - nread := 0 - - // loop over all files - for ; ; nread++ { - hdr, err := tr.Next() - if hdr == nil || err == io.EOF { - break - } - - // check the header - if !reflect.DeepEqual(*hdr, *headers[nread]) { - t.Errorf("Incorrect header:\nhave %+v\nwant %+v", - *hdr, headers[nread]) - } - - // read file contents in little chunks EOF, - // checksumming all the way - h := md5.New() - rdbuf := make([]uint8, 8) - for { - nr, err := tr.Read(rdbuf) - if err == io.EOF { - break - } - if err != nil { - t.Errorf("Read: unexpected error %v\n", err) - break - } - h.Write(rdbuf[0:nr]) - } - // verify checksum - have := fmt.Sprintf("%x", h.Sum(nil)) - want := cksums[nread] - if want != have { - t.Errorf("Bad checksum on file %s:\nhave %+v\nwant %+v", hdr.Name, have, want) - } - } - if nread != len(headers) { - t.Errorf("Didn't process all files\nexpected: %d\nprocessed %d\n", len(headers), nread) - } -} - -func TestNonSeekable(t *testing.T) { - test := gnuTarTest - f, err := os.Open(test.file) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - defer f.Close() - - type readerOnly struct { - io.Reader - } - tr := NewReader(readerOnly{f}) - nread := 0 - - for ; ; nread++ { - _, err := tr.Next() - if err == io.EOF { - break - } - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - } - - if nread != len(test.headers) { - t.Errorf("Didn't process all files\nexpected: %d\nprocessed %d\n", len(test.headers), nread) - } -} - -func TestParsePAXHeader(t *testing.T) { - paxTests := [][3]string{ - {"a", "a=name", "10 a=name\n"}, // Test case involving multiple acceptable lengths - {"a", "a=name", "9 a=name\n"}, // Test case involving multiple acceptable length - {"mtime", "mtime=1350244992.023960108", "30 mtime=1350244992.023960108\n"}} - for _, test := range paxTests { - key, expected, raw := test[0], test[1], test[2] - reader := bytes.NewReader([]byte(raw)) - headers, err := parsePAX(reader) - if err != nil { - t.Errorf("Couldn't parse correctly formatted headers: %v", err) - continue - } - if strings.EqualFold(headers[key], expected) { - t.Errorf("mtime header incorrectly parsed: got %s, wanted %s", headers[key], expected) - continue - } - trailer := make([]byte, 100) - n, err := reader.Read(trailer) - if err != io.EOF || n != 0 { - t.Error("Buffer wasn't consumed") - } - } - badHeader := bytes.NewReader([]byte("3 somelongkey=")) - if _, err := parsePAX(badHeader); err != ErrHeader { - t.Fatal("Unexpected success when parsing bad header") - } -} - -func TestParsePAXTime(t *testing.T) { - // Some valid PAX time values - timestamps := map[string]time.Time{ - "1350244992.023960108": time.Unix(1350244992, 23960108), // The common case - "1350244992.02396010": time.Unix(1350244992, 23960100), // Lower precision value - "1350244992.0239601089": time.Unix(1350244992, 23960108), // Higher precision value - "1350244992": time.Unix(1350244992, 0), // Low precision value - } - for input, expected := range timestamps { - ts, err := parsePAXTime(input) - if err != nil { - t.Fatal(err) - } - if !ts.Equal(expected) { - t.Fatalf("Time parsing failure %s %s", ts, expected) - } - } -} - -func TestMergePAX(t *testing.T) { - hdr := new(Header) - // Test a string, integer, and time based value. - headers := map[string]string{ - "path": "a/b/c", - "uid": "1000", - "mtime": "1350244992.023960108", - } - err := mergePAX(hdr, headers) - if err != nil { - t.Fatal(err) - } - want := &Header{ - Name: "a/b/c", - Uid: 1000, - ModTime: time.Unix(1350244992, 23960108), - } - if !reflect.DeepEqual(hdr, want) { - t.Errorf("incorrect merge: got %+v, want %+v", hdr, want) - } -} - -func TestSparseEndToEnd(t *testing.T) { - test := sparseTarTest - f, err := os.Open(test.file) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - defer f.Close() - - tr := NewReader(f) - - headers := test.headers - cksums := test.cksums - nread := 0 - - // loop over all files - for ; ; nread++ { - hdr, err := tr.Next() - if hdr == nil || err == io.EOF { - break - } - - // check the header - if !reflect.DeepEqual(*hdr, *headers[nread]) { - t.Errorf("Incorrect header:\nhave %+v\nwant %+v", - *hdr, headers[nread]) - } - - // read and checksum the file data - h := md5.New() - _, err = io.Copy(h, tr) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - - // verify checksum - have := fmt.Sprintf("%x", h.Sum(nil)) - want := cksums[nread] - if want != have { - t.Errorf("Bad checksum on file %s:\nhave %+v\nwant %+v", hdr.Name, have, want) - } - } - if nread != len(headers) { - t.Errorf("Didn't process all files\nexpected: %d\nprocessed %d\n", len(headers), nread) - } -} - -type sparseFileReadTest struct { - sparseData []byte - sparseMap []sparseEntry - realSize int64 - expected []byte -} - -var sparseFileReadTests = []sparseFileReadTest{ - { - sparseData: []byte("abcde"), - sparseMap: []sparseEntry{ - {offset: 0, numBytes: 2}, - {offset: 5, numBytes: 3}, - }, - realSize: 8, - expected: []byte("ab\x00\x00\x00cde"), - }, - { - sparseData: []byte("abcde"), - sparseMap: []sparseEntry{ - {offset: 0, numBytes: 2}, - {offset: 5, numBytes: 3}, - }, - realSize: 10, - expected: []byte("ab\x00\x00\x00cde\x00\x00"), - }, - { - sparseData: []byte("abcde"), - sparseMap: []sparseEntry{ - {offset: 1, numBytes: 3}, - {offset: 6, numBytes: 2}, - }, - realSize: 8, - expected: []byte("\x00abc\x00\x00de"), - }, - { - sparseData: []byte("abcde"), - sparseMap: []sparseEntry{ - {offset: 1, numBytes: 3}, - {offset: 6, numBytes: 2}, - }, - realSize: 10, - expected: []byte("\x00abc\x00\x00de\x00\x00"), - }, - { - sparseData: []byte(""), - sparseMap: nil, - realSize: 2, - expected: []byte("\x00\x00"), - }, -} - -func TestSparseFileReader(t *testing.T) { - for i, test := range sparseFileReadTests { - r := bytes.NewReader(test.sparseData) - nb := int64(r.Len()) - sfr := &sparseFileReader{ - rfr: ®FileReader{r: r, nb: nb}, - sp: test.sparseMap, - pos: 0, - tot: test.realSize, - } - if sfr.numBytes() != nb { - t.Errorf("test %d: Before reading, sfr.numBytes() = %d, want %d", i, sfr.numBytes(), nb) - } - buf, err := ioutil.ReadAll(sfr) - if err != nil { - t.Errorf("test %d: Unexpected error: %v", i, err) - } - if e := test.expected; !bytes.Equal(buf, e) { - t.Errorf("test %d: Contents = %v, want %v", i, buf, e) - } - if sfr.numBytes() != 0 { - t.Errorf("test %d: After draining the reader, numBytes() was nonzero", i) - } - } -} - -func TestSparseIncrementalRead(t *testing.T) { - sparseMap := []sparseEntry{{10, 2}} - sparseData := []byte("Go") - expected := "\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00Go\x00\x00\x00\x00\x00\x00\x00\x00" - - r := bytes.NewReader(sparseData) - nb := int64(r.Len()) - sfr := &sparseFileReader{ - rfr: ®FileReader{r: r, nb: nb}, - sp: sparseMap, - pos: 0, - tot: int64(len(expected)), - } - - // We'll read the data 6 bytes at a time, with a hole of size 10 at - // the beginning and one of size 8 at the end. - var outputBuf bytes.Buffer - buf := make([]byte, 6) - for { - n, err := sfr.Read(buf) - if err == io.EOF { - break - } - if err != nil { - t.Errorf("Read: unexpected error %v\n", err) - } - if n > 0 { - _, err := outputBuf.Write(buf[:n]) - if err != nil { - t.Errorf("Write: unexpected error %v\n", err) - } - } - } - got := outputBuf.String() - if got != expected { - t.Errorf("Contents = %v, want %v", got, expected) - } -} - -func TestReadGNUSparseMap0x1(t *testing.T) { - headers := map[string]string{ - paxGNUSparseNumBlocks: "4", - paxGNUSparseMap: "0,5,10,5,20,5,30,5", - } - expected := []sparseEntry{ - {offset: 0, numBytes: 5}, - {offset: 10, numBytes: 5}, - {offset: 20, numBytes: 5}, - {offset: 30, numBytes: 5}, - } - - sp, err := readGNUSparseMap0x1(headers) - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - if !reflect.DeepEqual(sp, expected) { - t.Errorf("Incorrect sparse map: got %v, wanted %v", sp, expected) - } -} - -func TestReadGNUSparseMap1x0(t *testing.T) { - // This test uses lots of holes so the sparse header takes up more than two blocks - numEntries := 100 - expected := make([]sparseEntry, 0, numEntries) - sparseMap := new(bytes.Buffer) - - fmt.Fprintf(sparseMap, "%d\n", numEntries) - for i := 0; i < numEntries; i++ { - offset := int64(2048 * i) - numBytes := int64(1024) - expected = append(expected, sparseEntry{offset: offset, numBytes: numBytes}) - fmt.Fprintf(sparseMap, "%d\n%d\n", offset, numBytes) - } - - // Make the header the smallest multiple of blockSize that fits the sparseMap - headerBlocks := (sparseMap.Len() + blockSize - 1) / blockSize - bufLen := blockSize * headerBlocks - buf := make([]byte, bufLen) - copy(buf, sparseMap.Bytes()) - - // Get an reader to read the sparse map - r := bytes.NewReader(buf) - - // Read the sparse map - sp, err := readGNUSparseMap1x0(r) - if err != nil { - t.Errorf("Unexpected error: %v", err) - } - if !reflect.DeepEqual(sp, expected) { - t.Errorf("Incorrect sparse map: got %v, wanted %v", sp, expected) - } -} - -func TestUninitializedRead(t *testing.T) { - test := gnuTarTest - f, err := os.Open(test.file) - if err != nil { - t.Fatalf("Unexpected error: %v", err) - } - defer f.Close() - - tr := NewReader(f) - _, err = tr.Read([]byte{}) - if err == nil || err != io.EOF { - t.Errorf("Unexpected error: %v, wanted %v", err, io.EOF) - } - -} diff --git a/src/pkg/archive/tar/stat_atim.go b/src/pkg/archive/tar/stat_atim.go deleted file mode 100644 index cf9cc79c5..000000000 --- a/src/pkg/archive/tar/stat_atim.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build linux dragonfly openbsd solaris - -package tar - -import ( - "syscall" - "time" -) - -func statAtime(st *syscall.Stat_t) time.Time { - return time.Unix(st.Atim.Unix()) -} - -func statCtime(st *syscall.Stat_t) time.Time { - return time.Unix(st.Ctim.Unix()) -} diff --git a/src/pkg/archive/tar/stat_atimespec.go b/src/pkg/archive/tar/stat_atimespec.go deleted file mode 100644 index 6f17dbe30..000000000 --- a/src/pkg/archive/tar/stat_atimespec.go +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin freebsd netbsd - -package tar - -import ( - "syscall" - "time" -) - -func statAtime(st *syscall.Stat_t) time.Time { - return time.Unix(st.Atimespec.Unix()) -} - -func statCtime(st *syscall.Stat_t) time.Time { - return time.Unix(st.Ctimespec.Unix()) -} diff --git a/src/pkg/archive/tar/stat_unix.go b/src/pkg/archive/tar/stat_unix.go deleted file mode 100644 index cb843db4c..000000000 --- a/src/pkg/archive/tar/stat_unix.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build linux darwin dragonfly freebsd openbsd netbsd solaris - -package tar - -import ( - "os" - "syscall" -) - -func init() { - sysStat = statUnix -} - -func statUnix(fi os.FileInfo, h *Header) error { - sys, ok := fi.Sys().(*syscall.Stat_t) - if !ok { - return nil - } - h.Uid = int(sys.Uid) - h.Gid = int(sys.Gid) - // TODO(bradfitz): populate username & group. os/user - // doesn't cache LookupId lookups, and lacks group - // lookup functions. - h.AccessTime = statAtime(sys) - h.ChangeTime = statCtime(sys) - // TODO(bradfitz): major/minor device numbers? - return nil -} diff --git a/src/pkg/archive/tar/tar_test.go b/src/pkg/archive/tar/tar_test.go deleted file mode 100644 index ed333f3ea..000000000 --- a/src/pkg/archive/tar/tar_test.go +++ /dev/null @@ -1,284 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tar - -import ( - "bytes" - "io/ioutil" - "os" - "path" - "reflect" - "strings" - "testing" - "time" -) - -func TestFileInfoHeader(t *testing.T) { - fi, err := os.Stat("testdata/small.txt") - if err != nil { - t.Fatal(err) - } - h, err := FileInfoHeader(fi, "") - if err != nil { - t.Fatalf("FileInfoHeader: %v", err) - } - if g, e := h.Name, "small.txt"; g != e { - t.Errorf("Name = %q; want %q", g, e) - } - if g, e := h.Mode, int64(fi.Mode().Perm())|c_ISREG; g != e { - t.Errorf("Mode = %#o; want %#o", g, e) - } - if g, e := h.Size, int64(5); g != e { - t.Errorf("Size = %v; want %v", g, e) - } - if g, e := h.ModTime, fi.ModTime(); !g.Equal(e) { - t.Errorf("ModTime = %v; want %v", g, e) - } - // FileInfoHeader should error when passing nil FileInfo - if _, err := FileInfoHeader(nil, ""); err == nil { - t.Fatalf("Expected error when passing nil to FileInfoHeader") - } -} - -func TestFileInfoHeaderDir(t *testing.T) { - fi, err := os.Stat("testdata") - if err != nil { - t.Fatal(err) - } - h, err := FileInfoHeader(fi, "") - if err != nil { - t.Fatalf("FileInfoHeader: %v", err) - } - if g, e := h.Name, "testdata/"; g != e { - t.Errorf("Name = %q; want %q", g, e) - } - // Ignoring c_ISGID for golang.org/issue/4867 - if g, e := h.Mode&^c_ISGID, int64(fi.Mode().Perm())|c_ISDIR; g != e { - t.Errorf("Mode = %#o; want %#o", g, e) - } - if g, e := h.Size, int64(0); g != e { - t.Errorf("Size = %v; want %v", g, e) - } - if g, e := h.ModTime, fi.ModTime(); !g.Equal(e) { - t.Errorf("ModTime = %v; want %v", g, e) - } -} - -func TestFileInfoHeaderSymlink(t *testing.T) { - h, err := FileInfoHeader(symlink{}, "some-target") - if err != nil { - t.Fatal(err) - } - if g, e := h.Name, "some-symlink"; g != e { - t.Errorf("Name = %q; want %q", g, e) - } - if g, e := h.Linkname, "some-target"; g != e { - t.Errorf("Linkname = %q; want %q", g, e) - } -} - -type symlink struct{} - -func (symlink) Name() string { return "some-symlink" } -func (symlink) Size() int64 { return 0 } -func (symlink) Mode() os.FileMode { return os.ModeSymlink } -func (symlink) ModTime() time.Time { return time.Time{} } -func (symlink) IsDir() bool { return false } -func (symlink) Sys() interface{} { return nil } - -func TestRoundTrip(t *testing.T) { - data := []byte("some file contents") - - var b bytes.Buffer - tw := NewWriter(&b) - hdr := &Header{ - Name: "file.txt", - Uid: 1 << 21, // too big for 8 octal digits - Size: int64(len(data)), - ModTime: time.Now(), - } - // tar only supports second precision. - hdr.ModTime = hdr.ModTime.Add(-time.Duration(hdr.ModTime.Nanosecond()) * time.Nanosecond) - if err := tw.WriteHeader(hdr); err != nil { - t.Fatalf("tw.WriteHeader: %v", err) - } - if _, err := tw.Write(data); err != nil { - t.Fatalf("tw.Write: %v", err) - } - if err := tw.Close(); err != nil { - t.Fatalf("tw.Close: %v", err) - } - - // Read it back. - tr := NewReader(&b) - rHdr, err := tr.Next() - if err != nil { - t.Fatalf("tr.Next: %v", err) - } - if !reflect.DeepEqual(rHdr, hdr) { - t.Errorf("Header mismatch.\n got %+v\nwant %+v", rHdr, hdr) - } - rData, err := ioutil.ReadAll(tr) - if err != nil { - t.Fatalf("Read: %v", err) - } - if !bytes.Equal(rData, data) { - t.Errorf("Data mismatch.\n got %q\nwant %q", rData, data) - } -} - -type headerRoundTripTest struct { - h *Header - fm os.FileMode -} - -func TestHeaderRoundTrip(t *testing.T) { - golden := []headerRoundTripTest{ - // regular file. - { - h: &Header{ - Name: "test.txt", - Mode: 0644 | c_ISREG, - Size: 12, - ModTime: time.Unix(1360600916, 0), - Typeflag: TypeReg, - }, - fm: 0644, - }, - // hard link. - { - h: &Header{ - Name: "hard.txt", - Mode: 0644 | c_ISLNK, - Size: 0, - ModTime: time.Unix(1360600916, 0), - Typeflag: TypeLink, - }, - fm: 0644 | os.ModeSymlink, - }, - // symbolic link. - { - h: &Header{ - Name: "link.txt", - Mode: 0777 | c_ISLNK, - Size: 0, - ModTime: time.Unix(1360600852, 0), - Typeflag: TypeSymlink, - }, - fm: 0777 | os.ModeSymlink, - }, - // character device node. - { - h: &Header{ - Name: "dev/null", - Mode: 0666 | c_ISCHR, - Size: 0, - ModTime: time.Unix(1360578951, 0), - Typeflag: TypeChar, - }, - fm: 0666 | os.ModeDevice | os.ModeCharDevice, - }, - // block device node. - { - h: &Header{ - Name: "dev/sda", - Mode: 0660 | c_ISBLK, - Size: 0, - ModTime: time.Unix(1360578954, 0), - Typeflag: TypeBlock, - }, - fm: 0660 | os.ModeDevice, - }, - // directory. - { - h: &Header{ - Name: "dir/", - Mode: 0755 | c_ISDIR, - Size: 0, - ModTime: time.Unix(1360601116, 0), - Typeflag: TypeDir, - }, - fm: 0755 | os.ModeDir, - }, - // fifo node. - { - h: &Header{ - Name: "dev/initctl", - Mode: 0600 | c_ISFIFO, - Size: 0, - ModTime: time.Unix(1360578949, 0), - Typeflag: TypeFifo, - }, - fm: 0600 | os.ModeNamedPipe, - }, - // setuid. - { - h: &Header{ - Name: "bin/su", - Mode: 0755 | c_ISREG | c_ISUID, - Size: 23232, - ModTime: time.Unix(1355405093, 0), - Typeflag: TypeReg, - }, - fm: 0755 | os.ModeSetuid, - }, - // setguid. - { - h: &Header{ - Name: "group.txt", - Mode: 0750 | c_ISREG | c_ISGID, - Size: 0, - ModTime: time.Unix(1360602346, 0), - Typeflag: TypeReg, - }, - fm: 0750 | os.ModeSetgid, - }, - // sticky. - { - h: &Header{ - Name: "sticky.txt", - Mode: 0600 | c_ISREG | c_ISVTX, - Size: 7, - ModTime: time.Unix(1360602540, 0), - Typeflag: TypeReg, - }, - fm: 0600 | os.ModeSticky, - }, - } - - for i, g := range golden { - fi := g.h.FileInfo() - h2, err := FileInfoHeader(fi, "") - if err != nil { - t.Error(err) - continue - } - if strings.Contains(fi.Name(), "/") { - t.Errorf("FileInfo of %q contains slash: %q", g.h.Name, fi.Name()) - } - name := path.Base(g.h.Name) - if fi.IsDir() { - name += "/" - } - if got, want := h2.Name, name; got != want { - t.Errorf("i=%d: Name: got %v, want %v", i, got, want) - } - if got, want := h2.Size, g.h.Size; got != want { - t.Errorf("i=%d: Size: got %v, want %v", i, got, want) - } - if got, want := h2.Mode, g.h.Mode; got != want { - t.Errorf("i=%d: Mode: got %o, want %o", i, got, want) - } - if got, want := fi.Mode(), g.fm; got != want { - t.Errorf("i=%d: fi.Mode: got %o, want %o", i, got, want) - } - if got, want := h2.ModTime, g.h.ModTime; got != want { - t.Errorf("i=%d: ModTime: got %v, want %v", i, got, want) - } - if sysh, ok := fi.Sys().(*Header); !ok || sysh != g.h { - t.Errorf("i=%d: Sys didn't return original *Header", i) - } - } -} diff --git a/src/pkg/archive/tar/testdata/gnu.tar b/src/pkg/archive/tar/testdata/gnu.tar deleted file mode 100644 index fc899dc8d..000000000 Binary files a/src/pkg/archive/tar/testdata/gnu.tar and /dev/null differ diff --git a/src/pkg/archive/tar/testdata/nil-uid.tar b/src/pkg/archive/tar/testdata/nil-uid.tar deleted file mode 100644 index cc9cfaa33..000000000 Binary files a/src/pkg/archive/tar/testdata/nil-uid.tar and /dev/null differ diff --git a/src/pkg/archive/tar/testdata/pax.tar b/src/pkg/archive/tar/testdata/pax.tar deleted file mode 100644 index 9bc24b658..000000000 Binary files a/src/pkg/archive/tar/testdata/pax.tar and /dev/null differ diff --git a/src/pkg/archive/tar/testdata/small.txt b/src/pkg/archive/tar/testdata/small.txt deleted file mode 100644 index b249bfc51..000000000 --- a/src/pkg/archive/tar/testdata/small.txt +++ /dev/null @@ -1 +0,0 @@ -Kilts \ No newline at end of file diff --git a/src/pkg/archive/tar/testdata/small2.txt b/src/pkg/archive/tar/testdata/small2.txt deleted file mode 100644 index 394ee3ecd..000000000 --- a/src/pkg/archive/tar/testdata/small2.txt +++ /dev/null @@ -1 +0,0 @@ -Google.com diff --git a/src/pkg/archive/tar/testdata/sparse-formats.tar b/src/pkg/archive/tar/testdata/sparse-formats.tar deleted file mode 100644 index 8bd4e74d5..000000000 Binary files a/src/pkg/archive/tar/testdata/sparse-formats.tar and /dev/null differ diff --git a/src/pkg/archive/tar/testdata/star.tar b/src/pkg/archive/tar/testdata/star.tar deleted file mode 100644 index 59e2d4e60..000000000 Binary files a/src/pkg/archive/tar/testdata/star.tar and /dev/null differ diff --git a/src/pkg/archive/tar/testdata/ustar.tar b/src/pkg/archive/tar/testdata/ustar.tar deleted file mode 100644 index 29679d9a3..000000000 Binary files a/src/pkg/archive/tar/testdata/ustar.tar and /dev/null differ diff --git a/src/pkg/archive/tar/testdata/v7.tar b/src/pkg/archive/tar/testdata/v7.tar deleted file mode 100644 index eb65fc941..000000000 Binary files a/src/pkg/archive/tar/testdata/v7.tar and /dev/null differ diff --git a/src/pkg/archive/tar/testdata/writer-big-long.tar b/src/pkg/archive/tar/testdata/writer-big-long.tar deleted file mode 100644 index 5960ee824..000000000 Binary files a/src/pkg/archive/tar/testdata/writer-big-long.tar and /dev/null differ diff --git a/src/pkg/archive/tar/testdata/writer-big.tar b/src/pkg/archive/tar/testdata/writer-big.tar deleted file mode 100644 index 753e883ce..000000000 Binary files a/src/pkg/archive/tar/testdata/writer-big.tar and /dev/null differ diff --git a/src/pkg/archive/tar/testdata/writer.tar b/src/pkg/archive/tar/testdata/writer.tar deleted file mode 100644 index e6d816ad0..000000000 Binary files a/src/pkg/archive/tar/testdata/writer.tar and /dev/null differ diff --git a/src/pkg/archive/tar/testdata/xattrs.tar b/src/pkg/archive/tar/testdata/xattrs.tar deleted file mode 100644 index 9701950ed..000000000 Binary files a/src/pkg/archive/tar/testdata/xattrs.tar and /dev/null differ diff --git a/src/pkg/archive/tar/writer.go b/src/pkg/archive/tar/writer.go deleted file mode 100644 index dafb2cabf..000000000 --- a/src/pkg/archive/tar/writer.go +++ /dev/null @@ -1,396 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tar - -// TODO(dsymonds): -// - catch more errors (no first header, etc.) - -import ( - "bytes" - "errors" - "fmt" - "io" - "os" - "path" - "strconv" - "strings" - "time" -) - -var ( - ErrWriteTooLong = errors.New("archive/tar: write too long") - ErrFieldTooLong = errors.New("archive/tar: header field too long") - ErrWriteAfterClose = errors.New("archive/tar: write after close") - errNameTooLong = errors.New("archive/tar: name too long") - errInvalidHeader = errors.New("archive/tar: header field too long or contains invalid values") -) - -// A Writer provides sequential writing of a tar archive in POSIX.1 format. -// A tar archive consists of a sequence of files. -// Call WriteHeader to begin a new file, and then call Write to supply that file's data, -// writing at most hdr.Size bytes in total. -type Writer struct { - w io.Writer - err error - nb int64 // number of unwritten bytes for current file entry - pad int64 // amount of padding to write after current file entry - closed bool - usedBinary bool // whether the binary numeric field extension was used - preferPax bool // use pax header instead of binary numeric header - hdrBuff [blockSize]byte // buffer to use in writeHeader when writing a regular header - paxHdrBuff [blockSize]byte // buffer to use in writeHeader when writing a pax header -} - -// NewWriter creates a new Writer writing to w. -func NewWriter(w io.Writer) *Writer { return &Writer{w: w} } - -// Flush finishes writing the current file (optional). -func (tw *Writer) Flush() error { - if tw.nb > 0 { - tw.err = fmt.Errorf("archive/tar: missed writing %d bytes", tw.nb) - return tw.err - } - - n := tw.nb + tw.pad - for n > 0 && tw.err == nil { - nr := n - if nr > blockSize { - nr = blockSize - } - var nw int - nw, tw.err = tw.w.Write(zeroBlock[0:nr]) - n -= int64(nw) - } - tw.nb = 0 - tw.pad = 0 - return tw.err -} - -// Write s into b, terminating it with a NUL if there is room. -// If the value is too long for the field and allowPax is true add a paxheader record instead -func (tw *Writer) cString(b []byte, s string, allowPax bool, paxKeyword string, paxHeaders map[string]string) { - needsPaxHeader := allowPax && len(s) > len(b) || !isASCII(s) - if needsPaxHeader { - paxHeaders[paxKeyword] = s - return - } - if len(s) > len(b) { - if tw.err == nil { - tw.err = ErrFieldTooLong - } - return - } - ascii := toASCII(s) - copy(b, ascii) - if len(ascii) < len(b) { - b[len(ascii)] = 0 - } -} - -// Encode x as an octal ASCII string and write it into b with leading zeros. -func (tw *Writer) octal(b []byte, x int64) { - s := strconv.FormatInt(x, 8) - // leading zeros, but leave room for a NUL. - for len(s)+1 < len(b) { - s = "0" + s - } - tw.cString(b, s, false, paxNone, nil) -} - -// Write x into b, either as octal or as binary (GNUtar/star extension). -// If the value is too long for the field and writingPax is enabled both for the field and the add a paxheader record instead -func (tw *Writer) numeric(b []byte, x int64, allowPax bool, paxKeyword string, paxHeaders map[string]string) { - // Try octal first. - s := strconv.FormatInt(x, 8) - if len(s) < len(b) { - tw.octal(b, x) - return - } - - // If it is too long for octal, and pax is preferred, use a pax header - if allowPax && tw.preferPax { - tw.octal(b, 0) - s := strconv.FormatInt(x, 10) - paxHeaders[paxKeyword] = s - return - } - - // Too big: use binary (big-endian). - tw.usedBinary = true - for i := len(b) - 1; x > 0 && i >= 0; i-- { - b[i] = byte(x) - x >>= 8 - } - b[0] |= 0x80 // highest bit indicates binary format -} - -var ( - minTime = time.Unix(0, 0) - // There is room for 11 octal digits (33 bits) of mtime. - maxTime = minTime.Add((1<<33 - 1) * time.Second) -) - -// WriteHeader writes hdr and prepares to accept the file's contents. -// WriteHeader calls Flush if it is not the first header. -// Calling after a Close will return ErrWriteAfterClose. -func (tw *Writer) WriteHeader(hdr *Header) error { - return tw.writeHeader(hdr, true) -} - -// WriteHeader writes hdr and prepares to accept the file's contents. -// WriteHeader calls Flush if it is not the first header. -// Calling after a Close will return ErrWriteAfterClose. -// As this method is called internally by writePax header to allow it to -// suppress writing the pax header. -func (tw *Writer) writeHeader(hdr *Header, allowPax bool) error { - if tw.closed { - return ErrWriteAfterClose - } - if tw.err == nil { - tw.Flush() - } - if tw.err != nil { - return tw.err - } - - // a map to hold pax header records, if any are needed - paxHeaders := make(map[string]string) - - // TODO(shanemhansen): we might want to use PAX headers for - // subsecond time resolution, but for now let's just capture - // too long fields or non ascii characters - - var header []byte - - // We need to select which scratch buffer to use carefully, - // since this method is called recursively to write PAX headers. - // If allowPax is true, this is the non-recursive call, and we will use hdrBuff. - // If allowPax is false, we are being called by writePAXHeader, and hdrBuff is - // already being used by the non-recursive call, so we must use paxHdrBuff. - header = tw.hdrBuff[:] - if !allowPax { - header = tw.paxHdrBuff[:] - } - copy(header, zeroBlock) - s := slicer(header) - - // keep a reference to the filename to allow to overwrite it later if we detect that we can use ustar longnames instead of pax - pathHeaderBytes := s.next(fileNameSize) - - tw.cString(pathHeaderBytes, hdr.Name, true, paxPath, paxHeaders) - - // Handle out of range ModTime carefully. - var modTime int64 - if !hdr.ModTime.Before(minTime) && !hdr.ModTime.After(maxTime) { - modTime = hdr.ModTime.Unix() - } - - tw.octal(s.next(8), hdr.Mode) // 100:108 - tw.numeric(s.next(8), int64(hdr.Uid), true, paxUid, paxHeaders) // 108:116 - tw.numeric(s.next(8), int64(hdr.Gid), true, paxGid, paxHeaders) // 116:124 - tw.numeric(s.next(12), hdr.Size, true, paxSize, paxHeaders) // 124:136 - tw.numeric(s.next(12), modTime, false, paxNone, nil) // 136:148 --- consider using pax for finer granularity - s.next(8) // chksum (148:156) - s.next(1)[0] = hdr.Typeflag // 156:157 - - tw.cString(s.next(100), hdr.Linkname, true, paxLinkpath, paxHeaders) - - copy(s.next(8), []byte("ustar\x0000")) // 257:265 - tw.cString(s.next(32), hdr.Uname, true, paxUname, paxHeaders) // 265:297 - tw.cString(s.next(32), hdr.Gname, true, paxGname, paxHeaders) // 297:329 - tw.numeric(s.next(8), hdr.Devmajor, false, paxNone, nil) // 329:337 - tw.numeric(s.next(8), hdr.Devminor, false, paxNone, nil) // 337:345 - - // keep a reference to the prefix to allow to overwrite it later if we detect that we can use ustar longnames instead of pax - prefixHeaderBytes := s.next(155) - tw.cString(prefixHeaderBytes, "", false, paxNone, nil) // 345:500 prefix - - // Use the GNU magic instead of POSIX magic if we used any GNU extensions. - if tw.usedBinary { - copy(header[257:265], []byte("ustar \x00")) - } - - _, paxPathUsed := paxHeaders[paxPath] - // try to use a ustar header when only the name is too long - if !tw.preferPax && len(paxHeaders) == 1 && paxPathUsed { - suffix := hdr.Name - prefix := "" - if len(hdr.Name) > fileNameSize && isASCII(hdr.Name) { - var err error - prefix, suffix, err = tw.splitUSTARLongName(hdr.Name) - if err == nil { - // ok we can use a ustar long name instead of pax, now correct the fields - - // remove the path field from the pax header. this will suppress the pax header - delete(paxHeaders, paxPath) - - // update the path fields - tw.cString(pathHeaderBytes, suffix, false, paxNone, nil) - tw.cString(prefixHeaderBytes, prefix, false, paxNone, nil) - - // Use the ustar magic if we used ustar long names. - if len(prefix) > 0 && !tw.usedBinary { - copy(header[257:265], []byte("ustar\x00")) - } - } - } - } - - // The chksum field is terminated by a NUL and a space. - // This is different from the other octal fields. - chksum, _ := checksum(header) - tw.octal(header[148:155], chksum) - header[155] = ' ' - - if tw.err != nil { - // problem with header; probably integer too big for a field. - return tw.err - } - - if allowPax { - for k, v := range hdr.Xattrs { - paxHeaders[paxXattr+k] = v - } - } - - if len(paxHeaders) > 0 { - if !allowPax { - return errInvalidHeader - } - if err := tw.writePAXHeader(hdr, paxHeaders); err != nil { - return err - } - } - tw.nb = int64(hdr.Size) - tw.pad = (blockSize - (tw.nb % blockSize)) % blockSize - - _, tw.err = tw.w.Write(header) - return tw.err -} - -// writeUSTARLongName splits a USTAR long name hdr.Name. -// name must be < 256 characters. errNameTooLong is returned -// if hdr.Name can't be split. The splitting heuristic -// is compatible with gnu tar. -func (tw *Writer) splitUSTARLongName(name string) (prefix, suffix string, err error) { - length := len(name) - if length > fileNamePrefixSize+1 { - length = fileNamePrefixSize + 1 - } else if name[length-1] == '/' { - length-- - } - i := strings.LastIndex(name[:length], "/") - // nlen contains the resulting length in the name field. - // plen contains the resulting length in the prefix field. - nlen := len(name) - i - 1 - plen := i - if i <= 0 || nlen > fileNameSize || nlen == 0 || plen > fileNamePrefixSize { - err = errNameTooLong - return - } - prefix, suffix = name[:i], name[i+1:] - return -} - -// writePaxHeader writes an extended pax header to the -// archive. -func (tw *Writer) writePAXHeader(hdr *Header, paxHeaders map[string]string) error { - // Prepare extended header - ext := new(Header) - ext.Typeflag = TypeXHeader - // Setting ModTime is required for reader parsing to - // succeed, and seems harmless enough. - ext.ModTime = hdr.ModTime - // The spec asks that we namespace our pseudo files - // with the current pid. - pid := os.Getpid() - dir, file := path.Split(hdr.Name) - fullName := path.Join(dir, - fmt.Sprintf("PaxHeaders.%d", pid), file) - - ascii := toASCII(fullName) - if len(ascii) > 100 { - ascii = ascii[:100] - } - ext.Name = ascii - // Construct the body - var buf bytes.Buffer - - for k, v := range paxHeaders { - fmt.Fprint(&buf, paxHeader(k+"="+v)) - } - - ext.Size = int64(len(buf.Bytes())) - if err := tw.writeHeader(ext, false); err != nil { - return err - } - if _, err := tw.Write(buf.Bytes()); err != nil { - return err - } - if err := tw.Flush(); err != nil { - return err - } - return nil -} - -// paxHeader formats a single pax record, prefixing it with the appropriate length -func paxHeader(msg string) string { - const padding = 2 // Extra padding for space and newline - size := len(msg) + padding - size += len(strconv.Itoa(size)) - record := fmt.Sprintf("%d %s\n", size, msg) - if len(record) != size { - // Final adjustment if adding size increased - // the number of digits in size - size = len(record) - record = fmt.Sprintf("%d %s\n", size, msg) - } - return record -} - -// Write writes to the current entry in the tar archive. -// Write returns the error ErrWriteTooLong if more than -// hdr.Size bytes are written after WriteHeader. -func (tw *Writer) Write(b []byte) (n int, err error) { - if tw.closed { - err = ErrWriteTooLong - return - } - overwrite := false - if int64(len(b)) > tw.nb { - b = b[0:tw.nb] - overwrite = true - } - n, err = tw.w.Write(b) - tw.nb -= int64(n) - if err == nil && overwrite { - err = ErrWriteTooLong - return - } - tw.err = err - return -} - -// Close closes the tar archive, flushing any unwritten -// data to the underlying writer. -func (tw *Writer) Close() error { - if tw.err != nil || tw.closed { - return tw.err - } - tw.Flush() - tw.closed = true - if tw.err != nil { - return tw.err - } - - // trailer: two zero blocks - for i := 0; i < 2; i++ { - _, tw.err = tw.w.Write(zeroBlock) - if tw.err != nil { - break - } - } - return tw.err -} diff --git a/src/pkg/archive/tar/writer_test.go b/src/pkg/archive/tar/writer_test.go deleted file mode 100644 index 5e42e322f..000000000 --- a/src/pkg/archive/tar/writer_test.go +++ /dev/null @@ -1,491 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tar - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "reflect" - "strings" - "testing" - "testing/iotest" - "time" -) - -type writerTestEntry struct { - header *Header - contents string -} - -type writerTest struct { - file string // filename of expected output - entries []*writerTestEntry -} - -var writerTests = []*writerTest{ - // The writer test file was produced with this command: - // tar (GNU tar) 1.26 - // ln -s small.txt link.txt - // tar -b 1 --format=ustar -c -f writer.tar small.txt small2.txt link.txt - { - file: "testdata/writer.tar", - entries: []*writerTestEntry{ - { - header: &Header{ - Name: "small.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 5, - ModTime: time.Unix(1246508266, 0), - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - }, - contents: "Kilts", - }, - { - header: &Header{ - Name: "small2.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 11, - ModTime: time.Unix(1245217492, 0), - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - }, - contents: "Google.com\n", - }, - { - header: &Header{ - Name: "link.txt", - Mode: 0777, - Uid: 1000, - Gid: 1000, - Size: 0, - ModTime: time.Unix(1314603082, 0), - Typeflag: '2', - Linkname: "small.txt", - Uname: "strings", - Gname: "strings", - }, - // no contents - }, - }, - }, - // The truncated test file was produced using these commands: - // dd if=/dev/zero bs=1048576 count=16384 > /tmp/16gig.txt - // tar -b 1 -c -f- /tmp/16gig.txt | dd bs=512 count=8 > writer-big.tar - { - file: "testdata/writer-big.tar", - entries: []*writerTestEntry{ - { - header: &Header{ - Name: "tmp/16gig.txt", - Mode: 0640, - Uid: 73025, - Gid: 5000, - Size: 16 << 30, - ModTime: time.Unix(1254699560, 0), - Typeflag: '0', - Uname: "dsymonds", - Gname: "eng", - }, - // fake contents - contents: strings.Repeat("\x00", 4<<10), - }, - }, - }, - // The truncated test file was produced using these commands: - // dd if=/dev/zero bs=1048576 count=16384 > (longname/)*15 /16gig.txt - // tar -b 1 -c -f- (longname/)*15 /16gig.txt | dd bs=512 count=8 > writer-big-long.tar - { - file: "testdata/writer-big-long.tar", - entries: []*writerTestEntry{ - { - header: &Header{ - Name: strings.Repeat("longname/", 15) + "16gig.txt", - Mode: 0644, - Uid: 1000, - Gid: 1000, - Size: 16 << 30, - ModTime: time.Unix(1399583047, 0), - Typeflag: '0', - Uname: "guillaume", - Gname: "guillaume", - }, - // fake contents - contents: strings.Repeat("\x00", 4<<10), - }, - }, - }, - // This file was produced using gnu tar 1.17 - // gnutar -b 4 --format=ustar (longname/)*15 + file.txt - { - file: "testdata/ustar.tar", - entries: []*writerTestEntry{ - { - header: &Header{ - Name: strings.Repeat("longname/", 15) + "file.txt", - Mode: 0644, - Uid: 0765, - Gid: 024, - Size: 06, - ModTime: time.Unix(1360135598, 0), - Typeflag: '0', - Uname: "shane", - Gname: "staff", - }, - contents: "hello\n", - }, - }, - }, -} - -// Render byte array in a two-character hexadecimal string, spaced for easy visual inspection. -func bytestr(offset int, b []byte) string { - const rowLen = 32 - s := fmt.Sprintf("%04x ", offset) - for _, ch := range b { - switch { - case '0' <= ch && ch <= '9', 'A' <= ch && ch <= 'Z', 'a' <= ch && ch <= 'z': - s += fmt.Sprintf(" %c", ch) - default: - s += fmt.Sprintf(" %02x", ch) - } - } - return s -} - -// Render a pseudo-diff between two blocks of bytes. -func bytediff(a []byte, b []byte) string { - const rowLen = 32 - s := fmt.Sprintf("(%d bytes vs. %d bytes)\n", len(a), len(b)) - for offset := 0; len(a)+len(b) > 0; offset += rowLen { - na, nb := rowLen, rowLen - if na > len(a) { - na = len(a) - } - if nb > len(b) { - nb = len(b) - } - sa := bytestr(offset, a[0:na]) - sb := bytestr(offset, b[0:nb]) - if sa != sb { - s += fmt.Sprintf("-%v\n+%v\n", sa, sb) - } - a = a[na:] - b = b[nb:] - } - return s -} - -func TestWriter(t *testing.T) { -testLoop: - for i, test := range writerTests { - expected, err := ioutil.ReadFile(test.file) - if err != nil { - t.Errorf("test %d: Unexpected error: %v", i, err) - continue - } - - buf := new(bytes.Buffer) - tw := NewWriter(iotest.TruncateWriter(buf, 4<<10)) // only catch the first 4 KB - big := false - for j, entry := range test.entries { - big = big || entry.header.Size > 1<<10 - if err := tw.WriteHeader(entry.header); err != nil { - t.Errorf("test %d, entry %d: Failed writing header: %v", i, j, err) - continue testLoop - } - if _, err := io.WriteString(tw, entry.contents); err != nil { - t.Errorf("test %d, entry %d: Failed writing contents: %v", i, j, err) - continue testLoop - } - } - // Only interested in Close failures for the small tests. - if err := tw.Close(); err != nil && !big { - t.Errorf("test %d: Failed closing archive: %v", i, err) - continue testLoop - } - - actual := buf.Bytes() - if !bytes.Equal(expected, actual) { - t.Errorf("test %d: Incorrect result: (-=expected, +=actual)\n%v", - i, bytediff(expected, actual)) - } - if testing.Short() { // The second test is expensive. - break - } - } -} - -func TestPax(t *testing.T) { - // Create an archive with a large name - fileinfo, err := os.Stat("testdata/small.txt") - if err != nil { - t.Fatal(err) - } - hdr, err := FileInfoHeader(fileinfo, "") - if err != nil { - t.Fatalf("os.Stat: %v", err) - } - // Force a PAX long name to be written - longName := strings.Repeat("ab", 100) - contents := strings.Repeat(" ", int(hdr.Size)) - hdr.Name = longName - var buf bytes.Buffer - writer := NewWriter(&buf) - if err := writer.WriteHeader(hdr); err != nil { - t.Fatal(err) - } - if _, err = writer.Write([]byte(contents)); err != nil { - t.Fatal(err) - } - if err := writer.Close(); err != nil { - t.Fatal(err) - } - // Simple test to make sure PAX extensions are in effect - if !bytes.Contains(buf.Bytes(), []byte("PaxHeaders.")) { - t.Fatal("Expected at least one PAX header to be written.") - } - // Test that we can get a long name back out of the archive. - reader := NewReader(&buf) - hdr, err = reader.Next() - if err != nil { - t.Fatal(err) - } - if hdr.Name != longName { - t.Fatal("Couldn't recover long file name") - } -} - -func TestPaxSymlink(t *testing.T) { - // Create an archive with a large linkname - fileinfo, err := os.Stat("testdata/small.txt") - if err != nil { - t.Fatal(err) - } - hdr, err := FileInfoHeader(fileinfo, "") - hdr.Typeflag = TypeSymlink - if err != nil { - t.Fatalf("os.Stat:1 %v", err) - } - // Force a PAX long linkname to be written - longLinkname := strings.Repeat("1234567890/1234567890", 10) - hdr.Linkname = longLinkname - - hdr.Size = 0 - var buf bytes.Buffer - writer := NewWriter(&buf) - if err := writer.WriteHeader(hdr); err != nil { - t.Fatal(err) - } - if err := writer.Close(); err != nil { - t.Fatal(err) - } - // Simple test to make sure PAX extensions are in effect - if !bytes.Contains(buf.Bytes(), []byte("PaxHeaders.")) { - t.Fatal("Expected at least one PAX header to be written.") - } - // Test that we can get a long name back out of the archive. - reader := NewReader(&buf) - hdr, err = reader.Next() - if err != nil { - t.Fatal(err) - } - if hdr.Linkname != longLinkname { - t.Fatal("Couldn't recover long link name") - } -} - -func TestPaxNonAscii(t *testing.T) { - // Create an archive with non ascii. These should trigger a pax header - // because pax headers have a defined utf-8 encoding. - fileinfo, err := os.Stat("testdata/small.txt") - if err != nil { - t.Fatal(err) - } - - hdr, err := FileInfoHeader(fileinfo, "") - if err != nil { - t.Fatalf("os.Stat:1 %v", err) - } - - // some sample data - chineseFilename := "文件名" - chineseGroupname := "組" - chineseUsername := "用戶名" - - hdr.Name = chineseFilename - hdr.Gname = chineseGroupname - hdr.Uname = chineseUsername - - contents := strings.Repeat(" ", int(hdr.Size)) - - var buf bytes.Buffer - writer := NewWriter(&buf) - if err := writer.WriteHeader(hdr); err != nil { - t.Fatal(err) - } - if _, err = writer.Write([]byte(contents)); err != nil { - t.Fatal(err) - } - if err := writer.Close(); err != nil { - t.Fatal(err) - } - // Simple test to make sure PAX extensions are in effect - if !bytes.Contains(buf.Bytes(), []byte("PaxHeaders.")) { - t.Fatal("Expected at least one PAX header to be written.") - } - // Test that we can get a long name back out of the archive. - reader := NewReader(&buf) - hdr, err = reader.Next() - if err != nil { - t.Fatal(err) - } - if hdr.Name != chineseFilename { - t.Fatal("Couldn't recover unicode name") - } - if hdr.Gname != chineseGroupname { - t.Fatal("Couldn't recover unicode group") - } - if hdr.Uname != chineseUsername { - t.Fatal("Couldn't recover unicode user") - } -} - -func TestPaxXattrs(t *testing.T) { - xattrs := map[string]string{ - "user.key": "value", - } - - // Create an archive with an xattr - fileinfo, err := os.Stat("testdata/small.txt") - if err != nil { - t.Fatal(err) - } - hdr, err := FileInfoHeader(fileinfo, "") - if err != nil { - t.Fatalf("os.Stat: %v", err) - } - contents := "Kilts" - hdr.Xattrs = xattrs - var buf bytes.Buffer - writer := NewWriter(&buf) - if err := writer.WriteHeader(hdr); err != nil { - t.Fatal(err) - } - if _, err = writer.Write([]byte(contents)); err != nil { - t.Fatal(err) - } - if err := writer.Close(); err != nil { - t.Fatal(err) - } - // Test that we can get the xattrs back out of the archive. - reader := NewReader(&buf) - hdr, err = reader.Next() - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(hdr.Xattrs, xattrs) { - t.Fatalf("xattrs did not survive round trip: got %+v, want %+v", - hdr.Xattrs, xattrs) - } -} - -func TestPAXHeader(t *testing.T) { - medName := strings.Repeat("CD", 50) - longName := strings.Repeat("AB", 100) - paxTests := [][2]string{ - {paxPath + "=/etc/hosts", "19 path=/etc/hosts\n"}, - {"a=b", "6 a=b\n"}, // Single digit length - {"a=names", "11 a=names\n"}, // Test case involving carries - {paxPath + "=" + longName, fmt.Sprintf("210 path=%s\n", longName)}, - {paxPath + "=" + medName, fmt.Sprintf("110 path=%s\n", medName)}} - - for _, test := range paxTests { - key, expected := test[0], test[1] - if result := paxHeader(key); result != expected { - t.Fatalf("paxHeader: got %s, expected %s", result, expected) - } - } -} - -func TestUSTARLongName(t *testing.T) { - // Create an archive with a path that failed to split with USTAR extension in previous versions. - fileinfo, err := os.Stat("testdata/small.txt") - if err != nil { - t.Fatal(err) - } - hdr, err := FileInfoHeader(fileinfo, "") - hdr.Typeflag = TypeDir - if err != nil { - t.Fatalf("os.Stat:1 %v", err) - } - // Force a PAX long name to be written. The name was taken from a practical example - // that fails and replaced ever char through numbers to anonymize the sample. - longName := "/0000_0000000/00000-000000000/0000_0000000/00000-0000000000000/0000_0000000/00000-0000000-00000000/0000_0000000/00000000/0000_0000000/000/0000_0000000/00000000v00/0000_0000000/000000/0000_0000000/0000000/0000_0000000/00000y-00/0000/0000/00000000/0x000000/" - hdr.Name = longName - - hdr.Size = 0 - var buf bytes.Buffer - writer := NewWriter(&buf) - if err := writer.WriteHeader(hdr); err != nil { - t.Fatal(err) - } - if err := writer.Close(); err != nil { - t.Fatal(err) - } - // Test that we can get a long name back out of the archive. - reader := NewReader(&buf) - hdr, err = reader.Next() - if err != nil { - t.Fatal(err) - } - if hdr.Name != longName { - t.Fatal("Couldn't recover long name") - } -} - -func TestValidTypeflagWithPAXHeader(t *testing.T) { - var buffer bytes.Buffer - tw := NewWriter(&buffer) - - fileName := strings.Repeat("ab", 100) - - hdr := &Header{ - Name: fileName, - Size: 4, - Typeflag: 0, - } - if err := tw.WriteHeader(hdr); err != nil { - t.Fatalf("Failed to write header: %s", err) - } - if _, err := tw.Write([]byte("fooo")); err != nil { - t.Fatalf("Failed to write the file's data: %s", err) - } - tw.Close() - - tr := NewReader(&buffer) - - for { - header, err := tr.Next() - if err == io.EOF { - break - } - if err != nil { - t.Fatalf("Failed to read header: %s", err) - } - if header.Typeflag != 0 { - t.Fatalf("Typeflag should've been 0, found %d", header.Typeflag) - } - } -} diff --git a/src/pkg/archive/zip/example_test.go b/src/pkg/archive/zip/example_test.go deleted file mode 100644 index c2ed9e79c..000000000 --- a/src/pkg/archive/zip/example_test.go +++ /dev/null @@ -1,75 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package zip_test - -import ( - "archive/zip" - "bytes" - "fmt" - "io" - "log" - "os" -) - -func ExampleWriter() { - // Create a buffer to write our archive to. - buf := new(bytes.Buffer) - - // Create a new zip archive. - w := zip.NewWriter(buf) - - // Add some files to the archive. - var files = []struct { - Name, Body string - }{ - {"readme.txt", "This archive contains some text files."}, - {"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"}, - {"todo.txt", "Get animal handling licence.\nWrite more examples."}, - } - for _, file := range files { - f, err := w.Create(file.Name) - if err != nil { - log.Fatal(err) - } - _, err = f.Write([]byte(file.Body)) - if err != nil { - log.Fatal(err) - } - } - - // Make sure to check the error on Close. - err := w.Close() - if err != nil { - log.Fatal(err) - } -} - -func ExampleReader() { - // Open a zip archive for reading. - r, err := zip.OpenReader("testdata/readme.zip") - if err != nil { - log.Fatal(err) - } - defer r.Close() - - // Iterate through the files in the archive, - // printing some of their contents. - for _, f := range r.File { - fmt.Printf("Contents of %s:\n", f.Name) - rc, err := f.Open() - if err != nil { - log.Fatal(err) - } - _, err = io.CopyN(os.Stdout, rc, 68) - if err != nil { - log.Fatal(err) - } - rc.Close() - fmt.Println() - } - // Output: - // Contents of README: - // This is the source code repository for the Go programming language. -} diff --git a/src/pkg/archive/zip/reader.go b/src/pkg/archive/zip/reader.go deleted file mode 100644 index 8136b840d..000000000 --- a/src/pkg/archive/zip/reader.go +++ /dev/null @@ -1,453 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package zip - -import ( - "bufio" - "encoding/binary" - "errors" - "hash" - "hash/crc32" - "io" - "os" -) - -var ( - ErrFormat = errors.New("zip: not a valid zip file") - ErrAlgorithm = errors.New("zip: unsupported compression algorithm") - ErrChecksum = errors.New("zip: checksum error") -) - -type Reader struct { - r io.ReaderAt - File []*File - Comment string -} - -type ReadCloser struct { - f *os.File - Reader -} - -type File struct { - FileHeader - zipr io.ReaderAt - zipsize int64 - headerOffset int64 -} - -func (f *File) hasDataDescriptor() bool { - return f.Flags&0x8 != 0 -} - -// OpenReader will open the Zip file specified by name and return a ReadCloser. -func OpenReader(name string) (*ReadCloser, error) { - f, err := os.Open(name) - if err != nil { - return nil, err - } - fi, err := f.Stat() - if err != nil { - f.Close() - return nil, err - } - r := new(ReadCloser) - if err := r.init(f, fi.Size()); err != nil { - f.Close() - return nil, err - } - r.f = f - return r, nil -} - -// NewReader returns a new Reader reading from r, which is assumed to -// have the given size in bytes. -func NewReader(r io.ReaderAt, size int64) (*Reader, error) { - zr := new(Reader) - if err := zr.init(r, size); err != nil { - return nil, err - } - return zr, nil -} - -func (z *Reader) init(r io.ReaderAt, size int64) error { - end, err := readDirectoryEnd(r, size) - if err != nil { - return err - } - z.r = r - z.File = make([]*File, 0, end.directoryRecords) - z.Comment = end.comment - rs := io.NewSectionReader(r, 0, size) - if _, err = rs.Seek(int64(end.directoryOffset), os.SEEK_SET); err != nil { - return err - } - buf := bufio.NewReader(rs) - - // The count of files inside a zip is truncated to fit in a uint16. - // Gloss over this by reading headers until we encounter - // a bad one, and then only report a ErrFormat or UnexpectedEOF if - // the file count modulo 65536 is incorrect. - for { - f := &File{zipr: r, zipsize: size} - err = readDirectoryHeader(f, buf) - if err == ErrFormat || err == io.ErrUnexpectedEOF { - break - } - if err != nil { - return err - } - z.File = append(z.File, f) - } - if uint16(len(z.File)) != uint16(end.directoryRecords) { // only compare 16 bits here - // Return the readDirectoryHeader error if we read - // the wrong number of directory entries. - return err - } - return nil -} - -// Close closes the Zip file, rendering it unusable for I/O. -func (rc *ReadCloser) Close() error { - return rc.f.Close() -} - -// DataOffset returns the offset of the file's possibly-compressed -// data, relative to the beginning of the zip file. -// -// Most callers should instead use Open, which transparently -// decompresses data and verifies checksums. -func (f *File) DataOffset() (offset int64, err error) { - bodyOffset, err := f.findBodyOffset() - if err != nil { - return - } - return f.headerOffset + bodyOffset, nil -} - -// Open returns a ReadCloser that provides access to the File's contents. -// Multiple files may be read concurrently. -func (f *File) Open() (rc io.ReadCloser, err error) { - bodyOffset, err := f.findBodyOffset() - if err != nil { - return - } - size := int64(f.CompressedSize64) - r := io.NewSectionReader(f.zipr, f.headerOffset+bodyOffset, size) - dcomp := decompressor(f.Method) - if dcomp == nil { - err = ErrAlgorithm - return - } - rc = dcomp(r) - var desr io.Reader - if f.hasDataDescriptor() { - desr = io.NewSectionReader(f.zipr, f.headerOffset+bodyOffset+size, dataDescriptorLen) - } - rc = &checksumReader{rc, crc32.NewIEEE(), f, desr, nil} - return -} - -type checksumReader struct { - rc io.ReadCloser - hash hash.Hash32 - f *File - desr io.Reader // if non-nil, where to read the data descriptor - err error // sticky error -} - -func (r *checksumReader) Read(b []byte) (n int, err error) { - if r.err != nil { - return 0, r.err - } - n, err = r.rc.Read(b) - r.hash.Write(b[:n]) - if err == nil { - return - } - if err == io.EOF { - if r.desr != nil { - if err1 := readDataDescriptor(r.desr, r.f); err1 != nil { - err = err1 - } else if r.hash.Sum32() != r.f.CRC32 { - err = ErrChecksum - } - } else { - // If there's not a data descriptor, we still compare - // the CRC32 of what we've read against the file header - // or TOC's CRC32, if it seems like it was set. - if r.f.CRC32 != 0 && r.hash.Sum32() != r.f.CRC32 { - err = ErrChecksum - } - } - } - r.err = err - return -} - -func (r *checksumReader) Close() error { return r.rc.Close() } - -// findBodyOffset does the minimum work to verify the file has a header -// and returns the file body offset. -func (f *File) findBodyOffset() (int64, error) { - var buf [fileHeaderLen]byte - if _, err := f.zipr.ReadAt(buf[:], f.headerOffset); err != nil { - return 0, err - } - b := readBuf(buf[:]) - if sig := b.uint32(); sig != fileHeaderSignature { - return 0, ErrFormat - } - b = b[22:] // skip over most of the header - filenameLen := int(b.uint16()) - extraLen := int(b.uint16()) - return int64(fileHeaderLen + filenameLen + extraLen), nil -} - -// readDirectoryHeader attempts to read a directory header from r. -// It returns io.ErrUnexpectedEOF if it cannot read a complete header, -// and ErrFormat if it doesn't find a valid header signature. -func readDirectoryHeader(f *File, r io.Reader) error { - var buf [directoryHeaderLen]byte - if _, err := io.ReadFull(r, buf[:]); err != nil { - return err - } - b := readBuf(buf[:]) - if sig := b.uint32(); sig != directoryHeaderSignature { - return ErrFormat - } - f.CreatorVersion = b.uint16() - f.ReaderVersion = b.uint16() - f.Flags = b.uint16() - f.Method = b.uint16() - f.ModifiedTime = b.uint16() - f.ModifiedDate = b.uint16() - f.CRC32 = b.uint32() - f.CompressedSize = b.uint32() - f.UncompressedSize = b.uint32() - f.CompressedSize64 = uint64(f.CompressedSize) - f.UncompressedSize64 = uint64(f.UncompressedSize) - filenameLen := int(b.uint16()) - extraLen := int(b.uint16()) - commentLen := int(b.uint16()) - b = b[4:] // skipped start disk number and internal attributes (2x uint16) - f.ExternalAttrs = b.uint32() - f.headerOffset = int64(b.uint32()) - d := make([]byte, filenameLen+extraLen+commentLen) - if _, err := io.ReadFull(r, d); err != nil { - return err - } - f.Name = string(d[:filenameLen]) - f.Extra = d[filenameLen : filenameLen+extraLen] - f.Comment = string(d[filenameLen+extraLen:]) - - if len(f.Extra) > 0 { - b := readBuf(f.Extra) - for len(b) >= 4 { // need at least tag and size - tag := b.uint16() - size := b.uint16() - if int(size) > len(b) { - return ErrFormat - } - if tag == zip64ExtraId { - // update directory values from the zip64 extra block - eb := readBuf(b[:size]) - if len(eb) >= 8 { - f.UncompressedSize64 = eb.uint64() - } - if len(eb) >= 8 { - f.CompressedSize64 = eb.uint64() - } - if len(eb) >= 8 { - f.headerOffset = int64(eb.uint64()) - } - } - b = b[size:] - } - // Should have consumed the whole header. - // But popular zip & JAR creation tools are broken and - // may pad extra zeros at the end, so accept those - // too. See golang.org/issue/8186. - for _, v := range b { - if v != 0 { - return ErrFormat - } - } - } - return nil -} - -func readDataDescriptor(r io.Reader, f *File) error { - var buf [dataDescriptorLen]byte - - // The spec says: "Although not originally assigned a - // signature, the value 0x08074b50 has commonly been adopted - // as a signature value for the data descriptor record. - // Implementers should be aware that ZIP files may be - // encountered with or without this signature marking data - // descriptors and should account for either case when reading - // ZIP files to ensure compatibility." - // - // dataDescriptorLen includes the size of the signature but - // first read just those 4 bytes to see if it exists. - if _, err := io.ReadFull(r, buf[:4]); err != nil { - return err - } - off := 0 - maybeSig := readBuf(buf[:4]) - if maybeSig.uint32() != dataDescriptorSignature { - // No data descriptor signature. Keep these four - // bytes. - off += 4 - } - if _, err := io.ReadFull(r, buf[off:12]); err != nil { - return err - } - b := readBuf(buf[:12]) - if b.uint32() != f.CRC32 { - return ErrChecksum - } - - // The two sizes that follow here can be either 32 bits or 64 bits - // but the spec is not very clear on this and different - // interpretations has been made causing incompatibilities. We - // already have the sizes from the central directory so we can - // just ignore these. - - return nil -} - -func readDirectoryEnd(r io.ReaderAt, size int64) (dir *directoryEnd, err error) { - // look for directoryEndSignature in the last 1k, then in the last 65k - var buf []byte - var directoryEndOffset int64 - for i, bLen := range []int64{1024, 65 * 1024} { - if bLen > size { - bLen = size - } - buf = make([]byte, int(bLen)) - if _, err := r.ReadAt(buf, size-bLen); err != nil && err != io.EOF { - return nil, err - } - if p := findSignatureInBlock(buf); p >= 0 { - buf = buf[p:] - directoryEndOffset = size - bLen + int64(p) - break - } - if i == 1 || bLen == size { - return nil, ErrFormat - } - } - - // read header into struct - b := readBuf(buf[4:]) // skip signature - d := &directoryEnd{ - diskNbr: uint32(b.uint16()), - dirDiskNbr: uint32(b.uint16()), - dirRecordsThisDisk: uint64(b.uint16()), - directoryRecords: uint64(b.uint16()), - directorySize: uint64(b.uint32()), - directoryOffset: uint64(b.uint32()), - commentLen: b.uint16(), - } - l := int(d.commentLen) - if l > len(b) { - return nil, errors.New("zip: invalid comment length") - } - d.comment = string(b[:l]) - - p, err := findDirectory64End(r, directoryEndOffset) - if err == nil && p >= 0 { - err = readDirectory64End(r, p, d) - } - if err != nil { - return nil, err - } - - // Make sure directoryOffset points to somewhere in our file. - if o := int64(d.directoryOffset); o < 0 || o >= size { - return nil, ErrFormat - } - return d, nil -} - -// findDirectory64End tries to read the zip64 locator just before the -// directory end and returns the offset of the zip64 directory end if -// found. -func findDirectory64End(r io.ReaderAt, directoryEndOffset int64) (int64, error) { - locOffset := directoryEndOffset - directory64LocLen - if locOffset < 0 { - return -1, nil // no need to look for a header outside the file - } - buf := make([]byte, directory64LocLen) - if _, err := r.ReadAt(buf, locOffset); err != nil { - return -1, err - } - b := readBuf(buf) - if sig := b.uint32(); sig != directory64LocSignature { - return -1, nil - } - b = b[4:] // skip number of the disk with the start of the zip64 end of central directory - p := b.uint64() // relative offset of the zip64 end of central directory record - return int64(p), nil -} - -// readDirectory64End reads the zip64 directory end and updates the -// directory end with the zip64 directory end values. -func readDirectory64End(r io.ReaderAt, offset int64, d *directoryEnd) (err error) { - buf := make([]byte, directory64EndLen) - if _, err := r.ReadAt(buf, offset); err != nil { - return err - } - - b := readBuf(buf) - if sig := b.uint32(); sig != directory64EndSignature { - return ErrFormat - } - - b = b[12:] // skip dir size, version and version needed (uint64 + 2x uint16) - d.diskNbr = b.uint32() // number of this disk - d.dirDiskNbr = b.uint32() // number of the disk with the start of the central directory - d.dirRecordsThisDisk = b.uint64() // total number of entries in the central directory on this disk - d.directoryRecords = b.uint64() // total number of entries in the central directory - d.directorySize = b.uint64() // size of the central directory - d.directoryOffset = b.uint64() // offset of start of central directory with respect to the starting disk number - - return nil -} - -func findSignatureInBlock(b []byte) int { - for i := len(b) - directoryEndLen; i >= 0; i-- { - // defined from directoryEndSignature in struct.go - if b[i] == 'P' && b[i+1] == 'K' && b[i+2] == 0x05 && b[i+3] == 0x06 { - // n is length of comment - n := int(b[i+directoryEndLen-2]) | int(b[i+directoryEndLen-1])<<8 - if n+directoryEndLen+i <= len(b) { - return i - } - } - } - return -1 -} - -type readBuf []byte - -func (b *readBuf) uint16() uint16 { - v := binary.LittleEndian.Uint16(*b) - *b = (*b)[2:] - return v -} - -func (b *readBuf) uint32() uint32 { - v := binary.LittleEndian.Uint32(*b) - *b = (*b)[4:] - return v -} - -func (b *readBuf) uint64() uint64 { - v := binary.LittleEndian.Uint64(*b) - *b = (*b)[8:] - return v -} diff --git a/src/pkg/archive/zip/reader_test.go b/src/pkg/archive/zip/reader_test.go deleted file mode 100644 index 29d0652dc..000000000 --- a/src/pkg/archive/zip/reader_test.go +++ /dev/null @@ -1,533 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package zip - -import ( - "bytes" - "encoding/binary" - "encoding/hex" - "io" - "io/ioutil" - "os" - "path/filepath" - "regexp" - "strings" - "testing" - "time" -) - -type ZipTest struct { - Name string - Source func() (r io.ReaderAt, size int64) // if non-nil, used instead of testdata/ file - Comment string - File []ZipTestFile - Error error // the error that Opening this file should return -} - -type ZipTestFile struct { - Name string - Content []byte // if blank, will attempt to compare against File - ContentErr error - File string // name of file to compare to (relative to testdata/) - Mtime string // modified time in format "mm-dd-yy hh:mm:ss" - Mode os.FileMode -} - -// Caution: The Mtime values found for the test files should correspond to -// the values listed with unzip -l . However, the values -// listed by unzip appear to be off by some hours. When creating -// fresh test files and testing them, this issue is not present. -// The test files were created in Sydney, so there might be a time -// zone issue. The time zone information does have to be encoded -// somewhere, because otherwise unzip -l could not provide a different -// time from what the archive/zip package provides, but there appears -// to be no documentation about this. - -var tests = []ZipTest{ - { - Name: "test.zip", - Comment: "This is a zipfile comment.", - File: []ZipTestFile{ - { - Name: "test.txt", - Content: []byte("This is a test text file.\n"), - Mtime: "09-05-10 12:12:02", - Mode: 0644, - }, - { - Name: "gophercolor16x16.png", - File: "gophercolor16x16.png", - Mtime: "09-05-10 15:52:58", - Mode: 0644, - }, - }, - }, - { - Name: "test-trailing-junk.zip", - Comment: "This is a zipfile comment.", - File: []ZipTestFile{ - { - Name: "test.txt", - Content: []byte("This is a test text file.\n"), - Mtime: "09-05-10 12:12:02", - Mode: 0644, - }, - { - Name: "gophercolor16x16.png", - File: "gophercolor16x16.png", - Mtime: "09-05-10 15:52:58", - Mode: 0644, - }, - }, - }, - { - Name: "r.zip", - Source: returnRecursiveZip, - File: []ZipTestFile{ - { - Name: "r/r.zip", - Content: rZipBytes(), - Mtime: "03-04-10 00:24:16", - Mode: 0666, - }, - }, - }, - { - Name: "symlink.zip", - File: []ZipTestFile{ - { - Name: "symlink", - Content: []byte("../target"), - Mode: 0777 | os.ModeSymlink, - }, - }, - }, - { - Name: "readme.zip", - }, - { - Name: "readme.notzip", - Error: ErrFormat, - }, - { - Name: "dd.zip", - File: []ZipTestFile{ - { - Name: "filename", - Content: []byte("This is a test textfile.\n"), - Mtime: "02-02-11 13:06:20", - Mode: 0666, - }, - }, - }, - { - // created in windows XP file manager. - Name: "winxp.zip", - File: crossPlatform, - }, - { - // created by Zip 3.0 under Linux - Name: "unix.zip", - File: crossPlatform, - }, - { - // created by Go, before we wrote the "optional" data - // descriptor signatures (which are required by OS X) - Name: "go-no-datadesc-sig.zip", - File: []ZipTestFile{ - { - Name: "foo.txt", - Content: []byte("foo\n"), - Mtime: "03-08-12 16:59:10", - Mode: 0644, - }, - { - Name: "bar.txt", - Content: []byte("bar\n"), - Mtime: "03-08-12 16:59:12", - Mode: 0644, - }, - }, - }, - { - // created by Go, after we wrote the "optional" data - // descriptor signatures (which are required by OS X) - Name: "go-with-datadesc-sig.zip", - File: []ZipTestFile{ - { - Name: "foo.txt", - Content: []byte("foo\n"), - Mode: 0666, - }, - { - Name: "bar.txt", - Content: []byte("bar\n"), - Mode: 0666, - }, - }, - }, - { - Name: "Bad-CRC32-in-data-descriptor", - Source: returnCorruptCRC32Zip, - File: []ZipTestFile{ - { - Name: "foo.txt", - Content: []byte("foo\n"), - Mode: 0666, - ContentErr: ErrChecksum, - }, - { - Name: "bar.txt", - Content: []byte("bar\n"), - Mode: 0666, - }, - }, - }, - // Tests that we verify (and accept valid) crc32s on files - // with crc32s in their file header (not in data descriptors) - { - Name: "crc32-not-streamed.zip", - File: []ZipTestFile{ - { - Name: "foo.txt", - Content: []byte("foo\n"), - Mtime: "03-08-12 16:59:10", - Mode: 0644, - }, - { - Name: "bar.txt", - Content: []byte("bar\n"), - Mtime: "03-08-12 16:59:12", - Mode: 0644, - }, - }, - }, - // Tests that we verify (and reject invalid) crc32s on files - // with crc32s in their file header (not in data descriptors) - { - Name: "crc32-not-streamed.zip", - Source: returnCorruptNotStreamedZip, - File: []ZipTestFile{ - { - Name: "foo.txt", - Content: []byte("foo\n"), - Mtime: "03-08-12 16:59:10", - Mode: 0644, - ContentErr: ErrChecksum, - }, - { - Name: "bar.txt", - Content: []byte("bar\n"), - Mtime: "03-08-12 16:59:12", - Mode: 0644, - }, - }, - }, - { - Name: "zip64.zip", - File: []ZipTestFile{ - { - Name: "README", - Content: []byte("This small file is in ZIP64 format.\n"), - Mtime: "08-10-12 14:33:32", - Mode: 0644, - }, - }, - }, - // Another zip64 file with different Extras fields. (golang.org/issue/7069) - { - Name: "zip64-2.zip", - File: []ZipTestFile{ - { - Name: "README", - Content: []byte("This small file is in ZIP64 format.\n"), - Mtime: "08-10-12 14:33:32", - Mode: 0644, - }, - }, - }, -} - -var crossPlatform = []ZipTestFile{ - { - Name: "hello", - Content: []byte("world \r\n"), - Mode: 0666, - }, - { - Name: "dir/bar", - Content: []byte("foo \r\n"), - Mode: 0666, - }, - { - Name: "dir/empty/", - Content: []byte{}, - Mode: os.ModeDir | 0777, - }, - { - Name: "readonly", - Content: []byte("important \r\n"), - Mode: 0444, - }, -} - -func TestReader(t *testing.T) { - for _, zt := range tests { - readTestZip(t, zt) - } -} - -func readTestZip(t *testing.T, zt ZipTest) { - var z *Reader - var err error - if zt.Source != nil { - rat, size := zt.Source() - z, err = NewReader(rat, size) - } else { - var rc *ReadCloser - rc, err = OpenReader(filepath.Join("testdata", zt.Name)) - if err == nil { - defer rc.Close() - z = &rc.Reader - } - } - if err != zt.Error { - t.Errorf("%s: error=%v, want %v", zt.Name, err, zt.Error) - return - } - - // bail if file is not zip - if err == ErrFormat { - return - } - - // bail here if no Files expected to be tested - // (there may actually be files in the zip, but we don't care) - if zt.File == nil { - return - } - - if z.Comment != zt.Comment { - t.Errorf("%s: comment=%q, want %q", zt.Name, z.Comment, zt.Comment) - } - if len(z.File) != len(zt.File) { - t.Fatalf("%s: file count=%d, want %d", zt.Name, len(z.File), len(zt.File)) - } - - // test read of each file - for i, ft := range zt.File { - readTestFile(t, zt, ft, z.File[i]) - } - - // test simultaneous reads - n := 0 - done := make(chan bool) - for i := 0; i < 5; i++ { - for j, ft := range zt.File { - go func(j int, ft ZipTestFile) { - readTestFile(t, zt, ft, z.File[j]) - done <- true - }(j, ft) - n++ - } - } - for ; n > 0; n-- { - <-done - } -} - -func readTestFile(t *testing.T, zt ZipTest, ft ZipTestFile, f *File) { - if f.Name != ft.Name { - t.Errorf("%s: name=%q, want %q", zt.Name, f.Name, ft.Name) - } - - if ft.Mtime != "" { - mtime, err := time.Parse("01-02-06 15:04:05", ft.Mtime) - if err != nil { - t.Error(err) - return - } - if ft := f.ModTime(); !ft.Equal(mtime) { - t.Errorf("%s: %s: mtime=%s, want %s", zt.Name, f.Name, ft, mtime) - } - } - - testFileMode(t, zt.Name, f, ft.Mode) - - var b bytes.Buffer - r, err := f.Open() - if err != nil { - t.Errorf("%s: %v", zt.Name, err) - return - } - - _, err = io.Copy(&b, r) - if err != ft.ContentErr { - t.Errorf("%s: copying contents: %v (want %v)", zt.Name, err, ft.ContentErr) - } - if err != nil { - return - } - r.Close() - - size := uint64(f.UncompressedSize) - if size == uint32max { - size = f.UncompressedSize64 - } - if g := uint64(b.Len()); g != size { - t.Errorf("%v: read %v bytes but f.UncompressedSize == %v", f.Name, g, size) - } - - var c []byte - if ft.Content != nil { - c = ft.Content - } else if c, err = ioutil.ReadFile("testdata/" + ft.File); err != nil { - t.Error(err) - return - } - - if b.Len() != len(c) { - t.Errorf("%s: len=%d, want %d", f.Name, b.Len(), len(c)) - return - } - - for i, b := range b.Bytes() { - if b != c[i] { - t.Errorf("%s: content[%d]=%q want %q", f.Name, i, b, c[i]) - return - } - } -} - -func testFileMode(t *testing.T, zipName string, f *File, want os.FileMode) { - mode := f.Mode() - if want == 0 { - t.Errorf("%s: %s mode: got %v, want none", zipName, f.Name, mode) - } else if mode != want { - t.Errorf("%s: %s mode: want %v, got %v", zipName, f.Name, want, mode) - } -} - -func TestInvalidFiles(t *testing.T) { - const size = 1024 * 70 // 70kb - b := make([]byte, size) - - // zeroes - _, err := NewReader(bytes.NewReader(b), size) - if err != ErrFormat { - t.Errorf("zeroes: error=%v, want %v", err, ErrFormat) - } - - // repeated directoryEndSignatures - sig := make([]byte, 4) - binary.LittleEndian.PutUint32(sig, directoryEndSignature) - for i := 0; i < size-4; i += 4 { - copy(b[i:i+4], sig) - } - _, err = NewReader(bytes.NewReader(b), size) - if err != ErrFormat { - t.Errorf("sigs: error=%v, want %v", err, ErrFormat) - } -} - -func messWith(fileName string, corrupter func(b []byte)) (r io.ReaderAt, size int64) { - data, err := ioutil.ReadFile(filepath.Join("testdata", fileName)) - if err != nil { - panic("Error reading " + fileName + ": " + err.Error()) - } - corrupter(data) - return bytes.NewReader(data), int64(len(data)) -} - -func returnCorruptCRC32Zip() (r io.ReaderAt, size int64) { - return messWith("go-with-datadesc-sig.zip", func(b []byte) { - // Corrupt one of the CRC32s in the data descriptor: - b[0x2d]++ - }) -} - -func returnCorruptNotStreamedZip() (r io.ReaderAt, size int64) { - return messWith("crc32-not-streamed.zip", func(b []byte) { - // Corrupt foo.txt's final crc32 byte, in both - // the file header and TOC. (0x7e -> 0x7f) - b[0x11]++ - b[0x9d]++ - - // TODO(bradfitz): add a new test that only corrupts - // one of these values, and verify that that's also an - // error. Currently, the reader code doesn't verify the - // fileheader and TOC's crc32 match if they're both - // non-zero and only the second line above, the TOC, - // is what matters. - }) -} - -// rZipBytes returns the bytes of a recursive zip file, without -// putting it on disk and triggering certain virus scanners. -func rZipBytes() []byte { - s := ` -0000000 50 4b 03 04 14 00 00 00 08 00 08 03 64 3c f9 f4 -0000010 89 64 48 01 00 00 b8 01 00 00 07 00 00 00 72 2f -0000020 72 2e 7a 69 70 00 25 00 da ff 50 4b 03 04 14 00 -0000030 00 00 08 00 08 03 64 3c f9 f4 89 64 48 01 00 00 -0000040 b8 01 00 00 07 00 00 00 72 2f 72 2e 7a 69 70 00 -0000050 2f 00 d0 ff 00 25 00 da ff 50 4b 03 04 14 00 00 -0000060 00 08 00 08 03 64 3c f9 f4 89 64 48 01 00 00 b8 -0000070 01 00 00 07 00 00 00 72 2f 72 2e 7a 69 70 00 2f -0000080 00 d0 ff c2 54 8e 57 39 00 05 00 fa ff c2 54 8e -0000090 57 39 00 05 00 fa ff 00 05 00 fa ff 00 14 00 eb -00000a0 ff c2 54 8e 57 39 00 05 00 fa ff 00 05 00 fa ff -00000b0 00 14 00 eb ff 42 88 21 c4 00 00 14 00 eb ff 42 -00000c0 88 21 c4 00 00 14 00 eb ff 42 88 21 c4 00 00 14 -00000d0 00 eb ff 42 88 21 c4 00 00 14 00 eb ff 42 88 21 -00000e0 c4 00 00 00 00 ff ff 00 00 00 ff ff 00 34 00 cb -00000f0 ff 42 88 21 c4 00 00 00 00 ff ff 00 00 00 ff ff -0000100 00 34 00 cb ff 42 e8 21 5e 0f 00 00 00 ff ff 0a -0000110 f0 66 64 12 61 c0 15 dc e8 a0 48 bf 48 af 2a b3 -0000120 20 c0 9b 95 0d c4 67 04 42 53 06 06 06 40 00 06 -0000130 00 f9 ff 6d 01 00 00 00 00 42 e8 21 5e 0f 00 00 -0000140 00 ff ff 0a f0 66 64 12 61 c0 15 dc e8 a0 48 bf -0000150 48 af 2a b3 20 c0 9b 95 0d c4 67 04 42 53 06 06 -0000160 06 40 00 06 00 f9 ff 6d 01 00 00 00 00 50 4b 01 -0000170 02 14 00 14 00 00 00 08 00 08 03 64 3c f9 f4 89 -0000180 64 48 01 00 00 b8 01 00 00 07 00 00 00 00 00 00 -0000190 00 00 00 00 00 00 00 00 00 00 00 72 2f 72 2e 7a -00001a0 69 70 50 4b 05 06 00 00 00 00 01 00 01 00 35 00 -00001b0 00 00 6d 01 00 00 00 00` - s = regexp.MustCompile(`[0-9a-f]{7}`).ReplaceAllString(s, "") - s = regexp.MustCompile(`\s+`).ReplaceAllString(s, "") - b, err := hex.DecodeString(s) - if err != nil { - panic(err) - } - return b -} - -func returnRecursiveZip() (r io.ReaderAt, size int64) { - b := rZipBytes() - return bytes.NewReader(b), int64(len(b)) -} - -func TestIssue8186(t *testing.T) { - // Directory headers & data found in the TOC of a JAR file. - dirEnts := []string{ - "PK\x01\x02\n\x00\n\x00\x00\b\x00\x004\x9d3?\xaa\x1b\x06\xf0\x81\x02\x00\x00\x81\x02\x00\x00-\x00\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00res/drawable-xhdpi-v4/ic_actionbar_accept.png\xfe\xca\x00\x00\x00", - "PK\x01\x02\n\x00\n\x00\x00\b\x00\x004\x9d3?\x90K\x89\xc7t\n\x00\x00t\n\x00\x00\x0e\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xd1\x02\x00\x00resources.arsc\x00\x00\x00", - "PK\x01\x02\x14\x00\x14\x00\b\b\b\x004\x9d3?\xff$\x18\xed3\x03\x00\x00\xb4\b\x00\x00\x13\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00t\r\x00\x00AndroidManifest.xml", - "PK\x01\x02\x14\x00\x14\x00\b\b\b\x004\x9d3?\x14\xc5K\xab\x192\x02\x00\xc8\xcd\x04\x00\v\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xe8\x10\x00\x00classes.dex", - "PK\x01\x02\x14\x00\x14\x00\b\b\b\x004\x9d3?E\x96\nD\xac\x01\x00\x00P\x03\x00\x00&\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00:C\x02\x00res/layout/actionbar_set_wallpaper.xml", - "PK\x01\x02\x14\x00\x14\x00\b\b\b\x004\x9d3?Ļ\x14\xe3\xd8\x01\x00\x00\xd8\x03\x00\x00 \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00:E\x02\x00res/layout/wallpaper_cropper.xml", - "PK\x01\x02\x14\x00\x14\x00\b\b\b\x004\x9d3?}\xc1\x15\x9eZ\x01\x00\x00!\x02\x00\x00\x14\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00`G\x02\x00META-INF/MANIFEST.MF", - "PK\x01\x02\x14\x00\x14\x00\b\b\b\x004\x9d3?\xe6\x98Ьo\x01\x00\x00\x84\x02\x00\x00\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xfcH\x02\x00META-INF/CERT.SF", - "PK\x01\x02\x14\x00\x14\x00\b\b\b\x004\x9d3?\xbfP\x96b\x86\x04\x00\x00\xb2\x06\x00\x00\x11\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa9J\x02\x00META-INF/CERT.RSA", - } - for i, s := range dirEnts { - var f File - err := readDirectoryHeader(&f, strings.NewReader(s)) - if err != nil { - t.Errorf("error reading #%d: %v", i, err) - } - } -} diff --git a/src/pkg/archive/zip/register.go b/src/pkg/archive/zip/register.go deleted file mode 100644 index 4211ec7af..000000000 --- a/src/pkg/archive/zip/register.go +++ /dev/null @@ -1,110 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package zip - -import ( - "compress/flate" - "errors" - "io" - "io/ioutil" - "sync" -) - -// A Compressor returns a compressing writer, writing to the -// provided writer. On Close, any pending data should be flushed. -type Compressor func(io.Writer) (io.WriteCloser, error) - -// Decompressor is a function that wraps a Reader with a decompressing Reader. -// The decompressed ReadCloser is returned to callers who open files from -// within the archive. These callers are responsible for closing this reader -// when they're finished reading. -type Decompressor func(io.Reader) io.ReadCloser - -var flateWriterPool sync.Pool - -func newFlateWriter(w io.Writer) io.WriteCloser { - fw, ok := flateWriterPool.Get().(*flate.Writer) - if ok { - fw.Reset(w) - } else { - fw, _ = flate.NewWriter(w, 5) - } - return &pooledFlateWriter{fw: fw} -} - -type pooledFlateWriter struct { - mu sync.Mutex // guards Close and Write - fw *flate.Writer -} - -func (w *pooledFlateWriter) Write(p []byte) (n int, err error) { - w.mu.Lock() - defer w.mu.Unlock() - if w.fw == nil { - return 0, errors.New("Write after Close") - } - return w.fw.Write(p) -} - -func (w *pooledFlateWriter) Close() error { - w.mu.Lock() - defer w.mu.Unlock() - var err error - if w.fw != nil { - err = w.fw.Close() - flateWriterPool.Put(w.fw) - w.fw = nil - } - return err -} - -var ( - mu sync.RWMutex // guards compressor and decompressor maps - - compressors = map[uint16]Compressor{ - Store: func(w io.Writer) (io.WriteCloser, error) { return &nopCloser{w}, nil }, - Deflate: func(w io.Writer) (io.WriteCloser, error) { return newFlateWriter(w), nil }, - } - - decompressors = map[uint16]Decompressor{ - Store: ioutil.NopCloser, - Deflate: flate.NewReader, - } -) - -// RegisterDecompressor allows custom decompressors for a specified method ID. -func RegisterDecompressor(method uint16, d Decompressor) { - mu.Lock() - defer mu.Unlock() - - if _, ok := decompressors[method]; ok { - panic("decompressor already registered") - } - decompressors[method] = d -} - -// RegisterCompressor registers custom compressors for a specified method ID. -// The common methods Store and Deflate are built in. -func RegisterCompressor(method uint16, comp Compressor) { - mu.Lock() - defer mu.Unlock() - - if _, ok := compressors[method]; ok { - panic("compressor already registered") - } - compressors[method] = comp -} - -func compressor(method uint16) Compressor { - mu.RLock() - defer mu.RUnlock() - return compressors[method] -} - -func decompressor(method uint16) Decompressor { - mu.RLock() - defer mu.RUnlock() - return decompressors[method] -} diff --git a/src/pkg/archive/zip/struct.go b/src/pkg/archive/zip/struct.go deleted file mode 100644 index cb28e8324..000000000 --- a/src/pkg/archive/zip/struct.go +++ /dev/null @@ -1,313 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* -Package zip provides support for reading and writing ZIP archives. - -See: http://www.pkware.com/documents/casestudies/APPNOTE.TXT - -This package does not support disk spanning. - -A note about ZIP64: - -To be backwards compatible the FileHeader has both 32 and 64 bit Size -fields. The 64 bit fields will always contain the correct value and -for normal archives both fields will be the same. For files requiring -the ZIP64 format the 32 bit fields will be 0xffffffff and the 64 bit -fields must be used instead. -*/ -package zip - -import ( - "os" - "path" - "time" -) - -// Compression methods. -const ( - Store uint16 = 0 - Deflate uint16 = 8 -) - -const ( - fileHeaderSignature = 0x04034b50 - directoryHeaderSignature = 0x02014b50 - directoryEndSignature = 0x06054b50 - directory64LocSignature = 0x07064b50 - directory64EndSignature = 0x06064b50 - dataDescriptorSignature = 0x08074b50 // de-facto standard; required by OS X Finder - fileHeaderLen = 30 // + filename + extra - directoryHeaderLen = 46 // + filename + extra + comment - directoryEndLen = 22 // + comment - dataDescriptorLen = 16 // four uint32: descriptor signature, crc32, compressed size, size - dataDescriptor64Len = 24 // descriptor with 8 byte sizes - directory64LocLen = 20 // - directory64EndLen = 56 // + extra - - // Constants for the first byte in CreatorVersion - creatorFAT = 0 - creatorUnix = 3 - creatorNTFS = 11 - creatorVFAT = 14 - creatorMacOSX = 19 - - // version numbers - zipVersion20 = 20 // 2.0 - zipVersion45 = 45 // 4.5 (reads and writes zip64 archives) - - // limits for non zip64 files - uint16max = (1 << 16) - 1 - uint32max = (1 << 32) - 1 - - // extra header id's - zip64ExtraId = 0x0001 // zip64 Extended Information Extra Field -) - -// FileHeader describes a file within a zip file. -// See the zip spec for details. -type FileHeader struct { - // Name is the name of the file. - // It must be a relative path: it must not start with a drive - // letter (e.g. C:) or leading slash, and only forward slashes - // are allowed. - Name string - - CreatorVersion uint16 - ReaderVersion uint16 - Flags uint16 - Method uint16 - ModifiedTime uint16 // MS-DOS time - ModifiedDate uint16 // MS-DOS date - CRC32 uint32 - CompressedSize uint32 // deprecated; use CompressedSize64 - UncompressedSize uint32 // deprecated; use UncompressedSize64 - CompressedSize64 uint64 - UncompressedSize64 uint64 - Extra []byte - ExternalAttrs uint32 // Meaning depends on CreatorVersion - Comment string -} - -// FileInfo returns an os.FileInfo for the FileHeader. -func (h *FileHeader) FileInfo() os.FileInfo { - return headerFileInfo{h} -} - -// headerFileInfo implements os.FileInfo. -type headerFileInfo struct { - fh *FileHeader -} - -func (fi headerFileInfo) Name() string { return path.Base(fi.fh.Name) } -func (fi headerFileInfo) Size() int64 { - if fi.fh.UncompressedSize64 > 0 { - return int64(fi.fh.UncompressedSize64) - } - return int64(fi.fh.UncompressedSize) -} -func (fi headerFileInfo) IsDir() bool { return fi.Mode().IsDir() } -func (fi headerFileInfo) ModTime() time.Time { return fi.fh.ModTime() } -func (fi headerFileInfo) Mode() os.FileMode { return fi.fh.Mode() } -func (fi headerFileInfo) Sys() interface{} { return fi.fh } - -// FileInfoHeader creates a partially-populated FileHeader from an -// os.FileInfo. -// Because os.FileInfo's Name method returns only the base name of -// the file it describes, it may be necessary to modify the Name field -// of the returned header to provide the full path name of the file. -func FileInfoHeader(fi os.FileInfo) (*FileHeader, error) { - size := fi.Size() - fh := &FileHeader{ - Name: fi.Name(), - UncompressedSize64: uint64(size), - } - fh.SetModTime(fi.ModTime()) - fh.SetMode(fi.Mode()) - if fh.UncompressedSize64 > uint32max { - fh.UncompressedSize = uint32max - } else { - fh.UncompressedSize = uint32(fh.UncompressedSize64) - } - return fh, nil -} - -type directoryEnd struct { - diskNbr uint32 // unused - dirDiskNbr uint32 // unused - dirRecordsThisDisk uint64 // unused - directoryRecords uint64 - directorySize uint64 - directoryOffset uint64 // relative to file - commentLen uint16 - comment string -} - -// msDosTimeToTime converts an MS-DOS date and time into a time.Time. -// The resolution is 2s. -// See: http://msdn.microsoft.com/en-us/library/ms724247(v=VS.85).aspx -func msDosTimeToTime(dosDate, dosTime uint16) time.Time { - return time.Date( - // date bits 0-4: day of month; 5-8: month; 9-15: years since 1980 - int(dosDate>>9+1980), - time.Month(dosDate>>5&0xf), - int(dosDate&0x1f), - - // time bits 0-4: second/2; 5-10: minute; 11-15: hour - int(dosTime>>11), - int(dosTime>>5&0x3f), - int(dosTime&0x1f*2), - 0, // nanoseconds - - time.UTC, - ) -} - -// timeToMsDosTime converts a time.Time to an MS-DOS date and time. -// The resolution is 2s. -// See: http://msdn.microsoft.com/en-us/library/ms724274(v=VS.85).aspx -func timeToMsDosTime(t time.Time) (fDate uint16, fTime uint16) { - t = t.In(time.UTC) - fDate = uint16(t.Day() + int(t.Month())<<5 + (t.Year()-1980)<<9) - fTime = uint16(t.Second()/2 + t.Minute()<<5 + t.Hour()<<11) - return -} - -// ModTime returns the modification time in UTC. -// The resolution is 2s. -func (h *FileHeader) ModTime() time.Time { - return msDosTimeToTime(h.ModifiedDate, h.ModifiedTime) -} - -// SetModTime sets the ModifiedTime and ModifiedDate fields to the given time in UTC. -// The resolution is 2s. -func (h *FileHeader) SetModTime(t time.Time) { - h.ModifiedDate, h.ModifiedTime = timeToMsDosTime(t) -} - -const ( - // Unix constants. The specification doesn't mention them, - // but these seem to be the values agreed on by tools. - s_IFMT = 0xf000 - s_IFSOCK = 0xc000 - s_IFLNK = 0xa000 - s_IFREG = 0x8000 - s_IFBLK = 0x6000 - s_IFDIR = 0x4000 - s_IFCHR = 0x2000 - s_IFIFO = 0x1000 - s_ISUID = 0x800 - s_ISGID = 0x400 - s_ISVTX = 0x200 - - msdosDir = 0x10 - msdosReadOnly = 0x01 -) - -// Mode returns the permission and mode bits for the FileHeader. -func (h *FileHeader) Mode() (mode os.FileMode) { - switch h.CreatorVersion >> 8 { - case creatorUnix, creatorMacOSX: - mode = unixModeToFileMode(h.ExternalAttrs >> 16) - case creatorNTFS, creatorVFAT, creatorFAT: - mode = msdosModeToFileMode(h.ExternalAttrs) - } - if len(h.Name) > 0 && h.Name[len(h.Name)-1] == '/' { - mode |= os.ModeDir - } - return mode -} - -// SetMode changes the permission and mode bits for the FileHeader. -func (h *FileHeader) SetMode(mode os.FileMode) { - h.CreatorVersion = h.CreatorVersion&0xff | creatorUnix<<8 - h.ExternalAttrs = fileModeToUnixMode(mode) << 16 - - // set MSDOS attributes too, as the original zip does. - if mode&os.ModeDir != 0 { - h.ExternalAttrs |= msdosDir - } - if mode&0200 == 0 { - h.ExternalAttrs |= msdosReadOnly - } -} - -// isZip64 returns true if the file size exceeds the 32 bit limit -func (fh *FileHeader) isZip64() bool { - return fh.CompressedSize64 > uint32max || fh.UncompressedSize64 > uint32max -} - -func msdosModeToFileMode(m uint32) (mode os.FileMode) { - if m&msdosDir != 0 { - mode = os.ModeDir | 0777 - } else { - mode = 0666 - } - if m&msdosReadOnly != 0 { - mode &^= 0222 - } - return mode -} - -func fileModeToUnixMode(mode os.FileMode) uint32 { - var m uint32 - switch mode & os.ModeType { - default: - m = s_IFREG - case os.ModeDir: - m = s_IFDIR - case os.ModeSymlink: - m = s_IFLNK - case os.ModeNamedPipe: - m = s_IFIFO - case os.ModeSocket: - m = s_IFSOCK - case os.ModeDevice: - if mode&os.ModeCharDevice != 0 { - m = s_IFCHR - } else { - m = s_IFBLK - } - } - if mode&os.ModeSetuid != 0 { - m |= s_ISUID - } - if mode&os.ModeSetgid != 0 { - m |= s_ISGID - } - if mode&os.ModeSticky != 0 { - m |= s_ISVTX - } - return m | uint32(mode&0777) -} - -func unixModeToFileMode(m uint32) os.FileMode { - mode := os.FileMode(m & 0777) - switch m & s_IFMT { - case s_IFBLK: - mode |= os.ModeDevice - case s_IFCHR: - mode |= os.ModeDevice | os.ModeCharDevice - case s_IFDIR: - mode |= os.ModeDir - case s_IFIFO: - mode |= os.ModeNamedPipe - case s_IFLNK: - mode |= os.ModeSymlink - case s_IFREG: - // nothing to do - case s_IFSOCK: - mode |= os.ModeSocket - } - if m&s_ISGID != 0 { - mode |= os.ModeSetgid - } - if m&s_ISUID != 0 { - mode |= os.ModeSetuid - } - if m&s_ISVTX != 0 { - mode |= os.ModeSticky - } - return mode -} diff --git a/src/pkg/archive/zip/testdata/crc32-not-streamed.zip b/src/pkg/archive/zip/testdata/crc32-not-streamed.zip deleted file mode 100644 index f268d8873..000000000 Binary files a/src/pkg/archive/zip/testdata/crc32-not-streamed.zip and /dev/null differ diff --git a/src/pkg/archive/zip/testdata/dd.zip b/src/pkg/archive/zip/testdata/dd.zip deleted file mode 100644 index e53378b0b..000000000 Binary files a/src/pkg/archive/zip/testdata/dd.zip and /dev/null differ diff --git a/src/pkg/archive/zip/testdata/go-no-datadesc-sig.zip b/src/pkg/archive/zip/testdata/go-no-datadesc-sig.zip deleted file mode 100644 index c3d593f44..000000000 Binary files a/src/pkg/archive/zip/testdata/go-no-datadesc-sig.zip and /dev/null differ diff --git a/src/pkg/archive/zip/testdata/go-with-datadesc-sig.zip b/src/pkg/archive/zip/testdata/go-with-datadesc-sig.zip deleted file mode 100644 index bcfe121bb..000000000 Binary files a/src/pkg/archive/zip/testdata/go-with-datadesc-sig.zip and /dev/null differ diff --git a/src/pkg/archive/zip/testdata/gophercolor16x16.png b/src/pkg/archive/zip/testdata/gophercolor16x16.png deleted file mode 100644 index 48854ff3b..000000000 Binary files a/src/pkg/archive/zip/testdata/gophercolor16x16.png and /dev/null differ diff --git a/src/pkg/archive/zip/testdata/readme.notzip b/src/pkg/archive/zip/testdata/readme.notzip deleted file mode 100644 index 06668c4c1..000000000 Binary files a/src/pkg/archive/zip/testdata/readme.notzip and /dev/null differ diff --git a/src/pkg/archive/zip/testdata/readme.zip b/src/pkg/archive/zip/testdata/readme.zip deleted file mode 100644 index db3bb900e..000000000 Binary files a/src/pkg/archive/zip/testdata/readme.zip and /dev/null differ diff --git a/src/pkg/archive/zip/testdata/symlink.zip b/src/pkg/archive/zip/testdata/symlink.zip deleted file mode 100644 index af846938c..000000000 Binary files a/src/pkg/archive/zip/testdata/symlink.zip and /dev/null differ diff --git a/src/pkg/archive/zip/testdata/test-trailing-junk.zip b/src/pkg/archive/zip/testdata/test-trailing-junk.zip deleted file mode 100644 index 42281b4e3..000000000 Binary files a/src/pkg/archive/zip/testdata/test-trailing-junk.zip and /dev/null differ diff --git a/src/pkg/archive/zip/testdata/test.zip b/src/pkg/archive/zip/testdata/test.zip deleted file mode 100644 index 03890c05d..000000000 Binary files a/src/pkg/archive/zip/testdata/test.zip and /dev/null differ diff --git a/src/pkg/archive/zip/testdata/unix.zip b/src/pkg/archive/zip/testdata/unix.zip deleted file mode 100644 index ce1a981b2..000000000 Binary files a/src/pkg/archive/zip/testdata/unix.zip and /dev/null differ diff --git a/src/pkg/archive/zip/testdata/winxp.zip b/src/pkg/archive/zip/testdata/winxp.zip deleted file mode 100644 index 3919322f0..000000000 Binary files a/src/pkg/archive/zip/testdata/winxp.zip and /dev/null differ diff --git a/src/pkg/archive/zip/testdata/zip64-2.zip b/src/pkg/archive/zip/testdata/zip64-2.zip deleted file mode 100644 index f844e3537..000000000 Binary files a/src/pkg/archive/zip/testdata/zip64-2.zip and /dev/null differ diff --git a/src/pkg/archive/zip/testdata/zip64.zip b/src/pkg/archive/zip/testdata/zip64.zip deleted file mode 100644 index a2ee1fa33..000000000 Binary files a/src/pkg/archive/zip/testdata/zip64.zip and /dev/null differ diff --git a/src/pkg/archive/zip/writer.go b/src/pkg/archive/zip/writer.go deleted file mode 100644 index 170beec0e..000000000 --- a/src/pkg/archive/zip/writer.go +++ /dev/null @@ -1,357 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package zip - -import ( - "bufio" - "encoding/binary" - "errors" - "hash" - "hash/crc32" - "io" -) - -// TODO(adg): support zip file comments -// TODO(adg): support specifying deflate level - -// Writer implements a zip file writer. -type Writer struct { - cw *countWriter - dir []*header - last *fileWriter - closed bool -} - -type header struct { - *FileHeader - offset uint64 -} - -// NewWriter returns a new Writer writing a zip file to w. -func NewWriter(w io.Writer) *Writer { - return &Writer{cw: &countWriter{w: bufio.NewWriter(w)}} -} - -// Flush flushes any buffered data to the underlying writer. -// Calling Flush is not normally necessary; calling Close is sufficient. -func (w *Writer) Flush() error { - return w.cw.w.(*bufio.Writer).Flush() -} - -// Close finishes writing the zip file by writing the central directory. -// It does not (and can not) close the underlying writer. -func (w *Writer) Close() error { - if w.last != nil && !w.last.closed { - if err := w.last.close(); err != nil { - return err - } - w.last = nil - } - if w.closed { - return errors.New("zip: writer closed twice") - } - w.closed = true - - // write central directory - start := w.cw.count - for _, h := range w.dir { - var buf [directoryHeaderLen]byte - b := writeBuf(buf[:]) - b.uint32(uint32(directoryHeaderSignature)) - b.uint16(h.CreatorVersion) - b.uint16(h.ReaderVersion) - b.uint16(h.Flags) - b.uint16(h.Method) - b.uint16(h.ModifiedTime) - b.uint16(h.ModifiedDate) - b.uint32(h.CRC32) - if h.isZip64() || h.offset > uint32max { - // the file needs a zip64 header. store maxint in both - // 32 bit size fields (and offset later) to signal that the - // zip64 extra header should be used. - b.uint32(uint32max) // compressed size - b.uint32(uint32max) // uncompressed size - - // append a zip64 extra block to Extra - var buf [28]byte // 2x uint16 + 3x uint64 - eb := writeBuf(buf[:]) - eb.uint16(zip64ExtraId) - eb.uint16(24) // size = 3x uint64 - eb.uint64(h.UncompressedSize64) - eb.uint64(h.CompressedSize64) - eb.uint64(h.offset) - h.Extra = append(h.Extra, buf[:]...) - } else { - b.uint32(h.CompressedSize) - b.uint32(h.UncompressedSize) - } - b.uint16(uint16(len(h.Name))) - b.uint16(uint16(len(h.Extra))) - b.uint16(uint16(len(h.Comment))) - b = b[4:] // skip disk number start and internal file attr (2x uint16) - b.uint32(h.ExternalAttrs) - if h.offset > uint32max { - b.uint32(uint32max) - } else { - b.uint32(uint32(h.offset)) - } - if _, err := w.cw.Write(buf[:]); err != nil { - return err - } - if _, err := io.WriteString(w.cw, h.Name); err != nil { - return err - } - if _, err := w.cw.Write(h.Extra); err != nil { - return err - } - if _, err := io.WriteString(w.cw, h.Comment); err != nil { - return err - } - } - end := w.cw.count - - records := uint64(len(w.dir)) - size := uint64(end - start) - offset := uint64(start) - - if records > uint16max || size > uint32max || offset > uint32max { - var buf [directory64EndLen + directory64LocLen]byte - b := writeBuf(buf[:]) - - // zip64 end of central directory record - b.uint32(directory64EndSignature) - b.uint64(directory64EndLen) - b.uint16(zipVersion45) // version made by - b.uint16(zipVersion45) // version needed to extract - b.uint32(0) // number of this disk - b.uint32(0) // number of the disk with the start of the central directory - b.uint64(records) // total number of entries in the central directory on this disk - b.uint64(records) // total number of entries in the central directory - b.uint64(size) // size of the central directory - b.uint64(offset) // offset of start of central directory with respect to the starting disk number - - // zip64 end of central directory locator - b.uint32(directory64LocSignature) - b.uint32(0) // number of the disk with the start of the zip64 end of central directory - b.uint64(uint64(end)) // relative offset of the zip64 end of central directory record - b.uint32(1) // total number of disks - - if _, err := w.cw.Write(buf[:]); err != nil { - return err - } - - // store max values in the regular end record to signal that - // that the zip64 values should be used instead - records = uint16max - size = uint32max - offset = uint32max - } - - // write end record - var buf [directoryEndLen]byte - b := writeBuf(buf[:]) - b.uint32(uint32(directoryEndSignature)) - b = b[4:] // skip over disk number and first disk number (2x uint16) - b.uint16(uint16(records)) // number of entries this disk - b.uint16(uint16(records)) // number of entries total - b.uint32(uint32(size)) // size of directory - b.uint32(uint32(offset)) // start of directory - // skipped size of comment (always zero) - if _, err := w.cw.Write(buf[:]); err != nil { - return err - } - - return w.cw.w.(*bufio.Writer).Flush() -} - -// Create adds a file to the zip file using the provided name. -// It returns a Writer to which the file contents should be written. -// The name must be a relative path: it must not start with a drive -// letter (e.g. C:) or leading slash, and only forward slashes are -// allowed. -// The file's contents must be written to the io.Writer before the next -// call to Create, CreateHeader, or Close. -func (w *Writer) Create(name string) (io.Writer, error) { - header := &FileHeader{ - Name: name, - Method: Deflate, - } - return w.CreateHeader(header) -} - -// CreateHeader adds a file to the zip file using the provided FileHeader -// for the file metadata. -// It returns a Writer to which the file contents should be written. -// The file's contents must be written to the io.Writer before the next -// call to Create, CreateHeader, or Close. -func (w *Writer) CreateHeader(fh *FileHeader) (io.Writer, error) { - if w.last != nil && !w.last.closed { - if err := w.last.close(); err != nil { - return nil, err - } - } - - fh.Flags |= 0x8 // we will write a data descriptor - - fh.CreatorVersion = fh.CreatorVersion&0xff00 | zipVersion20 // preserve compatibility byte - fh.ReaderVersion = zipVersion20 - - fw := &fileWriter{ - zipw: w.cw, - compCount: &countWriter{w: w.cw}, - crc32: crc32.NewIEEE(), - } - comp := compressor(fh.Method) - if comp == nil { - return nil, ErrAlgorithm - } - var err error - fw.comp, err = comp(fw.compCount) - if err != nil { - return nil, err - } - fw.rawCount = &countWriter{w: fw.comp} - - h := &header{ - FileHeader: fh, - offset: uint64(w.cw.count), - } - w.dir = append(w.dir, h) - fw.header = h - - if err := writeHeader(w.cw, fh); err != nil { - return nil, err - } - - w.last = fw - return fw, nil -} - -func writeHeader(w io.Writer, h *FileHeader) error { - var buf [fileHeaderLen]byte - b := writeBuf(buf[:]) - b.uint32(uint32(fileHeaderSignature)) - b.uint16(h.ReaderVersion) - b.uint16(h.Flags) - b.uint16(h.Method) - b.uint16(h.ModifiedTime) - b.uint16(h.ModifiedDate) - b.uint32(0) // since we are writing a data descriptor crc32, - b.uint32(0) // compressed size, - b.uint32(0) // and uncompressed size should be zero - b.uint16(uint16(len(h.Name))) - b.uint16(uint16(len(h.Extra))) - if _, err := w.Write(buf[:]); err != nil { - return err - } - if _, err := io.WriteString(w, h.Name); err != nil { - return err - } - _, err := w.Write(h.Extra) - return err -} - -type fileWriter struct { - *header - zipw io.Writer - rawCount *countWriter - comp io.WriteCloser - compCount *countWriter - crc32 hash.Hash32 - closed bool -} - -func (w *fileWriter) Write(p []byte) (int, error) { - if w.closed { - return 0, errors.New("zip: write to closed file") - } - w.crc32.Write(p) - return w.rawCount.Write(p) -} - -func (w *fileWriter) close() error { - if w.closed { - return errors.New("zip: file closed twice") - } - w.closed = true - if err := w.comp.Close(); err != nil { - return err - } - - // update FileHeader - fh := w.header.FileHeader - fh.CRC32 = w.crc32.Sum32() - fh.CompressedSize64 = uint64(w.compCount.count) - fh.UncompressedSize64 = uint64(w.rawCount.count) - - if fh.isZip64() { - fh.CompressedSize = uint32max - fh.UncompressedSize = uint32max - fh.ReaderVersion = zipVersion45 // requires 4.5 - File uses ZIP64 format extensions - } else { - fh.CompressedSize = uint32(fh.CompressedSize64) - fh.UncompressedSize = uint32(fh.UncompressedSize64) - } - - // Write data descriptor. This is more complicated than one would - // think, see e.g. comments in zipfile.c:putextended() and - // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7073588. - // The approach here is to write 8 byte sizes if needed without - // adding a zip64 extra in the local header (too late anyway). - var buf []byte - if fh.isZip64() { - buf = make([]byte, dataDescriptor64Len) - } else { - buf = make([]byte, dataDescriptorLen) - } - b := writeBuf(buf) - b.uint32(dataDescriptorSignature) // de-facto standard, required by OS X - b.uint32(fh.CRC32) - if fh.isZip64() { - b.uint64(fh.CompressedSize64) - b.uint64(fh.UncompressedSize64) - } else { - b.uint32(fh.CompressedSize) - b.uint32(fh.UncompressedSize) - } - _, err := w.zipw.Write(buf) - return err -} - -type countWriter struct { - w io.Writer - count int64 -} - -func (w *countWriter) Write(p []byte) (int, error) { - n, err := w.w.Write(p) - w.count += int64(n) - return n, err -} - -type nopCloser struct { - io.Writer -} - -func (w nopCloser) Close() error { - return nil -} - -type writeBuf []byte - -func (b *writeBuf) uint16(v uint16) { - binary.LittleEndian.PutUint16(*b, v) - *b = (*b)[2:] -} - -func (b *writeBuf) uint32(v uint32) { - binary.LittleEndian.PutUint32(*b, v) - *b = (*b)[4:] -} - -func (b *writeBuf) uint64(v uint64) { - binary.LittleEndian.PutUint64(*b, v) - *b = (*b)[8:] -} diff --git a/src/pkg/archive/zip/writer_test.go b/src/pkg/archive/zip/writer_test.go deleted file mode 100644 index 184a7d96a..000000000 --- a/src/pkg/archive/zip/writer_test.go +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package zip - -import ( - "bytes" - "io" - "io/ioutil" - "math/rand" - "os" - "testing" -) - -// TODO(adg): a more sophisticated test suite - -type WriteTest struct { - Name string - Data []byte - Method uint16 - Mode os.FileMode -} - -var writeTests = []WriteTest{ - { - Name: "foo", - Data: []byte("Rabbits, guinea pigs, gophers, marsupial rats, and quolls."), - Method: Store, - Mode: 0666, - }, - { - Name: "bar", - Data: nil, // large data set in the test - Method: Deflate, - Mode: 0644, - }, - { - Name: "setuid", - Data: []byte("setuid file"), - Method: Deflate, - Mode: 0755 | os.ModeSetuid, - }, - { - Name: "setgid", - Data: []byte("setgid file"), - Method: Deflate, - Mode: 0755 | os.ModeSetgid, - }, - { - Name: "symlink", - Data: []byte("../link/target"), - Method: Deflate, - Mode: 0755 | os.ModeSymlink, - }, -} - -func TestWriter(t *testing.T) { - largeData := make([]byte, 1<<17) - for i := range largeData { - largeData[i] = byte(rand.Int()) - } - writeTests[1].Data = largeData - defer func() { - writeTests[1].Data = nil - }() - - // write a zip file - buf := new(bytes.Buffer) - w := NewWriter(buf) - - for _, wt := range writeTests { - testCreate(t, w, &wt) - } - - if err := w.Close(); err != nil { - t.Fatal(err) - } - - // read it back - r, err := NewReader(bytes.NewReader(buf.Bytes()), int64(buf.Len())) - if err != nil { - t.Fatal(err) - } - for i, wt := range writeTests { - testReadFile(t, r.File[i], &wt) - } -} - -func TestWriterFlush(t *testing.T) { - var buf bytes.Buffer - w := NewWriter(struct{ io.Writer }{&buf}) - _, err := w.Create("foo") - if err != nil { - t.Fatal(err) - } - if buf.Len() > 0 { - t.Fatalf("Unexpected %d bytes already in buffer", buf.Len()) - } - if err := w.Flush(); err != nil { - t.Fatal(err) - } - if buf.Len() == 0 { - t.Fatal("No bytes written after Flush") - } -} - -func testCreate(t *testing.T, w *Writer, wt *WriteTest) { - header := &FileHeader{ - Name: wt.Name, - Method: wt.Method, - } - if wt.Mode != 0 { - header.SetMode(wt.Mode) - } - f, err := w.CreateHeader(header) - if err != nil { - t.Fatal(err) - } - _, err = f.Write(wt.Data) - if err != nil { - t.Fatal(err) - } -} - -func testReadFile(t *testing.T, f *File, wt *WriteTest) { - if f.Name != wt.Name { - t.Fatalf("File name: got %q, want %q", f.Name, wt.Name) - } - testFileMode(t, wt.Name, f, wt.Mode) - rc, err := f.Open() - if err != nil { - t.Fatal("opening:", err) - } - b, err := ioutil.ReadAll(rc) - if err != nil { - t.Fatal("reading:", err) - } - err = rc.Close() - if err != nil { - t.Fatal("closing:", err) - } - if !bytes.Equal(b, wt.Data) { - t.Errorf("File contents %q, want %q", b, wt.Data) - } -} - -func BenchmarkCompressedZipGarbage(b *testing.B) { - b.ReportAllocs() - var buf bytes.Buffer - bigBuf := bytes.Repeat([]byte("a"), 1<<20) - for i := 0; i < b.N; i++ { - buf.Reset() - zw := NewWriter(&buf) - for j := 0; j < 3; j++ { - w, _ := zw.CreateHeader(&FileHeader{ - Name: "foo", - Method: Deflate, - }) - w.Write(bigBuf) - } - zw.Close() - } -} diff --git a/src/pkg/archive/zip/zip_test.go b/src/pkg/archive/zip/zip_test.go deleted file mode 100644 index 32a16a79e..000000000 --- a/src/pkg/archive/zip/zip_test.go +++ /dev/null @@ -1,395 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Tests that involve both reading and writing. - -package zip - -import ( - "bytes" - "fmt" - "hash" - "io" - "io/ioutil" - "sort" - "strings" - "testing" - "time" -) - -func TestOver65kFiles(t *testing.T) { - buf := new(bytes.Buffer) - w := NewWriter(buf) - const nFiles = (1 << 16) + 42 - for i := 0; i < nFiles; i++ { - _, err := w.CreateHeader(&FileHeader{ - Name: fmt.Sprintf("%d.dat", i), - Method: Store, // avoid Issue 6136 and Issue 6138 - }) - if err != nil { - t.Fatalf("creating file %d: %v", i, err) - } - } - if err := w.Close(); err != nil { - t.Fatalf("Writer.Close: %v", err) - } - s := buf.String() - zr, err := NewReader(strings.NewReader(s), int64(len(s))) - if err != nil { - t.Fatalf("NewReader: %v", err) - } - if got := len(zr.File); got != nFiles { - t.Fatalf("File contains %d files, want %d", got, nFiles) - } - for i := 0; i < nFiles; i++ { - want := fmt.Sprintf("%d.dat", i) - if zr.File[i].Name != want { - t.Fatalf("File(%d) = %q, want %q", i, zr.File[i].Name, want) - } - } -} - -func TestModTime(t *testing.T) { - var testTime = time.Date(2009, time.November, 10, 23, 45, 58, 0, time.UTC) - fh := new(FileHeader) - fh.SetModTime(testTime) - outTime := fh.ModTime() - if !outTime.Equal(testTime) { - t.Errorf("times don't match: got %s, want %s", outTime, testTime) - } -} - -func testHeaderRoundTrip(fh *FileHeader, wantUncompressedSize uint32, wantUncompressedSize64 uint64, t *testing.T) { - fi := fh.FileInfo() - fh2, err := FileInfoHeader(fi) - if err != nil { - t.Fatal(err) - } - if got, want := fh2.Name, fh.Name; got != want { - t.Errorf("Name: got %s, want %s\n", got, want) - } - if got, want := fh2.UncompressedSize, wantUncompressedSize; got != want { - t.Errorf("UncompressedSize: got %d, want %d\n", got, want) - } - if got, want := fh2.UncompressedSize64, wantUncompressedSize64; got != want { - t.Errorf("UncompressedSize64: got %d, want %d\n", got, want) - } - if got, want := fh2.ModifiedTime, fh.ModifiedTime; got != want { - t.Errorf("ModifiedTime: got %d, want %d\n", got, want) - } - if got, want := fh2.ModifiedDate, fh.ModifiedDate; got != want { - t.Errorf("ModifiedDate: got %d, want %d\n", got, want) - } - - if sysfh, ok := fi.Sys().(*FileHeader); !ok && sysfh != fh { - t.Errorf("Sys didn't return original *FileHeader") - } -} - -func TestFileHeaderRoundTrip(t *testing.T) { - fh := &FileHeader{ - Name: "foo.txt", - UncompressedSize: 987654321, - ModifiedTime: 1234, - ModifiedDate: 5678, - } - testHeaderRoundTrip(fh, fh.UncompressedSize, uint64(fh.UncompressedSize), t) -} - -func TestFileHeaderRoundTrip64(t *testing.T) { - fh := &FileHeader{ - Name: "foo.txt", - UncompressedSize64: 9876543210, - ModifiedTime: 1234, - ModifiedDate: 5678, - } - testHeaderRoundTrip(fh, uint32max, fh.UncompressedSize64, t) -} - -type repeatedByte struct { - off int64 - b byte - n int64 -} - -// rleBuffer is a run-length-encoded byte buffer. -// It's an io.Writer (like a bytes.Buffer) and also an io.ReaderAt, -// allowing random-access reads. -type rleBuffer struct { - buf []repeatedByte -} - -func (r *rleBuffer) Size() int64 { - if len(r.buf) == 0 { - return 0 - } - last := &r.buf[len(r.buf)-1] - return last.off + last.n -} - -func (r *rleBuffer) Write(p []byte) (n int, err error) { - var rp *repeatedByte - if len(r.buf) > 0 { - rp = &r.buf[len(r.buf)-1] - // Fast path, if p is entirely the same byte repeated. - if lastByte := rp.b; len(p) > 0 && p[0] == lastByte { - all := true - for _, b := range p { - if b != lastByte { - all = false - break - } - } - if all { - rp.n += int64(len(p)) - return len(p), nil - } - } - } - - for _, b := range p { - if rp == nil || rp.b != b { - r.buf = append(r.buf, repeatedByte{r.Size(), b, 1}) - rp = &r.buf[len(r.buf)-1] - } else { - rp.n++ - } - } - return len(p), nil -} - -func (r *rleBuffer) ReadAt(p []byte, off int64) (n int, err error) { - if len(p) == 0 { - return - } - skipParts := sort.Search(len(r.buf), func(i int) bool { - part := &r.buf[i] - return part.off+part.n > off - }) - parts := r.buf[skipParts:] - if len(parts) > 0 { - skipBytes := off - parts[0].off - for len(parts) > 0 { - part := parts[0] - for i := skipBytes; i < part.n; i++ { - if n == len(p) { - return - } - p[n] = part.b - n++ - } - parts = parts[1:] - skipBytes = 0 - } - } - if n != len(p) { - err = io.ErrUnexpectedEOF - } - return -} - -// Just testing the rleBuffer used in the Zip64 test above. Not used by the zip code. -func TestRLEBuffer(t *testing.T) { - b := new(rleBuffer) - var all []byte - writes := []string{"abcdeee", "eeeeeee", "eeeefghaaiii"} - for _, w := range writes { - b.Write([]byte(w)) - all = append(all, w...) - } - if len(b.buf) != 10 { - t.Fatalf("len(b.buf) = %d; want 10", len(b.buf)) - } - - for i := 0; i < len(all); i++ { - for j := 0; j < len(all)-i; j++ { - buf := make([]byte, j) - n, err := b.ReadAt(buf, int64(i)) - if err != nil || n != len(buf) { - t.Errorf("ReadAt(%d, %d) = %d, %v; want %d, nil", i, j, n, err, len(buf)) - } - if !bytes.Equal(buf, all[i:i+j]) { - t.Errorf("ReadAt(%d, %d) = %q; want %q", i, j, buf, all[i:i+j]) - } - } - } -} - -// fakeHash32 is a dummy Hash32 that always returns 0. -type fakeHash32 struct { - hash.Hash32 -} - -func (fakeHash32) Write(p []byte) (int, error) { return len(p), nil } -func (fakeHash32) Sum32() uint32 { return 0 } - -func TestZip64(t *testing.T) { - if testing.Short() { - t.Skip("slow test; skipping") - } - const size = 1 << 32 // before the "END\n" part - testZip64(t, size) -} - -func testZip64(t testing.TB, size int64) { - const chunkSize = 1024 - chunks := int(size / chunkSize) - // write 2^32 bytes plus "END\n" to a zip file - buf := new(rleBuffer) - w := NewWriter(buf) - f, err := w.CreateHeader(&FileHeader{ - Name: "huge.txt", - Method: Store, - }) - if err != nil { - t.Fatal(err) - } - f.(*fileWriter).crc32 = fakeHash32{} - chunk := make([]byte, chunkSize) - for i := range chunk { - chunk[i] = '.' - } - for i := 0; i < chunks; i++ { - _, err := f.Write(chunk) - if err != nil { - t.Fatal("write chunk:", err) - } - } - end := []byte("END\n") - _, err = f.Write(end) - if err != nil { - t.Fatal("write end:", err) - } - if err := w.Close(); err != nil { - t.Fatal(err) - } - - // read back zip file and check that we get to the end of it - r, err := NewReader(buf, int64(buf.Size())) - if err != nil { - t.Fatal("reader:", err) - } - f0 := r.File[0] - rc, err := f0.Open() - if err != nil { - t.Fatal("opening:", err) - } - rc.(*checksumReader).hash = fakeHash32{} - for i := 0; i < chunks; i++ { - _, err := io.ReadFull(rc, chunk) - if err != nil { - t.Fatal("read:", err) - } - } - gotEnd, err := ioutil.ReadAll(rc) - if err != nil { - t.Fatal("read end:", err) - } - if !bytes.Equal(gotEnd, end) { - t.Errorf("End of zip64 archive %q, want %q", gotEnd, end) - } - err = rc.Close() - if err != nil { - t.Fatal("closing:", err) - } - if size == 1<<32 { - if got, want := f0.UncompressedSize, uint32(uint32max); got != want { - t.Errorf("UncompressedSize %d, want %d", got, want) - } - } - - if got, want := f0.UncompressedSize64, uint64(size)+uint64(len(end)); got != want { - t.Errorf("UncompressedSize64 %d, want %d", got, want) - } -} - -func testInvalidHeader(h *FileHeader, t *testing.T) { - var buf bytes.Buffer - z := NewWriter(&buf) - - f, err := z.CreateHeader(h) - if err != nil { - t.Fatalf("error creating header: %v", err) - } - if _, err := f.Write([]byte("hi")); err != nil { - t.Fatalf("error writing content: %v", err) - } - if err := z.Close(); err != nil { - t.Fatalf("error closing zip writer: %v", err) - } - - b := buf.Bytes() - if _, err = NewReader(bytes.NewReader(b), int64(len(b))); err != ErrFormat { - t.Fatalf("got %v, expected ErrFormat", err) - } -} - -func testValidHeader(h *FileHeader, t *testing.T) { - var buf bytes.Buffer - z := NewWriter(&buf) - - f, err := z.CreateHeader(h) - if err != nil { - t.Fatalf("error creating header: %v", err) - } - if _, err := f.Write([]byte("hi")); err != nil { - t.Fatalf("error writing content: %v", err) - } - if err := z.Close(); err != nil { - t.Fatalf("error closing zip writer: %v", err) - } - - b := buf.Bytes() - if _, err = NewReader(bytes.NewReader(b), int64(len(b))); err != nil { - t.Fatalf("got %v, expected nil", err) - } -} - -// Issue 4302. -func TestHeaderInvalidTagAndSize(t *testing.T) { - const timeFormat = "20060102T150405.000.txt" - - ts := time.Now() - filename := ts.Format(timeFormat) - - h := FileHeader{ - Name: filename, - Method: Deflate, - Extra: []byte(ts.Format(time.RFC3339Nano)), // missing tag and len - } - h.SetModTime(ts) - - testInvalidHeader(&h, t) -} - -func TestHeaderTooShort(t *testing.T) { - h := FileHeader{ - Name: "foo.txt", - Method: Deflate, - Extra: []byte{zip64ExtraId}, // missing size - } - testInvalidHeader(&h, t) -} - -// Issue 4393. It is valid to have an extra data header -// which contains no body. -func TestZeroLengthHeader(t *testing.T) { - h := FileHeader{ - Name: "extadata.txt", - Method: Deflate, - Extra: []byte{ - 85, 84, 5, 0, 3, 154, 144, 195, 77, // tag 21589 size 5 - 85, 120, 0, 0, // tag 30805 size 0 - }, - } - testValidHeader(&h, t) -} - -// Just benchmarking how fast the Zip64 test above is. Not related to -// our zip performance, since the test above disabled CRC32 and flate. -func BenchmarkZip64Test(b *testing.B) { - for i := 0; i < b.N; i++ { - testZip64(b, 1<<26) - } -} diff --git a/src/pkg/bufio/bufio.go b/src/pkg/bufio/bufio.go deleted file mode 100644 index d3c68fe6f..000000000 --- a/src/pkg/bufio/bufio.go +++ /dev/null @@ -1,698 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package bufio implements buffered I/O. It wraps an io.Reader or io.Writer -// object, creating another object (Reader or Writer) that also implements -// the interface but provides buffering and some help for textual I/O. -package bufio - -import ( - "bytes" - "errors" - "io" - "unicode/utf8" -) - -const ( - defaultBufSize = 4096 -) - -var ( - ErrInvalidUnreadByte = errors.New("bufio: invalid use of UnreadByte") - ErrInvalidUnreadRune = errors.New("bufio: invalid use of UnreadRune") - ErrBufferFull = errors.New("bufio: buffer full") - ErrNegativeCount = errors.New("bufio: negative count") -) - -// Buffered input. - -// Reader implements buffering for an io.Reader object. -type Reader struct { - buf []byte - rd io.Reader // reader provided by the client - r, w int // buf read and write positions - err error - lastByte int - lastRuneSize int -} - -const minReadBufferSize = 16 -const maxConsecutiveEmptyReads = 100 - -// NewReaderSize returns a new Reader whose buffer has at least the specified -// size. If the argument io.Reader is already a Reader with large enough -// size, it returns the underlying Reader. -func NewReaderSize(rd io.Reader, size int) *Reader { - // Is it already a Reader? - b, ok := rd.(*Reader) - if ok && len(b.buf) >= size { - return b - } - if size < minReadBufferSize { - size = minReadBufferSize - } - r := new(Reader) - r.reset(make([]byte, size), rd) - return r -} - -// NewReader returns a new Reader whose buffer has the default size. -func NewReader(rd io.Reader) *Reader { - return NewReaderSize(rd, defaultBufSize) -} - -// Reset discards any buffered data, resets all state, and switches -// the buffered reader to read from r. -func (b *Reader) Reset(r io.Reader) { - b.reset(b.buf, r) -} - -func (b *Reader) reset(buf []byte, r io.Reader) { - *b = Reader{ - buf: buf, - rd: r, - lastByte: -1, - lastRuneSize: -1, - } -} - -var errNegativeRead = errors.New("bufio: reader returned negative count from Read") - -// fill reads a new chunk into the buffer. -func (b *Reader) fill() { - // Slide existing data to beginning. - if b.r > 0 { - copy(b.buf, b.buf[b.r:b.w]) - b.w -= b.r - b.r = 0 - } - - if b.w >= len(b.buf) { - panic("bufio: tried to fill full buffer") - } - - // Read new data: try a limited number of times. - for i := maxConsecutiveEmptyReads; i > 0; i-- { - n, err := b.rd.Read(b.buf[b.w:]) - if n < 0 { - panic(errNegativeRead) - } - b.w += n - if err != nil { - b.err = err - return - } - if n > 0 { - return - } - } - b.err = io.ErrNoProgress -} - -func (b *Reader) readErr() error { - err := b.err - b.err = nil - return err -} - -// Peek returns the next n bytes without advancing the reader. The bytes stop -// being valid at the next read call. If Peek returns fewer than n bytes, it -// also returns an error explaining why the read is short. The error is -// ErrBufferFull if n is larger than b's buffer size. -func (b *Reader) Peek(n int) ([]byte, error) { - if n < 0 { - return nil, ErrNegativeCount - } - if n > len(b.buf) { - return nil, ErrBufferFull - } - // 0 <= n <= len(b.buf) - for b.w-b.r < n && b.err == nil { - b.fill() // b.w-b.r < len(b.buf) => buffer is not full - } - - var err error - if avail := b.w - b.r; avail < n { - // not enough data in buffer - n = avail - err = b.readErr() - if err == nil { - err = ErrBufferFull - } - } - return b.buf[b.r : b.r+n], err -} - -// Read reads data into p. -// It returns the number of bytes read into p. -// It calls Read at most once on the underlying Reader, -// hence n may be less than len(p). -// At EOF, the count will be zero and err will be io.EOF. -func (b *Reader) Read(p []byte) (n int, err error) { - n = len(p) - if n == 0 { - return 0, b.readErr() - } - if b.r == b.w { - if b.err != nil { - return 0, b.readErr() - } - if len(p) >= len(b.buf) { - // Large read, empty buffer. - // Read directly into p to avoid copy. - n, b.err = b.rd.Read(p) - if n < 0 { - panic(errNegativeRead) - } - if n > 0 { - b.lastByte = int(p[n-1]) - b.lastRuneSize = -1 - } - return n, b.readErr() - } - b.fill() // buffer is empty - if b.r == b.w { - return 0, b.readErr() - } - } - - // copy as much as we can - n = copy(p, b.buf[b.r:b.w]) - b.r += n - b.lastByte = int(b.buf[b.r-1]) - b.lastRuneSize = -1 - return n, nil -} - -// ReadByte reads and returns a single byte. -// If no byte is available, returns an error. -func (b *Reader) ReadByte() (c byte, err error) { - b.lastRuneSize = -1 - for b.r == b.w { - if b.err != nil { - return 0, b.readErr() - } - b.fill() // buffer is empty - } - c = b.buf[b.r] - b.r++ - b.lastByte = int(c) - return c, nil -} - -// UnreadByte unreads the last byte. Only the most recently read byte can be unread. -func (b *Reader) UnreadByte() error { - if b.lastByte < 0 || b.r == 0 && b.w > 0 { - return ErrInvalidUnreadByte - } - // b.r > 0 || b.w == 0 - if b.r > 0 { - b.r-- - } else { - // b.r == 0 && b.w == 0 - b.w = 1 - } - b.buf[b.r] = byte(b.lastByte) - b.lastByte = -1 - b.lastRuneSize = -1 - return nil -} - -// ReadRune reads a single UTF-8 encoded Unicode character and returns the -// rune and its size in bytes. If the encoded rune is invalid, it consumes one byte -// and returns unicode.ReplacementChar (U+FFFD) with a size of 1. -func (b *Reader) ReadRune() (r rune, size int, err error) { - for b.r+utf8.UTFMax > b.w && !utf8.FullRune(b.buf[b.r:b.w]) && b.err == nil && b.w-b.r < len(b.buf) { - b.fill() // b.w-b.r < len(buf) => buffer is not full - } - b.lastRuneSize = -1 - if b.r == b.w { - return 0, 0, b.readErr() - } - r, size = rune(b.buf[b.r]), 1 - if r >= 0x80 { - r, size = utf8.DecodeRune(b.buf[b.r:b.w]) - } - b.r += size - b.lastByte = int(b.buf[b.r-1]) - b.lastRuneSize = size - return r, size, nil -} - -// UnreadRune unreads the last rune. If the most recent read operation on -// the buffer was not a ReadRune, UnreadRune returns an error. (In this -// regard it is stricter than UnreadByte, which will unread the last byte -// from any read operation.) -func (b *Reader) UnreadRune() error { - if b.lastRuneSize < 0 || b.r < b.lastRuneSize { - return ErrInvalidUnreadRune - } - b.r -= b.lastRuneSize - b.lastByte = -1 - b.lastRuneSize = -1 - return nil -} - -// Buffered returns the number of bytes that can be read from the current buffer. -func (b *Reader) Buffered() int { return b.w - b.r } - -// ReadSlice reads until the first occurrence of delim in the input, -// returning a slice pointing at the bytes in the buffer. -// The bytes stop being valid at the next read. -// If ReadSlice encounters an error before finding a delimiter, -// it returns all the data in the buffer and the error itself (often io.EOF). -// ReadSlice fails with error ErrBufferFull if the buffer fills without a delim. -// Because the data returned from ReadSlice will be overwritten -// by the next I/O operation, most clients should use -// ReadBytes or ReadString instead. -// ReadSlice returns err != nil if and only if line does not end in delim. -func (b *Reader) ReadSlice(delim byte) (line []byte, err error) { - for { - // Search buffer. - if i := bytes.IndexByte(b.buf[b.r:b.w], delim); i >= 0 { - line = b.buf[b.r : b.r+i+1] - b.r += i + 1 - break - } - - // Pending error? - if b.err != nil { - line = b.buf[b.r:b.w] - b.r = b.w - err = b.readErr() - break - } - - // Buffer full? - if b.Buffered() >= len(b.buf) { - b.r = b.w - line = b.buf - err = ErrBufferFull - break - } - - b.fill() // buffer is not full - } - - // Handle last byte, if any. - if i := len(line) - 1; i >= 0 { - b.lastByte = int(line[i]) - b.lastRuneSize = -1 - } - - return -} - -// ReadLine is a low-level line-reading primitive. Most callers should use -// ReadBytes('\n') or ReadString('\n') instead or use a Scanner. -// -// ReadLine tries to return a single line, not including the end-of-line bytes. -// If the line was too long for the buffer then isPrefix is set and the -// beginning of the line is returned. The rest of the line will be returned -// from future calls. isPrefix will be false when returning the last fragment -// of the line. The returned buffer is only valid until the next call to -// ReadLine. ReadLine either returns a non-nil line or it returns an error, -// never both. -// -// The text returned from ReadLine does not include the line end ("\r\n" or "\n"). -// No indication or error is given if the input ends without a final line end. -// Calling UnreadByte after ReadLine will always unread the last byte read -// (possibly a character belonging to the line end) even if that byte is not -// part of the line returned by ReadLine. -func (b *Reader) ReadLine() (line []byte, isPrefix bool, err error) { - line, err = b.ReadSlice('\n') - if err == ErrBufferFull { - // Handle the case where "\r\n" straddles the buffer. - if len(line) > 0 && line[len(line)-1] == '\r' { - // Put the '\r' back on buf and drop it from line. - // Let the next call to ReadLine check for "\r\n". - if b.r == 0 { - // should be unreachable - panic("bufio: tried to rewind past start of buffer") - } - b.r-- - line = line[:len(line)-1] - } - return line, true, nil - } - - if len(line) == 0 { - if err != nil { - line = nil - } - return - } - err = nil - - if line[len(line)-1] == '\n' { - drop := 1 - if len(line) > 1 && line[len(line)-2] == '\r' { - drop = 2 - } - line = line[:len(line)-drop] - } - return -} - -// ReadBytes reads until the first occurrence of delim in the input, -// returning a slice containing the data up to and including the delimiter. -// If ReadBytes encounters an error before finding a delimiter, -// it returns the data read before the error and the error itself (often io.EOF). -// ReadBytes returns err != nil if and only if the returned data does not end in -// delim. -// For simple uses, a Scanner may be more convenient. -func (b *Reader) ReadBytes(delim byte) (line []byte, err error) { - // Use ReadSlice to look for array, - // accumulating full buffers. - var frag []byte - var full [][]byte - err = nil - - for { - var e error - frag, e = b.ReadSlice(delim) - if e == nil { // got final fragment - break - } - if e != ErrBufferFull { // unexpected error - err = e - break - } - - // Make a copy of the buffer. - buf := make([]byte, len(frag)) - copy(buf, frag) - full = append(full, buf) - } - - // Allocate new buffer to hold the full pieces and the fragment. - n := 0 - for i := range full { - n += len(full[i]) - } - n += len(frag) - - // Copy full pieces and fragment in. - buf := make([]byte, n) - n = 0 - for i := range full { - n += copy(buf[n:], full[i]) - } - copy(buf[n:], frag) - return buf, err -} - -// ReadString reads until the first occurrence of delim in the input, -// returning a string containing the data up to and including the delimiter. -// If ReadString encounters an error before finding a delimiter, -// it returns the data read before the error and the error itself (often io.EOF). -// ReadString returns err != nil if and only if the returned data does not end in -// delim. -// For simple uses, a Scanner may be more convenient. -func (b *Reader) ReadString(delim byte) (line string, err error) { - bytes, err := b.ReadBytes(delim) - line = string(bytes) - return line, err -} - -// WriteTo implements io.WriterTo. -func (b *Reader) WriteTo(w io.Writer) (n int64, err error) { - n, err = b.writeBuf(w) - if err != nil { - return - } - - if r, ok := b.rd.(io.WriterTo); ok { - m, err := r.WriteTo(w) - n += m - return n, err - } - - if w, ok := w.(io.ReaderFrom); ok { - m, err := w.ReadFrom(b.rd) - n += m - return n, err - } - - if b.w-b.r < len(b.buf) { - b.fill() // buffer not full - } - - for b.r < b.w { - // b.r < b.w => buffer is not empty - m, err := b.writeBuf(w) - n += m - if err != nil { - return n, err - } - b.fill() // buffer is empty - } - - if b.err == io.EOF { - b.err = nil - } - - return n, b.readErr() -} - -var errNegativeWrite = errors.New("bufio: writer returned negative count from Write") - -// writeBuf writes the Reader's buffer to the writer. -func (b *Reader) writeBuf(w io.Writer) (int64, error) { - n, err := w.Write(b.buf[b.r:b.w]) - if n < 0 { - panic(errNegativeWrite) - } - b.r += n - return int64(n), err -} - -// buffered output - -// Writer implements buffering for an io.Writer object. -// If an error occurs writing to a Writer, no more data will be -// accepted and all subsequent writes will return the error. -// After all data has been written, the client should call the -// Flush method to guarantee all data has been forwarded to -// the underlying io.Writer. -type Writer struct { - err error - buf []byte - n int - wr io.Writer -} - -// NewWriterSize returns a new Writer whose buffer has at least the specified -// size. If the argument io.Writer is already a Writer with large enough -// size, it returns the underlying Writer. -func NewWriterSize(w io.Writer, size int) *Writer { - // Is it already a Writer? - b, ok := w.(*Writer) - if ok && len(b.buf) >= size { - return b - } - if size <= 0 { - size = defaultBufSize - } - return &Writer{ - buf: make([]byte, size), - wr: w, - } -} - -// NewWriter returns a new Writer whose buffer has the default size. -func NewWriter(w io.Writer) *Writer { - return NewWriterSize(w, defaultBufSize) -} - -// Reset discards any unflushed buffered data, clears any error, and -// resets b to write its output to w. -func (b *Writer) Reset(w io.Writer) { - b.err = nil - b.n = 0 - b.wr = w -} - -// Flush writes any buffered data to the underlying io.Writer. -func (b *Writer) Flush() error { - err := b.flush() - return err -} - -func (b *Writer) flush() error { - if b.err != nil { - return b.err - } - if b.n == 0 { - return nil - } - n, err := b.wr.Write(b.buf[0:b.n]) - if n < b.n && err == nil { - err = io.ErrShortWrite - } - if err != nil { - if n > 0 && n < b.n { - copy(b.buf[0:b.n-n], b.buf[n:b.n]) - } - b.n -= n - b.err = err - return err - } - b.n = 0 - return nil -} - -// Available returns how many bytes are unused in the buffer. -func (b *Writer) Available() int { return len(b.buf) - b.n } - -// Buffered returns the number of bytes that have been written into the current buffer. -func (b *Writer) Buffered() int { return b.n } - -// Write writes the contents of p into the buffer. -// It returns the number of bytes written. -// If nn < len(p), it also returns an error explaining -// why the write is short. -func (b *Writer) Write(p []byte) (nn int, err error) { - for len(p) > b.Available() && b.err == nil { - var n int - if b.Buffered() == 0 { - // Large write, empty buffer. - // Write directly from p to avoid copy. - n, b.err = b.wr.Write(p) - } else { - n = copy(b.buf[b.n:], p) - b.n += n - b.flush() - } - nn += n - p = p[n:] - } - if b.err != nil { - return nn, b.err - } - n := copy(b.buf[b.n:], p) - b.n += n - nn += n - return nn, nil -} - -// WriteByte writes a single byte. -func (b *Writer) WriteByte(c byte) error { - if b.err != nil { - return b.err - } - if b.Available() <= 0 && b.flush() != nil { - return b.err - } - b.buf[b.n] = c - b.n++ - return nil -} - -// WriteRune writes a single Unicode code point, returning -// the number of bytes written and any error. -func (b *Writer) WriteRune(r rune) (size int, err error) { - if r < utf8.RuneSelf { - err = b.WriteByte(byte(r)) - if err != nil { - return 0, err - } - return 1, nil - } - if b.err != nil { - return 0, b.err - } - n := b.Available() - if n < utf8.UTFMax { - if b.flush(); b.err != nil { - return 0, b.err - } - n = b.Available() - if n < utf8.UTFMax { - // Can only happen if buffer is silly small. - return b.WriteString(string(r)) - } - } - size = utf8.EncodeRune(b.buf[b.n:], r) - b.n += size - return size, nil -} - -// WriteString writes a string. -// It returns the number of bytes written. -// If the count is less than len(s), it also returns an error explaining -// why the write is short. -func (b *Writer) WriteString(s string) (int, error) { - nn := 0 - for len(s) > b.Available() && b.err == nil { - n := copy(b.buf[b.n:], s) - b.n += n - nn += n - s = s[n:] - b.flush() - } - if b.err != nil { - return nn, b.err - } - n := copy(b.buf[b.n:], s) - b.n += n - nn += n - return nn, nil -} - -// ReadFrom implements io.ReaderFrom. -func (b *Writer) ReadFrom(r io.Reader) (n int64, err error) { - if b.Buffered() == 0 { - if w, ok := b.wr.(io.ReaderFrom); ok { - return w.ReadFrom(r) - } - } - var m int - for { - if b.Available() == 0 { - if err1 := b.flush(); err1 != nil { - return n, err1 - } - } - nr := 0 - for nr < maxConsecutiveEmptyReads { - m, err = r.Read(b.buf[b.n:]) - if m != 0 || err != nil { - break - } - nr++ - } - if nr == maxConsecutiveEmptyReads { - return n, io.ErrNoProgress - } - b.n += m - n += int64(m) - if err != nil { - break - } - } - if err == io.EOF { - // If we filled the buffer exactly, flush pre-emptively. - if b.Available() == 0 { - err = b.flush() - } else { - err = nil - } - } - return n, err -} - -// buffered input and output - -// ReadWriter stores pointers to a Reader and a Writer. -// It implements io.ReadWriter. -type ReadWriter struct { - *Reader - *Writer -} - -// NewReadWriter allocates a new ReadWriter that dispatches to r and w. -func NewReadWriter(r *Reader, w *Writer) *ReadWriter { - return &ReadWriter{r, w} -} diff --git a/src/pkg/bufio/bufio_test.go b/src/pkg/bufio/bufio_test.go deleted file mode 100644 index 550dac917..000000000 --- a/src/pkg/bufio/bufio_test.go +++ /dev/null @@ -1,1426 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package bufio_test - -import ( - . "bufio" - "bytes" - "errors" - "fmt" - "io" - "io/ioutil" - "strings" - "testing" - "testing/iotest" - "time" - "unicode/utf8" -) - -// Reads from a reader and rot13s the result. -type rot13Reader struct { - r io.Reader -} - -func newRot13Reader(r io.Reader) *rot13Reader { - r13 := new(rot13Reader) - r13.r = r - return r13 -} - -func (r13 *rot13Reader) Read(p []byte) (int, error) { - n, err := r13.r.Read(p) - for i := 0; i < n; i++ { - c := p[i] | 0x20 // lowercase byte - if 'a' <= c && c <= 'm' { - p[i] += 13 - } else if 'n' <= c && c <= 'z' { - p[i] -= 13 - } - } - return n, err -} - -// Call ReadByte to accumulate the text of a file -func readBytes(buf *Reader) string { - var b [1000]byte - nb := 0 - for { - c, err := buf.ReadByte() - if err == io.EOF { - break - } - if err == nil { - b[nb] = c - nb++ - } else if err != iotest.ErrTimeout { - panic("Data: " + err.Error()) - } - } - return string(b[0:nb]) -} - -func TestReaderSimple(t *testing.T) { - data := "hello world" - b := NewReader(strings.NewReader(data)) - if s := readBytes(b); s != "hello world" { - t.Errorf("simple hello world test failed: got %q", s) - } - - b = NewReader(newRot13Reader(strings.NewReader(data))) - if s := readBytes(b); s != "uryyb jbeyq" { - t.Errorf("rot13 hello world test failed: got %q", s) - } -} - -type readMaker struct { - name string - fn func(io.Reader) io.Reader -} - -var readMakers = []readMaker{ - {"full", func(r io.Reader) io.Reader { return r }}, - {"byte", iotest.OneByteReader}, - {"half", iotest.HalfReader}, - {"data+err", iotest.DataErrReader}, - {"timeout", iotest.TimeoutReader}, -} - -// Call ReadString (which ends up calling everything else) -// to accumulate the text of a file. -func readLines(b *Reader) string { - s := "" - for { - s1, err := b.ReadString('\n') - if err == io.EOF { - break - } - if err != nil && err != iotest.ErrTimeout { - panic("GetLines: " + err.Error()) - } - s += s1 - } - return s -} - -// Call Read to accumulate the text of a file -func reads(buf *Reader, m int) string { - var b [1000]byte - nb := 0 - for { - n, err := buf.Read(b[nb : nb+m]) - nb += n - if err == io.EOF { - break - } - } - return string(b[0:nb]) -} - -type bufReader struct { - name string - fn func(*Reader) string -} - -var bufreaders = []bufReader{ - {"1", func(b *Reader) string { return reads(b, 1) }}, - {"2", func(b *Reader) string { return reads(b, 2) }}, - {"3", func(b *Reader) string { return reads(b, 3) }}, - {"4", func(b *Reader) string { return reads(b, 4) }}, - {"5", func(b *Reader) string { return reads(b, 5) }}, - {"7", func(b *Reader) string { return reads(b, 7) }}, - {"bytes", readBytes}, - {"lines", readLines}, -} - -const minReadBufferSize = 16 - -var bufsizes = []int{ - 0, minReadBufferSize, 23, 32, 46, 64, 93, 128, 1024, 4096, -} - -func TestReader(t *testing.T) { - var texts [31]string - str := "" - all := "" - for i := 0; i < len(texts)-1; i++ { - texts[i] = str + "\n" - all += texts[i] - str += string(i%26 + 'a') - } - texts[len(texts)-1] = all - - for h := 0; h < len(texts); h++ { - text := texts[h] - for i := 0; i < len(readMakers); i++ { - for j := 0; j < len(bufreaders); j++ { - for k := 0; k < len(bufsizes); k++ { - readmaker := readMakers[i] - bufreader := bufreaders[j] - bufsize := bufsizes[k] - read := readmaker.fn(strings.NewReader(text)) - buf := NewReaderSize(read, bufsize) - s := bufreader.fn(buf) - if s != text { - t.Errorf("reader=%s fn=%s bufsize=%d want=%q got=%q", - readmaker.name, bufreader.name, bufsize, text, s) - } - } - } - } - } -} - -type zeroReader struct{} - -func (zeroReader) Read(p []byte) (int, error) { - return 0, nil -} - -func TestZeroReader(t *testing.T) { - var z zeroReader - r := NewReader(z) - - c := make(chan error) - go func() { - _, err := r.ReadByte() - c <- err - }() - - select { - case err := <-c: - if err == nil { - t.Error("error expected") - } else if err != io.ErrNoProgress { - t.Error("unexpected error:", err) - } - case <-time.After(time.Second): - t.Error("test timed out (endless loop in ReadByte?)") - } -} - -// A StringReader delivers its data one string segment at a time via Read. -type StringReader struct { - data []string - step int -} - -func (r *StringReader) Read(p []byte) (n int, err error) { - if r.step < len(r.data) { - s := r.data[r.step] - n = copy(p, s) - r.step++ - } else { - err = io.EOF - } - return -} - -func readRuneSegments(t *testing.T, segments []string) { - got := "" - want := strings.Join(segments, "") - r := NewReader(&StringReader{data: segments}) - for { - r, _, err := r.ReadRune() - if err != nil { - if err != io.EOF { - return - } - break - } - got += string(r) - } - if got != want { - t.Errorf("segments=%v got=%s want=%s", segments, got, want) - } -} - -var segmentList = [][]string{ - {}, - {""}, - {"日", "本語"}, - {"\u65e5", "\u672c", "\u8a9e"}, - {"\U000065e5", "\U0000672c", "\U00008a9e"}, - {"\xe6", "\x97\xa5\xe6", "\x9c\xac\xe8\xaa\x9e"}, - {"Hello", ", ", "World", "!"}, - {"Hello", ", ", "", "World", "!"}, -} - -func TestReadRune(t *testing.T) { - for _, s := range segmentList { - readRuneSegments(t, s) - } -} - -func TestUnreadRune(t *testing.T) { - segments := []string{"Hello, world:", "日本語"} - r := NewReader(&StringReader{data: segments}) - got := "" - want := strings.Join(segments, "") - // Normal execution. - for { - r1, _, err := r.ReadRune() - if err != nil { - if err != io.EOF { - t.Error("unexpected error on ReadRune:", err) - } - break - } - got += string(r1) - // Put it back and read it again. - if err = r.UnreadRune(); err != nil { - t.Fatal("unexpected error on UnreadRune:", err) - } - r2, _, err := r.ReadRune() - if err != nil { - t.Fatal("unexpected error reading after unreading:", err) - } - if r1 != r2 { - t.Fatalf("incorrect rune after unread: got %c, want %c", r1, r2) - } - } - if got != want { - t.Errorf("got %q, want %q", got, want) - } -} - -func TestUnreadByte(t *testing.T) { - segments := []string{"Hello, ", "world"} - r := NewReader(&StringReader{data: segments}) - got := "" - want := strings.Join(segments, "") - // Normal execution. - for { - b1, err := r.ReadByte() - if err != nil { - if err != io.EOF { - t.Error("unexpected error on ReadByte:", err) - } - break - } - got += string(b1) - // Put it back and read it again. - if err = r.UnreadByte(); err != nil { - t.Fatal("unexpected error on UnreadByte:", err) - } - b2, err := r.ReadByte() - if err != nil { - t.Fatal("unexpected error reading after unreading:", err) - } - if b1 != b2 { - t.Fatalf("incorrect byte after unread: got %q, want %q", b1, b2) - } - } - if got != want { - t.Errorf("got %q, want %q", got, want) - } -} - -func TestUnreadByteMultiple(t *testing.T) { - segments := []string{"Hello, ", "world"} - data := strings.Join(segments, "") - for n := 0; n <= len(data); n++ { - r := NewReader(&StringReader{data: segments}) - // Read n bytes. - for i := 0; i < n; i++ { - b, err := r.ReadByte() - if err != nil { - t.Fatalf("n = %d: unexpected error on ReadByte: %v", n, err) - } - if b != data[i] { - t.Fatalf("n = %d: incorrect byte returned from ReadByte: got %q, want %q", n, b, data[i]) - } - } - // Unread one byte if there is one. - if n > 0 { - if err := r.UnreadByte(); err != nil { - t.Errorf("n = %d: unexpected error on UnreadByte: %v", n, err) - } - } - // Test that we cannot unread any further. - if err := r.UnreadByte(); err == nil { - t.Errorf("n = %d: expected error on UnreadByte", n) - } - } -} - -func TestUnreadByteOthers(t *testing.T) { - // A list of readers to use in conjunction with UnreadByte. - var readers = []func(*Reader, byte) ([]byte, error){ - (*Reader).ReadBytes, - (*Reader).ReadSlice, - func(r *Reader, delim byte) ([]byte, error) { - data, err := r.ReadString(delim) - return []byte(data), err - }, - // ReadLine doesn't fit the data/pattern easily - // so we leave it out. It should be covered via - // the ReadSlice test since ReadLine simply calls - // ReadSlice, and it's that function that handles - // the last byte. - } - - // Try all readers with UnreadByte. - for rno, read := range readers { - // Some input data that is longer than the minimum reader buffer size. - const n = 10 - var buf bytes.Buffer - for i := 0; i < n; i++ { - buf.WriteString("abcdefg") - } - - r := NewReaderSize(&buf, minReadBufferSize) - readTo := func(delim byte, want string) { - data, err := read(r, delim) - if err != nil { - t.Fatalf("#%d: unexpected error reading to %c: %v", rno, delim, err) - } - if got := string(data); got != want { - t.Fatalf("#%d: got %q, want %q", rno, got, want) - } - } - - // Read the data with occasional UnreadByte calls. - for i := 0; i < n; i++ { - readTo('d', "abcd") - for j := 0; j < 3; j++ { - if err := r.UnreadByte(); err != nil { - t.Fatalf("#%d: unexpected error on UnreadByte: %v", rno, err) - } - readTo('d', "d") - } - readTo('g', "efg") - } - - // All data should have been read. - _, err := r.ReadByte() - if err != io.EOF { - t.Errorf("#%d: got error %v; want EOF", rno, err) - } - } -} - -// Test that UnreadRune fails if the preceding operation was not a ReadRune. -func TestUnreadRuneError(t *testing.T) { - buf := make([]byte, 3) // All runes in this test are 3 bytes long - r := NewReader(&StringReader{data: []string{"日本語日本語日本語"}}) - if r.UnreadRune() == nil { - t.Error("expected error on UnreadRune from fresh buffer") - } - _, _, err := r.ReadRune() - if err != nil { - t.Error("unexpected error on ReadRune (1):", err) - } - if err = r.UnreadRune(); err != nil { - t.Error("unexpected error on UnreadRune (1):", err) - } - if r.UnreadRune() == nil { - t.Error("expected error after UnreadRune (1)") - } - // Test error after Read. - _, _, err = r.ReadRune() // reset state - if err != nil { - t.Error("unexpected error on ReadRune (2):", err) - } - _, err = r.Read(buf) - if err != nil { - t.Error("unexpected error on Read (2):", err) - } - if r.UnreadRune() == nil { - t.Error("expected error after Read (2)") - } - // Test error after ReadByte. - _, _, err = r.ReadRune() // reset state - if err != nil { - t.Error("unexpected error on ReadRune (2):", err) - } - for range buf { - _, err = r.ReadByte() - if err != nil { - t.Error("unexpected error on ReadByte (2):", err) - } - } - if r.UnreadRune() == nil { - t.Error("expected error after ReadByte") - } - // Test error after UnreadByte. - _, _, err = r.ReadRune() // reset state - if err != nil { - t.Error("unexpected error on ReadRune (3):", err) - } - _, err = r.ReadByte() - if err != nil { - t.Error("unexpected error on ReadByte (3):", err) - } - err = r.UnreadByte() - if err != nil { - t.Error("unexpected error on UnreadByte (3):", err) - } - if r.UnreadRune() == nil { - t.Error("expected error after UnreadByte (3)") - } - // Test error after ReadSlice. - _, _, err = r.ReadRune() // reset state - if err != nil { - t.Error("unexpected error on ReadRune (4):", err) - } - _, err = r.ReadSlice(0) - if err != io.EOF { - t.Error("unexpected error on ReadSlice (4):", err) - } - if r.UnreadRune() == nil { - t.Error("expected error after ReadSlice (4)") - } -} - -func TestUnreadRuneAtEOF(t *testing.T) { - // UnreadRune/ReadRune should error at EOF (was a bug; used to panic) - r := NewReader(strings.NewReader("x")) - r.ReadRune() - r.ReadRune() - r.UnreadRune() - _, _, err := r.ReadRune() - if err == nil { - t.Error("expected error at EOF") - } else if err != io.EOF { - t.Error("expected EOF; got", err) - } -} - -func TestReadWriteRune(t *testing.T) { - const NRune = 1000 - byteBuf := new(bytes.Buffer) - w := NewWriter(byteBuf) - // Write the runes out using WriteRune - buf := make([]byte, utf8.UTFMax) - for r := rune(0); r < NRune; r++ { - size := utf8.EncodeRune(buf, r) - nbytes, err := w.WriteRune(r) - if err != nil { - t.Fatalf("WriteRune(0x%x) error: %s", r, err) - } - if nbytes != size { - t.Fatalf("WriteRune(0x%x) expected %d, got %d", r, size, nbytes) - } - } - w.Flush() - - r := NewReader(byteBuf) - // Read them back with ReadRune - for r1 := rune(0); r1 < NRune; r1++ { - size := utf8.EncodeRune(buf, r1) - nr, nbytes, err := r.ReadRune() - if nr != r1 || nbytes != size || err != nil { - t.Fatalf("ReadRune(0x%x) got 0x%x,%d not 0x%x,%d (err=%s)", r1, nr, nbytes, r1, size, err) - } - } -} - -func TestWriter(t *testing.T) { - var data [8192]byte - - for i := 0; i < len(data); i++ { - data[i] = byte(' ' + i%('~'-' ')) - } - w := new(bytes.Buffer) - for i := 0; i < len(bufsizes); i++ { - for j := 0; j < len(bufsizes); j++ { - nwrite := bufsizes[i] - bs := bufsizes[j] - - // Write nwrite bytes using buffer size bs. - // Check that the right amount makes it out - // and that the data is correct. - - w.Reset() - buf := NewWriterSize(w, bs) - context := fmt.Sprintf("nwrite=%d bufsize=%d", nwrite, bs) - n, e1 := buf.Write(data[0:nwrite]) - if e1 != nil || n != nwrite { - t.Errorf("%s: buf.Write %d = %d, %v", context, nwrite, n, e1) - continue - } - if e := buf.Flush(); e != nil { - t.Errorf("%s: buf.Flush = %v", context, e) - } - - written := w.Bytes() - if len(written) != nwrite { - t.Errorf("%s: %d bytes written", context, len(written)) - } - for l := 0; l < len(written); l++ { - if written[i] != data[i] { - t.Errorf("wrong bytes written") - t.Errorf("want=%q", data[0:len(written)]) - t.Errorf("have=%q", written) - } - } - } - } -} - -// Check that write errors are returned properly. - -type errorWriterTest struct { - n, m int - err error - expect error -} - -func (w errorWriterTest) Write(p []byte) (int, error) { - return len(p) * w.n / w.m, w.err -} - -var errorWriterTests = []errorWriterTest{ - {0, 1, nil, io.ErrShortWrite}, - {1, 2, nil, io.ErrShortWrite}, - {1, 1, nil, nil}, - {0, 1, io.ErrClosedPipe, io.ErrClosedPipe}, - {1, 2, io.ErrClosedPipe, io.ErrClosedPipe}, - {1, 1, io.ErrClosedPipe, io.ErrClosedPipe}, -} - -func TestWriteErrors(t *testing.T) { - for _, w := range errorWriterTests { - buf := NewWriter(w) - _, e := buf.Write([]byte("hello world")) - if e != nil { - t.Errorf("Write hello to %v: %v", w, e) - continue - } - // Two flushes, to verify the error is sticky. - for i := 0; i < 2; i++ { - e = buf.Flush() - if e != w.expect { - t.Errorf("Flush %d/2 %v: got %v, wanted %v", i+1, w, e, w.expect) - } - } - } -} - -func TestNewReaderSizeIdempotent(t *testing.T) { - const BufSize = 1000 - b := NewReaderSize(strings.NewReader("hello world"), BufSize) - // Does it recognize itself? - b1 := NewReaderSize(b, BufSize) - if b1 != b { - t.Error("NewReaderSize did not detect underlying Reader") - } - // Does it wrap if existing buffer is too small? - b2 := NewReaderSize(b, 2*BufSize) - if b2 == b { - t.Error("NewReaderSize did not enlarge buffer") - } -} - -func TestNewWriterSizeIdempotent(t *testing.T) { - const BufSize = 1000 - b := NewWriterSize(new(bytes.Buffer), BufSize) - // Does it recognize itself? - b1 := NewWriterSize(b, BufSize) - if b1 != b { - t.Error("NewWriterSize did not detect underlying Writer") - } - // Does it wrap if existing buffer is too small? - b2 := NewWriterSize(b, 2*BufSize) - if b2 == b { - t.Error("NewWriterSize did not enlarge buffer") - } -} - -func TestWriteString(t *testing.T) { - const BufSize = 8 - buf := new(bytes.Buffer) - b := NewWriterSize(buf, BufSize) - b.WriteString("0") // easy - b.WriteString("123456") // still easy - b.WriteString("7890") // easy after flush - b.WriteString("abcdefghijklmnopqrstuvwxy") // hard - b.WriteString("z") - if err := b.Flush(); err != nil { - t.Error("WriteString", err) - } - s := "01234567890abcdefghijklmnopqrstuvwxyz" - if string(buf.Bytes()) != s { - t.Errorf("WriteString wants %q gets %q", s, string(buf.Bytes())) - } -} - -func TestBufferFull(t *testing.T) { - const longString = "And now, hello, world! It is the time for all good men to come to the aid of their party" - buf := NewReaderSize(strings.NewReader(longString), minReadBufferSize) - line, err := buf.ReadSlice('!') - if string(line) != "And now, hello, " || err != ErrBufferFull { - t.Errorf("first ReadSlice(,) = %q, %v", line, err) - } - line, err = buf.ReadSlice('!') - if string(line) != "world!" || err != nil { - t.Errorf("second ReadSlice(,) = %q, %v", line, err) - } -} - -func TestPeek(t *testing.T) { - p := make([]byte, 10) - // string is 16 (minReadBufferSize) long. - buf := NewReaderSize(strings.NewReader("abcdefghijklmnop"), minReadBufferSize) - if s, err := buf.Peek(1); string(s) != "a" || err != nil { - t.Fatalf("want %q got %q, err=%v", "a", string(s), err) - } - if s, err := buf.Peek(4); string(s) != "abcd" || err != nil { - t.Fatalf("want %q got %q, err=%v", "abcd", string(s), err) - } - if _, err := buf.Peek(-1); err != ErrNegativeCount { - t.Fatalf("want ErrNegativeCount got %v", err) - } - if _, err := buf.Peek(32); err != ErrBufferFull { - t.Fatalf("want ErrBufFull got %v", err) - } - if _, err := buf.Read(p[0:3]); string(p[0:3]) != "abc" || err != nil { - t.Fatalf("want %q got %q, err=%v", "abc", string(p[0:3]), err) - } - if s, err := buf.Peek(1); string(s) != "d" || err != nil { - t.Fatalf("want %q got %q, err=%v", "d", string(s), err) - } - if s, err := buf.Peek(2); string(s) != "de" || err != nil { - t.Fatalf("want %q got %q, err=%v", "de", string(s), err) - } - if _, err := buf.Read(p[0:3]); string(p[0:3]) != "def" || err != nil { - t.Fatalf("want %q got %q, err=%v", "def", string(p[0:3]), err) - } - if s, err := buf.Peek(4); string(s) != "ghij" || err != nil { - t.Fatalf("want %q got %q, err=%v", "ghij", string(s), err) - } - if _, err := buf.Read(p[0:]); string(p[0:]) != "ghijklmnop" || err != nil { - t.Fatalf("want %q got %q, err=%v", "ghijklmnop", string(p[0:minReadBufferSize]), err) - } - if s, err := buf.Peek(0); string(s) != "" || err != nil { - t.Fatalf("want %q got %q, err=%v", "", string(s), err) - } - if _, err := buf.Peek(1); err != io.EOF { - t.Fatalf("want EOF got %v", err) - } - - // Test for issue 3022, not exposing a reader's error on a successful Peek. - buf = NewReaderSize(dataAndEOFReader("abcd"), 32) - if s, err := buf.Peek(2); string(s) != "ab" || err != nil { - t.Errorf(`Peek(2) on "abcd", EOF = %q, %v; want "ab", nil`, string(s), err) - } - if s, err := buf.Peek(4); string(s) != "abcd" || err != nil { - t.Errorf(`Peek(4) on "abcd", EOF = %q, %v; want "abcd", nil`, string(s), err) - } - if n, err := buf.Read(p[0:5]); string(p[0:n]) != "abcd" || err != nil { - t.Fatalf("Read after peek = %q, %v; want abcd, EOF", p[0:n], err) - } - if n, err := buf.Read(p[0:1]); string(p[0:n]) != "" || err != io.EOF { - t.Fatalf(`second Read after peek = %q, %v; want "", EOF`, p[0:n], err) - } -} - -type dataAndEOFReader string - -func (r dataAndEOFReader) Read(p []byte) (int, error) { - return copy(p, r), io.EOF -} - -func TestPeekThenUnreadRune(t *testing.T) { - // This sequence used to cause a crash. - r := NewReader(strings.NewReader("x")) - r.ReadRune() - r.Peek(1) - r.UnreadRune() - r.ReadRune() // Used to panic here -} - -var testOutput = []byte("0123456789abcdefghijklmnopqrstuvwxy") -var testInput = []byte("012\n345\n678\n9ab\ncde\nfgh\nijk\nlmn\nopq\nrst\nuvw\nxy") -var testInputrn = []byte("012\r\n345\r\n678\r\n9ab\r\ncde\r\nfgh\r\nijk\r\nlmn\r\nopq\r\nrst\r\nuvw\r\nxy\r\n\n\r\n") - -// TestReader wraps a []byte and returns reads of a specific length. -type testReader struct { - data []byte - stride int -} - -func (t *testReader) Read(buf []byte) (n int, err error) { - n = t.stride - if n > len(t.data) { - n = len(t.data) - } - if n > len(buf) { - n = len(buf) - } - copy(buf, t.data) - t.data = t.data[n:] - if len(t.data) == 0 { - err = io.EOF - } - return -} - -func testReadLine(t *testing.T, input []byte) { - //for stride := 1; stride < len(input); stride++ { - for stride := 1; stride < 2; stride++ { - done := 0 - reader := testReader{input, stride} - l := NewReaderSize(&reader, len(input)+1) - for { - line, isPrefix, err := l.ReadLine() - if len(line) > 0 && err != nil { - t.Errorf("ReadLine returned both data and error: %s", err) - } - if isPrefix { - t.Errorf("ReadLine returned prefix") - } - if err != nil { - if err != io.EOF { - t.Fatalf("Got unknown error: %s", err) - } - break - } - if want := testOutput[done : done+len(line)]; !bytes.Equal(want, line) { - t.Errorf("Bad line at stride %d: want: %x got: %x", stride, want, line) - } - done += len(line) - } - if done != len(testOutput) { - t.Errorf("ReadLine didn't return everything: got: %d, want: %d (stride: %d)", done, len(testOutput), stride) - } - } -} - -func TestReadLine(t *testing.T) { - testReadLine(t, testInput) - testReadLine(t, testInputrn) -} - -func TestLineTooLong(t *testing.T) { - data := make([]byte, 0) - for i := 0; i < minReadBufferSize*5/2; i++ { - data = append(data, '0'+byte(i%10)) - } - buf := bytes.NewReader(data) - l := NewReaderSize(buf, minReadBufferSize) - line, isPrefix, err := l.ReadLine() - if !isPrefix || !bytes.Equal(line, data[:minReadBufferSize]) || err != nil { - t.Errorf("bad result for first line: got %q want %q %v", line, data[:minReadBufferSize], err) - } - data = data[len(line):] - line, isPrefix, err = l.ReadLine() - if !isPrefix || !bytes.Equal(line, data[:minReadBufferSize]) || err != nil { - t.Errorf("bad result for second line: got %q want %q %v", line, data[:minReadBufferSize], err) - } - data = data[len(line):] - line, isPrefix, err = l.ReadLine() - if isPrefix || !bytes.Equal(line, data[:minReadBufferSize/2]) || err != nil { - t.Errorf("bad result for third line: got %q want %q %v", line, data[:minReadBufferSize/2], err) - } - line, isPrefix, err = l.ReadLine() - if isPrefix || err == nil { - t.Errorf("expected no more lines: %x %s", line, err) - } -} - -func TestReadAfterLines(t *testing.T) { - line1 := "this is line1" - restData := "this is line2\nthis is line 3\n" - inbuf := bytes.NewReader([]byte(line1 + "\n" + restData)) - outbuf := new(bytes.Buffer) - maxLineLength := len(line1) + len(restData)/2 - l := NewReaderSize(inbuf, maxLineLength) - line, isPrefix, err := l.ReadLine() - if isPrefix || err != nil || string(line) != line1 { - t.Errorf("bad result for first line: isPrefix=%v err=%v line=%q", isPrefix, err, string(line)) - } - n, err := io.Copy(outbuf, l) - if int(n) != len(restData) || err != nil { - t.Errorf("bad result for Read: n=%d err=%v", n, err) - } - if outbuf.String() != restData { - t.Errorf("bad result for Read: got %q; expected %q", outbuf.String(), restData) - } -} - -func TestReadEmptyBuffer(t *testing.T) { - l := NewReaderSize(new(bytes.Buffer), minReadBufferSize) - line, isPrefix, err := l.ReadLine() - if err != io.EOF { - t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err) - } -} - -func TestLinesAfterRead(t *testing.T) { - l := NewReaderSize(bytes.NewReader([]byte("foo")), minReadBufferSize) - _, err := ioutil.ReadAll(l) - if err != nil { - t.Error(err) - return - } - - line, isPrefix, err := l.ReadLine() - if err != io.EOF { - t.Errorf("expected EOF from ReadLine, got '%s' %t %s", line, isPrefix, err) - } -} - -func TestReadLineNonNilLineOrError(t *testing.T) { - r := NewReader(strings.NewReader("line 1\n")) - for i := 0; i < 2; i++ { - l, _, err := r.ReadLine() - if l != nil && err != nil { - t.Fatalf("on line %d/2; ReadLine=%#v, %v; want non-nil line or Error, but not both", - i+1, l, err) - } - } -} - -type readLineResult struct { - line []byte - isPrefix bool - err error -} - -var readLineNewlinesTests = []struct { - input string - expect []readLineResult -}{ - {"012345678901234\r\n012345678901234\r\n", []readLineResult{ - {[]byte("012345678901234"), true, nil}, - {nil, false, nil}, - {[]byte("012345678901234"), true, nil}, - {nil, false, nil}, - {nil, false, io.EOF}, - }}, - {"0123456789012345\r012345678901234\r", []readLineResult{ - {[]byte("0123456789012345"), true, nil}, - {[]byte("\r012345678901234"), true, nil}, - {[]byte("\r"), false, nil}, - {nil, false, io.EOF}, - }}, -} - -func TestReadLineNewlines(t *testing.T) { - for _, e := range readLineNewlinesTests { - testReadLineNewlines(t, e.input, e.expect) - } -} - -func testReadLineNewlines(t *testing.T, input string, expect []readLineResult) { - b := NewReaderSize(strings.NewReader(input), minReadBufferSize) - for i, e := range expect { - line, isPrefix, err := b.ReadLine() - if !bytes.Equal(line, e.line) { - t.Errorf("%q call %d, line == %q, want %q", input, i, line, e.line) - return - } - if isPrefix != e.isPrefix { - t.Errorf("%q call %d, isPrefix == %v, want %v", input, i, isPrefix, e.isPrefix) - return - } - if err != e.err { - t.Errorf("%q call %d, err == %v, want %v", input, i, err, e.err) - return - } - } -} - -func createTestInput(n int) []byte { - input := make([]byte, n) - for i := range input { - // 101 and 251 are arbitrary prime numbers. - // The idea is to create an input sequence - // which doesn't repeat too frequently. - input[i] = byte(i % 251) - if i%101 == 0 { - input[i] ^= byte(i / 101) - } - } - return input -} - -func TestReaderWriteTo(t *testing.T) { - input := createTestInput(8192) - r := NewReader(onlyReader{bytes.NewReader(input)}) - w := new(bytes.Buffer) - if n, err := r.WriteTo(w); err != nil || n != int64(len(input)) { - t.Fatalf("r.WriteTo(w) = %d, %v, want %d, nil", n, err, len(input)) - } - - for i, val := range w.Bytes() { - if val != input[i] { - t.Errorf("after write: out[%d] = %#x, want %#x", i, val, input[i]) - } - } -} - -type errorWriterToTest struct { - rn, wn int - rerr, werr error - expected error -} - -func (r errorWriterToTest) Read(p []byte) (int, error) { - return len(p) * r.rn, r.rerr -} - -func (w errorWriterToTest) Write(p []byte) (int, error) { - return len(p) * w.wn, w.werr -} - -var errorWriterToTests = []errorWriterToTest{ - {1, 0, nil, io.ErrClosedPipe, io.ErrClosedPipe}, - {0, 1, io.ErrClosedPipe, nil, io.ErrClosedPipe}, - {0, 0, io.ErrUnexpectedEOF, io.ErrClosedPipe, io.ErrClosedPipe}, - {0, 1, io.EOF, nil, nil}, -} - -func TestReaderWriteToErrors(t *testing.T) { - for i, rw := range errorWriterToTests { - r := NewReader(rw) - if _, err := r.WriteTo(rw); err != rw.expected { - t.Errorf("r.WriteTo(errorWriterToTests[%d]) = _, %v, want _,%v", i, err, rw.expected) - } - } -} - -func TestWriterReadFrom(t *testing.T) { - ws := []func(io.Writer) io.Writer{ - func(w io.Writer) io.Writer { return onlyWriter{w} }, - func(w io.Writer) io.Writer { return w }, - } - - rs := []func(io.Reader) io.Reader{ - iotest.DataErrReader, - func(r io.Reader) io.Reader { return r }, - } - - for ri, rfunc := range rs { - for wi, wfunc := range ws { - input := createTestInput(8192) - b := new(bytes.Buffer) - w := NewWriter(wfunc(b)) - r := rfunc(bytes.NewReader(input)) - if n, err := w.ReadFrom(r); err != nil || n != int64(len(input)) { - t.Errorf("ws[%d],rs[%d]: w.ReadFrom(r) = %d, %v, want %d, nil", wi, ri, n, err, len(input)) - continue - } - if err := w.Flush(); err != nil { - t.Errorf("Flush returned %v", err) - continue - } - if got, want := b.String(), string(input); got != want { - t.Errorf("ws[%d], rs[%d]:\ngot %q\nwant %q\n", wi, ri, got, want) - } - } - } -} - -type errorReaderFromTest struct { - rn, wn int - rerr, werr error - expected error -} - -func (r errorReaderFromTest) Read(p []byte) (int, error) { - return len(p) * r.rn, r.rerr -} - -func (w errorReaderFromTest) Write(p []byte) (int, error) { - return len(p) * w.wn, w.werr -} - -var errorReaderFromTests = []errorReaderFromTest{ - {0, 1, io.EOF, nil, nil}, - {1, 1, io.EOF, nil, nil}, - {0, 1, io.ErrClosedPipe, nil, io.ErrClosedPipe}, - {0, 0, io.ErrClosedPipe, io.ErrShortWrite, io.ErrClosedPipe}, - {1, 0, nil, io.ErrShortWrite, io.ErrShortWrite}, -} - -func TestWriterReadFromErrors(t *testing.T) { - for i, rw := range errorReaderFromTests { - w := NewWriter(rw) - if _, err := w.ReadFrom(rw); err != rw.expected { - t.Errorf("w.ReadFrom(errorReaderFromTests[%d]) = _, %v, want _,%v", i, err, rw.expected) - } - } -} - -// TestWriterReadFromCounts tests that using io.Copy to copy into a -// bufio.Writer does not prematurely flush the buffer. For example, when -// buffering writes to a network socket, excessive network writes should be -// avoided. -func TestWriterReadFromCounts(t *testing.T) { - var w0 writeCountingDiscard - b0 := NewWriterSize(&w0, 1234) - b0.WriteString(strings.Repeat("x", 1000)) - if w0 != 0 { - t.Fatalf("write 1000 'x's: got %d writes, want 0", w0) - } - b0.WriteString(strings.Repeat("x", 200)) - if w0 != 0 { - t.Fatalf("write 1200 'x's: got %d writes, want 0", w0) - } - io.Copy(b0, onlyReader{strings.NewReader(strings.Repeat("x", 30))}) - if w0 != 0 { - t.Fatalf("write 1230 'x's: got %d writes, want 0", w0) - } - io.Copy(b0, onlyReader{strings.NewReader(strings.Repeat("x", 9))}) - if w0 != 1 { - t.Fatalf("write 1239 'x's: got %d writes, want 1", w0) - } - - var w1 writeCountingDiscard - b1 := NewWriterSize(&w1, 1234) - b1.WriteString(strings.Repeat("x", 1200)) - b1.Flush() - if w1 != 1 { - t.Fatalf("flush 1200 'x's: got %d writes, want 1", w1) - } - b1.WriteString(strings.Repeat("x", 89)) - if w1 != 1 { - t.Fatalf("write 1200 + 89 'x's: got %d writes, want 1", w1) - } - io.Copy(b1, onlyReader{strings.NewReader(strings.Repeat("x", 700))}) - if w1 != 1 { - t.Fatalf("write 1200 + 789 'x's: got %d writes, want 1", w1) - } - io.Copy(b1, onlyReader{strings.NewReader(strings.Repeat("x", 600))}) - if w1 != 2 { - t.Fatalf("write 1200 + 1389 'x's: got %d writes, want 2", w1) - } - b1.Flush() - if w1 != 3 { - t.Fatalf("flush 1200 + 1389 'x's: got %d writes, want 3", w1) - } -} - -// A writeCountingDiscard is like ioutil.Discard and counts the number of times -// Write is called on it. -type writeCountingDiscard int - -func (w *writeCountingDiscard) Write(p []byte) (int, error) { - *w++ - return len(p), nil -} - -type negativeReader int - -func (r *negativeReader) Read([]byte) (int, error) { return -1, nil } - -func TestNegativeRead(t *testing.T) { - // should panic with a description pointing at the reader, not at itself. - // (should NOT panic with slice index error, for example.) - b := NewReader(new(negativeReader)) - defer func() { - switch err := recover().(type) { - case nil: - t.Fatal("read did not panic") - case error: - if !strings.Contains(err.Error(), "reader returned negative count from Read") { - t.Fatalf("wrong panic: %v", err) - } - default: - t.Fatalf("unexpected panic value: %T(%v)", err, err) - } - }() - b.Read(make([]byte, 100)) -} - -var errFake = errors.New("fake error") - -type errorThenGoodReader struct { - didErr bool - nread int -} - -func (r *errorThenGoodReader) Read(p []byte) (int, error) { - r.nread++ - if !r.didErr { - r.didErr = true - return 0, errFake - } - return len(p), nil -} - -func TestReaderClearError(t *testing.T) { - r := &errorThenGoodReader{} - b := NewReader(r) - buf := make([]byte, 1) - if _, err := b.Read(nil); err != nil { - t.Fatalf("1st nil Read = %v; want nil", err) - } - if _, err := b.Read(buf); err != errFake { - t.Fatalf("1st Read = %v; want errFake", err) - } - if _, err := b.Read(nil); err != nil { - t.Fatalf("2nd nil Read = %v; want nil", err) - } - if _, err := b.Read(buf); err != nil { - t.Fatalf("3rd Read with buffer = %v; want nil", err) - } - if r.nread != 2 { - t.Errorf("num reads = %d; want 2", r.nread) - } -} - -// Test for golang.org/issue/5947 -func TestWriterReadFromWhileFull(t *testing.T) { - buf := new(bytes.Buffer) - w := NewWriterSize(buf, 10) - - // Fill buffer exactly. - n, err := w.Write([]byte("0123456789")) - if n != 10 || err != nil { - t.Fatalf("Write returned (%v, %v), want (10, nil)", n, err) - } - - // Use ReadFrom to read in some data. - n2, err := w.ReadFrom(strings.NewReader("abcdef")) - if n2 != 6 || err != nil { - t.Fatalf("ReadFrom returned (%v, %v), want (6, nil)", n2, err) - } -} - -type emptyThenNonEmptyReader struct { - r io.Reader - n int -} - -func (r *emptyThenNonEmptyReader) Read(p []byte) (int, error) { - if r.n <= 0 { - return r.r.Read(p) - } - r.n-- - return 0, nil -} - -// Test for golang.org/issue/7611 -func TestWriterReadFromUntilEOF(t *testing.T) { - buf := new(bytes.Buffer) - w := NewWriterSize(buf, 5) - - // Partially fill buffer - n, err := w.Write([]byte("0123")) - if n != 4 || err != nil { - t.Fatalf("Write returned (%v, %v), want (4, nil)", n, err) - } - - // Use ReadFrom to read in some data. - r := &emptyThenNonEmptyReader{r: strings.NewReader("abcd"), n: 3} - n2, err := w.ReadFrom(r) - if n2 != 4 || err != nil { - t.Fatalf("ReadFrom returned (%v, %v), want (4, nil)", n2, err) - } - w.Flush() - if got, want := string(buf.Bytes()), "0123abcd"; got != want { - t.Fatalf("buf.Bytes() returned %q, want %q", got, want) - } -} - -func TestWriterReadFromErrNoProgress(t *testing.T) { - buf := new(bytes.Buffer) - w := NewWriterSize(buf, 5) - - // Partially fill buffer - n, err := w.Write([]byte("0123")) - if n != 4 || err != nil { - t.Fatalf("Write returned (%v, %v), want (4, nil)", n, err) - } - - // Use ReadFrom to read in some data. - r := &emptyThenNonEmptyReader{r: strings.NewReader("abcd"), n: 100} - n2, err := w.ReadFrom(r) - if n2 != 0 || err != io.ErrNoProgress { - t.Fatalf("buf.Bytes() returned (%v, %v), want (0, io.ErrNoProgress)", n2, err) - } -} - -func TestReaderReset(t *testing.T) { - r := NewReader(strings.NewReader("foo foo")) - buf := make([]byte, 3) - r.Read(buf) - if string(buf) != "foo" { - t.Errorf("buf = %q; want foo", buf) - } - r.Reset(strings.NewReader("bar bar")) - all, err := ioutil.ReadAll(r) - if err != nil { - t.Fatal(err) - } - if string(all) != "bar bar" { - t.Errorf("ReadAll = %q; want bar bar", all) - } -} - -func TestWriterReset(t *testing.T) { - var buf1, buf2 bytes.Buffer - w := NewWriter(&buf1) - w.WriteString("foo") - w.Reset(&buf2) // and not flushed - w.WriteString("bar") - w.Flush() - if buf1.String() != "" { - t.Errorf("buf1 = %q; want empty", buf1.String()) - } - if buf2.String() != "bar" { - t.Errorf("buf2 = %q; want bar", buf2.String()) - } -} - -// An onlyReader only implements io.Reader, no matter what other methods the underlying implementation may have. -type onlyReader struct { - io.Reader -} - -// An onlyWriter only implements io.Writer, no matter what other methods the underlying implementation may have. -type onlyWriter struct { - io.Writer -} - -func BenchmarkReaderCopyOptimal(b *testing.B) { - // Optimal case is where the underlying reader implements io.WriterTo - srcBuf := bytes.NewBuffer(make([]byte, 8192)) - src := NewReader(srcBuf) - dstBuf := new(bytes.Buffer) - dst := onlyWriter{dstBuf} - for i := 0; i < b.N; i++ { - srcBuf.Reset() - src.Reset(srcBuf) - dstBuf.Reset() - io.Copy(dst, src) - } -} - -func BenchmarkReaderCopyUnoptimal(b *testing.B) { - // Unoptimal case is where the underlying reader doesn't implement io.WriterTo - srcBuf := bytes.NewBuffer(make([]byte, 8192)) - src := NewReader(onlyReader{srcBuf}) - dstBuf := new(bytes.Buffer) - dst := onlyWriter{dstBuf} - for i := 0; i < b.N; i++ { - srcBuf.Reset() - src.Reset(onlyReader{srcBuf}) - dstBuf.Reset() - io.Copy(dst, src) - } -} - -func BenchmarkReaderCopyNoWriteTo(b *testing.B) { - srcBuf := bytes.NewBuffer(make([]byte, 8192)) - srcReader := NewReader(srcBuf) - src := onlyReader{srcReader} - dstBuf := new(bytes.Buffer) - dst := onlyWriter{dstBuf} - for i := 0; i < b.N; i++ { - srcBuf.Reset() - srcReader.Reset(srcBuf) - dstBuf.Reset() - io.Copy(dst, src) - } -} - -func BenchmarkReaderWriteToOptimal(b *testing.B) { - const bufSize = 16 << 10 - buf := make([]byte, bufSize) - r := bytes.NewReader(buf) - srcReader := NewReaderSize(onlyReader{r}, 1<<10) - if _, ok := ioutil.Discard.(io.ReaderFrom); !ok { - b.Fatal("ioutil.Discard doesn't support ReaderFrom") - } - for i := 0; i < b.N; i++ { - r.Seek(0, 0) - srcReader.Reset(onlyReader{r}) - n, err := srcReader.WriteTo(ioutil.Discard) - if err != nil { - b.Fatal(err) - } - if n != bufSize { - b.Fatalf("n = %d; want %d", n, bufSize) - } - } -} - -func BenchmarkWriterCopyOptimal(b *testing.B) { - // Optimal case is where the underlying writer implements io.ReaderFrom - srcBuf := bytes.NewBuffer(make([]byte, 8192)) - src := onlyReader{srcBuf} - dstBuf := new(bytes.Buffer) - dst := NewWriter(dstBuf) - for i := 0; i < b.N; i++ { - srcBuf.Reset() - dstBuf.Reset() - dst.Reset(dstBuf) - io.Copy(dst, src) - } -} - -func BenchmarkWriterCopyUnoptimal(b *testing.B) { - srcBuf := bytes.NewBuffer(make([]byte, 8192)) - src := onlyReader{srcBuf} - dstBuf := new(bytes.Buffer) - dst := NewWriter(onlyWriter{dstBuf}) - for i := 0; i < b.N; i++ { - srcBuf.Reset() - dstBuf.Reset() - dst.Reset(onlyWriter{dstBuf}) - io.Copy(dst, src) - } -} - -func BenchmarkWriterCopyNoReadFrom(b *testing.B) { - srcBuf := bytes.NewBuffer(make([]byte, 8192)) - src := onlyReader{srcBuf} - dstBuf := new(bytes.Buffer) - dstWriter := NewWriter(dstBuf) - dst := onlyWriter{dstWriter} - for i := 0; i < b.N; i++ { - srcBuf.Reset() - dstBuf.Reset() - dstWriter.Reset(dstBuf) - io.Copy(dst, src) - } -} - -func BenchmarkReaderEmpty(b *testing.B) { - b.ReportAllocs() - str := strings.Repeat("x", 16<<10) - for i := 0; i < b.N; i++ { - br := NewReader(strings.NewReader(str)) - n, err := io.Copy(ioutil.Discard, br) - if err != nil { - b.Fatal(err) - } - if n != int64(len(str)) { - b.Fatal("wrong length") - } - } -} - -func BenchmarkWriterEmpty(b *testing.B) { - b.ReportAllocs() - str := strings.Repeat("x", 1<<10) - bs := []byte(str) - for i := 0; i < b.N; i++ { - bw := NewWriter(ioutil.Discard) - bw.Flush() - bw.WriteByte('a') - bw.Flush() - bw.WriteRune('B') - bw.Flush() - bw.Write(bs) - bw.Flush() - bw.WriteString(str) - bw.Flush() - } -} - -func BenchmarkWriterFlush(b *testing.B) { - b.ReportAllocs() - bw := NewWriter(ioutil.Discard) - str := strings.Repeat("x", 50) - for i := 0; i < b.N; i++ { - bw.WriteString(str) - bw.Flush() - } -} diff --git a/src/pkg/bufio/example_test.go b/src/pkg/bufio/example_test.go deleted file mode 100644 index 3da914142..000000000 --- a/src/pkg/bufio/example_test.go +++ /dev/null @@ -1,82 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package bufio_test - -import ( - "bufio" - "fmt" - "os" - "strconv" - "strings" -) - -func ExampleWriter() { - w := bufio.NewWriter(os.Stdout) - fmt.Fprint(w, "Hello, ") - fmt.Fprint(w, "world!") - w.Flush() // Don't forget to flush! - // Output: Hello, world! -} - -// The simplest use of a Scanner, to read standard input as a set of lines. -func ExampleScanner_lines() { - scanner := bufio.NewScanner(os.Stdin) - for scanner.Scan() { - fmt.Println(scanner.Text()) // Println will add back the final '\n' - } - if err := scanner.Err(); err != nil { - fmt.Fprintln(os.Stderr, "reading standard input:", err) - } -} - -// Use a Scanner to implement a simple word-count utility by scanning the -// input as a sequence of space-delimited tokens. -func ExampleScanner_words() { - // An artificial input source. - const input = "Now is the winter of our discontent,\nMade glorious summer by this sun of York.\n" - scanner := bufio.NewScanner(strings.NewReader(input)) - // Set the split function for the scanning operation. - scanner.Split(bufio.ScanWords) - // Count the words. - count := 0 - for scanner.Scan() { - count++ - } - if err := scanner.Err(); err != nil { - fmt.Fprintln(os.Stderr, "reading input:", err) - } - fmt.Printf("%d\n", count) - // Output: 15 -} - -// Use a Scanner with a custom split function (built by wrapping ScanWords) to validate -// 32-bit decimal input. -func ExampleScanner_custom() { - // An artificial input source. - const input = "1234 5678 1234567901234567890" - scanner := bufio.NewScanner(strings.NewReader(input)) - // Create a custom split function by wrapping the existing ScanWords function. - split := func(data []byte, atEOF bool) (advance int, token []byte, err error) { - advance, token, err = bufio.ScanWords(data, atEOF) - if err == nil && token != nil { - _, err = strconv.ParseInt(string(token), 10, 32) - } - return - } - // Set the split function for the scanning operation. - scanner.Split(split) - // Validate the input - for scanner.Scan() { - fmt.Printf("%s\n", scanner.Text()) - } - - if err := scanner.Err(); err != nil { - fmt.Printf("Invalid input: %s", err) - } - // Output: - // 1234 - // 5678 - // Invalid input: strconv.ParseInt: parsing "1234567901234567890": value out of range -} diff --git a/src/pkg/bufio/export_test.go b/src/pkg/bufio/export_test.go deleted file mode 100644 index 3d3bb27d8..000000000 --- a/src/pkg/bufio/export_test.go +++ /dev/null @@ -1,27 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package bufio - -// Exported for testing only. -import ( - "unicode/utf8" -) - -var IsSpace = isSpace - -func (s *Scanner) MaxTokenSize(n int) { - if n < utf8.UTFMax || n > 1e9 { - panic("bad max token size") - } - if n < len(s.buf) { - s.buf = make([]byte, n) - } - s.maxTokenSize = n -} - -// ErrOrEOF is like Err, but returns EOF. Used to test a corner case. -func (s *Scanner) ErrOrEOF() error { - return s.err -} diff --git a/src/pkg/bufio/scan.go b/src/pkg/bufio/scan.go deleted file mode 100644 index c5714f331..000000000 --- a/src/pkg/bufio/scan.go +++ /dev/null @@ -1,344 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package bufio - -import ( - "bytes" - "errors" - "io" - "unicode/utf8" -) - -// Scanner provides a convenient interface for reading data such as -// a file of newline-delimited lines of text. Successive calls to -// the Scan method will step through the 'tokens' of a file, skipping -// the bytes between the tokens. The specification of a token is -// defined by a split function of type SplitFunc; the default split -// function breaks the input into lines with line termination stripped. Split -// functions are defined in this package for scanning a file into -// lines, bytes, UTF-8-encoded runes, and space-delimited words. The -// client may instead provide a custom split function. -// -// Scanning stops unrecoverably at EOF, the first I/O error, or a token too -// large to fit in the buffer. When a scan stops, the reader may have -// advanced arbitrarily far past the last token. Programs that need more -// control over error handling or large tokens, or must run sequential scans -// on a reader, should use bufio.Reader instead. -// -type Scanner struct { - r io.Reader // The reader provided by the client. - split SplitFunc // The function to split the tokens. - maxTokenSize int // Maximum size of a token; modified by tests. - token []byte // Last token returned by split. - buf []byte // Buffer used as argument to split. - start int // First non-processed byte in buf. - end int // End of data in buf. - err error // Sticky error. -} - -// SplitFunc is the signature of the split function used to tokenize the -// input. The arguments are an initial substring of the remaining unprocessed -// data and a flag, atEOF, that reports whether the Reader has no more data -// to give. The return values are the number of bytes to advance the input -// and the next token to return to the user, plus an error, if any. If the -// data does not yet hold a complete token, for instance if it has no newline -// while scanning lines, SplitFunc can return (0, nil, nil) to signal the -// Scanner to read more data into the slice and try again with a longer slice -// starting at the same point in the input. -// -// If the returned error is non-nil, scanning stops and the error -// is returned to the client. -// -// The function is never called with an empty data slice unless atEOF -// is true. If atEOF is true, however, data may be non-empty and, -// as always, holds unprocessed text. -type SplitFunc func(data []byte, atEOF bool) (advance int, token []byte, err error) - -// Errors returned by Scanner. -var ( - ErrTooLong = errors.New("bufio.Scanner: token too long") - ErrNegativeAdvance = errors.New("bufio.Scanner: SplitFunc returns negative advance count") - ErrAdvanceTooFar = errors.New("bufio.Scanner: SplitFunc returns advance count beyond input") -) - -const ( - // MaxScanTokenSize is the maximum size used to buffer a token. - // The actual maximum token size may be smaller as the buffer - // may need to include, for instance, a newline. - MaxScanTokenSize = 64 * 1024 -) - -// NewScanner returns a new Scanner to read from r. -// The split function defaults to ScanLines. -func NewScanner(r io.Reader) *Scanner { - return &Scanner{ - r: r, - split: ScanLines, - maxTokenSize: MaxScanTokenSize, - buf: make([]byte, 4096), // Plausible starting size; needn't be large. - } -} - -// Err returns the first non-EOF error that was encountered by the Scanner. -func (s *Scanner) Err() error { - if s.err == io.EOF { - return nil - } - return s.err -} - -// Bytes returns the most recent token generated by a call to Scan. -// The underlying array may point to data that will be overwritten -// by a subsequent call to Scan. It does no allocation. -func (s *Scanner) Bytes() []byte { - return s.token -} - -// Text returns the most recent token generated by a call to Scan -// as a newly allocated string holding its bytes. -func (s *Scanner) Text() string { - return string(s.token) -} - -// Scan advances the Scanner to the next token, which will then be -// available through the Bytes or Text method. It returns false when the -// scan stops, either by reaching the end of the input or an error. -// After Scan returns false, the Err method will return any error that -// occurred during scanning, except that if it was io.EOF, Err -// will return nil. -func (s *Scanner) Scan() bool { - // Loop until we have a token. - for { - // See if we can get a token with what we already have. - if s.end > s.start { - advance, token, err := s.split(s.buf[s.start:s.end], s.err != nil) - if err != nil { - s.setErr(err) - return false - } - if !s.advance(advance) { - return false - } - s.token = token - if token != nil { - return true - } - } - // We cannot generate a token with what we are holding. - // If we've already hit EOF or an I/O error, we are done. - if s.err != nil { - // Shut it down. - s.start = 0 - s.end = 0 - return false - } - // Must read more data. - // First, shift data to beginning of buffer if there's lots of empty space - // or space is needed. - if s.start > 0 && (s.end == len(s.buf) || s.start > len(s.buf)/2) { - copy(s.buf, s.buf[s.start:s.end]) - s.end -= s.start - s.start = 0 - } - // Is the buffer full? If so, resize. - if s.end == len(s.buf) { - if len(s.buf) >= s.maxTokenSize { - s.setErr(ErrTooLong) - return false - } - newSize := len(s.buf) * 2 - if newSize > s.maxTokenSize { - newSize = s.maxTokenSize - } - newBuf := make([]byte, newSize) - copy(newBuf, s.buf[s.start:s.end]) - s.buf = newBuf - s.end -= s.start - s.start = 0 - continue - } - // Finally we can read some input. Make sure we don't get stuck with - // a misbehaving Reader. Officially we don't need to do this, but let's - // be extra careful: Scanner is for safe, simple jobs. - for loop := 0; ; { - n, err := s.r.Read(s.buf[s.end:len(s.buf)]) - s.end += n - if err != nil { - s.setErr(err) - break - } - if n > 0 { - break - } - loop++ - if loop > maxConsecutiveEmptyReads { - s.setErr(io.ErrNoProgress) - break - } - } - } -} - -// advance consumes n bytes of the buffer. It reports whether the advance was legal. -func (s *Scanner) advance(n int) bool { - if n < 0 { - s.setErr(ErrNegativeAdvance) - return false - } - if n > s.end-s.start { - s.setErr(ErrAdvanceTooFar) - return false - } - s.start += n - return true -} - -// setErr records the first error encountered. -func (s *Scanner) setErr(err error) { - if s.err == nil || s.err == io.EOF { - s.err = err - } -} - -// Split sets the split function for the Scanner. If called, it must be -// called before Scan. The default split function is ScanLines. -func (s *Scanner) Split(split SplitFunc) { - s.split = split -} - -// Split functions - -// ScanBytes is a split function for a Scanner that returns each byte as a token. -func ScanBytes(data []byte, atEOF bool) (advance int, token []byte, err error) { - if atEOF && len(data) == 0 { - return 0, nil, nil - } - return 1, data[0:1], nil -} - -var errorRune = []byte(string(utf8.RuneError)) - -// ScanRunes is a split function for a Scanner that returns each -// UTF-8-encoded rune as a token. The sequence of runes returned is -// equivalent to that from a range loop over the input as a string, which -// means that erroneous UTF-8 encodings translate to U+FFFD = "\xef\xbf\xbd". -// Because of the Scan interface, this makes it impossible for the client to -// distinguish correctly encoded replacement runes from encoding errors. -func ScanRunes(data []byte, atEOF bool) (advance int, token []byte, err error) { - if atEOF && len(data) == 0 { - return 0, nil, nil - } - - // Fast path 1: ASCII. - if data[0] < utf8.RuneSelf { - return 1, data[0:1], nil - } - - // Fast path 2: Correct UTF-8 decode without error. - _, width := utf8.DecodeRune(data) - if width > 1 { - // It's a valid encoding. Width cannot be one for a correctly encoded - // non-ASCII rune. - return width, data[0:width], nil - } - - // We know it's an error: we have width==1 and implicitly r==utf8.RuneError. - // Is the error because there wasn't a full rune to be decoded? - // FullRune distinguishes correctly between erroneous and incomplete encodings. - if !atEOF && !utf8.FullRune(data) { - // Incomplete; get more bytes. - return 0, nil, nil - } - - // We have a real UTF-8 encoding error. Return a properly encoded error rune - // but advance only one byte. This matches the behavior of a range loop over - // an incorrectly encoded string. - return 1, errorRune, nil -} - -// dropCR drops a terminal \r from the data. -func dropCR(data []byte) []byte { - if len(data) > 0 && data[len(data)-1] == '\r' { - return data[0 : len(data)-1] - } - return data -} - -// ScanLines is a split function for a Scanner that returns each line of -// text, stripped of any trailing end-of-line marker. The returned line may -// be empty. The end-of-line marker is one optional carriage return followed -// by one mandatory newline. In regular expression notation, it is `\r?\n`. -// The last non-empty line of input will be returned even if it has no -// newline. -func ScanLines(data []byte, atEOF bool) (advance int, token []byte, err error) { - if atEOF && len(data) == 0 { - return 0, nil, nil - } - if i := bytes.IndexByte(data, '\n'); i >= 0 { - // We have a full newline-terminated line. - return i + 1, dropCR(data[0:i]), nil - } - // If we're at EOF, we have a final, non-terminated line. Return it. - if atEOF { - return len(data), dropCR(data), nil - } - // Request more data. - return 0, nil, nil -} - -// isSpace reports whether the character is a Unicode white space character. -// We avoid dependency on the unicode package, but check validity of the implementation -// in the tests. -func isSpace(r rune) bool { - if r <= '\u00FF' { - // Obvious ASCII ones: \t through \r plus space. Plus two Latin-1 oddballs. - switch r { - case ' ', '\t', '\n', '\v', '\f', '\r': - return true - case '\u0085', '\u00A0': - return true - } - return false - } - // High-valued ones. - if '\u2000' <= r && r <= '\u200a' { - return true - } - switch r { - case '\u1680', '\u2028', '\u2029', '\u202f', '\u205f', '\u3000': - return true - } - return false -} - -// ScanWords is a split function for a Scanner that returns each -// space-separated word of text, with surrounding spaces deleted. It will -// never return an empty string. The definition of space is set by -// unicode.IsSpace. -func ScanWords(data []byte, atEOF bool) (advance int, token []byte, err error) { - // Skip leading spaces. - start := 0 - for width := 0; start < len(data); start += width { - var r rune - r, width = utf8.DecodeRune(data[start:]) - if !isSpace(r) { - break - } - } - // Scan until space, marking end of word. - for width, i := 0, start; i < len(data); i += width { - var r rune - r, width = utf8.DecodeRune(data[i:]) - if isSpace(r) { - return i + width, data[start:i], nil - } - } - // If we're at EOF, we have a final, non-empty, non-terminated word. Return it. - if atEOF && len(data) > start { - return len(data), data[start:], nil - } - // Request more data. - return start, nil, nil -} diff --git a/src/pkg/bufio/scan_test.go b/src/pkg/bufio/scan_test.go deleted file mode 100644 index 3ddb25acf..000000000 --- a/src/pkg/bufio/scan_test.go +++ /dev/null @@ -1,421 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package bufio_test - -import ( - . "bufio" - "bytes" - "errors" - "io" - "strings" - "testing" - "unicode" - "unicode/utf8" -) - -const smallMaxTokenSize = 256 // Much smaller for more efficient testing. - -// Test white space table matches the Unicode definition. -func TestSpace(t *testing.T) { - for r := rune(0); r <= utf8.MaxRune; r++ { - if IsSpace(r) != unicode.IsSpace(r) { - t.Fatalf("white space property disagrees: %#U should be %t", r, unicode.IsSpace(r)) - } - } -} - -var scanTests = []string{ - "", - "a", - "¼", - "☹", - "\x81", // UTF-8 error - "\uFFFD", // correctly encoded RuneError - "abcdefgh", - "abc def\n\t\tgh ", - "abc¼☹\x81\uFFFD日本語\x82abc", -} - -func TestScanByte(t *testing.T) { - for n, test := range scanTests { - buf := strings.NewReader(test) - s := NewScanner(buf) - s.Split(ScanBytes) - var i int - for i = 0; s.Scan(); i++ { - if b := s.Bytes(); len(b) != 1 || b[0] != test[i] { - t.Errorf("#%d: %d: expected %q got %q", n, i, test, b) - } - } - if i != len(test) { - t.Errorf("#%d: termination expected at %d; got %d", n, len(test), i) - } - err := s.Err() - if err != nil { - t.Errorf("#%d: %v", n, err) - } - } -} - -// Test that the rune splitter returns same sequence of runes (not bytes) as for range string. -func TestScanRune(t *testing.T) { - for n, test := range scanTests { - buf := strings.NewReader(test) - s := NewScanner(buf) - s.Split(ScanRunes) - var i, runeCount int - var expect rune - // Use a string range loop to validate the sequence of runes. - for i, expect = range string(test) { - if !s.Scan() { - break - } - runeCount++ - got, _ := utf8.DecodeRune(s.Bytes()) - if got != expect { - t.Errorf("#%d: %d: expected %q got %q", n, i, expect, got) - } - } - if s.Scan() { - t.Errorf("#%d: scan ran too long, got %q", n, s.Text()) - } - testRuneCount := utf8.RuneCountInString(test) - if runeCount != testRuneCount { - t.Errorf("#%d: termination expected at %d; got %d", n, testRuneCount, runeCount) - } - err := s.Err() - if err != nil { - t.Errorf("#%d: %v", n, err) - } - } -} - -var wordScanTests = []string{ - "", - " ", - "\n", - "a", - " a ", - "abc def", - " abc def ", - " abc\tdef\nghi\rjkl\fmno\vpqr\u0085stu\u00a0\n", -} - -// Test that the word splitter returns the same data as strings.Fields. -func TestScanWords(t *testing.T) { - for n, test := range wordScanTests { - buf := strings.NewReader(test) - s := NewScanner(buf) - s.Split(ScanWords) - words := strings.Fields(test) - var wordCount int - for wordCount = 0; wordCount < len(words); wordCount++ { - if !s.Scan() { - break - } - got := s.Text() - if got != words[wordCount] { - t.Errorf("#%d: %d: expected %q got %q", n, wordCount, words[wordCount], got) - } - } - if s.Scan() { - t.Errorf("#%d: scan ran too long, got %q", n, s.Text()) - } - if wordCount != len(words) { - t.Errorf("#%d: termination expected at %d; got %d", n, len(words), wordCount) - } - err := s.Err() - if err != nil { - t.Errorf("#%d: %v", n, err) - } - } -} - -// slowReader is a reader that returns only a few bytes at a time, to test the incremental -// reads in Scanner.Scan. -type slowReader struct { - max int - buf io.Reader -} - -func (sr *slowReader) Read(p []byte) (n int, err error) { - if len(p) > sr.max { - p = p[0:sr.max] - } - return sr.buf.Read(p) -} - -// genLine writes to buf a predictable but non-trivial line of text of length -// n, including the terminal newline and an occasional carriage return. -// If addNewline is false, the \r and \n are not emitted. -func genLine(buf *bytes.Buffer, lineNum, n int, addNewline bool) { - buf.Reset() - doCR := lineNum%5 == 0 - if doCR { - n-- - } - for i := 0; i < n-1; i++ { // Stop early for \n. - c := 'a' + byte(lineNum+i) - if c == '\n' || c == '\r' { // Don't confuse us. - c = 'N' - } - buf.WriteByte(c) - } - if addNewline { - if doCR { - buf.WriteByte('\r') - } - buf.WriteByte('\n') - } - return -} - -// Test the line splitter, including some carriage returns but no long lines. -func TestScanLongLines(t *testing.T) { - // Build a buffer of lots of line lengths up to but not exceeding smallMaxTokenSize. - tmp := new(bytes.Buffer) - buf := new(bytes.Buffer) - lineNum := 0 - j := 0 - for i := 0; i < 2*smallMaxTokenSize; i++ { - genLine(tmp, lineNum, j, true) - if j < smallMaxTokenSize { - j++ - } else { - j-- - } - buf.Write(tmp.Bytes()) - lineNum++ - } - s := NewScanner(&slowReader{1, buf}) - s.Split(ScanLines) - s.MaxTokenSize(smallMaxTokenSize) - j = 0 - for lineNum := 0; s.Scan(); lineNum++ { - genLine(tmp, lineNum, j, false) - if j < smallMaxTokenSize { - j++ - } else { - j-- - } - line := tmp.String() // We use the string-valued token here, for variety. - if s.Text() != line { - t.Errorf("%d: bad line: %d %d\n%.100q\n%.100q\n", lineNum, len(s.Bytes()), len(line), s.Text(), line) - } - } - err := s.Err() - if err != nil { - t.Fatal(err) - } -} - -// Test that the line splitter errors out on a long line. -func TestScanLineTooLong(t *testing.T) { - const smallMaxTokenSize = 256 // Much smaller for more efficient testing. - // Build a buffer of lots of line lengths up to but not exceeding smallMaxTokenSize. - tmp := new(bytes.Buffer) - buf := new(bytes.Buffer) - lineNum := 0 - j := 0 - for i := 0; i < 2*smallMaxTokenSize; i++ { - genLine(tmp, lineNum, j, true) - j++ - buf.Write(tmp.Bytes()) - lineNum++ - } - s := NewScanner(&slowReader{3, buf}) - s.Split(ScanLines) - s.MaxTokenSize(smallMaxTokenSize) - j = 0 - for lineNum := 0; s.Scan(); lineNum++ { - genLine(tmp, lineNum, j, false) - if j < smallMaxTokenSize { - j++ - } else { - j-- - } - line := tmp.Bytes() - if !bytes.Equal(s.Bytes(), line) { - t.Errorf("%d: bad line: %d %d\n%.100q\n%.100q\n", lineNum, len(s.Bytes()), len(line), s.Bytes(), line) - } - } - err := s.Err() - if err != ErrTooLong { - t.Fatalf("expected ErrTooLong; got %s", err) - } -} - -// Test that the line splitter handles a final line without a newline. -func testNoNewline(text string, lines []string, t *testing.T) { - buf := strings.NewReader(text) - s := NewScanner(&slowReader{7, buf}) - s.Split(ScanLines) - for lineNum := 0; s.Scan(); lineNum++ { - line := lines[lineNum] - if s.Text() != line { - t.Errorf("%d: bad line: %d %d\n%.100q\n%.100q\n", lineNum, len(s.Bytes()), len(line), s.Bytes(), line) - } - } - err := s.Err() - if err != nil { - t.Fatal(err) - } -} - -var noNewlineLines = []string{ - "abcdefghijklmn\nopqrstuvwxyz", -} - -// Test that the line splitter handles a final line without a newline. -func TestScanLineNoNewline(t *testing.T) { - const text = "abcdefghijklmn\nopqrstuvwxyz" - lines := []string{ - "abcdefghijklmn", - "opqrstuvwxyz", - } - testNoNewline(text, lines, t) -} - -// Test that the line splitter handles a final line with a carriage return but no newline. -func TestScanLineReturnButNoNewline(t *testing.T) { - const text = "abcdefghijklmn\nopqrstuvwxyz\r" - lines := []string{ - "abcdefghijklmn", - "opqrstuvwxyz", - } - testNoNewline(text, lines, t) -} - -// Test that the line splitter handles a final empty line. -func TestScanLineEmptyFinalLine(t *testing.T) { - const text = "abcdefghijklmn\nopqrstuvwxyz\n\n" - lines := []string{ - "abcdefghijklmn", - "opqrstuvwxyz", - "", - } - testNoNewline(text, lines, t) -} - -// Test that the line splitter handles a final empty line with a carriage return but no newline. -func TestScanLineEmptyFinalLineWithCR(t *testing.T) { - const text = "abcdefghijklmn\nopqrstuvwxyz\n\r" - lines := []string{ - "abcdefghijklmn", - "opqrstuvwxyz", - "", - } - testNoNewline(text, lines, t) -} - -var testError = errors.New("testError") - -// Test the correct error is returned when the split function errors out. -func TestSplitError(t *testing.T) { - // Create a split function that delivers a little data, then a predictable error. - numSplits := 0 - const okCount = 7 - errorSplit := func(data []byte, atEOF bool) (advance int, token []byte, err error) { - if atEOF { - panic("didn't get enough data") - } - if numSplits >= okCount { - return 0, nil, testError - } - numSplits++ - return 1, data[0:1], nil - } - // Read the data. - const text = "abcdefghijklmnopqrstuvwxyz" - buf := strings.NewReader(text) - s := NewScanner(&slowReader{1, buf}) - s.Split(errorSplit) - var i int - for i = 0; s.Scan(); i++ { - if len(s.Bytes()) != 1 || text[i] != s.Bytes()[0] { - t.Errorf("#%d: expected %q got %q", i, text[i], s.Bytes()[0]) - } - } - // Check correct termination location and error. - if i != okCount { - t.Errorf("unexpected termination; expected %d tokens got %d", okCount, i) - } - err := s.Err() - if err != testError { - t.Fatalf("expected %q got %v", testError, err) - } -} - -// Test that an EOF is overridden by a user-generated scan error. -func TestErrAtEOF(t *testing.T) { - s := NewScanner(strings.NewReader("1 2 33")) - // This spitter will fail on last entry, after s.err==EOF. - split := func(data []byte, atEOF bool) (advance int, token []byte, err error) { - advance, token, err = ScanWords(data, atEOF) - if len(token) > 1 { - if s.ErrOrEOF() != io.EOF { - t.Fatal("not testing EOF") - } - err = testError - } - return - } - s.Split(split) - for s.Scan() { - } - if s.Err() != testError { - t.Fatal("wrong error:", s.Err()) - } -} - -// Test for issue 5268. -type alwaysError struct{} - -func (alwaysError) Read(p []byte) (int, error) { - return 0, io.ErrUnexpectedEOF -} - -func TestNonEOFWithEmptyRead(t *testing.T) { - scanner := NewScanner(alwaysError{}) - for scanner.Scan() { - t.Fatal("read should fail") - } - err := scanner.Err() - if err != io.ErrUnexpectedEOF { - t.Errorf("unexpected error: %v", err) - } -} - -// Test that Scan finishes if we have endless empty reads. -type endlessZeros struct{} - -func (endlessZeros) Read(p []byte) (int, error) { - return 0, nil -} - -func TestBadReader(t *testing.T) { - scanner := NewScanner(endlessZeros{}) - for scanner.Scan() { - t.Fatal("read should fail") - } - err := scanner.Err() - if err != io.ErrNoProgress { - t.Errorf("unexpected error: %v", err) - } -} - -func TestScanWordsExcessiveWhiteSpace(t *testing.T) { - const word = "ipsum" - s := strings.Repeat(" ", 4*smallMaxTokenSize) + word - scanner := NewScanner(strings.NewReader(s)) - scanner.MaxTokenSize(smallMaxTokenSize) - scanner.Split(ScanWords) - if !scanner.Scan() { - t.Fatalf("scan failed: %v", scanner.Err()) - } - if token := scanner.Text(); token != word { - t.Fatalf("unexpected token: %v", token) - } -} diff --git a/src/pkg/builtin/builtin.go b/src/pkg/builtin/builtin.go deleted file mode 100644 index 51550a459..000000000 --- a/src/pkg/builtin/builtin.go +++ /dev/null @@ -1,256 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* - Package builtin provides documentation for Go's predeclared identifiers. - The items documented here are not actually in package builtin - but their descriptions here allow godoc to present documentation - for the language's special identifiers. -*/ -package builtin - -// bool is the set of boolean values, true and false. -type bool bool - -// true and false are the two untyped boolean values. -const ( - true = 0 == 0 // Untyped bool. - false = 0 != 0 // Untyped bool. -) - -// uint8 is the set of all unsigned 8-bit integers. -// Range: 0 through 255. -type uint8 uint8 - -// uint16 is the set of all unsigned 16-bit integers. -// Range: 0 through 65535. -type uint16 uint16 - -// uint32 is the set of all unsigned 32-bit integers. -// Range: 0 through 4294967295. -type uint32 uint32 - -// uint64 is the set of all unsigned 64-bit integers. -// Range: 0 through 18446744073709551615. -type uint64 uint64 - -// int8 is the set of all signed 8-bit integers. -// Range: -128 through 127. -type int8 int8 - -// int16 is the set of all signed 16-bit integers. -// Range: -32768 through 32767. -type int16 int16 - -// int32 is the set of all signed 32-bit integers. -// Range: -2147483648 through 2147483647. -type int32 int32 - -// int64 is the set of all signed 64-bit integers. -// Range: -9223372036854775808 through 9223372036854775807. -type int64 int64 - -// float32 is the set of all IEEE-754 32-bit floating-point numbers. -type float32 float32 - -// float64 is the set of all IEEE-754 64-bit floating-point numbers. -type float64 float64 - -// complex64 is the set of all complex numbers with float32 real and -// imaginary parts. -type complex64 complex64 - -// complex128 is the set of all complex numbers with float64 real and -// imaginary parts. -type complex128 complex128 - -// string is the set of all strings of 8-bit bytes, conventionally but not -// necessarily representing UTF-8-encoded text. A string may be empty, but -// not nil. Values of string type are immutable. -type string string - -// int is a signed integer type that is at least 32 bits in size. It is a -// distinct type, however, and not an alias for, say, int32. -type int int - -// uint is an unsigned integer type that is at least 32 bits in size. It is a -// distinct type, however, and not an alias for, say, uint32. -type uint uint - -// uintptr is an integer type that is large enough to hold the bit pattern of -// any pointer. -type uintptr uintptr - -// byte is an alias for uint8 and is equivalent to uint8 in all ways. It is -// used, by convention, to distinguish byte values from 8-bit unsigned -// integer values. -type byte byte - -// rune is an alias for int32 and is equivalent to int32 in all ways. It is -// used, by convention, to distinguish character values from integer values. -type rune rune - -// iota is a predeclared identifier representing the untyped integer ordinal -// number of the current const specification in a (usually parenthesized) -// const declaration. It is zero-indexed. -const iota = 0 // Untyped int. - -// nil is a predeclared identifier representing the zero value for a -// pointer, channel, func, interface, map, or slice type. -var nil Type // Type must be a pointer, channel, func, interface, map, or slice type - -// Type is here for the purposes of documentation only. It is a stand-in -// for any Go type, but represents the same type for any given function -// invocation. -type Type int - -// Type1 is here for the purposes of documentation only. It is a stand-in -// for any Go type, but represents the same type for any given function -// invocation. -type Type1 int - -// IntegerType is here for the purposes of documentation only. It is a stand-in -// for any integer type: int, uint, int8 etc. -type IntegerType int - -// FloatType is here for the purposes of documentation only. It is a stand-in -// for either float type: float32 or float64. -type FloatType float32 - -// ComplexType is here for the purposes of documentation only. It is a -// stand-in for either complex type: complex64 or complex128. -type ComplexType complex64 - -// The append built-in function appends elements to the end of a slice. If -// it has sufficient capacity, the destination is resliced to accommodate the -// new elements. If it does not, a new underlying array will be allocated. -// Append returns the updated slice. It is therefore necessary to store the -// result of append, often in the variable holding the slice itself: -// slice = append(slice, elem1, elem2) -// slice = append(slice, anotherSlice...) -// As a special case, it is legal to append a string to a byte slice, like this: -// slice = append([]byte("hello "), "world"...) -func append(slice []Type, elems ...Type) []Type - -// The copy built-in function copies elements from a source slice into a -// destination slice. (As a special case, it also will copy bytes from a -// string to a slice of bytes.) The source and destination may overlap. Copy -// returns the number of elements copied, which will be the minimum of -// len(src) and len(dst). -func copy(dst, src []Type) int - -// The delete built-in function deletes the element with the specified key -// (m[key]) from the map. If m is nil or there is no such element, delete -// is a no-op. -func delete(m map[Type]Type1, key Type) - -// The len built-in function returns the length of v, according to its type: -// Array: the number of elements in v. -// Pointer to array: the number of elements in *v (even if v is nil). -// Slice, or map: the number of elements in v; if v is nil, len(v) is zero. -// String: the number of bytes in v. -// Channel: the number of elements queued (unread) in the channel buffer; -// if v is nil, len(v) is zero. -func len(v Type) int - -// The cap built-in function returns the capacity of v, according to its type: -// Array: the number of elements in v (same as len(v)). -// Pointer to array: the number of elements in *v (same as len(v)). -// Slice: the maximum length the slice can reach when resliced; -// if v is nil, cap(v) is zero. -// Channel: the channel buffer capacity, in units of elements; -// if v is nil, cap(v) is zero. -func cap(v Type) int - -// The make built-in function allocates and initializes an object of type -// slice, map, or chan (only). Like new, the first argument is a type, not a -// value. Unlike new, make's return type is the same as the type of its -// argument, not a pointer to it. The specification of the result depends on -// the type: -// Slice: The size specifies the length. The capacity of the slice is -// equal to its length. A second integer argument may be provided to -// specify a different capacity; it must be no smaller than the -// length, so make([]int, 0, 10) allocates a slice of length 0 and -// capacity 10. -// Map: An initial allocation is made according to the size but the -// resulting map has length 0. The size may be omitted, in which case -// a small starting size is allocated. -// Channel: The channel's buffer is initialized with the specified -// buffer capacity. If zero, or the size is omitted, the channel is -// unbuffered. -func make(Type, size IntegerType) Type - -// The new built-in function allocates memory. The first argument is a type, -// not a value, and the value returned is a pointer to a newly -// allocated zero value of that type. -func new(Type) *Type - -// The complex built-in function constructs a complex value from two -// floating-point values. The real and imaginary parts must be of the same -// size, either float32 or float64 (or assignable to them), and the return -// value will be the corresponding complex type (complex64 for float32, -// complex128 for float64). -func complex(r, i FloatType) ComplexType - -// The real built-in function returns the real part of the complex number c. -// The return value will be floating point type corresponding to the type of c. -func real(c ComplexType) FloatType - -// The imag built-in function returns the imaginary part of the complex -// number c. The return value will be floating point type corresponding to -// the type of c. -func imag(c ComplexType) FloatType - -// The close built-in function closes a channel, which must be either -// bidirectional or send-only. It should be executed only by the sender, -// never the receiver, and has the effect of shutting down the channel after -// the last sent value is received. After the last value has been received -// from a closed channel c, any receive from c will succeed without -// blocking, returning the zero value for the channel element. The form -// x, ok := <-c -// will also set ok to false for a closed channel. -func close(c chan<- Type) - -// The panic built-in function stops normal execution of the current -// goroutine. When a function F calls panic, normal execution of F stops -// immediately. Any functions whose execution was deferred by F are run in -// the usual way, and then F returns to its caller. To the caller G, the -// invocation of F then behaves like a call to panic, terminating G's -// execution and running any deferred functions. This continues until all -// functions in the executing goroutine have stopped, in reverse order. At -// that point, the program is terminated and the error condition is reported, -// including the value of the argument to panic. This termination sequence -// is called panicking and can be controlled by the built-in function -// recover. -func panic(v interface{}) - -// The recover built-in function allows a program to manage behavior of a -// panicking goroutine. Executing a call to recover inside a deferred -// function (but not any function called by it) stops the panicking sequence -// by restoring normal execution and retrieves the error value passed to the -// call of panic. If recover is called outside the deferred function it will -// not stop a panicking sequence. In this case, or when the goroutine is not -// panicking, or if the argument supplied to panic was nil, recover returns -// nil. Thus the return value from recover reports whether the goroutine is -// panicking. -func recover() interface{} - -// The print built-in function formats its arguments in an implementation- -// specific way and writes the result to standard error. -// Print is useful for bootstrapping and debugging; it is not guaranteed -// to stay in the language. -func print(args ...Type) - -// The println built-in function formats its arguments in an implementation- -// specific way and writes the result to standard error. -// Spaces are always added between arguments and a newline is appended. -// Println is useful for bootstrapping and debugging; it is not guaranteed -// to stay in the language. -func println(args ...Type) - -// The error built-in interface type is the conventional interface for -// representing an error condition, with the nil value representing no error. -type error interface { - Error() string -} diff --git a/src/pkg/bytes/buffer.go b/src/pkg/bytes/buffer.go deleted file mode 100644 index 46ca1d5ad..000000000 --- a/src/pkg/bytes/buffer.go +++ /dev/null @@ -1,412 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package bytes - -// Simple byte buffer for marshaling data. - -import ( - "errors" - "io" - "unicode/utf8" -) - -// A Buffer is a variable-sized buffer of bytes with Read and Write methods. -// The zero value for Buffer is an empty buffer ready to use. -type Buffer struct { - buf []byte // contents are the bytes buf[off : len(buf)] - off int // read at &buf[off], write at &buf[len(buf)] - runeBytes [utf8.UTFMax]byte // avoid allocation of slice on each WriteByte or Rune - bootstrap [64]byte // memory to hold first slice; helps small buffers (Printf) avoid allocation. - lastRead readOp // last read operation, so that Unread* can work correctly. -} - -// The readOp constants describe the last action performed on -// the buffer, so that UnreadRune and UnreadByte can -// check for invalid usage. -type readOp int - -const ( - opInvalid readOp = iota // Non-read operation. - opReadRune // Read rune. - opRead // Any other read operation. -) - -// ErrTooLarge is passed to panic if memory cannot be allocated to store data in a buffer. -var ErrTooLarge = errors.New("bytes.Buffer: too large") - -// Bytes returns a slice of the contents of the unread portion of the buffer; -// len(b.Bytes()) == b.Len(). If the caller changes the contents of the -// returned slice, the contents of the buffer will change provided there -// are no intervening method calls on the Buffer. -func (b *Buffer) Bytes() []byte { return b.buf[b.off:] } - -// String returns the contents of the unread portion of the buffer -// as a string. If the Buffer is a nil pointer, it returns "". -func (b *Buffer) String() string { - if b == nil { - // Special case, useful in debugging. - return "" - } - return string(b.buf[b.off:]) -} - -// Len returns the number of bytes of the unread portion of the buffer; -// b.Len() == len(b.Bytes()). -func (b *Buffer) Len() int { return len(b.buf) - b.off } - -// Truncate discards all but the first n unread bytes from the buffer. -// It panics if n is negative or greater than the length of the buffer. -func (b *Buffer) Truncate(n int) { - b.lastRead = opInvalid - switch { - case n < 0 || n > b.Len(): - panic("bytes.Buffer: truncation out of range") - case n == 0: - // Reuse buffer space. - b.off = 0 - } - b.buf = b.buf[0 : b.off+n] -} - -// Reset resets the buffer so it has no content. -// b.Reset() is the same as b.Truncate(0). -func (b *Buffer) Reset() { b.Truncate(0) } - -// grow grows the buffer to guarantee space for n more bytes. -// It returns the index where bytes should be written. -// If the buffer can't grow it will panic with ErrTooLarge. -func (b *Buffer) grow(n int) int { - m := b.Len() - // If buffer is empty, reset to recover space. - if m == 0 && b.off != 0 { - b.Truncate(0) - } - if len(b.buf)+n > cap(b.buf) { - var buf []byte - if b.buf == nil && n <= len(b.bootstrap) { - buf = b.bootstrap[0:] - } else if m+n <= cap(b.buf)/2 { - // We can slide things down instead of allocating a new - // slice. We only need m+n <= cap(b.buf) to slide, but - // we instead let capacity get twice as large so we - // don't spend all our time copying. - copy(b.buf[:], b.buf[b.off:]) - buf = b.buf[:m] - } else { - // not enough space anywhere - buf = makeSlice(2*cap(b.buf) + n) - copy(buf, b.buf[b.off:]) - } - b.buf = buf - b.off = 0 - } - b.buf = b.buf[0 : b.off+m+n] - return b.off + m -} - -// Grow grows the buffer's capacity, if necessary, to guarantee space for -// another n bytes. After Grow(n), at least n bytes can be written to the -// buffer without another allocation. -// If n is negative, Grow will panic. -// If the buffer can't grow it will panic with ErrTooLarge. -func (b *Buffer) Grow(n int) { - if n < 0 { - panic("bytes.Buffer.Grow: negative count") - } - m := b.grow(n) - b.buf = b.buf[0:m] -} - -// Write appends the contents of p to the buffer, growing the buffer as -// needed. The return value n is the length of p; err is always nil. If the -// buffer becomes too large, Write will panic with ErrTooLarge. -func (b *Buffer) Write(p []byte) (n int, err error) { - b.lastRead = opInvalid - m := b.grow(len(p)) - return copy(b.buf[m:], p), nil -} - -// WriteString appends the contents of s to the buffer, growing the buffer as -// needed. The return value n is the length of s; err is always nil. If the -// buffer becomes too large, WriteString will panic with ErrTooLarge. -func (b *Buffer) WriteString(s string) (n int, err error) { - b.lastRead = opInvalid - m := b.grow(len(s)) - return copy(b.buf[m:], s), nil -} - -// MinRead is the minimum slice size passed to a Read call by -// Buffer.ReadFrom. As long as the Buffer has at least MinRead bytes beyond -// what is required to hold the contents of r, ReadFrom will not grow the -// underlying buffer. -const MinRead = 512 - -// ReadFrom reads data from r until EOF and appends it to the buffer, growing -// the buffer as needed. The return value n is the number of bytes read. Any -// error except io.EOF encountered during the read is also returned. If the -// buffer becomes too large, ReadFrom will panic with ErrTooLarge. -func (b *Buffer) ReadFrom(r io.Reader) (n int64, err error) { - b.lastRead = opInvalid - // If buffer is empty, reset to recover space. - if b.off >= len(b.buf) { - b.Truncate(0) - } - for { - if free := cap(b.buf) - len(b.buf); free < MinRead { - // not enough space at end - newBuf := b.buf - if b.off+free < MinRead { - // not enough space using beginning of buffer; - // double buffer capacity - newBuf = makeSlice(2*cap(b.buf) + MinRead) - } - copy(newBuf, b.buf[b.off:]) - b.buf = newBuf[:len(b.buf)-b.off] - b.off = 0 - } - m, e := r.Read(b.buf[len(b.buf):cap(b.buf)]) - b.buf = b.buf[0 : len(b.buf)+m] - n += int64(m) - if e == io.EOF { - break - } - if e != nil { - return n, e - } - } - return n, nil // err is EOF, so return nil explicitly -} - -// makeSlice allocates a slice of size n. If the allocation fails, it panics -// with ErrTooLarge. -func makeSlice(n int) []byte { - // If the make fails, give a known error. - defer func() { - if recover() != nil { - panic(ErrTooLarge) - } - }() - return make([]byte, n) -} - -// WriteTo writes data to w until the buffer is drained or an error occurs. -// The return value n is the number of bytes written; it always fits into an -// int, but it is int64 to match the io.WriterTo interface. Any error -// encountered during the write is also returned. -func (b *Buffer) WriteTo(w io.Writer) (n int64, err error) { - b.lastRead = opInvalid - if b.off < len(b.buf) { - nBytes := b.Len() - m, e := w.Write(b.buf[b.off:]) - if m > nBytes { - panic("bytes.Buffer.WriteTo: invalid Write count") - } - b.off += m - n = int64(m) - if e != nil { - return n, e - } - // all bytes should have been written, by definition of - // Write method in io.Writer - if m != nBytes { - return n, io.ErrShortWrite - } - } - // Buffer is now empty; reset. - b.Truncate(0) - return -} - -// WriteByte appends the byte c to the buffer, growing the buffer as needed. -// The returned error is always nil, but is included to match bufio.Writer's -// WriteByte. If the buffer becomes too large, WriteByte will panic with -// ErrTooLarge. -func (b *Buffer) WriteByte(c byte) error { - b.lastRead = opInvalid - m := b.grow(1) - b.buf[m] = c - return nil -} - -// WriteRune appends the UTF-8 encoding of Unicode code point r to the -// buffer, returning its length and an error, which is always nil but is -// included to match bufio.Writer's WriteRune. The buffer is grown as needed; -// if it becomes too large, WriteRune will panic with ErrTooLarge. -func (b *Buffer) WriteRune(r rune) (n int, err error) { - if r < utf8.RuneSelf { - b.WriteByte(byte(r)) - return 1, nil - } - n = utf8.EncodeRune(b.runeBytes[0:], r) - b.Write(b.runeBytes[0:n]) - return n, nil -} - -// Read reads the next len(p) bytes from the buffer or until the buffer -// is drained. The return value n is the number of bytes read. If the -// buffer has no data to return, err is io.EOF (unless len(p) is zero); -// otherwise it is nil. -func (b *Buffer) Read(p []byte) (n int, err error) { - b.lastRead = opInvalid - if b.off >= len(b.buf) { - // Buffer is empty, reset to recover space. - b.Truncate(0) - if len(p) == 0 { - return - } - return 0, io.EOF - } - n = copy(p, b.buf[b.off:]) - b.off += n - if n > 0 { - b.lastRead = opRead - } - return -} - -// Next returns a slice containing the next n bytes from the buffer, -// advancing the buffer as if the bytes had been returned by Read. -// If there are fewer than n bytes in the buffer, Next returns the entire buffer. -// The slice is only valid until the next call to a read or write method. -func (b *Buffer) Next(n int) []byte { - b.lastRead = opInvalid - m := b.Len() - if n > m { - n = m - } - data := b.buf[b.off : b.off+n] - b.off += n - if n > 0 { - b.lastRead = opRead - } - return data -} - -// ReadByte reads and returns the next byte from the buffer. -// If no byte is available, it returns error io.EOF. -func (b *Buffer) ReadByte() (c byte, err error) { - b.lastRead = opInvalid - if b.off >= len(b.buf) { - // Buffer is empty, reset to recover space. - b.Truncate(0) - return 0, io.EOF - } - c = b.buf[b.off] - b.off++ - b.lastRead = opRead - return c, nil -} - -// ReadRune reads and returns the next UTF-8-encoded -// Unicode code point from the buffer. -// If no bytes are available, the error returned is io.EOF. -// If the bytes are an erroneous UTF-8 encoding, it -// consumes one byte and returns U+FFFD, 1. -func (b *Buffer) ReadRune() (r rune, size int, err error) { - b.lastRead = opInvalid - if b.off >= len(b.buf) { - // Buffer is empty, reset to recover space. - b.Truncate(0) - return 0, 0, io.EOF - } - b.lastRead = opReadRune - c := b.buf[b.off] - if c < utf8.RuneSelf { - b.off++ - return rune(c), 1, nil - } - r, n := utf8.DecodeRune(b.buf[b.off:]) - b.off += n - return r, n, nil -} - -// UnreadRune unreads the last rune returned by ReadRune. -// If the most recent read or write operation on the buffer was -// not a ReadRune, UnreadRune returns an error. (In this regard -// it is stricter than UnreadByte, which will unread the last byte -// from any read operation.) -func (b *Buffer) UnreadRune() error { - if b.lastRead != opReadRune { - return errors.New("bytes.Buffer: UnreadRune: previous operation was not ReadRune") - } - b.lastRead = opInvalid - if b.off > 0 { - _, n := utf8.DecodeLastRune(b.buf[0:b.off]) - b.off -= n - } - return nil -} - -// UnreadByte unreads the last byte returned by the most recent -// read operation. If write has happened since the last read, UnreadByte -// returns an error. -func (b *Buffer) UnreadByte() error { - if b.lastRead != opReadRune && b.lastRead != opRead { - return errors.New("bytes.Buffer: UnreadByte: previous operation was not a read") - } - b.lastRead = opInvalid - if b.off > 0 { - b.off-- - } - return nil -} - -// ReadBytes reads until the first occurrence of delim in the input, -// returning a slice containing the data up to and including the delimiter. -// If ReadBytes encounters an error before finding a delimiter, -// it returns the data read before the error and the error itself (often io.EOF). -// ReadBytes returns err != nil if and only if the returned data does not end in -// delim. -func (b *Buffer) ReadBytes(delim byte) (line []byte, err error) { - slice, err := b.readSlice(delim) - // return a copy of slice. The buffer's backing array may - // be overwritten by later calls. - line = append(line, slice...) - return -} - -// readSlice is like ReadBytes but returns a reference to internal buffer data. -func (b *Buffer) readSlice(delim byte) (line []byte, err error) { - i := IndexByte(b.buf[b.off:], delim) - end := b.off + i + 1 - if i < 0 { - end = len(b.buf) - err = io.EOF - } - line = b.buf[b.off:end] - b.off = end - b.lastRead = opRead - return line, err -} - -// ReadString reads until the first occurrence of delim in the input, -// returning a string containing the data up to and including the delimiter. -// If ReadString encounters an error before finding a delimiter, -// it returns the data read before the error and the error itself (often io.EOF). -// ReadString returns err != nil if and only if the returned data does not end -// in delim. -func (b *Buffer) ReadString(delim byte) (line string, err error) { - slice, err := b.readSlice(delim) - return string(slice), err -} - -// NewBuffer creates and initializes a new Buffer using buf as its initial -// contents. It is intended to prepare a Buffer to read existing data. It -// can also be used to size the internal buffer for writing. To do that, -// buf should have the desired capacity but a length of zero. -// -// In most cases, new(Buffer) (or just declaring a Buffer variable) is -// sufficient to initialize a Buffer. -func NewBuffer(buf []byte) *Buffer { return &Buffer{buf: buf} } - -// NewBufferString creates and initializes a new Buffer using string s as its -// initial contents. It is intended to prepare a buffer to read an existing -// string. -// -// In most cases, new(Buffer) (or just declaring a Buffer variable) is -// sufficient to initialize a Buffer. -func NewBufferString(s string) *Buffer { - return &Buffer{buf: []byte(s)} -} diff --git a/src/pkg/bytes/buffer_test.go b/src/pkg/bytes/buffer_test.go deleted file mode 100644 index 75145b05e..000000000 --- a/src/pkg/bytes/buffer_test.go +++ /dev/null @@ -1,527 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package bytes_test - -import ( - . "bytes" - "io" - "math/rand" - "runtime" - "testing" - "unicode/utf8" -) - -const N = 10000 // make this bigger for a larger (and slower) test -var data string // test data for write tests -var testBytes []byte // test data; same as data but as a slice. - -func init() { - testBytes = make([]byte, N) - for i := 0; i < N; i++ { - testBytes[i] = 'a' + byte(i%26) - } - data = string(testBytes) -} - -// Verify that contents of buf match the string s. -func check(t *testing.T, testname string, buf *Buffer, s string) { - bytes := buf.Bytes() - str := buf.String() - if buf.Len() != len(bytes) { - t.Errorf("%s: buf.Len() == %d, len(buf.Bytes()) == %d", testname, buf.Len(), len(bytes)) - } - - if buf.Len() != len(str) { - t.Errorf("%s: buf.Len() == %d, len(buf.String()) == %d", testname, buf.Len(), len(str)) - } - - if buf.Len() != len(s) { - t.Errorf("%s: buf.Len() == %d, len(s) == %d", testname, buf.Len(), len(s)) - } - - if string(bytes) != s { - t.Errorf("%s: string(buf.Bytes()) == %q, s == %q", testname, string(bytes), s) - } -} - -// Fill buf through n writes of string fus. -// The initial contents of buf corresponds to the string s; -// the result is the final contents of buf returned as a string. -func fillString(t *testing.T, testname string, buf *Buffer, s string, n int, fus string) string { - check(t, testname+" (fill 1)", buf, s) - for ; n > 0; n-- { - m, err := buf.WriteString(fus) - if m != len(fus) { - t.Errorf(testname+" (fill 2): m == %d, expected %d", m, len(fus)) - } - if err != nil { - t.Errorf(testname+" (fill 3): err should always be nil, found err == %s", err) - } - s += fus - check(t, testname+" (fill 4)", buf, s) - } - return s -} - -// Fill buf through n writes of byte slice fub. -// The initial contents of buf corresponds to the string s; -// the result is the final contents of buf returned as a string. -func fillBytes(t *testing.T, testname string, buf *Buffer, s string, n int, fub []byte) string { - check(t, testname+" (fill 1)", buf, s) - for ; n > 0; n-- { - m, err := buf.Write(fub) - if m != len(fub) { - t.Errorf(testname+" (fill 2): m == %d, expected %d", m, len(fub)) - } - if err != nil { - t.Errorf(testname+" (fill 3): err should always be nil, found err == %s", err) - } - s += string(fub) - check(t, testname+" (fill 4)", buf, s) - } - return s -} - -func TestNewBuffer(t *testing.T) { - buf := NewBuffer(testBytes) - check(t, "NewBuffer", buf, data) -} - -func TestNewBufferString(t *testing.T) { - buf := NewBufferString(data) - check(t, "NewBufferString", buf, data) -} - -// Empty buf through repeated reads into fub. -// The initial contents of buf corresponds to the string s. -func empty(t *testing.T, testname string, buf *Buffer, s string, fub []byte) { - check(t, testname+" (empty 1)", buf, s) - - for { - n, err := buf.Read(fub) - if n == 0 { - break - } - if err != nil { - t.Errorf(testname+" (empty 2): err should always be nil, found err == %s", err) - } - s = s[n:] - check(t, testname+" (empty 3)", buf, s) - } - - check(t, testname+" (empty 4)", buf, "") -} - -func TestBasicOperations(t *testing.T) { - var buf Buffer - - for i := 0; i < 5; i++ { - check(t, "TestBasicOperations (1)", &buf, "") - - buf.Reset() - check(t, "TestBasicOperations (2)", &buf, "") - - buf.Truncate(0) - check(t, "TestBasicOperations (3)", &buf, "") - - n, err := buf.Write([]byte(data[0:1])) - if n != 1 { - t.Errorf("wrote 1 byte, but n == %d", n) - } - if err != nil { - t.Errorf("err should always be nil, but err == %s", err) - } - check(t, "TestBasicOperations (4)", &buf, "a") - - buf.WriteByte(data[1]) - check(t, "TestBasicOperations (5)", &buf, "ab") - - n, err = buf.Write([]byte(data[2:26])) - if n != 24 { - t.Errorf("wrote 25 bytes, but n == %d", n) - } - check(t, "TestBasicOperations (6)", &buf, string(data[0:26])) - - buf.Truncate(26) - check(t, "TestBasicOperations (7)", &buf, string(data[0:26])) - - buf.Truncate(20) - check(t, "TestBasicOperations (8)", &buf, string(data[0:20])) - - empty(t, "TestBasicOperations (9)", &buf, string(data[0:20]), make([]byte, 5)) - empty(t, "TestBasicOperations (10)", &buf, "", make([]byte, 100)) - - buf.WriteByte(data[1]) - c, err := buf.ReadByte() - if err != nil { - t.Error("ReadByte unexpected eof") - } - if c != data[1] { - t.Errorf("ReadByte wrong value c=%v", c) - } - c, err = buf.ReadByte() - if err == nil { - t.Error("ReadByte unexpected not eof") - } - } -} - -func TestLargeStringWrites(t *testing.T) { - var buf Buffer - limit := 30 - if testing.Short() { - limit = 9 - } - for i := 3; i < limit; i += 3 { - s := fillString(t, "TestLargeWrites (1)", &buf, "", 5, data) - empty(t, "TestLargeStringWrites (2)", &buf, s, make([]byte, len(data)/i)) - } - check(t, "TestLargeStringWrites (3)", &buf, "") -} - -func TestLargeByteWrites(t *testing.T) { - var buf Buffer - limit := 30 - if testing.Short() { - limit = 9 - } - for i := 3; i < limit; i += 3 { - s := fillBytes(t, "TestLargeWrites (1)", &buf, "", 5, testBytes) - empty(t, "TestLargeByteWrites (2)", &buf, s, make([]byte, len(data)/i)) - } - check(t, "TestLargeByteWrites (3)", &buf, "") -} - -func TestLargeStringReads(t *testing.T) { - var buf Buffer - for i := 3; i < 30; i += 3 { - s := fillString(t, "TestLargeReads (1)", &buf, "", 5, data[0:len(data)/i]) - empty(t, "TestLargeReads (2)", &buf, s, make([]byte, len(data))) - } - check(t, "TestLargeStringReads (3)", &buf, "") -} - -func TestLargeByteReads(t *testing.T) { - var buf Buffer - for i := 3; i < 30; i += 3 { - s := fillBytes(t, "TestLargeReads (1)", &buf, "", 5, testBytes[0:len(testBytes)/i]) - empty(t, "TestLargeReads (2)", &buf, s, make([]byte, len(data))) - } - check(t, "TestLargeByteReads (3)", &buf, "") -} - -func TestMixedReadsAndWrites(t *testing.T) { - var buf Buffer - s := "" - for i := 0; i < 50; i++ { - wlen := rand.Intn(len(data)) - if i%2 == 0 { - s = fillString(t, "TestMixedReadsAndWrites (1)", &buf, s, 1, data[0:wlen]) - } else { - s = fillBytes(t, "TestMixedReadsAndWrites (1)", &buf, s, 1, testBytes[0:wlen]) - } - - rlen := rand.Intn(len(data)) - fub := make([]byte, rlen) - n, _ := buf.Read(fub) - s = s[n:] - } - empty(t, "TestMixedReadsAndWrites (2)", &buf, s, make([]byte, buf.Len())) -} - -func TestNil(t *testing.T) { - var b *Buffer - if b.String() != "" { - t.Errorf("expected ; got %q", b.String()) - } -} - -func TestReadFrom(t *testing.T) { - var buf Buffer - for i := 3; i < 30; i += 3 { - s := fillBytes(t, "TestReadFrom (1)", &buf, "", 5, testBytes[0:len(testBytes)/i]) - var b Buffer - b.ReadFrom(&buf) - empty(t, "TestReadFrom (2)", &b, s, make([]byte, len(data))) - } -} - -func TestWriteTo(t *testing.T) { - var buf Buffer - for i := 3; i < 30; i += 3 { - s := fillBytes(t, "TestWriteTo (1)", &buf, "", 5, testBytes[0:len(testBytes)/i]) - var b Buffer - buf.WriteTo(&b) - empty(t, "TestWriteTo (2)", &b, s, make([]byte, len(data))) - } -} - -func TestRuneIO(t *testing.T) { - const NRune = 1000 - // Built a test slice while we write the data - b := make([]byte, utf8.UTFMax*NRune) - var buf Buffer - n := 0 - for r := rune(0); r < NRune; r++ { - size := utf8.EncodeRune(b[n:], r) - nbytes, err := buf.WriteRune(r) - if err != nil { - t.Fatalf("WriteRune(%U) error: %s", r, err) - } - if nbytes != size { - t.Fatalf("WriteRune(%U) expected %d, got %d", r, size, nbytes) - } - n += size - } - b = b[0:n] - - // Check the resulting bytes - if !Equal(buf.Bytes(), b) { - t.Fatalf("incorrect result from WriteRune: %q not %q", buf.Bytes(), b) - } - - p := make([]byte, utf8.UTFMax) - // Read it back with ReadRune - for r := rune(0); r < NRune; r++ { - size := utf8.EncodeRune(p, r) - nr, nbytes, err := buf.ReadRune() - if nr != r || nbytes != size || err != nil { - t.Fatalf("ReadRune(%U) got %U,%d not %U,%d (err=%s)", r, nr, nbytes, r, size, err) - } - } - - // Check that UnreadRune works - buf.Reset() - buf.Write(b) - for r := rune(0); r < NRune; r++ { - r1, size, _ := buf.ReadRune() - if err := buf.UnreadRune(); err != nil { - t.Fatalf("UnreadRune(%U) got error %q", r, err) - } - r2, nbytes, err := buf.ReadRune() - if r1 != r2 || r1 != r || nbytes != size || err != nil { - t.Fatalf("ReadRune(%U) after UnreadRune got %U,%d not %U,%d (err=%s)", r, r2, nbytes, r, size, err) - } - } -} - -func TestNext(t *testing.T) { - b := []byte{0, 1, 2, 3, 4} - tmp := make([]byte, 5) - for i := 0; i <= 5; i++ { - for j := i; j <= 5; j++ { - for k := 0; k <= 6; k++ { - // 0 <= i <= j <= 5; 0 <= k <= 6 - // Check that if we start with a buffer - // of length j at offset i and ask for - // Next(k), we get the right bytes. - buf := NewBuffer(b[0:j]) - n, _ := buf.Read(tmp[0:i]) - if n != i { - t.Fatalf("Read %d returned %d", i, n) - } - bb := buf.Next(k) - want := k - if want > j-i { - want = j - i - } - if len(bb) != want { - t.Fatalf("in %d,%d: len(Next(%d)) == %d", i, j, k, len(bb)) - } - for l, v := range bb { - if v != byte(l+i) { - t.Fatalf("in %d,%d: Next(%d)[%d] = %d, want %d", i, j, k, l, v, l+i) - } - } - } - } - } -} - -var readBytesTests = []struct { - buffer string - delim byte - expected []string - err error -}{ - {"", 0, []string{""}, io.EOF}, - {"a\x00", 0, []string{"a\x00"}, nil}, - {"abbbaaaba", 'b', []string{"ab", "b", "b", "aaab"}, nil}, - {"hello\x01world", 1, []string{"hello\x01"}, nil}, - {"foo\nbar", 0, []string{"foo\nbar"}, io.EOF}, - {"alpha\nbeta\ngamma\n", '\n', []string{"alpha\n", "beta\n", "gamma\n"}, nil}, - {"alpha\nbeta\ngamma", '\n', []string{"alpha\n", "beta\n", "gamma"}, io.EOF}, -} - -func TestReadBytes(t *testing.T) { - for _, test := range readBytesTests { - buf := NewBufferString(test.buffer) - var err error - for _, expected := range test.expected { - var bytes []byte - bytes, err = buf.ReadBytes(test.delim) - if string(bytes) != expected { - t.Errorf("expected %q, got %q", expected, bytes) - } - if err != nil { - break - } - } - if err != test.err { - t.Errorf("expected error %v, got %v", test.err, err) - } - } -} - -func TestReadString(t *testing.T) { - for _, test := range readBytesTests { - buf := NewBufferString(test.buffer) - var err error - for _, expected := range test.expected { - var s string - s, err = buf.ReadString(test.delim) - if s != expected { - t.Errorf("expected %q, got %q", expected, s) - } - if err != nil { - break - } - } - if err != test.err { - t.Errorf("expected error %v, got %v", test.err, err) - } - } -} - -func BenchmarkReadString(b *testing.B) { - const n = 32 << 10 - - data := make([]byte, n) - data[n-1] = 'x' - b.SetBytes(int64(n)) - for i := 0; i < b.N; i++ { - buf := NewBuffer(data) - _, err := buf.ReadString('x') - if err != nil { - b.Fatal(err) - } - } -} - -func TestGrow(t *testing.T) { - x := []byte{'x'} - y := []byte{'y'} - tmp := make([]byte, 72) - for _, startLen := range []int{0, 100, 1000, 10000, 100000} { - xBytes := Repeat(x, startLen) - for _, growLen := range []int{0, 100, 1000, 10000, 100000} { - buf := NewBuffer(xBytes) - // If we read, this affects buf.off, which is good to test. - readBytes, _ := buf.Read(tmp) - buf.Grow(growLen) - yBytes := Repeat(y, growLen) - // Check no allocation occurs in write, as long as we're single-threaded. - var m1, m2 runtime.MemStats - runtime.ReadMemStats(&m1) - buf.Write(yBytes) - runtime.ReadMemStats(&m2) - if runtime.GOMAXPROCS(-1) == 1 && m1.Mallocs != m2.Mallocs { - t.Errorf("allocation occurred during write") - } - // Check that buffer has correct data. - if !Equal(buf.Bytes()[0:startLen-readBytes], xBytes[readBytes:]) { - t.Errorf("bad initial data at %d %d", startLen, growLen) - } - if !Equal(buf.Bytes()[startLen-readBytes:startLen-readBytes+growLen], yBytes) { - t.Errorf("bad written data at %d %d", startLen, growLen) - } - } - } -} - -// Was a bug: used to give EOF reading empty slice at EOF. -func TestReadEmptyAtEOF(t *testing.T) { - b := new(Buffer) - slice := make([]byte, 0) - n, err := b.Read(slice) - if err != nil { - t.Errorf("read error: %v", err) - } - if n != 0 { - t.Errorf("wrong count; got %d want 0", n) - } -} - -func TestUnreadByte(t *testing.T) { - b := new(Buffer) - b.WriteString("abcdefghijklmnopqrstuvwxyz") - - _, err := b.ReadBytes('m') - if err != nil { - t.Fatalf("ReadBytes: %v", err) - } - - err = b.UnreadByte() - if err != nil { - t.Fatalf("UnreadByte: %v", err) - } - c, err := b.ReadByte() - if err != nil { - t.Fatalf("ReadByte: %v", err) - } - if c != 'm' { - t.Errorf("ReadByte = %q; want %q", c, 'm') - } -} - -// Tests that we occasionally compact. Issue 5154. -func TestBufferGrowth(t *testing.T) { - var b Buffer - buf := make([]byte, 1024) - b.Write(buf[0:1]) - var cap0 int - for i := 0; i < 5<<10; i++ { - b.Write(buf) - b.Read(buf) - if i == 0 { - cap0 = b.Cap() - } - } - cap1 := b.Cap() - // (*Buffer).grow allows for 2x capacity slop before sliding, - // so set our error threshold at 3x. - if cap1 > cap0*3 { - t.Errorf("buffer cap = %d; too big (grew from %d)", cap1, cap0) - } -} - -// From Issue 5154. -func BenchmarkBufferNotEmptyWriteRead(b *testing.B) { - buf := make([]byte, 1024) - for i := 0; i < b.N; i++ { - var b Buffer - b.Write(buf[0:1]) - for i := 0; i < 5<<10; i++ { - b.Write(buf) - b.Read(buf) - } - } -} - -// Check that we don't compact too often. From Issue 5154. -func BenchmarkBufferFullSmallReads(b *testing.B) { - buf := make([]byte, 1024) - for i := 0; i < b.N; i++ { - var b Buffer - b.Write(buf) - for b.Len()+20 < b.Cap() { - b.Write(buf[:10]) - } - for i := 0; i < 5<<10; i++ { - b.Read(buf[:1]) - b.Write(buf[:1]) - } - } -} diff --git a/src/pkg/bytes/bytes.go b/src/pkg/bytes/bytes.go deleted file mode 100644 index 34c22bbfb..000000000 --- a/src/pkg/bytes/bytes.go +++ /dev/null @@ -1,701 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package bytes implements functions for the manipulation of byte slices. -// It is analogous to the facilities of the strings package. -package bytes - -import ( - "unicode" - "unicode/utf8" -) - -func equalPortable(a, b []byte) bool { - if len(a) != len(b) { - return false - } - for i, c := range a { - if c != b[i] { - return false - } - } - return true -} - -// explode splits s into a slice of UTF-8 sequences, one per Unicode character (still slices of bytes), -// up to a maximum of n byte slices. Invalid UTF-8 sequences are chopped into individual bytes. -func explode(s []byte, n int) [][]byte { - if n <= 0 { - n = len(s) - } - a := make([][]byte, n) - var size int - na := 0 - for len(s) > 0 { - if na+1 >= n { - a[na] = s - na++ - break - } - _, size = utf8.DecodeRune(s) - a[na] = s[0:size] - s = s[size:] - na++ - } - return a[0:na] -} - -// Count counts the number of non-overlapping instances of sep in s. -func Count(s, sep []byte) int { - n := len(sep) - if n == 0 { - return utf8.RuneCount(s) + 1 - } - if n > len(s) { - return 0 - } - count := 0 - c := sep[0] - i := 0 - t := s[:len(s)-n+1] - for i < len(t) { - if t[i] != c { - o := IndexByte(t[i:], c) - if o < 0 { - break - } - i += o - } - if n == 1 || Equal(s[i:i+n], sep) { - count++ - i += n - continue - } - i++ - } - return count -} - -// Contains reports whether subslice is within b. -func Contains(b, subslice []byte) bool { - return Index(b, subslice) != -1 -} - -// Index returns the index of the first instance of sep in s, or -1 if sep is not present in s. -func Index(s, sep []byte) int { - n := len(sep) - if n == 0 { - return 0 - } - if n > len(s) { - return -1 - } - c := sep[0] - if n == 1 { - return IndexByte(s, c) - } - i := 0 - t := s[:len(s)-n+1] - for i < len(t) { - if t[i] != c { - o := IndexByte(t[i:], c) - if o < 0 { - break - } - i += o - } - if Equal(s[i:i+n], sep) { - return i - } - i++ - } - return -1 -} - -func indexBytePortable(s []byte, c byte) int { - for i, b := range s { - if b == c { - return i - } - } - return -1 -} - -// LastIndex returns the index of the last instance of sep in s, or -1 if sep is not present in s. -func LastIndex(s, sep []byte) int { - n := len(sep) - if n == 0 { - return len(s) - } - c := sep[0] - for i := len(s) - n; i >= 0; i-- { - if s[i] == c && (n == 1 || Equal(s[i:i+n], sep)) { - return i - } - } - return -1 -} - -// IndexRune interprets s as a sequence of UTF-8-encoded Unicode code points. -// It returns the byte index of the first occurrence in s of the given rune. -// It returns -1 if rune is not present in s. -func IndexRune(s []byte, r rune) int { - for i := 0; i < len(s); { - r1, size := utf8.DecodeRune(s[i:]) - if r == r1 { - return i - } - i += size - } - return -1 -} - -// IndexAny interprets s as a sequence of UTF-8-encoded Unicode code points. -// It returns the byte index of the first occurrence in s of any of the Unicode -// code points in chars. It returns -1 if chars is empty or if there is no code -// point in common. -func IndexAny(s []byte, chars string) int { - if len(chars) > 0 { - var r rune - var width int - for i := 0; i < len(s); i += width { - r = rune(s[i]) - if r < utf8.RuneSelf { - width = 1 - } else { - r, width = utf8.DecodeRune(s[i:]) - } - for _, ch := range chars { - if r == ch { - return i - } - } - } - } - return -1 -} - -// LastIndexAny interprets s as a sequence of UTF-8-encoded Unicode code -// points. It returns the byte index of the last occurrence in s of any of -// the Unicode code points in chars. It returns -1 if chars is empty or if -// there is no code point in common. -func LastIndexAny(s []byte, chars string) int { - if len(chars) > 0 { - for i := len(s); i > 0; { - r, size := utf8.DecodeLastRune(s[0:i]) - i -= size - for _, ch := range chars { - if r == ch { - return i - } - } - } - } - return -1 -} - -// Generic split: splits after each instance of sep, -// including sepSave bytes of sep in the subslices. -func genSplit(s, sep []byte, sepSave, n int) [][]byte { - if n == 0 { - return nil - } - if len(sep) == 0 { - return explode(s, n) - } - if n < 0 { - n = Count(s, sep) + 1 - } - c := sep[0] - start := 0 - a := make([][]byte, n) - na := 0 - for i := 0; i+len(sep) <= len(s) && na+1 < n; i++ { - if s[i] == c && (len(sep) == 1 || Equal(s[i:i+len(sep)], sep)) { - a[na] = s[start : i+sepSave] - na++ - start = i + len(sep) - i += len(sep) - 1 - } - } - a[na] = s[start:] - return a[0 : na+1] -} - -// SplitN slices s into subslices separated by sep and returns a slice of -// the subslices between those separators. -// If sep is empty, SplitN splits after each UTF-8 sequence. -// The count determines the number of subslices to return: -// n > 0: at most n subslices; the last subslice will be the unsplit remainder. -// n == 0: the result is nil (zero subslices) -// n < 0: all subslices -func SplitN(s, sep []byte, n int) [][]byte { return genSplit(s, sep, 0, n) } - -// SplitAfterN slices s into subslices after each instance of sep and -// returns a slice of those subslices. -// If sep is empty, SplitAfterN splits after each UTF-8 sequence. -// The count determines the number of subslices to return: -// n > 0: at most n subslices; the last subslice will be the unsplit remainder. -// n == 0: the result is nil (zero subslices) -// n < 0: all subslices -func SplitAfterN(s, sep []byte, n int) [][]byte { - return genSplit(s, sep, len(sep), n) -} - -// Split slices s into all subslices separated by sep and returns a slice of -// the subslices between those separators. -// If sep is empty, Split splits after each UTF-8 sequence. -// It is equivalent to SplitN with a count of -1. -func Split(s, sep []byte) [][]byte { return genSplit(s, sep, 0, -1) } - -// SplitAfter slices s into all subslices after each instance of sep and -// returns a slice of those subslices. -// If sep is empty, SplitAfter splits after each UTF-8 sequence. -// It is equivalent to SplitAfterN with a count of -1. -func SplitAfter(s, sep []byte) [][]byte { - return genSplit(s, sep, len(sep), -1) -} - -// Fields splits the slice s around each instance of one or more consecutive white space -// characters, returning a slice of subslices of s or an empty list if s contains only white space. -func Fields(s []byte) [][]byte { - return FieldsFunc(s, unicode.IsSpace) -} - -// FieldsFunc interprets s as a sequence of UTF-8-encoded Unicode code points. -// It splits the slice s at each run of code points c satisfying f(c) and -// returns a slice of subslices of s. If all code points in s satisfy f(c), or -// len(s) == 0, an empty slice is returned. -func FieldsFunc(s []byte, f func(rune) bool) [][]byte { - n := 0 - inField := false - for i := 0; i < len(s); { - r, size := utf8.DecodeRune(s[i:]) - wasInField := inField - inField = !f(r) - if inField && !wasInField { - n++ - } - i += size - } - - a := make([][]byte, n) - na := 0 - fieldStart := -1 - for i := 0; i <= len(s) && na < n; { - r, size := utf8.DecodeRune(s[i:]) - if fieldStart < 0 && size > 0 && !f(r) { - fieldStart = i - i += size - continue - } - if fieldStart >= 0 && (size == 0 || f(r)) { - a[na] = s[fieldStart:i] - na++ - fieldStart = -1 - } - if size == 0 { - break - } - i += size - } - return a[0:na] -} - -// Join concatenates the elements of s to create a new byte slice. The separator -// sep is placed between elements in the resulting slice. -func Join(s [][]byte, sep []byte) []byte { - if len(s) == 0 { - return []byte{} - } - if len(s) == 1 { - // Just return a copy. - return append([]byte(nil), s[0]...) - } - n := len(sep) * (len(s) - 1) - for _, v := range s { - n += len(v) - } - - b := make([]byte, n) - bp := copy(b, s[0]) - for _, v := range s[1:] { - bp += copy(b[bp:], sep) - bp += copy(b[bp:], v) - } - return b -} - -// HasPrefix tests whether the byte slice s begins with prefix. -func HasPrefix(s, prefix []byte) bool { - return len(s) >= len(prefix) && Equal(s[0:len(prefix)], prefix) -} - -// HasSuffix tests whether the byte slice s ends with suffix. -func HasSuffix(s, suffix []byte) bool { - return len(s) >= len(suffix) && Equal(s[len(s)-len(suffix):], suffix) -} - -// Map returns a copy of the byte slice s with all its characters modified -// according to the mapping function. If mapping returns a negative value, the character is -// dropped from the string with no replacement. The characters in s and the -// output are interpreted as UTF-8-encoded Unicode code points. -func Map(mapping func(r rune) rune, s []byte) []byte { - // In the worst case, the slice can grow when mapped, making - // things unpleasant. But it's so rare we barge in assuming it's - // fine. It could also shrink but that falls out naturally. - maxbytes := len(s) // length of b - nbytes := 0 // number of bytes encoded in b - b := make([]byte, maxbytes) - for i := 0; i < len(s); { - wid := 1 - r := rune(s[i]) - if r >= utf8.RuneSelf { - r, wid = utf8.DecodeRune(s[i:]) - } - r = mapping(r) - if r >= 0 { - rl := utf8.RuneLen(r) - if rl < 0 { - rl = len(string(utf8.RuneError)) - } - if nbytes+rl > maxbytes { - // Grow the buffer. - maxbytes = maxbytes*2 + utf8.UTFMax - nb := make([]byte, maxbytes) - copy(nb, b[0:nbytes]) - b = nb - } - nbytes += utf8.EncodeRune(b[nbytes:maxbytes], r) - } - i += wid - } - return b[0:nbytes] -} - -// Repeat returns a new byte slice consisting of count copies of b. -func Repeat(b []byte, count int) []byte { - nb := make([]byte, len(b)*count) - bp := copy(nb, b) - for bp < len(nb) { - copy(nb[bp:], nb[:bp]) - bp *= 2 - } - return nb -} - -// ToUpper returns a copy of the byte slice s with all Unicode letters mapped to their upper case. -func ToUpper(s []byte) []byte { return Map(unicode.ToUpper, s) } - -// ToLower returns a copy of the byte slice s with all Unicode letters mapped to their lower case. -func ToLower(s []byte) []byte { return Map(unicode.ToLower, s) } - -// ToTitle returns a copy of the byte slice s with all Unicode letters mapped to their title case. -func ToTitle(s []byte) []byte { return Map(unicode.ToTitle, s) } - -// ToUpperSpecial returns a copy of the byte slice s with all Unicode letters mapped to their -// upper case, giving priority to the special casing rules. -func ToUpperSpecial(_case unicode.SpecialCase, s []byte) []byte { - return Map(func(r rune) rune { return _case.ToUpper(r) }, s) -} - -// ToLowerSpecial returns a copy of the byte slice s with all Unicode letters mapped to their -// lower case, giving priority to the special casing rules. -func ToLowerSpecial(_case unicode.SpecialCase, s []byte) []byte { - return Map(func(r rune) rune { return _case.ToLower(r) }, s) -} - -// ToTitleSpecial returns a copy of the byte slice s with all Unicode letters mapped to their -// title case, giving priority to the special casing rules. -func ToTitleSpecial(_case unicode.SpecialCase, s []byte) []byte { - return Map(func(r rune) rune { return _case.ToTitle(r) }, s) -} - -// isSeparator reports whether the rune could mark a word boundary. -// TODO: update when package unicode captures more of the properties. -func isSeparator(r rune) bool { - // ASCII alphanumerics and underscore are not separators - if r <= 0x7F { - switch { - case '0' <= r && r <= '9': - return false - case 'a' <= r && r <= 'z': - return false - case 'A' <= r && r <= 'Z': - return false - case r == '_': - return false - } - return true - } - // Letters and digits are not separators - if unicode.IsLetter(r) || unicode.IsDigit(r) { - return false - } - // Otherwise, all we can do for now is treat spaces as separators. - return unicode.IsSpace(r) -} - -// Title returns a copy of s with all Unicode letters that begin words -// mapped to their title case. -// -// BUG: The rule Title uses for word boundaries does not handle Unicode punctuation properly. -func Title(s []byte) []byte { - // Use a closure here to remember state. - // Hackish but effective. Depends on Map scanning in order and calling - // the closure once per rune. - prev := ' ' - return Map( - func(r rune) rune { - if isSeparator(prev) { - prev = r - return unicode.ToTitle(r) - } - prev = r - return r - }, - s) -} - -// TrimLeftFunc returns a subslice of s by slicing off all leading UTF-8-encoded -// Unicode code points c that satisfy f(c). -func TrimLeftFunc(s []byte, f func(r rune) bool) []byte { - i := indexFunc(s, f, false) - if i == -1 { - return nil - } - return s[i:] -} - -// TrimRightFunc returns a subslice of s by slicing off all trailing UTF-8 -// encoded Unicode code points c that satisfy f(c). -func TrimRightFunc(s []byte, f func(r rune) bool) []byte { - i := lastIndexFunc(s, f, false) - if i >= 0 && s[i] >= utf8.RuneSelf { - _, wid := utf8.DecodeRune(s[i:]) - i += wid - } else { - i++ - } - return s[0:i] -} - -// TrimFunc returns a subslice of s by slicing off all leading and trailing -// UTF-8-encoded Unicode code points c that satisfy f(c). -func TrimFunc(s []byte, f func(r rune) bool) []byte { - return TrimRightFunc(TrimLeftFunc(s, f), f) -} - -// TrimPrefix returns s without the provided leading prefix string. -// If s doesn't start with prefix, s is returned unchanged. -func TrimPrefix(s, prefix []byte) []byte { - if HasPrefix(s, prefix) { - return s[len(prefix):] - } - return s -} - -// TrimSuffix returns s without the provided trailing suffix string. -// If s doesn't end with suffix, s is returned unchanged. -func TrimSuffix(s, suffix []byte) []byte { - if HasSuffix(s, suffix) { - return s[:len(s)-len(suffix)] - } - return s -} - -// IndexFunc interprets s as a sequence of UTF-8-encoded Unicode code points. -// It returns the byte index in s of the first Unicode -// code point satisfying f(c), or -1 if none do. -func IndexFunc(s []byte, f func(r rune) bool) int { - return indexFunc(s, f, true) -} - -// LastIndexFunc interprets s as a sequence of UTF-8-encoded Unicode code points. -// It returns the byte index in s of the last Unicode -// code point satisfying f(c), or -1 if none do. -func LastIndexFunc(s []byte, f func(r rune) bool) int { - return lastIndexFunc(s, f, true) -} - -// indexFunc is the same as IndexFunc except that if -// truth==false, the sense of the predicate function is -// inverted. -func indexFunc(s []byte, f func(r rune) bool, truth bool) int { - start := 0 - for start < len(s) { - wid := 1 - r := rune(s[start]) - if r >= utf8.RuneSelf { - r, wid = utf8.DecodeRune(s[start:]) - } - if f(r) == truth { - return start - } - start += wid - } - return -1 -} - -// lastIndexFunc is the same as LastIndexFunc except that if -// truth==false, the sense of the predicate function is -// inverted. -func lastIndexFunc(s []byte, f func(r rune) bool, truth bool) int { - for i := len(s); i > 0; { - r, size := rune(s[i-1]), 1 - if r >= utf8.RuneSelf { - r, size = utf8.DecodeLastRune(s[0:i]) - } - i -= size - if f(r) == truth { - return i - } - } - return -1 -} - -func makeCutsetFunc(cutset string) func(r rune) bool { - return func(r rune) bool { - for _, c := range cutset { - if c == r { - return true - } - } - return false - } -} - -// Trim returns a subslice of s by slicing off all leading and -// trailing UTF-8-encoded Unicode code points contained in cutset. -func Trim(s []byte, cutset string) []byte { - return TrimFunc(s, makeCutsetFunc(cutset)) -} - -// TrimLeft returns a subslice of s by slicing off all leading -// UTF-8-encoded Unicode code points contained in cutset. -func TrimLeft(s []byte, cutset string) []byte { - return TrimLeftFunc(s, makeCutsetFunc(cutset)) -} - -// TrimRight returns a subslice of s by slicing off all trailing -// UTF-8-encoded Unicode code points that are contained in cutset. -func TrimRight(s []byte, cutset string) []byte { - return TrimRightFunc(s, makeCutsetFunc(cutset)) -} - -// TrimSpace returns a subslice of s by slicing off all leading and -// trailing white space, as defined by Unicode. -func TrimSpace(s []byte) []byte { - return TrimFunc(s, unicode.IsSpace) -} - -// Runes returns a slice of runes (Unicode code points) equivalent to s. -func Runes(s []byte) []rune { - t := make([]rune, utf8.RuneCount(s)) - i := 0 - for len(s) > 0 { - r, l := utf8.DecodeRune(s) - t[i] = r - i++ - s = s[l:] - } - return t -} - -// Replace returns a copy of the slice s with the first n -// non-overlapping instances of old replaced by new. -// If old is empty, it matches at the beginning of the slice -// and after each UTF-8 sequence, yielding up to k+1 replacements -// for a k-rune slice. -// If n < 0, there is no limit on the number of replacements. -func Replace(s, old, new []byte, n int) []byte { - m := 0 - if n != 0 { - // Compute number of replacements. - m = Count(s, old) - } - if m == 0 { - // Just return a copy. - return append([]byte(nil), s...) - } - if n < 0 || m < n { - n = m - } - - // Apply replacements to buffer. - t := make([]byte, len(s)+n*(len(new)-len(old))) - w := 0 - start := 0 - for i := 0; i < n; i++ { - j := start - if len(old) == 0 { - if i > 0 { - _, wid := utf8.DecodeRune(s[start:]) - j += wid - } - } else { - j += Index(s[start:], old) - } - w += copy(t[w:], s[start:j]) - w += copy(t[w:], new) - start = j + len(old) - } - w += copy(t[w:], s[start:]) - return t[0:w] -} - -// EqualFold reports whether s and t, interpreted as UTF-8 strings, -// are equal under Unicode case-folding. -func EqualFold(s, t []byte) bool { - for len(s) != 0 && len(t) != 0 { - // Extract first rune from each. - var sr, tr rune - if s[0] < utf8.RuneSelf { - sr, s = rune(s[0]), s[1:] - } else { - r, size := utf8.DecodeRune(s) - sr, s = r, s[size:] - } - if t[0] < utf8.RuneSelf { - tr, t = rune(t[0]), t[1:] - } else { - r, size := utf8.DecodeRune(t) - tr, t = r, t[size:] - } - - // If they match, keep going; if not, return false. - - // Easy case. - if tr == sr { - continue - } - - // Make sr < tr to simplify what follows. - if tr < sr { - tr, sr = sr, tr - } - // Fast check for ASCII. - if tr < utf8.RuneSelf && 'A' <= sr && sr <= 'Z' { - // ASCII, and sr is upper case. tr must be lower case. - if tr == sr+'a'-'A' { - continue - } - return false - } - - // General case. SimpleFold(x) returns the next equivalent rune > x - // or wraps around to smaller values. - r := unicode.SimpleFold(sr) - for r != sr && r < tr { - r = unicode.SimpleFold(r) - } - if r == tr { - continue - } - return false - } - - // One string is empty. Are both? - return len(s) == len(t) -} diff --git a/src/pkg/bytes/bytes.s b/src/pkg/bytes/bytes.s deleted file mode 100644 index 55103bae0..000000000 --- a/src/pkg/bytes/bytes.s +++ /dev/null @@ -1,5 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file is here just to make the go tool happy. diff --git a/src/pkg/bytes/bytes_decl.go b/src/pkg/bytes/bytes_decl.go deleted file mode 100644 index 617d7489a..000000000 --- a/src/pkg/bytes/bytes_decl.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package bytes - -//go:noescape - -// IndexByte returns the index of the first instance of c in s, or -1 if c is not present in s. -func IndexByte(s []byte, c byte) int // ../runtime/asm_$GOARCH.s - -//go:noescape - -// Equal returns a boolean reporting whether a and b -// are the same length and contain the same bytes. -// A nil argument is equivalent to an empty slice. -func Equal(a, b []byte) bool // ../runtime/asm_$GOARCH.s - -//go:noescape - -// Compare returns an integer comparing two byte slices lexicographically. -// The result will be 0 if a==b, -1 if a < b, and +1 if a > b. -// A nil argument is equivalent to an empty slice. -func Compare(a, b []byte) int // ../runtime/noasm_arm.goc or ../runtime/asm_{386,amd64}.s diff --git a/src/pkg/bytes/bytes_test.go b/src/pkg/bytes/bytes_test.go deleted file mode 100644 index 980c41d75..000000000 --- a/src/pkg/bytes/bytes_test.go +++ /dev/null @@ -1,1240 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package bytes_test - -import ( - . "bytes" - "math/rand" - "reflect" - "testing" - "unicode" - "unicode/utf8" -) - -func eq(a, b []string) bool { - if len(a) != len(b) { - return false - } - for i := 0; i < len(a); i++ { - if a[i] != b[i] { - return false - } - } - return true -} - -func sliceOfString(s [][]byte) []string { - result := make([]string, len(s)) - for i, v := range s { - result[i] = string(v) - } - return result -} - -// For ease of reading, the test cases use strings that are converted to byte -// slices before invoking the functions. - -var abcd = "abcd" -var faces = "☺☻☹" -var commas = "1,2,3,4" -var dots = "1....2....3....4" - -type BinOpTest struct { - a string - b string - i int -} - -var equalTests = []struct { - a, b []byte - i int -}{ - {[]byte(""), []byte(""), 0}, - {[]byte("a"), []byte(""), 1}, - {[]byte(""), []byte("a"), -1}, - {[]byte("abc"), []byte("abc"), 0}, - {[]byte("ab"), []byte("abc"), -1}, - {[]byte("abc"), []byte("ab"), 1}, - {[]byte("x"), []byte("ab"), 1}, - {[]byte("ab"), []byte("x"), -1}, - {[]byte("x"), []byte("a"), 1}, - {[]byte("b"), []byte("x"), -1}, - // test runtime·memeq's chunked implementation - {[]byte("abcdefgh"), []byte("abcdefgh"), 0}, - {[]byte("abcdefghi"), []byte("abcdefghi"), 0}, - {[]byte("abcdefghi"), []byte("abcdefghj"), -1}, - // nil tests - {nil, nil, 0}, - {[]byte(""), nil, 0}, - {nil, []byte(""), 0}, - {[]byte("a"), nil, 1}, - {nil, []byte("a"), -1}, -} - -func TestEqual(t *testing.T) { - for _, tt := range compareTests { - eql := Equal(tt.a, tt.b) - if eql != (tt.i == 0) { - t.Errorf(`Equal(%q, %q) = %v`, tt.a, tt.b, eql) - } - eql = EqualPortable(tt.a, tt.b) - if eql != (tt.i == 0) { - t.Errorf(`EqualPortable(%q, %q) = %v`, tt.a, tt.b, eql) - } - } -} - -func TestEqualExhaustive(t *testing.T) { - var size = 128 - if testing.Short() { - size = 32 - } - a := make([]byte, size) - b := make([]byte, size) - b_init := make([]byte, size) - // randomish but deterministic data - for i := 0; i < size; i++ { - a[i] = byte(17 * i) - b_init[i] = byte(23*i + 100) - } - - for len := 0; len <= size; len++ { - for x := 0; x <= size-len; x++ { - for y := 0; y <= size-len; y++ { - copy(b, b_init) - copy(b[y:y+len], a[x:x+len]) - if !Equal(a[x:x+len], b[y:y+len]) || !Equal(b[y:y+len], a[x:x+len]) { - t.Errorf("Equal(%d, %d, %d) = false", len, x, y) - } - } - } - } -} - -// make sure Equal returns false for minimally different strings. The data -// is all zeros except for a single one in one location. -func TestNotEqual(t *testing.T) { - var size = 128 - if testing.Short() { - size = 32 - } - a := make([]byte, size) - b := make([]byte, size) - - for len := 0; len <= size; len++ { - for x := 0; x <= size-len; x++ { - for y := 0; y <= size-len; y++ { - for diffpos := x; diffpos < x+len; diffpos++ { - a[diffpos] = 1 - if Equal(a[x:x+len], b[y:y+len]) || Equal(b[y:y+len], a[x:x+len]) { - t.Errorf("NotEqual(%d, %d, %d, %d) = true", len, x, y, diffpos) - } - a[diffpos] = 0 - } - } - } - } -} - -var indexTests = []BinOpTest{ - {"", "", 0}, - {"", "a", -1}, - {"", "foo", -1}, - {"fo", "foo", -1}, - {"foo", "baz", -1}, - {"foo", "foo", 0}, - {"oofofoofooo", "f", 2}, - {"oofofoofooo", "foo", 4}, - {"barfoobarfoo", "foo", 3}, - {"foo", "", 0}, - {"foo", "o", 1}, - {"abcABCabc", "A", 3}, - // cases with one byte strings - test IndexByte and special case in Index() - {"", "a", -1}, - {"x", "a", -1}, - {"x", "x", 0}, - {"abc", "a", 0}, - {"abc", "b", 1}, - {"abc", "c", 2}, - {"abc", "x", -1}, - {"barfoobarfooyyyzzzyyyzzzyyyzzzyyyxxxzzzyyy", "x", 33}, - {"foofyfoobarfoobar", "y", 4}, - {"oooooooooooooooooooooo", "r", -1}, -} - -var lastIndexTests = []BinOpTest{ - {"", "", 0}, - {"", "a", -1}, - {"", "foo", -1}, - {"fo", "foo", -1}, - {"foo", "foo", 0}, - {"foo", "f", 0}, - {"oofofoofooo", "f", 7}, - {"oofofoofooo", "foo", 7}, - {"barfoobarfoo", "foo", 9}, - {"foo", "", 3}, - {"foo", "o", 2}, - {"abcABCabc", "A", 3}, - {"abcABCabc", "a", 6}, -} - -var indexAnyTests = []BinOpTest{ - {"", "", -1}, - {"", "a", -1}, - {"", "abc", -1}, - {"a", "", -1}, - {"a", "a", 0}, - {"aaa", "a", 0}, - {"abc", "xyz", -1}, - {"abc", "xcz", 2}, - {"ab☺c", "x☺yz", 2}, - {"aRegExp*", ".(|)*+?^$[]", 7}, - {dots + dots + dots, " ", -1}, -} - -var lastIndexAnyTests = []BinOpTest{ - {"", "", -1}, - {"", "a", -1}, - {"", "abc", -1}, - {"a", "", -1}, - {"a", "a", 0}, - {"aaa", "a", 2}, - {"abc", "xyz", -1}, - {"abc", "ab", 1}, - {"a☺b☻c☹d", "uvw☻xyz", 2 + len("☺")}, - {"a.RegExp*", ".(|)*+?^$[]", 8}, - {dots + dots + dots, " ", -1}, -} - -var indexRuneTests = []BinOpTest{ - {"", "a", -1}, - {"", "☺", -1}, - {"foo", "☹", -1}, - {"foo", "o", 1}, - {"foo☺bar", "☺", 3}, - {"foo☺☻☹bar", "☹", 9}, -} - -// Execute f on each test case. funcName should be the name of f; it's used -// in failure reports. -func runIndexTests(t *testing.T, f func(s, sep []byte) int, funcName string, testCases []BinOpTest) { - for _, test := range testCases { - a := []byte(test.a) - b := []byte(test.b) - actual := f(a, b) - if actual != test.i { - t.Errorf("%s(%q,%q) = %v; want %v", funcName, a, b, actual, test.i) - } - } -} - -func runIndexAnyTests(t *testing.T, f func(s []byte, chars string) int, funcName string, testCases []BinOpTest) { - for _, test := range testCases { - a := []byte(test.a) - actual := f(a, test.b) - if actual != test.i { - t.Errorf("%s(%q,%q) = %v; want %v", funcName, a, test.b, actual, test.i) - } - } -} - -func TestIndex(t *testing.T) { runIndexTests(t, Index, "Index", indexTests) } -func TestLastIndex(t *testing.T) { runIndexTests(t, LastIndex, "LastIndex", lastIndexTests) } -func TestIndexAny(t *testing.T) { runIndexAnyTests(t, IndexAny, "IndexAny", indexAnyTests) } -func TestLastIndexAny(t *testing.T) { - runIndexAnyTests(t, LastIndexAny, "LastIndexAny", lastIndexAnyTests) -} - -func TestIndexByte(t *testing.T) { - for _, tt := range indexTests { - if len(tt.b) != 1 { - continue - } - a := []byte(tt.a) - b := tt.b[0] - pos := IndexByte(a, b) - if pos != tt.i { - t.Errorf(`IndexByte(%q, '%c') = %v`, tt.a, b, pos) - } - posp := IndexBytePortable(a, b) - if posp != tt.i { - t.Errorf(`indexBytePortable(%q, '%c') = %v`, tt.a, b, posp) - } - } -} - -// test a larger buffer with different sizes and alignments -func TestIndexByteBig(t *testing.T) { - var n = 1024 - if testing.Short() { - n = 128 - } - b := make([]byte, n) - for i := 0; i < n; i++ { - // different start alignments - b1 := b[i:] - for j := 0; j < len(b1); j++ { - b1[j] = 'x' - pos := IndexByte(b1, 'x') - if pos != j { - t.Errorf("IndexByte(%q, 'x') = %v", b1, pos) - } - b1[j] = 0 - pos = IndexByte(b1, 'x') - if pos != -1 { - t.Errorf("IndexByte(%q, 'x') = %v", b1, pos) - } - } - // different end alignments - b1 = b[:i] - for j := 0; j < len(b1); j++ { - b1[j] = 'x' - pos := IndexByte(b1, 'x') - if pos != j { - t.Errorf("IndexByte(%q, 'x') = %v", b1, pos) - } - b1[j] = 0 - pos = IndexByte(b1, 'x') - if pos != -1 { - t.Errorf("IndexByte(%q, 'x') = %v", b1, pos) - } - } - // different start and end alignments - b1 = b[i/2 : n-(i+1)/2] - for j := 0; j < len(b1); j++ { - b1[j] = 'x' - pos := IndexByte(b1, 'x') - if pos != j { - t.Errorf("IndexByte(%q, 'x') = %v", b1, pos) - } - b1[j] = 0 - pos = IndexByte(b1, 'x') - if pos != -1 { - t.Errorf("IndexByte(%q, 'x') = %v", b1, pos) - } - } - } -} - -func TestIndexRune(t *testing.T) { - for _, tt := range indexRuneTests { - a := []byte(tt.a) - r, _ := utf8.DecodeRuneInString(tt.b) - pos := IndexRune(a, r) - if pos != tt.i { - t.Errorf(`IndexRune(%q, '%c') = %v`, tt.a, r, pos) - } - } -} - -var bmbuf []byte - -func BenchmarkIndexByte32(b *testing.B) { bmIndexByte(b, IndexByte, 32) } -func BenchmarkIndexByte4K(b *testing.B) { bmIndexByte(b, IndexByte, 4<<10) } -func BenchmarkIndexByte4M(b *testing.B) { bmIndexByte(b, IndexByte, 4<<20) } -func BenchmarkIndexByte64M(b *testing.B) { bmIndexByte(b, IndexByte, 64<<20) } -func BenchmarkIndexBytePortable32(b *testing.B) { bmIndexByte(b, IndexBytePortable, 32) } -func BenchmarkIndexBytePortable4K(b *testing.B) { bmIndexByte(b, IndexBytePortable, 4<<10) } -func BenchmarkIndexBytePortable4M(b *testing.B) { bmIndexByte(b, IndexBytePortable, 4<<20) } -func BenchmarkIndexBytePortable64M(b *testing.B) { bmIndexByte(b, IndexBytePortable, 64<<20) } - -func bmIndexByte(b *testing.B, index func([]byte, byte) int, n int) { - if len(bmbuf) < n { - bmbuf = make([]byte, n) - } - b.SetBytes(int64(n)) - buf := bmbuf[0:n] - buf[n-1] = 'x' - for i := 0; i < b.N; i++ { - j := index(buf, 'x') - if j != n-1 { - b.Fatal("bad index", j) - } - } - buf[n-1] = '\x00' -} - -func BenchmarkEqual0(b *testing.B) { - var buf [4]byte - buf1 := buf[0:0] - buf2 := buf[1:1] - for i := 0; i < b.N; i++ { - eq := Equal(buf1, buf2) - if !eq { - b.Fatal("bad equal") - } - } -} - -func BenchmarkEqual1(b *testing.B) { bmEqual(b, Equal, 1) } -func BenchmarkEqual6(b *testing.B) { bmEqual(b, Equal, 6) } -func BenchmarkEqual9(b *testing.B) { bmEqual(b, Equal, 9) } -func BenchmarkEqual15(b *testing.B) { bmEqual(b, Equal, 15) } -func BenchmarkEqual16(b *testing.B) { bmEqual(b, Equal, 16) } -func BenchmarkEqual20(b *testing.B) { bmEqual(b, Equal, 20) } -func BenchmarkEqual32(b *testing.B) { bmEqual(b, Equal, 32) } -func BenchmarkEqual4K(b *testing.B) { bmEqual(b, Equal, 4<<10) } -func BenchmarkEqual4M(b *testing.B) { bmEqual(b, Equal, 4<<20) } -func BenchmarkEqual64M(b *testing.B) { bmEqual(b, Equal, 64<<20) } -func BenchmarkEqualPort1(b *testing.B) { bmEqual(b, EqualPortable, 1) } -func BenchmarkEqualPort6(b *testing.B) { bmEqual(b, EqualPortable, 6) } -func BenchmarkEqualPort32(b *testing.B) { bmEqual(b, EqualPortable, 32) } -func BenchmarkEqualPort4K(b *testing.B) { bmEqual(b, EqualPortable, 4<<10) } -func BenchmarkEqualPortable4M(b *testing.B) { bmEqual(b, EqualPortable, 4<<20) } -func BenchmarkEqualPortable64M(b *testing.B) { bmEqual(b, EqualPortable, 64<<20) } - -func bmEqual(b *testing.B, equal func([]byte, []byte) bool, n int) { - if len(bmbuf) < 2*n { - bmbuf = make([]byte, 2*n) - } - b.SetBytes(int64(n)) - buf1 := bmbuf[0:n] - buf2 := bmbuf[n : 2*n] - buf1[n-1] = 'x' - buf2[n-1] = 'x' - for i := 0; i < b.N; i++ { - eq := equal(buf1, buf2) - if !eq { - b.Fatal("bad equal") - } - } - buf1[n-1] = '\x00' - buf2[n-1] = '\x00' -} - -func BenchmarkIndex32(b *testing.B) { bmIndex(b, Index, 32) } -func BenchmarkIndex4K(b *testing.B) { bmIndex(b, Index, 4<<10) } -func BenchmarkIndex4M(b *testing.B) { bmIndex(b, Index, 4<<20) } -func BenchmarkIndex64M(b *testing.B) { bmIndex(b, Index, 64<<20) } - -func bmIndex(b *testing.B, index func([]byte, []byte) int, n int) { - if len(bmbuf) < n { - bmbuf = make([]byte, n) - } - b.SetBytes(int64(n)) - buf := bmbuf[0:n] - buf[n-1] = 'x' - for i := 0; i < b.N; i++ { - j := index(buf, buf[n-7:]) - if j != n-7 { - b.Fatal("bad index", j) - } - } - buf[n-1] = '\x00' -} - -func BenchmarkIndexEasy32(b *testing.B) { bmIndexEasy(b, Index, 32) } -func BenchmarkIndexEasy4K(b *testing.B) { bmIndexEasy(b, Index, 4<<10) } -func BenchmarkIndexEasy4M(b *testing.B) { bmIndexEasy(b, Index, 4<<20) } -func BenchmarkIndexEasy64M(b *testing.B) { bmIndexEasy(b, Index, 64<<20) } - -func bmIndexEasy(b *testing.B, index func([]byte, []byte) int, n int) { - if len(bmbuf) < n { - bmbuf = make([]byte, n) - } - b.SetBytes(int64(n)) - buf := bmbuf[0:n] - buf[n-1] = 'x' - buf[n-7] = 'x' - for i := 0; i < b.N; i++ { - j := index(buf, buf[n-7:]) - if j != n-7 { - b.Fatal("bad index", j) - } - } - buf[n-1] = '\x00' - buf[n-7] = '\x00' -} - -func BenchmarkCount32(b *testing.B) { bmCount(b, Count, 32) } -func BenchmarkCount4K(b *testing.B) { bmCount(b, Count, 4<<10) } -func BenchmarkCount4M(b *testing.B) { bmCount(b, Count, 4<<20) } -func BenchmarkCount64M(b *testing.B) { bmCount(b, Count, 64<<20) } - -func bmCount(b *testing.B, count func([]byte, []byte) int, n int) { - if len(bmbuf) < n { - bmbuf = make([]byte, n) - } - b.SetBytes(int64(n)) - buf := bmbuf[0:n] - buf[n-1] = 'x' - for i := 0; i < b.N; i++ { - j := count(buf, buf[n-7:]) - if j != 1 { - b.Fatal("bad count", j) - } - } - buf[n-1] = '\x00' -} - -func BenchmarkCountEasy32(b *testing.B) { bmCountEasy(b, Count, 32) } -func BenchmarkCountEasy4K(b *testing.B) { bmCountEasy(b, Count, 4<<10) } -func BenchmarkCountEasy4M(b *testing.B) { bmCountEasy(b, Count, 4<<20) } -func BenchmarkCountEasy64M(b *testing.B) { bmCountEasy(b, Count, 64<<20) } - -func bmCountEasy(b *testing.B, count func([]byte, []byte) int, n int) { - if len(bmbuf) < n { - bmbuf = make([]byte, n) - } - b.SetBytes(int64(n)) - buf := bmbuf[0:n] - buf[n-1] = 'x' - buf[n-7] = 'x' - for i := 0; i < b.N; i++ { - j := count(buf, buf[n-7:]) - if j != 1 { - b.Fatal("bad count", j) - } - } - buf[n-1] = '\x00' - buf[n-7] = '\x00' -} - -type ExplodeTest struct { - s string - n int - a []string -} - -var explodetests = []ExplodeTest{ - {"", -1, []string{}}, - {abcd, -1, []string{"a", "b", "c", "d"}}, - {faces, -1, []string{"☺", "☻", "☹"}}, - {abcd, 2, []string{"a", "bcd"}}, -} - -func TestExplode(t *testing.T) { - for _, tt := range explodetests { - a := SplitN([]byte(tt.s), nil, tt.n) - result := sliceOfString(a) - if !eq(result, tt.a) { - t.Errorf(`Explode("%s", %d) = %v; want %v`, tt.s, tt.n, result, tt.a) - continue - } - s := Join(a, []byte{}) - if string(s) != tt.s { - t.Errorf(`Join(Explode("%s", %d), "") = "%s"`, tt.s, tt.n, s) - } - } -} - -type SplitTest struct { - s string - sep string - n int - a []string -} - -var splittests = []SplitTest{ - {abcd, "a", 0, nil}, - {abcd, "a", -1, []string{"", "bcd"}}, - {abcd, "z", -1, []string{"abcd"}}, - {abcd, "", -1, []string{"a", "b", "c", "d"}}, - {commas, ",", -1, []string{"1", "2", "3", "4"}}, - {dots, "...", -1, []string{"1", ".2", ".3", ".4"}}, - {faces, "☹", -1, []string{"☺☻", ""}}, - {faces, "~", -1, []string{faces}}, - {faces, "", -1, []string{"☺", "☻", "☹"}}, - {"1 2 3 4", " ", 3, []string{"1", "2", "3 4"}}, - {"1 2", " ", 3, []string{"1", "2"}}, - {"123", "", 2, []string{"1", "23"}}, - {"123", "", 17, []string{"1", "2", "3"}}, -} - -func TestSplit(t *testing.T) { - for _, tt := range splittests { - a := SplitN([]byte(tt.s), []byte(tt.sep), tt.n) - result := sliceOfString(a) - if !eq(result, tt.a) { - t.Errorf(`Split(%q, %q, %d) = %v; want %v`, tt.s, tt.sep, tt.n, result, tt.a) - continue - } - if tt.n == 0 { - continue - } - s := Join(a, []byte(tt.sep)) - if string(s) != tt.s { - t.Errorf(`Join(Split(%q, %q, %d), %q) = %q`, tt.s, tt.sep, tt.n, tt.sep, s) - } - if tt.n < 0 { - b := Split([]byte(tt.s), []byte(tt.sep)) - if !reflect.DeepEqual(a, b) { - t.Errorf("Split disagrees withSplitN(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, b, a) - } - } - if len(a) > 0 { - in, out := a[0], s - if cap(in) == cap(out) && &in[:1][0] == &out[:1][0] { - t.Errorf("Join(%#v, %q) didn't copy", a, tt.sep) - } - } - } -} - -var splitaftertests = []SplitTest{ - {abcd, "a", -1, []string{"a", "bcd"}}, - {abcd, "z", -1, []string{"abcd"}}, - {abcd, "", -1, []string{"a", "b", "c", "d"}}, - {commas, ",", -1, []string{"1,", "2,", "3,", "4"}}, - {dots, "...", -1, []string{"1...", ".2...", ".3...", ".4"}}, - {faces, "☹", -1, []string{"☺☻☹", ""}}, - {faces, "~", -1, []string{faces}}, - {faces, "", -1, []string{"☺", "☻", "☹"}}, - {"1 2 3 4", " ", 3, []string{"1 ", "2 ", "3 4"}}, - {"1 2 3", " ", 3, []string{"1 ", "2 ", "3"}}, - {"1 2", " ", 3, []string{"1 ", "2"}}, - {"123", "", 2, []string{"1", "23"}}, - {"123", "", 17, []string{"1", "2", "3"}}, -} - -func TestSplitAfter(t *testing.T) { - for _, tt := range splitaftertests { - a := SplitAfterN([]byte(tt.s), []byte(tt.sep), tt.n) - result := sliceOfString(a) - if !eq(result, tt.a) { - t.Errorf(`Split(%q, %q, %d) = %v; want %v`, tt.s, tt.sep, tt.n, result, tt.a) - continue - } - s := Join(a, nil) - if string(s) != tt.s { - t.Errorf(`Join(Split(%q, %q, %d), %q) = %q`, tt.s, tt.sep, tt.n, tt.sep, s) - } - if tt.n < 0 { - b := SplitAfter([]byte(tt.s), []byte(tt.sep)) - if !reflect.DeepEqual(a, b) { - t.Errorf("SplitAfter disagrees withSplitAfterN(%q, %q, %d) = %v; want %v", tt.s, tt.sep, tt.n, b, a) - } - } - } -} - -type FieldsTest struct { - s string - a []string -} - -var fieldstests = []FieldsTest{ - {"", []string{}}, - {" ", []string{}}, - {" \t ", []string{}}, - {" abc ", []string{"abc"}}, - {"1 2 3 4", []string{"1", "2", "3", "4"}}, - {"1 2 3 4", []string{"1", "2", "3", "4"}}, - {"1\t\t2\t\t3\t4", []string{"1", "2", "3", "4"}}, - {"1\u20002\u20013\u20024", []string{"1", "2", "3", "4"}}, - {"\u2000\u2001\u2002", []string{}}, - {"\n™\t™\n", []string{"™", "™"}}, - {faces, []string{faces}}, -} - -func TestFields(t *testing.T) { - for _, tt := range fieldstests { - a := Fields([]byte(tt.s)) - result := sliceOfString(a) - if !eq(result, tt.a) { - t.Errorf("Fields(%q) = %v; want %v", tt.s, a, tt.a) - continue - } - } -} - -func TestFieldsFunc(t *testing.T) { - for _, tt := range fieldstests { - a := FieldsFunc([]byte(tt.s), unicode.IsSpace) - result := sliceOfString(a) - if !eq(result, tt.a) { - t.Errorf("FieldsFunc(%q, unicode.IsSpace) = %v; want %v", tt.s, a, tt.a) - continue - } - } - pred := func(c rune) bool { return c == 'X' } - var fieldsFuncTests = []FieldsTest{ - {"", []string{}}, - {"XX", []string{}}, - {"XXhiXXX", []string{"hi"}}, - {"aXXbXXXcX", []string{"a", "b", "c"}}, - } - for _, tt := range fieldsFuncTests { - a := FieldsFunc([]byte(tt.s), pred) - result := sliceOfString(a) - if !eq(result, tt.a) { - t.Errorf("FieldsFunc(%q) = %v, want %v", tt.s, a, tt.a) - } - } -} - -// Test case for any function which accepts and returns a byte slice. -// For ease of creation, we write the byte slices as strings. -type StringTest struct { - in, out string -} - -var upperTests = []StringTest{ - {"", ""}, - {"abc", "ABC"}, - {"AbC123", "ABC123"}, - {"azAZ09_", "AZAZ09_"}, - {"\u0250\u0250\u0250\u0250\u0250", "\u2C6F\u2C6F\u2C6F\u2C6F\u2C6F"}, // grows one byte per char -} - -var lowerTests = []StringTest{ - {"", ""}, - {"abc", "abc"}, - {"AbC123", "abc123"}, - {"azAZ09_", "azaz09_"}, - {"\u2C6D\u2C6D\u2C6D\u2C6D\u2C6D", "\u0251\u0251\u0251\u0251\u0251"}, // shrinks one byte per char -} - -const space = "\t\v\r\f\n\u0085\u00a0\u2000\u3000" - -var trimSpaceTests = []StringTest{ - {"", ""}, - {"abc", "abc"}, - {space + "abc" + space, "abc"}, - {" ", ""}, - {" \t\r\n \t\t\r\r\n\n ", ""}, - {" \t\r\n x\t\t\r\r\n\n ", "x"}, - {" \u2000\t\r\n x\t\t\r\r\ny\n \u3000", "x\t\t\r\r\ny"}, - {"1 \t\r\n2", "1 \t\r\n2"}, - {" x\x80", "x\x80"}, - {" x\xc0", "x\xc0"}, - {"x \xc0\xc0 ", "x \xc0\xc0"}, - {"x \xc0", "x \xc0"}, - {"x \xc0 ", "x \xc0"}, - {"x \xc0\xc0 ", "x \xc0\xc0"}, - {"x ☺\xc0\xc0 ", "x ☺\xc0\xc0"}, - {"x ☺ ", "x ☺"}, -} - -// Execute f on each test case. funcName should be the name of f; it's used -// in failure reports. -func runStringTests(t *testing.T, f func([]byte) []byte, funcName string, testCases []StringTest) { - for _, tc := range testCases { - actual := string(f([]byte(tc.in))) - if actual != tc.out { - t.Errorf("%s(%q) = %q; want %q", funcName, tc.in, actual, tc.out) - } - } -} - -func tenRunes(r rune) string { - runes := make([]rune, 10) - for i := range runes { - runes[i] = r - } - return string(runes) -} - -// User-defined self-inverse mapping function -func rot13(r rune) rune { - const step = 13 - if r >= 'a' && r <= 'z' { - return ((r - 'a' + step) % 26) + 'a' - } - if r >= 'A' && r <= 'Z' { - return ((r - 'A' + step) % 26) + 'A' - } - return r -} - -func TestMap(t *testing.T) { - // Run a couple of awful growth/shrinkage tests - a := tenRunes('a') - - // 1. Grow. This triggers two reallocations in Map. - maxRune := func(r rune) rune { return unicode.MaxRune } - m := Map(maxRune, []byte(a)) - expect := tenRunes(unicode.MaxRune) - if string(m) != expect { - t.Errorf("growing: expected %q got %q", expect, m) - } - - // 2. Shrink - minRune := func(r rune) rune { return 'a' } - m = Map(minRune, []byte(tenRunes(unicode.MaxRune))) - expect = a - if string(m) != expect { - t.Errorf("shrinking: expected %q got %q", expect, m) - } - - // 3. Rot13 - m = Map(rot13, []byte("a to zed")) - expect = "n gb mrq" - if string(m) != expect { - t.Errorf("rot13: expected %q got %q", expect, m) - } - - // 4. Rot13^2 - m = Map(rot13, Map(rot13, []byte("a to zed"))) - expect = "a to zed" - if string(m) != expect { - t.Errorf("rot13: expected %q got %q", expect, m) - } - - // 5. Drop - dropNotLatin := func(r rune) rune { - if unicode.Is(unicode.Latin, r) { - return r - } - return -1 - } - m = Map(dropNotLatin, []byte("Hello, 세계")) - expect = "Hello" - if string(m) != expect { - t.Errorf("drop: expected %q got %q", expect, m) - } - - // 6. Invalid rune - invalidRune := func(r rune) rune { - return utf8.MaxRune + 1 - } - m = Map(invalidRune, []byte("x")) - expect = "\uFFFD" - if string(m) != expect { - t.Errorf("invalidRune: expected %q got %q", expect, m) - } -} - -func TestToUpper(t *testing.T) { runStringTests(t, ToUpper, "ToUpper", upperTests) } - -func TestToLower(t *testing.T) { runStringTests(t, ToLower, "ToLower", lowerTests) } - -func TestTrimSpace(t *testing.T) { runStringTests(t, TrimSpace, "TrimSpace", trimSpaceTests) } - -type RepeatTest struct { - in, out string - count int -} - -var RepeatTests = []RepeatTest{ - {"", "", 0}, - {"", "", 1}, - {"", "", 2}, - {"-", "", 0}, - {"-", "-", 1}, - {"-", "----------", 10}, - {"abc ", "abc abc abc ", 3}, -} - -func TestRepeat(t *testing.T) { - for _, tt := range RepeatTests { - tin := []byte(tt.in) - tout := []byte(tt.out) - a := Repeat(tin, tt.count) - if !Equal(a, tout) { - t.Errorf("Repeat(%q, %d) = %q; want %q", tin, tt.count, a, tout) - continue - } - } -} - -func runesEqual(a, b []rune) bool { - if len(a) != len(b) { - return false - } - for i, r := range a { - if r != b[i] { - return false - } - } - return true -} - -type RunesTest struct { - in string - out []rune - lossy bool -} - -var RunesTests = []RunesTest{ - {"", []rune{}, false}, - {" ", []rune{32}, false}, - {"ABC", []rune{65, 66, 67}, false}, - {"abc", []rune{97, 98, 99}, false}, - {"\u65e5\u672c\u8a9e", []rune{26085, 26412, 35486}, false}, - {"ab\x80c", []rune{97, 98, 0xFFFD, 99}, true}, - {"ab\xc0c", []rune{97, 98, 0xFFFD, 99}, true}, -} - -func TestRunes(t *testing.T) { - for _, tt := range RunesTests { - tin := []byte(tt.in) - a := Runes(tin) - if !runesEqual(a, tt.out) { - t.Errorf("Runes(%q) = %v; want %v", tin, a, tt.out) - continue - } - if !tt.lossy { - // can only test reassembly if we didn't lose information - s := string(a) - if s != tt.in { - t.Errorf("string(Runes(%q)) = %x; want %x", tin, s, tin) - } - } - } -} - -type TrimTest struct { - f string - in, arg, out string -} - -var trimTests = []TrimTest{ - {"Trim", "abba", "a", "bb"}, - {"Trim", "abba", "ab", ""}, - {"TrimLeft", "abba", "ab", ""}, - {"TrimRight", "abba", "ab", ""}, - {"TrimLeft", "abba", "a", "bba"}, - {"TrimRight", "abba", "a", "abb"}, - {"Trim", "", "<>", "tag"}, - {"Trim", "* listitem", " *", "listitem"}, - {"Trim", `"quote"`, `"`, "quote"}, - {"Trim", "\u2C6F\u2C6F\u0250\u0250\u2C6F\u2C6F", "\u2C6F", "\u0250\u0250"}, - //empty string tests - {"Trim", "abba", "", "abba"}, - {"Trim", "", "123", ""}, - {"Trim", "", "", ""}, - {"TrimLeft", "abba", "", "abba"}, - {"TrimLeft", "", "123", ""}, - {"TrimLeft", "", "", ""}, - {"TrimRight", "abba", "", "abba"}, - {"TrimRight", "", "123", ""}, - {"TrimRight", "", "", ""}, - {"TrimRight", "☺\xc0", "☺", "☺\xc0"}, - {"TrimPrefix", "aabb", "a", "abb"}, - {"TrimPrefix", "aabb", "b", "aabb"}, - {"TrimSuffix", "aabb", "a", "aabb"}, - {"TrimSuffix", "aabb", "b", "aab"}, -} - -func TestTrim(t *testing.T) { - for _, tc := range trimTests { - name := tc.f - var f func([]byte, string) []byte - var fb func([]byte, []byte) []byte - switch name { - case "Trim": - f = Trim - case "TrimLeft": - f = TrimLeft - case "TrimRight": - f = TrimRight - case "TrimPrefix": - fb = TrimPrefix - case "TrimSuffix": - fb = TrimSuffix - default: - t.Errorf("Undefined trim function %s", name) - } - var actual string - if f != nil { - actual = string(f([]byte(tc.in), tc.arg)) - } else { - actual = string(fb([]byte(tc.in), []byte(tc.arg))) - } - if actual != tc.out { - t.Errorf("%s(%q, %q) = %q; want %q", name, tc.in, tc.arg, actual, tc.out) - } - } -} - -type predicate struct { - f func(r rune) bool - name string -} - -var isSpace = predicate{unicode.IsSpace, "IsSpace"} -var isDigit = predicate{unicode.IsDigit, "IsDigit"} -var isUpper = predicate{unicode.IsUpper, "IsUpper"} -var isValidRune = predicate{ - func(r rune) bool { - return r != utf8.RuneError - }, - "IsValidRune", -} - -type TrimFuncTest struct { - f predicate - in, out string -} - -func not(p predicate) predicate { - return predicate{ - func(r rune) bool { - return !p.f(r) - }, - "not " + p.name, - } -} - -var trimFuncTests = []TrimFuncTest{ - {isSpace, space + " hello " + space, "hello"}, - {isDigit, "\u0e50\u0e5212hello34\u0e50\u0e51", "hello"}, - {isUpper, "\u2C6F\u2C6F\u2C6F\u2C6FABCDhelloEF\u2C6F\u2C6FGH\u2C6F\u2C6F", "hello"}, - {not(isSpace), "hello" + space + "hello", space}, - {not(isDigit), "hello\u0e50\u0e521234\u0e50\u0e51helo", "\u0e50\u0e521234\u0e50\u0e51"}, - {isValidRune, "ab\xc0a\xc0cd", "\xc0a\xc0"}, - {not(isValidRune), "\xc0a\xc0", "a"}, -} - -func TestTrimFunc(t *testing.T) { - for _, tc := range trimFuncTests { - actual := string(TrimFunc([]byte(tc.in), tc.f.f)) - if actual != tc.out { - t.Errorf("TrimFunc(%q, %q) = %q; want %q", tc.in, tc.f.name, actual, tc.out) - } - } -} - -type IndexFuncTest struct { - in string - f predicate - first, last int -} - -var indexFuncTests = []IndexFuncTest{ - {"", isValidRune, -1, -1}, - {"abc", isDigit, -1, -1}, - {"0123", isDigit, 0, 3}, - {"a1b", isDigit, 1, 1}, - {space, isSpace, 0, len(space) - 3}, // last rune in space is 3 bytes - {"\u0e50\u0e5212hello34\u0e50\u0e51", isDigit, 0, 18}, - {"\u2C6F\u2C6F\u2C6F\u2C6FABCDhelloEF\u2C6F\u2C6FGH\u2C6F\u2C6F", isUpper, 0, 34}, - {"12\u0e50\u0e52hello34\u0e50\u0e51", not(isDigit), 8, 12}, - - // tests of invalid UTF-8 - {"\x801", isDigit, 1, 1}, - {"\x80abc", isDigit, -1, -1}, - {"\xc0a\xc0", isValidRune, 1, 1}, - {"\xc0a\xc0", not(isValidRune), 0, 2}, - {"\xc0☺\xc0", not(isValidRune), 0, 4}, - {"\xc0☺\xc0\xc0", not(isValidRune), 0, 5}, - {"ab\xc0a\xc0cd", not(isValidRune), 2, 4}, - {"a\xe0\x80cd", not(isValidRune), 1, 2}, -} - -func TestIndexFunc(t *testing.T) { - for _, tc := range indexFuncTests { - first := IndexFunc([]byte(tc.in), tc.f.f) - if first != tc.first { - t.Errorf("IndexFunc(%q, %s) = %d; want %d", tc.in, tc.f.name, first, tc.first) - } - last := LastIndexFunc([]byte(tc.in), tc.f.f) - if last != tc.last { - t.Errorf("LastIndexFunc(%q, %s) = %d; want %d", tc.in, tc.f.name, last, tc.last) - } - } -} - -type ReplaceTest struct { - in string - old, new string - n int - out string -} - -var ReplaceTests = []ReplaceTest{ - {"hello", "l", "L", 0, "hello"}, - {"hello", "l", "L", -1, "heLLo"}, - {"hello", "x", "X", -1, "hello"}, - {"", "x", "X", -1, ""}, - {"radar", "r", "", -1, "ada"}, - {"", "", "<>", -1, "<>"}, - {"banana", "a", "<>", -1, "b<>n<>n<>"}, - {"banana", "a", "<>", 1, "b<>nana"}, - {"banana", "a", "<>", 1000, "b<>n<>n<>"}, - {"banana", "an", "<>", -1, "b<><>a"}, - {"banana", "ana", "<>", -1, "b<>na"}, - {"banana", "", "<>", -1, "<>b<>a<>n<>a<>n<>a<>"}, - {"banana", "", "<>", 10, "<>b<>a<>n<>a<>n<>a<>"}, - {"banana", "", "<>", 6, "<>b<>a<>n<>a<>n<>a"}, - {"banana", "", "<>", 5, "<>b<>a<>n<>a<>na"}, - {"banana", "", "<>", 1, "<>banana"}, - {"banana", "a", "a", -1, "banana"}, - {"banana", "a", "a", 1, "banana"}, - {"☺☻☹", "", "<>", -1, "<>☺<>☻<>☹<>"}, -} - -func TestReplace(t *testing.T) { - for _, tt := range ReplaceTests { - in := append([]byte(tt.in), ""...) - in = in[:len(tt.in)] - out := Replace(in, []byte(tt.old), []byte(tt.new), tt.n) - if s := string(out); s != tt.out { - t.Errorf("Replace(%q, %q, %q, %d) = %q, want %q", tt.in, tt.old, tt.new, tt.n, s, tt.out) - } - if cap(in) == cap(out) && &in[:1][0] == &out[:1][0] { - t.Errorf("Replace(%q, %q, %q, %d) didn't copy", tt.in, tt.old, tt.new, tt.n) - } - } -} - -type TitleTest struct { - in, out string -} - -var TitleTests = []TitleTest{ - {"", ""}, - {"a", "A"}, - {" aaa aaa aaa ", " Aaa Aaa Aaa "}, - {" Aaa Aaa Aaa ", " Aaa Aaa Aaa "}, - {"123a456", "123a456"}, - {"double-blind", "Double-Blind"}, - {"ÿøû", "Ÿøû"}, - {"with_underscore", "With_underscore"}, - {"unicode \xe2\x80\xa8 line separator", "Unicode \xe2\x80\xa8 Line Separator"}, -} - -func TestTitle(t *testing.T) { - for _, tt := range TitleTests { - if s := string(Title([]byte(tt.in))); s != tt.out { - t.Errorf("Title(%q) = %q, want %q", tt.in, s, tt.out) - } - } -} - -var ToTitleTests = []TitleTest{ - {"", ""}, - {"a", "A"}, - {" aaa aaa aaa ", " AAA AAA AAA "}, - {" Aaa Aaa Aaa ", " AAA AAA AAA "}, - {"123a456", "123A456"}, - {"double-blind", "DOUBLE-BLIND"}, - {"ÿøû", "ŸØÛ"}, -} - -func TestToTitle(t *testing.T) { - for _, tt := range ToTitleTests { - if s := string(ToTitle([]byte(tt.in))); s != tt.out { - t.Errorf("ToTitle(%q) = %q, want %q", tt.in, s, tt.out) - } - } -} - -var EqualFoldTests = []struct { - s, t string - out bool -}{ - {"abc", "abc", true}, - {"ABcd", "ABcd", true}, - {"123abc", "123ABC", true}, - {"αβδ", "ΑΒΔ", true}, - {"abc", "xyz", false}, - {"abc", "XYZ", false}, - {"abcdefghijk", "abcdefghijX", false}, - {"abcdefghijk", "abcdefghij\u212A", true}, - {"abcdefghijK", "abcdefghij\u212A", true}, - {"abcdefghijkz", "abcdefghij\u212Ay", false}, - {"abcdefghijKz", "abcdefghij\u212Ay", false}, -} - -func TestEqualFold(t *testing.T) { - for _, tt := range EqualFoldTests { - if out := EqualFold([]byte(tt.s), []byte(tt.t)); out != tt.out { - t.Errorf("EqualFold(%#q, %#q) = %v, want %v", tt.s, tt.t, out, tt.out) - } - if out := EqualFold([]byte(tt.t), []byte(tt.s)); out != tt.out { - t.Errorf("EqualFold(%#q, %#q) = %v, want %v", tt.t, tt.s, out, tt.out) - } - } -} - -func TestBufferGrowNegative(t *testing.T) { - defer func() { - if err := recover(); err == nil { - t.Fatal("Grow(-1) should have panicked") - } - }() - var b Buffer - b.Grow(-1) -} - -func TestBufferTruncateNegative(t *testing.T) { - defer func() { - if err := recover(); err == nil { - t.Fatal("Truncate(-1) should have panicked") - } - }() - var b Buffer - b.Truncate(-1) -} - -func TestBufferTruncateOutOfRange(t *testing.T) { - defer func() { - if err := recover(); err == nil { - t.Fatal("Truncate(20) should have panicked") - } - }() - var b Buffer - b.Write(make([]byte, 10)) - b.Truncate(20) -} - -var containsTests = []struct { - b, subslice []byte - want bool -}{ - {[]byte("hello"), []byte("hel"), true}, - {[]byte("日本語"), []byte("日本"), true}, - {[]byte("hello"), []byte("Hello, world"), false}, - {[]byte("東京"), []byte("京東"), false}, -} - -func TestContains(t *testing.T) { - for _, tt := range containsTests { - if got := Contains(tt.b, tt.subslice); got != tt.want { - t.Errorf("Contains(%q, %q) = %v, want %v", tt.b, tt.subslice, got, tt.want) - } - } -} - -var makeFieldsInput = func() []byte { - x := make([]byte, 1<<20) - // Input is ~10% space, ~10% 2-byte UTF-8, rest ASCII non-space. - for i := range x { - switch rand.Intn(10) { - case 0: - x[i] = ' ' - case 1: - if i > 0 && x[i-1] == 'x' { - copy(x[i-1:], "χ") - break - } - fallthrough - default: - x[i] = 'x' - } - } - return x -} - -var fieldsInput = makeFieldsInput() - -func BenchmarkFields(b *testing.B) { - b.SetBytes(int64(len(fieldsInput))) - for i := 0; i < b.N; i++ { - Fields(fieldsInput) - } -} - -func BenchmarkFieldsFunc(b *testing.B) { - b.SetBytes(int64(len(fieldsInput))) - for i := 0; i < b.N; i++ { - FieldsFunc(fieldsInput, unicode.IsSpace) - } -} - -func BenchmarkTrimSpace(b *testing.B) { - s := []byte(" Some text. \n") - for i := 0; i < b.N; i++ { - TrimSpace(s) - } -} - -func BenchmarkRepeat(b *testing.B) { - for i := 0; i < b.N; i++ { - Repeat([]byte("-"), 80) - } -} diff --git a/src/pkg/bytes/compare_test.go b/src/pkg/bytes/compare_test.go deleted file mode 100644 index 63522374e..000000000 --- a/src/pkg/bytes/compare_test.go +++ /dev/null @@ -1,208 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package bytes_test - -import ( - . "bytes" - "testing" -) - -var compareTests = []struct { - a, b []byte - i int -}{ - {[]byte(""), []byte(""), 0}, - {[]byte("a"), []byte(""), 1}, - {[]byte(""), []byte("a"), -1}, - {[]byte("abc"), []byte("abc"), 0}, - {[]byte("ab"), []byte("abc"), -1}, - {[]byte("abc"), []byte("ab"), 1}, - {[]byte("x"), []byte("ab"), 1}, - {[]byte("ab"), []byte("x"), -1}, - {[]byte("x"), []byte("a"), 1}, - {[]byte("b"), []byte("x"), -1}, - // test runtime·memeq's chunked implementation - {[]byte("abcdefgh"), []byte("abcdefgh"), 0}, - {[]byte("abcdefghi"), []byte("abcdefghi"), 0}, - {[]byte("abcdefghi"), []byte("abcdefghj"), -1}, - // nil tests - {nil, nil, 0}, - {[]byte(""), nil, 0}, - {nil, []byte(""), 0}, - {[]byte("a"), nil, 1}, - {nil, []byte("a"), -1}, -} - -func TestCompare(t *testing.T) { - for _, tt := range compareTests { - cmp := Compare(tt.a, tt.b) - if cmp != tt.i { - t.Errorf(`Compare(%q, %q) = %v`, tt.a, tt.b, cmp) - } - } -} - -func TestCompareIdenticalSlice(t *testing.T) { - var b = []byte("Hello Gophers!") - if Compare(b, b) != 0 { - t.Error("b != b") - } - if Compare(b, b[:1]) != 1 { - t.Error("b > b[:1] failed") - } -} - -func TestCompareBytes(t *testing.T) { - n := 128 - a := make([]byte, n+1) - b := make([]byte, n+1) - for len := 0; len < 128; len++ { - // randomish but deterministic data. No 0 or 255. - for i := 0; i < len; i++ { - a[i] = byte(1 + 31*i%254) - b[i] = byte(1 + 31*i%254) - } - // data past the end is different - for i := len; i <= n; i++ { - a[i] = 8 - b[i] = 9 - } - cmp := Compare(a[:len], b[:len]) - if cmp != 0 { - t.Errorf(`CompareIdentical(%d) = %d`, len, cmp) - } - if len > 0 { - cmp = Compare(a[:len-1], b[:len]) - if cmp != -1 { - t.Errorf(`CompareAshorter(%d) = %d`, len, cmp) - } - cmp = Compare(a[:len], b[:len-1]) - if cmp != 1 { - t.Errorf(`CompareBshorter(%d) = %d`, len, cmp) - } - } - for k := 0; k < len; k++ { - b[k] = a[k] - 1 - cmp = Compare(a[:len], b[:len]) - if cmp != 1 { - t.Errorf(`CompareAbigger(%d,%d) = %d`, len, k, cmp) - } - b[k] = a[k] + 1 - cmp = Compare(a[:len], b[:len]) - if cmp != -1 { - t.Errorf(`CompareBbigger(%d,%d) = %d`, len, k, cmp) - } - b[k] = a[k] - } - } -} - -func BenchmarkCompareBytesEqual(b *testing.B) { - b1 := []byte("Hello Gophers!") - b2 := []byte("Hello Gophers!") - for i := 0; i < b.N; i++ { - if Compare(b1, b2) != 0 { - b.Fatal("b1 != b2") - } - } -} - -func BenchmarkCompareBytesToNil(b *testing.B) { - b1 := []byte("Hello Gophers!") - var b2 []byte - for i := 0; i < b.N; i++ { - if Compare(b1, b2) != 1 { - b.Fatal("b1 > b2 failed") - } - } -} - -func BenchmarkCompareBytesEmpty(b *testing.B) { - b1 := []byte("") - b2 := b1 - for i := 0; i < b.N; i++ { - if Compare(b1, b2) != 0 { - b.Fatal("b1 != b2") - } - } -} - -func BenchmarkCompareBytesIdentical(b *testing.B) { - b1 := []byte("Hello Gophers!") - b2 := b1 - for i := 0; i < b.N; i++ { - if Compare(b1, b2) != 0 { - b.Fatal("b1 != b2") - } - } -} - -func BenchmarkCompareBytesSameLength(b *testing.B) { - b1 := []byte("Hello Gophers!") - b2 := []byte("Hello, Gophers") - for i := 0; i < b.N; i++ { - if Compare(b1, b2) != -1 { - b.Fatal("b1 < b2 failed") - } - } -} - -func BenchmarkCompareBytesDifferentLength(b *testing.B) { - b1 := []byte("Hello Gophers!") - b2 := []byte("Hello, Gophers!") - for i := 0; i < b.N; i++ { - if Compare(b1, b2) != -1 { - b.Fatal("b1 < b2 failed") - } - } -} - -func BenchmarkCompareBytesBigUnaligned(b *testing.B) { - b.StopTimer() - b1 := make([]byte, 0, 1<<20) - for len(b1) < 1<<20 { - b1 = append(b1, "Hello Gophers!"...) - } - b2 := append([]byte("hello"), b1...) - b.StartTimer() - for i := 0; i < b.N; i++ { - if Compare(b1, b2[len("hello"):]) != 0 { - b.Fatal("b1 != b2") - } - } - b.SetBytes(int64(len(b1))) -} - -func BenchmarkCompareBytesBig(b *testing.B) { - b.StopTimer() - b1 := make([]byte, 0, 1<<20) - for len(b1) < 1<<20 { - b1 = append(b1, "Hello Gophers!"...) - } - b2 := append([]byte{}, b1...) - b.StartTimer() - for i := 0; i < b.N; i++ { - if Compare(b1, b2) != 0 { - b.Fatal("b1 != b2") - } - } - b.SetBytes(int64(len(b1))) -} - -func BenchmarkCompareBytesBigIdentical(b *testing.B) { - b.StopTimer() - b1 := make([]byte, 0, 1<<20) - for len(b1) < 1<<20 { - b1 = append(b1, "Hello Gophers!"...) - } - b2 := b1 - b.StartTimer() - for i := 0; i < b.N; i++ { - if Compare(b1, b2) != 0 { - b.Fatal("b1 != b2") - } - } - b.SetBytes(int64(len(b1))) -} diff --git a/src/pkg/bytes/equal_test.go b/src/pkg/bytes/equal_test.go deleted file mode 100644 index 1bf19a74b..000000000 --- a/src/pkg/bytes/equal_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// -// +build linux - -package bytes_test - -import ( - . "bytes" - "syscall" - "testing" - "unsafe" -) - -// This file tests the situation where memeq is checking -// data very near to a page boundary. We want to make sure -// equal does not read across the boundary and cause a page -// fault where it shouldn't. - -// This test runs only on linux. The code being tested is -// not OS-specific, so it does not need to be tested on all -// operating systems. - -func TestEqualNearPageBoundary(t *testing.T) { - pagesize := syscall.Getpagesize() - b := make([]byte, 4*pagesize) - i := pagesize - for ; uintptr(unsafe.Pointer(&b[i]))%uintptr(pagesize) != 0; i++ { - } - syscall.Mprotect(b[i-pagesize:i], 0) - syscall.Mprotect(b[i+pagesize:i+2*pagesize], 0) - defer syscall.Mprotect(b[i-pagesize:i], syscall.PROT_READ|syscall.PROT_WRITE) - defer syscall.Mprotect(b[i+pagesize:i+2*pagesize], syscall.PROT_READ|syscall.PROT_WRITE) - - // both of these should fault - //pagesize += int(b[i-1]) - //pagesize += int(b[i+pagesize]) - - for j := 0; j < pagesize; j++ { - b[i+j] = 'A' - } - for j := 0; j <= pagesize; j++ { - Equal(b[i:i+j], b[i+pagesize-j:i+pagesize]) - Equal(b[i+pagesize-j:i+pagesize], b[i:i+j]) - } -} diff --git a/src/pkg/bytes/example_test.go b/src/pkg/bytes/example_test.go deleted file mode 100644 index ad2dbc69b..000000000 --- a/src/pkg/bytes/example_test.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package bytes_test - -import ( - "bytes" - "encoding/base64" - "fmt" - "io" - "os" - "sort" -) - -func ExampleBuffer() { - var b bytes.Buffer // A Buffer needs no initialization. - b.Write([]byte("Hello ")) - fmt.Fprintf(&b, "world!") - b.WriteTo(os.Stdout) - // Output: Hello world! -} - -func ExampleBuffer_reader() { - // A Buffer can turn a string or a []byte into an io.Reader. - buf := bytes.NewBufferString("R29waGVycyBydWxlIQ==") - dec := base64.NewDecoder(base64.StdEncoding, buf) - io.Copy(os.Stdout, dec) - // Output: Gophers rule! -} - -func ExampleCompare() { - // Interpret Compare's result by comparing it to zero. - var a, b []byte - if bytes.Compare(a, b) < 0 { - // a less b - } - if bytes.Compare(a, b) <= 0 { - // a less or equal b - } - if bytes.Compare(a, b) > 0 { - // a greater b - } - if bytes.Compare(a, b) >= 0 { - // a greater or equal b - } - - // Prefer Equal to Compare for equality comparisons. - if bytes.Equal(a, b) { - // a equal b - } - if !bytes.Equal(a, b) { - // a not equal b - } -} - -func ExampleCompare_search() { - // Binary search to find a matching byte slice. - var needle []byte - var haystack [][]byte // Assume sorted - i := sort.Search(len(haystack), func(i int) bool { - // Return haystack[i] >= needle. - return bytes.Compare(haystack[i], needle) >= 0 - }) - if i < len(haystack) && bytes.Equal(haystack[i], needle) { - // Found it! - } -} - -func ExampleTrimSuffix() { - var b = []byte("Hello, goodbye, etc!") - b = bytes.TrimSuffix(b, []byte("goodbye, etc!")) - b = bytes.TrimSuffix(b, []byte("gopher")) - b = append(b, bytes.TrimSuffix([]byte("world!"), []byte("x!"))...) - os.Stdout.Write(b) - // Output: Hello, world! -} - -func ExampleTrimPrefix() { - var b = []byte("Goodbye,, world!") - b = bytes.TrimPrefix(b, []byte("Goodbye,")) - b = bytes.TrimPrefix(b, []byte("See ya,")) - fmt.Printf("Hello%s", b) - // Output: Hello, world! -} diff --git a/src/pkg/bytes/export_test.go b/src/pkg/bytes/export_test.go deleted file mode 100644 index 3b915d5ea..000000000 --- a/src/pkg/bytes/export_test.go +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package bytes - -// Export func for testing -var IndexBytePortable = indexBytePortable -var EqualPortable = equalPortable - -func (b *Buffer) Cap() int { - return cap(b.buf) -} diff --git a/src/pkg/bytes/reader.go b/src/pkg/bytes/reader.go deleted file mode 100644 index d2d40fa7c..000000000 --- a/src/pkg/bytes/reader.go +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package bytes - -import ( - "errors" - "io" - "unicode/utf8" -) - -// A Reader implements the io.Reader, io.ReaderAt, io.WriterTo, io.Seeker, -// io.ByteScanner, and io.RuneScanner interfaces by reading from -// a byte slice. -// Unlike a Buffer, a Reader is read-only and supports seeking. -type Reader struct { - s []byte - i int64 // current reading index - prevRune int // index of previous rune; or < 0 -} - -// Len returns the number of bytes of the unread portion of the -// slice. -func (r *Reader) Len() int { - if r.i >= int64(len(r.s)) { - return 0 - } - return int(int64(len(r.s)) - r.i) -} - -func (r *Reader) Read(b []byte) (n int, err error) { - if len(b) == 0 { - return 0, nil - } - if r.i >= int64(len(r.s)) { - return 0, io.EOF - } - r.prevRune = -1 - n = copy(b, r.s[r.i:]) - r.i += int64(n) - return -} - -func (r *Reader) ReadAt(b []byte, off int64) (n int, err error) { - // cannot modify state - see io.ReaderAt - if off < 0 { - return 0, errors.New("bytes.Reader.ReadAt: negative offset") - } - if off >= int64(len(r.s)) { - return 0, io.EOF - } - n = copy(b, r.s[off:]) - if n < len(b) { - err = io.EOF - } - return -} - -func (r *Reader) ReadByte() (b byte, err error) { - r.prevRune = -1 - if r.i >= int64(len(r.s)) { - return 0, io.EOF - } - b = r.s[r.i] - r.i++ - return -} - -func (r *Reader) UnreadByte() error { - r.prevRune = -1 - if r.i <= 0 { - return errors.New("bytes.Reader.UnreadByte: at beginning of slice") - } - r.i-- - return nil -} - -func (r *Reader) ReadRune() (ch rune, size int, err error) { - if r.i >= int64(len(r.s)) { - r.prevRune = -1 - return 0, 0, io.EOF - } - r.prevRune = int(r.i) - if c := r.s[r.i]; c < utf8.RuneSelf { - r.i++ - return rune(c), 1, nil - } - ch, size = utf8.DecodeRune(r.s[r.i:]) - r.i += int64(size) - return -} - -func (r *Reader) UnreadRune() error { - if r.prevRune < 0 { - return errors.New("bytes.Reader.UnreadRune: previous operation was not ReadRune") - } - r.i = int64(r.prevRune) - r.prevRune = -1 - return nil -} - -// Seek implements the io.Seeker interface. -func (r *Reader) Seek(offset int64, whence int) (int64, error) { - r.prevRune = -1 - var abs int64 - switch whence { - case 0: - abs = offset - case 1: - abs = int64(r.i) + offset - case 2: - abs = int64(len(r.s)) + offset - default: - return 0, errors.New("bytes.Reader.Seek: invalid whence") - } - if abs < 0 { - return 0, errors.New("bytes.Reader.Seek: negative position") - } - r.i = abs - return abs, nil -} - -// WriteTo implements the io.WriterTo interface. -func (r *Reader) WriteTo(w io.Writer) (n int64, err error) { - r.prevRune = -1 - if r.i >= int64(len(r.s)) { - return 0, nil - } - b := r.s[r.i:] - m, err := w.Write(b) - if m > len(b) { - panic("bytes.Reader.WriteTo: invalid Write count") - } - r.i += int64(m) - n = int64(m) - if m != len(b) && err == nil { - err = io.ErrShortWrite - } - return -} - -// NewReader returns a new Reader reading from b. -func NewReader(b []byte) *Reader { return &Reader{b, 0, -1} } diff --git a/src/pkg/bytes/reader_test.go b/src/pkg/bytes/reader_test.go deleted file mode 100644 index d3dce5349..000000000 --- a/src/pkg/bytes/reader_test.go +++ /dev/null @@ -1,246 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package bytes_test - -import ( - . "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "sync" - "testing" -) - -func TestReader(t *testing.T) { - r := NewReader([]byte("0123456789")) - tests := []struct { - off int64 - seek int - n int - want string - wantpos int64 - seekerr string - }{ - {seek: os.SEEK_SET, off: 0, n: 20, want: "0123456789"}, - {seek: os.SEEK_SET, off: 1, n: 1, want: "1"}, - {seek: os.SEEK_CUR, off: 1, wantpos: 3, n: 2, want: "34"}, - {seek: os.SEEK_SET, off: -1, seekerr: "bytes.Reader.Seek: negative position"}, - {seek: os.SEEK_SET, off: 1 << 33, wantpos: 1 << 33}, - {seek: os.SEEK_CUR, off: 1, wantpos: 1<<33 + 1}, - {seek: os.SEEK_SET, n: 5, want: "01234"}, - {seek: os.SEEK_CUR, n: 5, want: "56789"}, - {seek: os.SEEK_END, off: -1, n: 1, wantpos: 9, want: "9"}, - } - - for i, tt := range tests { - pos, err := r.Seek(tt.off, tt.seek) - if err == nil && tt.seekerr != "" { - t.Errorf("%d. want seek error %q", i, tt.seekerr) - continue - } - if err != nil && err.Error() != tt.seekerr { - t.Errorf("%d. seek error = %q; want %q", i, err.Error(), tt.seekerr) - continue - } - if tt.wantpos != 0 && tt.wantpos != pos { - t.Errorf("%d. pos = %d, want %d", i, pos, tt.wantpos) - } - buf := make([]byte, tt.n) - n, err := r.Read(buf) - if err != nil { - t.Errorf("%d. read = %v", i, err) - continue - } - got := string(buf[:n]) - if got != tt.want { - t.Errorf("%d. got %q; want %q", i, got, tt.want) - } - } -} - -func TestReadAfterBigSeek(t *testing.T) { - r := NewReader([]byte("0123456789")) - if _, err := r.Seek(1<<31+5, os.SEEK_SET); err != nil { - t.Fatal(err) - } - if n, err := r.Read(make([]byte, 10)); n != 0 || err != io.EOF { - t.Errorf("Read = %d, %v; want 0, EOF", n, err) - } -} - -func TestReaderAt(t *testing.T) { - r := NewReader([]byte("0123456789")) - tests := []struct { - off int64 - n int - want string - wanterr interface{} - }{ - {0, 10, "0123456789", nil}, - {1, 10, "123456789", io.EOF}, - {1, 9, "123456789", nil}, - {11, 10, "", io.EOF}, - {0, 0, "", nil}, - {-1, 0, "", "bytes.Reader.ReadAt: negative offset"}, - } - for i, tt := range tests { - b := make([]byte, tt.n) - rn, err := r.ReadAt(b, tt.off) - got := string(b[:rn]) - if got != tt.want { - t.Errorf("%d. got %q; want %q", i, got, tt.want) - } - if fmt.Sprintf("%v", err) != fmt.Sprintf("%v", tt.wanterr) { - t.Errorf("%d. got error = %v; want %v", i, err, tt.wanterr) - } - } -} - -func TestReaderAtConcurrent(t *testing.T) { - // Test for the race detector, to verify ReadAt doesn't mutate - // any state. - r := NewReader([]byte("0123456789")) - var wg sync.WaitGroup - for i := 0; i < 5; i++ { - wg.Add(1) - go func(i int) { - defer wg.Done() - var buf [1]byte - r.ReadAt(buf[:], int64(i)) - }(i) - } - wg.Wait() -} - -func TestEmptyReaderConcurrent(t *testing.T) { - // Test for the race detector, to verify a Read that doesn't yield any bytes - // is okay to use from multiple goroutines. This was our historic behavior. - // See golang.org/issue/7856 - r := NewReader([]byte{}) - var wg sync.WaitGroup - for i := 0; i < 5; i++ { - wg.Add(2) - go func() { - defer wg.Done() - var buf [1]byte - r.Read(buf[:]) - }() - go func() { - defer wg.Done() - r.Read(nil) - }() - } - wg.Wait() -} - -func TestReaderWriteTo(t *testing.T) { - for i := 0; i < 30; i += 3 { - var l int - if i > 0 { - l = len(data) / i - } - s := data[:l] - r := NewReader(testBytes[:l]) - var b Buffer - n, err := r.WriteTo(&b) - if expect := int64(len(s)); n != expect { - t.Errorf("got %v; want %v", n, expect) - } - if err != nil { - t.Errorf("for length %d: got error = %v; want nil", l, err) - } - if b.String() != s { - t.Errorf("got string %q; want %q", b.String(), s) - } - if r.Len() != 0 { - t.Errorf("reader contains %v bytes; want 0", r.Len()) - } - } -} - -func TestReaderLen(t *testing.T) { - const data = "hello world" - r := NewReader([]byte(data)) - if got, want := r.Len(), 11; got != want { - t.Errorf("r.Len(): got %d, want %d", got, want) - } - if n, err := r.Read(make([]byte, 10)); err != nil || n != 10 { - t.Errorf("Read failed: read %d %v", n, err) - } - if got, want := r.Len(), 1; got != want { - t.Errorf("r.Len(): got %d, want %d", got, want) - } - if n, err := r.Read(make([]byte, 1)); err != nil || n != 1 { - t.Errorf("Read failed: read %d %v", n, err) - } - if got, want := r.Len(), 0; got != want { - t.Errorf("r.Len(): got %d, want %d", got, want) - } -} - -var UnreadRuneErrorTests = []struct { - name string - f func(*Reader) -}{ - {"Read", func(r *Reader) { r.Read([]byte{0}) }}, - {"ReadByte", func(r *Reader) { r.ReadByte() }}, - {"UnreadRune", func(r *Reader) { r.UnreadRune() }}, - {"Seek", func(r *Reader) { r.Seek(0, 1) }}, - {"WriteTo", func(r *Reader) { r.WriteTo(&Buffer{}) }}, -} - -func TestUnreadRuneError(t *testing.T) { - for _, tt := range UnreadRuneErrorTests { - reader := NewReader([]byte("0123456789")) - if _, _, err := reader.ReadRune(); err != nil { - // should not happen - t.Fatal(err) - } - tt.f(reader) - err := reader.UnreadRune() - if err == nil { - t.Errorf("Unreading after %s: expected error", tt.name) - } - } -} - -func TestReaderDoubleUnreadRune(t *testing.T) { - buf := NewBuffer([]byte("groucho")) - if _, _, err := buf.ReadRune(); err != nil { - // should not happen - t.Fatal(err) - } - if err := buf.UnreadByte(); err != nil { - // should not happen - t.Fatal(err) - } - if err := buf.UnreadByte(); err == nil { - t.Fatal("UnreadByte: expected error, got nil") - } -} - -// verify that copying from an empty reader always has the same results, -// regardless of the presence of a WriteTo method. -func TestReaderCopyNothing(t *testing.T) { - type nErr struct { - n int64 - err error - } - type justReader struct { - io.Reader - } - type justWriter struct { - io.Writer - } - discard := justWriter{ioutil.Discard} // hide ReadFrom - - var with, withOut nErr - with.n, with.err = io.Copy(discard, NewReader(nil)) - withOut.n, withOut.err = io.Copy(discard, justReader{NewReader(nil)}) - if with != withOut { - t.Errorf("behavior differs: with = %#v; without: %#v", with, withOut) - } -} diff --git a/src/pkg/compress/bzip2/bit_reader.go b/src/pkg/compress/bzip2/bit_reader.go deleted file mode 100644 index 32d1036ae..000000000 --- a/src/pkg/compress/bzip2/bit_reader.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package bzip2 - -import ( - "bufio" - "io" -) - -// bitReader wraps an io.Reader and provides the ability to read values, -// bit-by-bit, from it. Its Read* methods don't return the usual error -// because the error handling was verbose. Instead, any error is kept and can -// be checked afterwards. -type bitReader struct { - r io.ByteReader - n uint64 - bits uint - err error -} - -// newBitReader returns a new bitReader reading from r. If r is not -// already an io.ByteReader, it will be converted via a bufio.Reader. -func newBitReader(r io.Reader) bitReader { - byter, ok := r.(io.ByteReader) - if !ok { - byter = bufio.NewReader(r) - } - return bitReader{r: byter} -} - -// ReadBits64 reads the given number of bits and returns them in the -// least-significant part of a uint64. In the event of an error, it returns 0 -// and the error can be obtained by calling Err(). -func (br *bitReader) ReadBits64(bits uint) (n uint64) { - for bits > br.bits { - b, err := br.r.ReadByte() - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - if err != nil { - br.err = err - return 0 - } - br.n <<= 8 - br.n |= uint64(b) - br.bits += 8 - } - - // br.n looks like this (assuming that br.bits = 14 and bits = 6): - // Bit: 111111 - // 5432109876543210 - // - // (6 bits, the desired output) - // |-----| - // V V - // 0101101101001110 - // ^ ^ - // |------------| - // br.bits (num valid bits) - // - // This the next line right shifts the desired bits into the - // least-significant places and masks off anything above. - n = (br.n >> (br.bits - bits)) & ((1 << bits) - 1) - br.bits -= bits - return -} - -func (br *bitReader) ReadBits(bits uint) (n int) { - n64 := br.ReadBits64(bits) - return int(n64) -} - -func (br *bitReader) ReadBit() bool { - n := br.ReadBits(1) - return n != 0 -} - -func (br *bitReader) TryReadBit() (bit byte, ok bool) { - if br.bits > 0 { - br.bits-- - return byte(br.n>>br.bits) & 1, true - } - return 0, false -} - -func (br *bitReader) Err() error { - return br.err -} diff --git a/src/pkg/compress/bzip2/bzip2.go b/src/pkg/compress/bzip2/bzip2.go deleted file mode 100644 index d318116a1..000000000 --- a/src/pkg/compress/bzip2/bzip2.go +++ /dev/null @@ -1,501 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package bzip2 implements bzip2 decompression. -package bzip2 - -import "io" - -// There's no RFC for bzip2. I used the Wikipedia page for reference and a lot -// of guessing: http://en.wikipedia.org/wiki/Bzip2 -// The source code to pyflate was useful for debugging: -// http://www.paul.sladen.org/projects/pyflate - -// A StructuralError is returned when the bzip2 data is found to be -// syntactically invalid. -type StructuralError string - -func (s StructuralError) Error() string { - return "bzip2 data invalid: " + string(s) -} - -// A reader decompresses bzip2 compressed data. -type reader struct { - br bitReader - fileCRC uint32 - blockCRC uint32 - wantBlockCRC uint32 - setupDone bool // true if we have parsed the bzip2 header. - blockSize int // blockSize in bytes, i.e. 900 * 1024. - eof bool - buf []byte // stores Burrows-Wheeler transformed data. - c [256]uint // the `C' array for the inverse BWT. - tt []uint32 // mirrors the `tt' array in the bzip2 source and contains the P array in the upper 24 bits. - tPos uint32 // Index of the next output byte in tt. - - preRLE []uint32 // contains the RLE data still to be processed. - preRLEUsed int // number of entries of preRLE used. - lastByte int // the last byte value seen. - byteRepeats uint // the number of repeats of lastByte seen. - repeats uint // the number of copies of lastByte to output. -} - -// NewReader returns an io.Reader which decompresses bzip2 data from r. -func NewReader(r io.Reader) io.Reader { - bz2 := new(reader) - bz2.br = newBitReader(r) - return bz2 -} - -const bzip2FileMagic = 0x425a // "BZ" -const bzip2BlockMagic = 0x314159265359 -const bzip2FinalMagic = 0x177245385090 - -// setup parses the bzip2 header. -func (bz2 *reader) setup(needMagic bool) error { - br := &bz2.br - - if needMagic { - magic := br.ReadBits(16) - if magic != bzip2FileMagic { - return StructuralError("bad magic value") - } - } - - t := br.ReadBits(8) - if t != 'h' { - return StructuralError("non-Huffman entropy encoding") - } - - level := br.ReadBits(8) - if level < '1' || level > '9' { - return StructuralError("invalid compression level") - } - - bz2.fileCRC = 0 - bz2.blockSize = 100 * 1024 * (int(level) - '0') - if bz2.blockSize > len(bz2.tt) { - bz2.tt = make([]uint32, bz2.blockSize) - } - return nil -} - -func (bz2 *reader) Read(buf []byte) (n int, err error) { - if bz2.eof { - return 0, io.EOF - } - - if !bz2.setupDone { - err = bz2.setup(true) - brErr := bz2.br.Err() - if brErr != nil { - err = brErr - } - if err != nil { - return 0, err - } - bz2.setupDone = true - } - - n, err = bz2.read(buf) - brErr := bz2.br.Err() - if brErr != nil { - err = brErr - } - return -} - -func (bz2 *reader) readFromBlock(buf []byte) int { - // bzip2 is a block based compressor, except that it has a run-length - // preprocessing step. The block based nature means that we can - // preallocate fixed-size buffers and reuse them. However, the RLE - // preprocessing would require allocating huge buffers to store the - // maximum expansion. Thus we process blocks all at once, except for - // the RLE which we decompress as required. - n := 0 - for (bz2.repeats > 0 || bz2.preRLEUsed < len(bz2.preRLE)) && n < len(buf) { - // We have RLE data pending. - - // The run-length encoding works like this: - // Any sequence of four equal bytes is followed by a length - // byte which contains the number of repeats of that byte to - // include. (The number of repeats can be zero.) Because we are - // decompressing on-demand our state is kept in the reader - // object. - - if bz2.repeats > 0 { - buf[n] = byte(bz2.lastByte) - n++ - bz2.repeats-- - if bz2.repeats == 0 { - bz2.lastByte = -1 - } - continue - } - - bz2.tPos = bz2.preRLE[bz2.tPos] - b := byte(bz2.tPos) - bz2.tPos >>= 8 - bz2.preRLEUsed++ - - if bz2.byteRepeats == 3 { - bz2.repeats = uint(b) - bz2.byteRepeats = 0 - continue - } - - if bz2.lastByte == int(b) { - bz2.byteRepeats++ - } else { - bz2.byteRepeats = 0 - } - bz2.lastByte = int(b) - - buf[n] = b - n++ - } - - return n -} - -func (bz2 *reader) read(buf []byte) (int, error) { - for { - n := bz2.readFromBlock(buf) - if n > 0 { - bz2.blockCRC = updateCRC(bz2.blockCRC, buf[:n]) - return n, nil - } - - // End of block. Check CRC. - if bz2.blockCRC != bz2.wantBlockCRC { - bz2.br.err = StructuralError("block checksum mismatch") - return 0, bz2.br.err - } - - // Find next block. - br := &bz2.br - switch br.ReadBits64(48) { - default: - return 0, StructuralError("bad magic value found") - - case bzip2BlockMagic: - // Start of block. - err := bz2.readBlock() - if err != nil { - return 0, err - } - - case bzip2FinalMagic: - // Check end-of-file CRC. - wantFileCRC := uint32(br.ReadBits64(32)) - if br.err != nil { - return 0, br.err - } - if bz2.fileCRC != wantFileCRC { - br.err = StructuralError("file checksum mismatch") - return 0, br.err - } - - // Skip ahead to byte boundary. - // Is there a file concatenated to this one? - // It would start with BZ. - if br.bits%8 != 0 { - br.ReadBits(br.bits % 8) - } - b, err := br.r.ReadByte() - if err == io.EOF { - br.err = io.EOF - bz2.eof = true - return 0, io.EOF - } - if err != nil { - br.err = err - return 0, err - } - z, err := br.r.ReadByte() - if err != nil { - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - br.err = err - return 0, err - } - if b != 'B' || z != 'Z' { - return 0, StructuralError("bad magic value in continuation file") - } - if err := bz2.setup(false); err != nil { - return 0, err - } - } - } -} - -// readBlock reads a bzip2 block. The magic number should already have been consumed. -func (bz2 *reader) readBlock() (err error) { - br := &bz2.br - bz2.wantBlockCRC = uint32(br.ReadBits64(32)) // skip checksum. TODO: check it if we can figure out what it is. - bz2.blockCRC = 0 - bz2.fileCRC = (bz2.fileCRC<<1 | bz2.fileCRC>>31) ^ bz2.wantBlockCRC - randomized := br.ReadBits(1) - if randomized != 0 { - return StructuralError("deprecated randomized files") - } - origPtr := uint(br.ReadBits(24)) - - // If not every byte value is used in the block (i.e., it's text) then - // the symbol set is reduced. The symbols used are stored as a - // two-level, 16x16 bitmap. - symbolRangeUsedBitmap := br.ReadBits(16) - symbolPresent := make([]bool, 256) - numSymbols := 0 - for symRange := uint(0); symRange < 16; symRange++ { - if symbolRangeUsedBitmap&(1<<(15-symRange)) != 0 { - bits := br.ReadBits(16) - for symbol := uint(0); symbol < 16; symbol++ { - if bits&(1<<(15-symbol)) != 0 { - symbolPresent[16*symRange+symbol] = true - numSymbols++ - } - } - } - } - - if numSymbols == 0 { - // There must be an EOF symbol. - return StructuralError("no symbols in input") - } - - // A block uses between two and six different Huffman trees. - numHuffmanTrees := br.ReadBits(3) - if numHuffmanTrees < 2 || numHuffmanTrees > 6 { - return StructuralError("invalid number of Huffman trees") - } - - // The Huffman tree can switch every 50 symbols so there's a list of - // tree indexes telling us which tree to use for each 50 symbol block. - numSelectors := br.ReadBits(15) - treeIndexes := make([]uint8, numSelectors) - - // The tree indexes are move-to-front transformed and stored as unary - // numbers. - mtfTreeDecoder := newMTFDecoderWithRange(numHuffmanTrees) - for i := range treeIndexes { - c := 0 - for { - inc := br.ReadBits(1) - if inc == 0 { - break - } - c++ - } - if c >= numHuffmanTrees { - return StructuralError("tree index too large") - } - treeIndexes[i] = uint8(mtfTreeDecoder.Decode(c)) - } - - // The list of symbols for the move-to-front transform is taken from - // the previously decoded symbol bitmap. - symbols := make([]byte, numSymbols) - nextSymbol := 0 - for i := 0; i < 256; i++ { - if symbolPresent[i] { - symbols[nextSymbol] = byte(i) - nextSymbol++ - } - } - mtf := newMTFDecoder(symbols) - - numSymbols += 2 // to account for RUNA and RUNB symbols - huffmanTrees := make([]huffmanTree, numHuffmanTrees) - - // Now we decode the arrays of code-lengths for each tree. - lengths := make([]uint8, numSymbols) - for i := range huffmanTrees { - // The code lengths are delta encoded from a 5-bit base value. - length := br.ReadBits(5) - for j := range lengths { - for { - if !br.ReadBit() { - break - } - if br.ReadBit() { - length-- - } else { - length++ - } - } - if length < 0 || length > 20 { - return StructuralError("Huffman length out of range") - } - lengths[j] = uint8(length) - } - huffmanTrees[i], err = newHuffmanTree(lengths) - if err != nil { - return err - } - } - - selectorIndex := 1 // the next tree index to use - if len(treeIndexes) == 0 { - return StructuralError("no tree selectors given") - } - if int(treeIndexes[0]) >= len(huffmanTrees) { - return StructuralError("tree selector out of range") - } - currentHuffmanTree := huffmanTrees[treeIndexes[0]] - bufIndex := 0 // indexes bz2.buf, the output buffer. - // The output of the move-to-front transform is run-length encoded and - // we merge the decoding into the Huffman parsing loop. These two - // variables accumulate the repeat count. See the Wikipedia page for - // details. - repeat := 0 - repeat_power := 0 - - // The `C' array (used by the inverse BWT) needs to be zero initialized. - for i := range bz2.c { - bz2.c[i] = 0 - } - - decoded := 0 // counts the number of symbols decoded by the current tree. - for { - if decoded == 50 { - if selectorIndex >= numSelectors { - return StructuralError("insufficient selector indices for number of symbols") - } - if int(treeIndexes[selectorIndex]) >= len(huffmanTrees) { - return StructuralError("tree selector out of range") - } - currentHuffmanTree = huffmanTrees[treeIndexes[selectorIndex]] - selectorIndex++ - decoded = 0 - } - - v := currentHuffmanTree.Decode(br) - decoded++ - - if v < 2 { - // This is either the RUNA or RUNB symbol. - if repeat == 0 { - repeat_power = 1 - } - repeat += repeat_power << v - repeat_power <<= 1 - - // This limit of 2 million comes from the bzip2 source - // code. It prevents repeat from overflowing. - if repeat > 2*1024*1024 { - return StructuralError("repeat count too large") - } - continue - } - - if repeat > 0 { - // We have decoded a complete run-length so we need to - // replicate the last output symbol. - if repeat > bz2.blockSize-bufIndex { - return StructuralError("repeats past end of block") - } - for i := 0; i < repeat; i++ { - b := byte(mtf.First()) - bz2.tt[bufIndex] = uint32(b) - bz2.c[b]++ - bufIndex++ - } - repeat = 0 - } - - if int(v) == numSymbols-1 { - // This is the EOF symbol. Because it's always at the - // end of the move-to-front list, and never gets moved - // to the front, it has this unique value. - break - } - - // Since two metasymbols (RUNA and RUNB) have values 0 and 1, - // one would expect |v-2| to be passed to the MTF decoder. - // However, the front of the MTF list is never referenced as 0, - // it's always referenced with a run-length of 1. Thus 0 - // doesn't need to be encoded and we have |v-1| in the next - // line. - b := byte(mtf.Decode(int(v - 1))) - if bufIndex >= bz2.blockSize { - return StructuralError("data exceeds block size") - } - bz2.tt[bufIndex] = uint32(b) - bz2.c[b]++ - bufIndex++ - } - - if origPtr >= uint(bufIndex) { - return StructuralError("origPtr out of bounds") - } - - // We have completed the entropy decoding. Now we can perform the - // inverse BWT and setup the RLE buffer. - bz2.preRLE = bz2.tt[:bufIndex] - bz2.preRLEUsed = 0 - bz2.tPos = inverseBWT(bz2.preRLE, origPtr, bz2.c[:]) - bz2.lastByte = -1 - bz2.byteRepeats = 0 - bz2.repeats = 0 - - return nil -} - -// inverseBWT implements the inverse Burrows-Wheeler transform as described in -// http://www.hpl.hp.com/techreports/Compaq-DEC/SRC-RR-124.pdf, section 4.2. -// In that document, origPtr is called `I' and c is the `C' array after the -// first pass over the data. It's an argument here because we merge the first -// pass with the Huffman decoding. -// -// This also implements the `single array' method from the bzip2 source code -// which leaves the output, still shuffled, in the bottom 8 bits of tt with the -// index of the next byte in the top 24-bits. The index of the first byte is -// returned. -func inverseBWT(tt []uint32, origPtr uint, c []uint) uint32 { - sum := uint(0) - for i := 0; i < 256; i++ { - sum += c[i] - c[i] = sum - c[i] - } - - for i := range tt { - b := tt[i] & 0xff - tt[c[b]] |= uint32(i) << 8 - c[b]++ - } - - return tt[origPtr] >> 8 -} - -// This is a standard CRC32 like in hash/crc32 except that all the shifts are reversed, -// causing the bits in the input to be processed in the reverse of the usual order. - -var crctab [256]uint32 - -func init() { - const poly = 0x04C11DB7 - for i := range crctab { - crc := uint32(i) << 24 - for j := 0; j < 8; j++ { - if crc&0x80000000 != 0 { - crc = (crc << 1) ^ poly - } else { - crc <<= 1 - } - } - crctab[i] = crc - } -} - -// updateCRC updates the crc value to incorporate the data in b. -// The initial value is 0. -func updateCRC(val uint32, b []byte) uint32 { - crc := ^val - for _, v := range b { - crc = crctab[byte(crc>>24)^v] ^ (crc << 8) - } - return ^crc -} diff --git a/src/pkg/compress/bzip2/bzip2_test.go b/src/pkg/compress/bzip2/bzip2_test.go deleted file mode 100644 index fb79d089e..000000000 --- a/src/pkg/compress/bzip2/bzip2_test.go +++ /dev/null @@ -1,419 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package bzip2 - -import ( - "bytes" - "encoding/base64" - "encoding/hex" - "io" - "io/ioutil" - "testing" -) - -func TestBitReader(t *testing.T) { - buf := bytes.NewReader([]byte{0xaa}) - br := newBitReader(buf) - if n := br.ReadBits(1); n != 1 { - t.Errorf("read 1 wrong") - } - if n := br.ReadBits(1); n != 0 { - t.Errorf("read 2 wrong") - } - if n := br.ReadBits(1); n != 1 { - t.Errorf("read 3 wrong") - } - if n := br.ReadBits(1); n != 0 { - t.Errorf("read 4 wrong") - } -} - -func TestBitReaderLarge(t *testing.T) { - buf := bytes.NewReader([]byte{0x12, 0x34, 0x56, 0x78}) - br := newBitReader(buf) - if n := br.ReadBits(32); n != 0x12345678 { - t.Errorf("got: %x want: %x", n, 0x12345678) - } -} - -func readerFromHex(s string) io.Reader { - data, err := hex.DecodeString(s) - if err != nil { - panic("readerFromHex: bad input") - } - return bytes.NewReader(data) -} - -func decompressHex(s string) (out []byte, err error) { - r := NewReader(readerFromHex(s)) - return ioutil.ReadAll(r) -} - -func TestHelloWorldBZ2(t *testing.T) { - out, err := decompressHex(helloWorldBZ2Hex) - if err != nil { - t.Errorf("error from Read: %s", err) - return - } - - if !bytes.Equal(helloWorld, out) { - t.Errorf("got %x, want %x", out, helloWorld) - } -} - -func TestConcat(t *testing.T) { - out, err := decompressHex(helloWorldBZ2Hex + helloWorldBZ2Hex) - if err != nil { - t.Errorf("error from Read: %s", err) - return - } - - hello2 := bytes.Repeat(helloWorld, 2) - if !bytes.Equal(hello2, out) { - t.Errorf("got %x, want %x", out, hello2) - } -} - -func testZeros(t *testing.T, inHex string, n int) { - out, err := decompressHex(inHex) - if err != nil { - t.Errorf("error from Read: %s", err) - return - } - - expected := make([]byte, n) - - if !bytes.Equal(expected, out) { - allZeros := true - for _, b := range out { - if b != 0 { - allZeros = false - break - } - } - t.Errorf("incorrect result, got %d bytes (allZeros: %t)", len(out), allZeros) - } -} - -func Test32Zeros(t *testing.T) { - testZeros(t, thirtyTwoZerosBZ2Hex, 32) -} - -func Test1MBZeros(t *testing.T) { - testZeros(t, oneMBZerosBZ2Hex, 1024*1024) -} - -func testRandomData(t *testing.T, compressedHex, uncompressedHex string) { - out, err := decompressHex(compressedHex) - if err != nil { - t.Errorf("error from Read: %s", err) - return - } - - expected, _ := hex.DecodeString(uncompressedHex) - - if !bytes.Equal(out, expected) { - t.Errorf("incorrect result\ngot: %x\nwant: %x", out, expected) - } -} - -func TestRandomData1(t *testing.T) { - testRandomData(t, randBZ2Hex, randHex) -} - -func TestRandomData2(t *testing.T) { - // This test involves several repeated bytes in the output, but they - // should trigger RLE decoding. - testRandomData(t, rand2BZ2Hex, rand2Hex) -} - -func TestRandomData3(t *testing.T) { - // This test uses the full range of symbols. - testRandomData(t, rand3BZ2Hex, rand3Hex) -} - -func Test1MBSawtooth(t *testing.T) { - out, err := decompressHex(oneMBSawtoothBZ2Hex) - if err != nil { - t.Errorf("error from Read: %s", err) - return - } - - expected := make([]byte, 1024*1024) - - for i := range expected { - expected[i] = byte(i) - } - - if !bytes.Equal(out, expected) { - t.Error("incorrect result") - } -} - -const helloWorldBZ2Hex = "425a68393141592653594eece83600000251800010400006449080200031064c4101a7a9a580bb9431f8bb9229c28482776741b0" - -var helloWorld = []byte("hello world\n") - -const thirtyTwoZerosBZ2Hex = "425a6839314159265359b5aa5098000000600040000004200021008283177245385090b5aa5098" -const oneMBZerosBZ2Hex = "425a683931415926535938571ce50008084000c0040008200030cc0529a60806c4201e2ee48a70a12070ae39ca" - -const randBZ2Hex = "425a6839314159265359905d990d0001957fffffffffffafffffffffffffffffbfff6fffdfffffffffffffffffffffffffffffc002b6dd75676ed5b77720098320d11a64626981323d4da47a83131a13d09e8040f534cd4f4d27a464d193008cd09804601347a980026350c9886234d36864193d1351b44c136919e90340d26127a4cd264c32023009898981310c0344c340027a8303427a99a04c00003534c230d034f5006468d268cf54d36a3009a69a62626261311b40026013d34201a6934c9a604c98ca6c8460989fa9346234d30d3469a2604fd4131a7aa6d0046043d4c62098479269e89e835190d018d4c046001a11e801a0264792321932308c43a130688c260d46686804cd01a9e80981193684c6a68c00000004c4c20c04627a4c0000260003400d04c0681a01334026009a6f48041466132581ec5212b081d96b0effc16543e2228b052fcd30f2567ee8d970e0f10aabca68dd8270591c376cfc1baae0dba00aaff2d6caf6b211322c997cc18eaee5927f75185336bf907021324c71626c1dd20e22b9b0977f05d0f901eaa51db9fbaf7c603b4c87bc82890e6dd7e61d0079e27ec050dd788fd958152061cd01e222f9547cb9efc465d775b6fc98bac7d387bffd151ae09dadf19494f7a638e2eae58e550faba5fe6820ea520eb986096de4e527d80def3ba625e71fbefdcf7e7844e0a25d29b52dcd1344fca083737d42692aab38d230485f3c8ed54c2ed31f15cf0270c8143765b10b92157233fa1dfe0d7ce8ffe70b8b8f7250071701dfe9f1c94de362c9031455951c93eb098a6b50ee45c6131fefc3b6f9643e21f4adc59497138e246f5c57d834aa67c4f10d8bd8b3908d8130dd7388409c299a268eab3664fa4907c5c31574874bd8d388a4ab22b339660804e53e1b8d05867d40e3082560608d35d5d2c6054e8bab23da28f61f83efd41d25529ad6ea15fb50505cacfabb0902166427354ca3830a2c8415f21b19e592690fbe447020d685a4bcd16ecc4ff1a1c0e572627d0ef6265c008a43fc243240541061ed7840606be466d1c0dac2c53250ed567507d926c844154560d631960c65e15157829b2c7f16859f111a3a8cb72bf24ffa57a680c3be67b1be67c8dd8aea73ac2437a78df5b686d427080ebc01bd30b71a49f6ea31dc0f08e4849e38face96717690239538bc08b6cc5aa8d467cb9c36aa83d40ac7e58bddbfa185b22065e89a86c0145569d9e23726651aec49e31588d70f40fe9a4449dcf4f89eac220171e9c938e803dc195679651004b79ad33cc0c13aeeba5941b33ffeeb8fbe16e76c7811445c67b4269c90479433ddf9e8ed1d00c166b6c17217fb22c3ef1b0c1c7e28e185446a111c37f1ea6c07a59fbcc6546ecc6968d36ba58bc5489a5640647e426b0c39350cb6f07d5dc7a717648c4ec7f841467597ae1f65f408fd2d9940a4b1b860b3c9ae351dcae0b4425f7e8538710f2e40b7f70d13b51ac05ccc6ecda8264a88cad2d721d18132a9b9110a9e759c2483c77dcefc7e464ec88588174cb0c9abff93230ea0bed8decdd8ed8bfe2b5df0a253803678df04fab44c03b9ab7cc97d6e6d6fd0c4c840ce0efc498436f453bbb181603459471f2b588724592b222ec990614db530e10cadd84705621cfdd9261fa44a5f5806a2d74b575056b3c915255c65678f9c16e6dc00a99180fef1a840aff0e842ac02731080cc92782538360a60a727991013984da4fad95f79d5030677b7528d076b2483685fca4429edf804682fdc110dfc2f7c30e23e20a72e039108a0ad6fdee2f76985a4b4be4f5afc6101bf9d5042b657a05dc914e1424241766434" -const randHex = "c95138082bdf2b9bfa5b1072b23f729735d42c785eeb94320fb14c265b9c2ca421d01a3db986df1ac2acde5a0e6bf955d6f95e61261540905928e195f1a66644cc7f37281744fff4dc6df35566a494c41a8167151950eb74f5fc45f85ad0e5ed28b49adfe218aa7ec1707e8e1d55825f61f72beda3b4c006b8c9188d7336a5d875329b1b58c27cc4e89ecbae02c7712400c39dd131d2c6de82e2863da51d472bdfb21ecce62cc9cf769ed28aedc7583d755da45a0d90874bda269dd53283a9bdfd05f95fc8e9a304bb338ea1a2111894678c18134f17d31a15d9bfc1237894650f3e715e2548639ecbddb845cfe4a46a7b3a3c540f48629488e8c869f1e9f3f4c552243a8105b20eb8e264994214349dae83b165fd6c2a5b8e83fce09fc0a80d3281c8d53a9a08095bd19cbc1388df23975646ed259e003d39261ee68cbece8bcf32971f7fe7e588e8ba8f5e8597909abaea693836a79a1964050ed910a45a0f13a58cd2d3ae18992c5b23082407fd920d0bf01e33118a017bb5e39f44931346845af52128f7965206759433a346034ea481671f501280067567619f5ecef6cded077f92ed7f3b3ce8e308c80f34ba06939e9303f91b4318c8c1dd4cc223c1f057ac0c91211c629cd30e46ee9ec1d9fd493086b7bc2bc83e33f08749a5d430b0ed4f79d70f481940c9b0930b16321886a0df4fa5a1465d5208c7d3494a7987d9a5e42aa256f0c9523947f8318d0ef0af3d59a45cfc2418d0785c9a548b32b81e7de18be7d55a69a4c156bbb3d7579c0ac8e9c72b24646e54b0d0e8725f8f49fb44ae3c6b9d0287be118586255a90a4a83483ed0328518037e52aa959c5748ed83e13023e532306be98b8288da306bbb040bcf5d92176f84a9306dc6b274b040370b61d71fde58dd6d20e6fee348eae0c54bd0a5a487b2d005f329794f2a902c296af0a4c1f638f63292a1fa18e006c1b1838636f4de71c73635b25660d32e88a0917e1a5677f6a02ca65585b82cbd99fb4badbfa97a585da1e6cadf6737b4ec6ca33f245d66ee6a9fae6785d69b003c17b9fc6ec34fe5824ab8caae5e8e14dc6f9e116e7bf4a60c04388783c8ae929e1b46b3ef3bbe81b38f2fa6da771bf39dfba2374d3d2ed356b8e2c42081d885a91a3afb2f31986d2f9873354c48cf5448492c32e62385af423aa4f83db6d1b2669650379a1134b0a04cbca0862d6f9743c791cbb527d36cd5d1f0fc7f503831c8bd1b7a0ef8ae1a5ed1155dfdd9e32b6bb33138112d3d476b802179cb85a2a6c354ccfed2f31604fbd8d6ec4baf9f1c8454f72c6588c06a7df3178c43a6970bfa02dd6f74cb5ec3b63f9eddaa17db5cbf27fac6de8e57c384afd0954179f7b5690c3bee42abc4fa79b4b12101a9cf5f0b9aecdda945def0bd04163237247d3539850e123fe18139f316fa0256d5bd2faa8" - -const oneMBSawtoothBZ2Hex = "425a683931415926535971931ea00006ddffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe007de00000000000000024c00130001300000000000000000000000000000000000000000000000000000000126000980009800000000000000000000000000000000000000000000000000000000930004c0004c000000000000000000000000000000000000000000000000000000004980026000260000000000000000000000000000000000000000000000000000000009aaaaa0000000000000000000000000000000000000000000000000000000000000000498002600026000000000000000000000000000000000000000000000000000000007fc42271980d044c0a822607411304a08982d044c1a82260f411308a08984d044c2a82261741130ca08986d044c3a82261f411310a08988d044c4a822627411314a0898ad044c5a82262f411318a0898cd044c6a82263741131ca0898ed044c7a82263f411320a08990d044c8a822647411324a08992d044c9a82264f411328a08994d044caa82265741132ca08996d044cba82265f411330a08998d044cca822667411334a0899ad044cda82266f411338a0899cd044cea82267741133ca0899ed044cfa82267f411340a089a0d044d0a822687411344a089a2d044d1a82268f411348a089a4d044d2a82269741134ca089a6d044d3a82269f411350a089a8d044d4a8226a7411354a089aad044d5a8226af411358a089acd044d6a8226b741135ca089aed044d7a8226bf411360a089b0d044d8a8226c7411364a089b2d044d9a8226cf411368a089b4d044daa8226d741136ca089b6d044dba8226df411370a089b8d044dca8226e7411374a089bad044dda8226ef411378a089bcd044dea8226f741137ca089bed044dfa8226ff411380a089c0d044e0a822707411384a089c2d044e1a82270f411388a089c4d044e2a82271741138ca089c59089c69089c71089c79089c81089c89089c91089c99089ca1089ca9089cb1089cb9089cc1089cc9089cd1089cd9089ce1089ce9089cf1089cf9089d01089d09089d11089d19089d21089d29089d31089d39089d41089d49089d51089d59089d61089d69089d71089d79089d81089d89089d91089d99089da1089da9089db1089db9089dc1089dc9089dd1089dd9089de1089de9089df1089df9089e01089e09089e11089e19089e21089e29089e31089e39089e41089e49089e51089e59089e61089e69089e71089e79089e81089e89089e91089e99089ea1089ea9089eb1089eb9089ec1089ec9089ed1089ed9089ee1089ee9089ef1089ef9089f01089f09089f11089f19089f21089f29089f31089f39089f41089f49089f51089f59089f61089f69089f71089f79089f81089f89089f91089f99089fa1089fa9089fb1089fb9089fc1089fc9089fd1089fd9089fe1089fe9089ff1089ff98a0ac9329acf23ba884804fdd3ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0034f800000000000024c00130001300000000000000000000000000000000000000000000000000000000126000980009800000000000000000000000000000000000000000000000000000000930004c0004c000000000000000000000000000000000000000000000000000000004980026000260000000000000000000000000000000000000000000000000000000024c0013000130000000000000000000000000000000000000000000000000000000002955540000000000000000000000000000000000000000000000000000000000000001ff108c00846024230221181908c108460a4230621183908c20846124230a21185908c308461a4230e21187908c40846224231221189908c508462a423162118b908c60846324231a2118d908c708463a4231e2118f908c80846424232221191908c908464a4232621193908ca0846524232a21195908cb08465a4232e21197908cc0846624233221199908cd08466a423362119b908ce0846724233a2119d908cf08467a4233e2119f908d008468242342211a1908d108468a42346211a3908d20846924234a211a5908d308469a4234e211a7908d40846a242352211a9908d50846aa42356211ab908d60846b24235a211ad908d70846ba4235e211af908d80846c242362211b1908d90846ca42366211b3908da0846d24236a211b5908db0846da4236e211b7908dc0846e242372211b9908dd0846ea42376211bb908de0846f24237a211bd908df0846fa4237e211bf908e008470242382211c1908e108470a42386211c3908e20847124238a211c5908e2f8c211c6c8471d211c7c84721211c8c84725211c9c84729211cac8472d211cbc84731211ccc84735211cdc84739211cec8473d211cfc84741211d0c84745211d1c84749211d2c8474d211d3c84751211d4c84755211d5c84759211d6c8475d211d7c84761211d8c84765211d9c84769211dac8476d211dbc84771211dcc84775211ddc84779211dec8477d211dfc84781211e0c84785211e1c84789211e2c8478d211e3c84791211e4c84795211e5c84799211e6c8479d211e7c847a1211e8c847a5211e9c847a9211eac847ad211ebc847b1211ecc847b5211edc847b9211eec847bd211efc847c1211f0c847c5211f1c847c9211f2c847cd211f3c847d1211f4c847d5211f5c847d9211f6c847dd211f7c847e1211f8c847e5211f9c847e9211fac847ed211fbc847f1211fcc847f5211fdc847f9211fec847fd211ff8bb9229c284803a8b6248" - -const rand2BZ2Hex = "425a6839314159265359d992d0f60000137dfe84020310091c1e280e100e042801099210094806c0110002e70806402000546034000034000000f2830000032000d3403264049270eb7a9280d308ca06ad28f6981bee1bf8160727c7364510d73a1e123083421b63f031f63993a0f40051fbf177245385090d992d0f60" -const rand2Hex = "92d5652616ac444a4a04af1a8a3964aca0450d43d6cf233bd03233f4ba92f8719e6c2a2bd4f5f88db07ecd0da3a33b263483db9b2c158786ad6363be35d17335ba" - -const rand3BZ2Hex = "425a68393141592653593be669d00000327ffffffffffffffffffffffffffffffffffff7ffffffffffffffffffffffffffffffc002b3b2b1b6e2bae400004c00132300004c0d268c004c08c0130026001a008683234c0684c34008c230261a04c0260064d07a8d00034000d27a1268c9931a8d327a3427a41faa69ea0da264c1a34219326869b51b49a6469a3268c689fa53269a62794687a9a68f5189994c9e487a8f534fd49a3d34043629e8c93d04da4f4648d30d4f44d3234c4d3023d0840680984d309934c234d3131a000640984f536a6132601300130130c8d00d04d1841ea7a8d31a02609b40023460010c01a34d4c1a0d04d3069306810034d0d0d4c0046130d034d0131a9a64d321804c68003400098344c13000991808c0001a00000000098004d3d4da4604c47a13012140aadf8d673c922c607ef6212a8c0403adea4b28aee578900e653b9cdeb8d11e6b838815f3ebaad5a01c5408d84a332170aff8734d4e06612d3c2889f31925fb89e33561f5100ae89b1f7047102e729373d3667e58d73aaa80fa7be368a1cc2dadd81d81ec8e1b504bd772ca31d03649269b01ceddaca07bf3d4eba24de141be3f86f93601e03714c0f64654671684f9f9528626fd4e1b76753dc0c54b842486b8d59d8ab314e86ca818e7a1f079463cbbd70d9b79b283c7edc419406311022e4be98c2c1374df9cdde2d008ce1d00e5f06ad1024baf555631f70831fc1023034e62be7c4bcb648caf276963ffa20e96bb50377fe1c113da0db4625b50741c35a058edb009c6ee5dbf93b8a6b060eec568180e8db791b82aab96cbf4326ca98361461379425ba8dcc347be670bdba7641883e5526ae3d833f6e9cb9bac9557747c79e206151072f7f0071dff3880411846f66bf4075c7462f302b53cb3400a74cf35652ad5641ed33572fd54e7ed7f85f58a0acba89327e7c6be5c58cb71528b99df2431f1d0358f8d28d81d95292da631fb06701decabb205fac59ff0fb1df536afc681eece6ea658c4d9eaa45f1342aa1ff70bdaff2ddaf25ec88c22f12829a0553db1ec2505554cb17d7b282e213a5a2aa30431ded2bce665bb199d023840832fedb2c0c350a27291407ff77440792872137df281592e82076a05c64c345ffb058c64f7f7c207ef78420b7010520610f17e302cc4dfcfaef72a0ed091aab4b541eb0531bbe941ca2f792bf7b31ca6162882b68054a8470115bc2c19f2df2023f7800432b39b04d3a304e8085ba3f1f0ca5b1ba4d38d339e6084de979cdea6d0e244c6c9fa0366bd890621e3d30846f5e8497e21597b8f29bbf52c961a485dfbea647600da0fc1f25ce4d203a8352ece310c39073525044e7ac46acf2ed9120bae1b4f6f02364abfe343f80b290983160c103557af1c68416480d024cc31b6c06cfec011456f1e95c420a12b48b1c3fe220c2879a982fb099948ac440db844b9a112a5188c7783fd3b19593290785f908d95c9db4b280bafe89c1313aeec24772046d9bc089645f0d182a21184e143823c5f52de50e5d7e98d3d7ab56f5413bbccd1415c9bcff707def475b643fb7f29842582104d4cc1dbaaca8f10a2f44273c339e0984f2b1e06ab2f0771db01fafa8142298345f3196f23e5847bda024034b6f59b11c29e981c881456e40d211929fd4f766200258aad8212016322bd5c605790dcfdf1bd2a93d99c9b8f498722d311d7eae7ff420496a31804c55f4759a7b13aaaf5f7ce006c3a8a998897d5e0a504398c2b627852545baf440798bcc5cc049357cf3f17d9771e4528a1af3d77dc794a11346e1bdf5efe37a405b127b4c43b616d61fbc5dc914e14240ef99a7400" -const rand3Hex = "1744b384d68c042371244e13500d4bfb98c6244e3d71a5b700224420b59c593553f33bd786e3d0ce31626f511bc985f59d1a88aa38ba8ad6218d306abee60dd9172540232b95be1af146c69e72e5fde667a090dc3f93bdc5c5af0ab80acdbaa7a505f628c59dc0247b31a439cacf5010a94376d71521df08c178b02fb96fdb1809144ea38c68536187c53201fea8631fb0a880b4451ccdca7cc61f6aafca21cc7449d920599db61789ac3b1e164b3390124f95022aeea39ccca3ec1053f4fa10de2978e2861ea58e477085c2220021a0927aa94c5d0006b5055abba340e4f9eba22e969978dfd18e278a8b89d877328ae34268bc0174cfe211954c0036f078025217d1269fac1932a03b05a0b616012271bbe1fb554171c7a59b196d8a4479f45a77931b5d97aaf6c0c673cbe597b79b96e2a0c1eae2e66e46ccc8c85798e23ffe972ebdaa3f6caea243c004e60321eb47cd79137d78fd0613be606feacc5b3637bdc96a89c13746db8cad886f3ccf912b2178c823bcac395f06d28080269bdca2debf3419c66c690fd1adcfbd53e32e79443d7a42511a84cb22ca94fffad9149275a075b2f8ae0b021dcde9bf62b102db920733b897560518b06e1ad7f4b03458493ddaa7f4fa2c1609f7a1735aeeb1b3e2cea3ab45fc376323cc91873b7e9c90d07c192e38d3f5dfc9bfab1fd821c854da9e607ea596c391c7ec4161c6c4493929a8176badaa5a5af7211c623f29643a937677d3df0da9266181b7c4da5dd40376db677fe8f4a1dc456adf6f33c1e37cec471dd318c2647644fe52f93707a77da7d1702380a80e14cc0fdce7bf2eed48a529090bae0388ee277ce6c7018c5fb00b88362554362205c641f0d0fab94fd5b8357b5ff08b207fee023709bc126ec90cfb17c006754638f8186aaeb1265e80be0c1189ec07d01d5f6f96cb9ce82744147d18490de7dc72862f42f024a16968891a356f5e7e0e695d8c933ba5b5e43ad4c4ade5399bc2cae9bb6189b7870d7f22956194d277f28b10e01c10c6ffe3e065f7e2d6d056aa790db5649ca84dc64c35566c0af1b68c32b5b7874aaa66467afa44f40e9a0846a07ae75360a641dd2acc69d93219b2891f190621511e62a27f5e4fbe641ece1fa234fc7e9a74f48d2a760d82160d9540f649256b169d1fed6fbefdc491126530f3cbad7913e19fbd7aa53b1e243fbf28d5f38c10ebd77c8b986775975cc1d619efb27cdcd733fa1ca36cffe9c0a33cc9f02463c91a886601fd349efee85ef1462065ef9bd2c8f533220ad93138b8382d5938103ab25b2d9af8ae106e1211eb9b18793fba033900c809c02cd6d17e2f3e6fc84dae873411f8e87c3f0a8f1765b7825d185ce3730f299c3028d4a62da9ee95c2b870fb70c79370d485f9d5d9acb78926d20444033d960524d2776dc31988ec7c0dbf23b9905d" - -const ( - digits = iota - twain -) - -var testfiles = []string{ - // Digits is the digits of the irrational number e. Its decimal representation - // does not repeat, but there are only 10 possible digits, so it should be - // reasonably compressible. - digits: "testdata/e.txt.bz2", - // Twain is Project Gutenberg's edition of Mark Twain's classic English novel. - twain: "testdata/Mark.Twain-Tom.Sawyer.txt.bz2", -} - -func benchmarkDecode(b *testing.B, testfile int) { - compressed, err := ioutil.ReadFile(testfiles[testfile]) - if err != nil { - b.Fatal(err) - } - b.SetBytes(int64(len(compressed))) - for i := 0; i < b.N; i++ { - r := bytes.NewReader(compressed) - io.Copy(ioutil.Discard, NewReader(r)) - } -} - -func BenchmarkDecodeDigits(b *testing.B) { benchmarkDecode(b, digits) } -func BenchmarkDecodeTwain(b *testing.B) { benchmarkDecode(b, twain) } - -func TestBufferOverrun(t *testing.T) { - // Tests https://code.google.com/p/go/issues/detail?id=5747. - buffer := bytes.NewReader([]byte(bufferOverrunBase64)) - decoder := base64.NewDecoder(base64.StdEncoding, buffer) - decompressor := NewReader(decoder) - // This shouldn't panic. - ioutil.ReadAll(decompressor) -} - -func TestOutOfRangeSelector(t *testing.T) { - // Tests https://code.google.com/p/go/issues/detail?id=8363. - buffer := bytes.NewReader(outOfRangeSelector) - decompressor := NewReader(buffer) - // This shouldn't panic. - ioutil.ReadAll(decompressor) -} - -func TestMTF(t *testing.T) { - mtf := newMTFDecoderWithRange(5) - - // 0 1 2 3 4 - expect := byte(1) - x := mtf.Decode(1) - if x != expect { - t.Errorf("expected %v, got %v", expect, x) - } - - // 1 0 2 3 4 - x = mtf.Decode(0) - if x != expect { - t.Errorf("expected %v, got %v", expect, x) - } - - // 1 0 2 3 4 - expect = byte(0) - x = mtf.Decode(1) - if x != expect { - t.Errorf("expected %v, got %v", expect, x) - } - - // 0 1 2 3 4 - expect = byte(4) - x = mtf.Decode(4) - if x != expect { - t.Errorf("expected %v, got %v", expect, x) - } - - // 4 0 1 2 3 - expect = byte(0) - x = mtf.Decode(1) - if x != expect { - t.Errorf("expected %v, got %v", expect, x) - } -} - -var bufferOverrunBase64 string = ` -QlpoNTFBWSZTWTzyiGcACMP/////////////////////////////////3/7f3/// -////4N/fCZODak2Xo44GIHZgkGzDRbFAuwAAKoFV7T6AO6qwA6APb6s2rOoAkAAD -oACUoDtndh0iQAPkAAAAaPWihQoCgr5t97Obju21ChQB0NBm3RbA7apXrRoBooAA -AhA+IAHWl2Us3O7t9yieb3udvd76+4+fd33nd3HO1bVvfcGRne6+3vfPvfc++995 -w7k973eJhasLVec970tzDNXdX28LoPXZ3H3K9z0s5ufWAfes49d5594c3dUYtI+2 -+h1dvtpRa+uvrVEAG9bl893RVEN7cWvroSqWjPMGgAQi7Gq8TJSgKKdjKFBIB9Ae -LqWxleu715eXe7ml9e5098Z6G1vr7t1QZ6ot76YzPd3j7333t2ql2Chm7XrA9ICQ -VF77z3rVBWqkSXtlfb099hyezAr6USbGpICTSCFAaqHrKo+tUnm32rpE4Ue+t2mj -bKUeipEqwc93EdhhTwmQpOhhesC9iqDSPNTWYNSnUtBdm1nsA0nqqNd7OWwDXtFL -ONmmA6Ubke26I9UblvWIPR5VOWOnctai443URunnDy77uVC59OfRvezlDu33Z7Ly -3NNuuHW63088xu3t3NHZhkZbG7tXRlj00qOtbaXTJUUdspTbABR9R6EUwQAEAAAA -EMEwRpoAAAABMmhoAAjBNNAaCMhponpoGpgJpk9TEyp6niGKZkAaAEfqMQ09U80p -+pMGSCKngIAAAAgAAg0AAJhGgABGCEaaTyTKeNI1PE0wkj01GajMSNPSZGnqbU9T -anlPUNAHqGQ0DQAMg9TamgAAYRU/IAAICAmjQJgjQBMEwp5DTSaaYmhTeqfplPID -U1T9TynoU82pT1NPU/VP0j1NHqRpk9TTR7SnqaNNGmmQAaAD1Aeo0PSAAAAaaBiK -eBAQBGgIABGQA0AmBNNBoaAgaJmpglPEyYap6npiTT0agGjJjUaaDTQAAAAAAM1A -9QAaAAAADU8iEAQAEyAJk0NNNJgIZTJ5E00YSemiaZNGm1MpGNJ+lPU9qm9U2RDM -oY0EzJB6h6nqDID1NMBDDRpo1AGNAjCMmhkMgaYSJIgAAAQyAAEyBoATECCNhTT0 -U/IZAmCM1DSTxkzUE8p6NDaGiZGJqntTFHvUyU9qPQp7Kn5GgKNPU9QAGg9QAAA3 -wz0Pk/g/m/m9P9H4vxv2+dH3gCS8nhbbbbbYxtgNsBsG0m2MbG0NNtsbYNsaY0wb -bBibGmm22mxptNpsaGNDTY02JsG0MY0xg2MaYNNDbGwG0L5vsK/F9DO+EAA447Kq -p7Wdf6Y+5c20T7DfHyMXIzRKrZexw72uiQI+y55vOe52xpqbCLC2uR20JdER7Zvr -7ufuKb6zhiBxLuj0eA27v8RpMLucw9Ohwcizi2wrpt+yU1FdpM7ZYPcwS3XTef+A -Wzjxwhdrgw3aH1LeC1eZW900x8V9Nv4hTPXp4l067P/4ANVZFF/imOe/d5bdueam -/DFFokQWnFaU+ZqLBCM+d0PialJQWnLqRQZk/KhfbbYc2pCUTgffcSYbrCM1N+8l -HU6gSz+h2GJXs+tbrNviL83M97X0vcTn/F82P8wen8/3/h3sHY+sf9CSej9ThYTV -3lQ+FUHpfpGD4kv7dYMV995dpDX/y3xR8FoXx1bjUxBTNxuutwQ/h/Eedn9wpn6w -E3+ND8YhN1HSriIxRE/6uFyMv6/oC6Elarw3aHMMqHJkGiiz6tejmvnYLQa+Qm6G -deZ7jXTZV6NlpocgDnRdimS06bTYSkvPAL/xoWNLkX6N6VljU0dfKSBmm2uZE/xu -sutQ1EdP7GdjhglIq4xlOFUFEQpmX+xx7R8y6c0GSAaqusOjNZwxZRudOvmXm1tZ -T+YnbeB2ir9eiHNrtJNSLD/J/WDyuQpwBUtLKo0krccY/wIILP7f86teb9Z/9oyz -OX05qEWbObfhpRw+9+rCvp/35ML8KX3aHaI0n+tudbFRsV5FLW+Oa8ruLN4peyVL -DWjTHrXNthq/s7zAJYMeFJZkZt5mT9rfpH+5g3nc+piOSZ+J5nHtOnKI7Ff8Xl+j -0t76XTNucCHQ6whav1OHdF53TY5wuv5OzvrdnxoId8fTyUvERr0ERINu/8XxZZ5f -B5/kTZ8bBO0wv54Jp+ED/GQI8lZHzIQCP3vfQhwnCTj9TvITic7P4mYLDbH3fyzR -i+6EajCcpXLWSGf+ZXkOrWspDWDhXtEKas0v3UqWksqgY1rTj45krX4KihN+daXs -pZl5WPlta5p06CX6Xm2SfzqkMw12/3ix1bpnnZ+kFeBNX7A+E9zzG6OZaN78GOpl -9Ht/eZn9PqWdav852zr0zqkDK2H5IjdvNah+b1YVGdQGzwR4Nw+f13yEKnV+y66W -djfq7zWp7m5w+hzfv+Ly8O7oet5Vvd8/wQvO7qzOZ2vjf9X8Tj8PnMb/nc/nKqRR -+ml4UEhOOwfCeJEEI109CMYSh91iAJqPjMyH6KjrPD7W25llZVcREYNCTg6htbQt -M38wYoquCWP6tdKYlVIv14xTNUeUf4El/FunCf6csZkmv+9tfWx7t59wuKIa3saU -tZs9M+3HFOZtz3OLg/Unoaj9BYazYqA78xBU9tZzrtmF/rQL9CGJt90o/oYnSfcS -SL3haaw351LXWQ1XOsv1SmH3v6ymuxEpPPnEDmBELaTYsvvMIWJsmPZFFww++Kd7 -s/Jo0JFeUU7uNtI+gVosAIpVVuWfI/9tOIycz7I5Z7zjV+NR2OuZbYtW5F08KX4o -2k/xuJIchcNFPtxPfw9dkDgscRbMckyFMrzuZ3IvrcGzk0J6iI5ytrv37bGpAXMz -WK9mMMPebepNevmLjjo/QWoM968Sjv7ldlPS5AinHcXwsFv6dmmh8lJt7UOJWoKu -lMD1cB2ksIGpMdv8iuqR42Rn/kn+17BhhUZcwDBaUXVdX6bKW7fxlUYbq+mlqIcf -a9v8HF87M9ANbi9bq9onf9TD7nQ6Xf6vZci8TBPX+/GI0He6j31fTVQYW+NsQxvO -J8xrx+e58CCLQNjxeIyPt+F+qk/QMiXw+LyxGVkV/XcGQT9X03jSDP6beJ5QG1JW -9Q3qLv/YixWI7gPV9Mrhf2oRYTc/9KLFRhkE3SjKOTKuSSBKQ24fI+hEznamH71D -66Hwez8/0et7AtTv9zvamv2OD5He6fMV4k+ePl6+qPfO5CdHtK+eCDZL5+4f5yrl -gTcRFiq8fXbc5IaI5fbbc1KMM/2T0Mr7+Hwaco6FtXm0fmhCgTZRqY4pKiEIfmaz -QwHNOOCrtMJ2VwsyMumt7xsOolGnizRev6lILH43qPcczQM7Gc5zRin80YvFt1Qm -h/57Z0auR2h0fuX50MBO4XQ+26y5l6v4j902R66c0j3z2KHstKQ04J/h6LbuNQE4 -D6cu/lyfK69DxxX8wb8XaQkMUcJdo1LzqUGDAb3Kfn/A3P/JYc99MO9qv67+SxWb -wYTyqKdWTd+1KbR/Rcn0Io5zI/QquX7FA1bxfMytjQ/X+l0fh0Pf+Hx97meH4fQL -7/T8/sdTm9Tn8nELvedyhydLlPPTScINdXyLIq9wgIJr4fWPbp9ZhFh/56fdSgOG -HDXg+gkXsN2Rddr4HQ5P3u+RhLzmSjhzoqY5EsPC4QvRlX9JXjB84rPV5USR66qa -/kjw4156GJnzoXtydKJE53t6PHfZWO+3ujsfI6iAdshc7OFzGXiZB9PtItKodhYq -nABkTKdcpu4+TOpf9h5piX5slsaBjkeTnj/Ba02ilboQfcDVigxrYn/iTH5ySWUW -/lHtg78s5UZM8sErwhNe3N3w+6ZOMnU+5i86/xFNtqZfDdXTGy1H3PzGbdtZXYT+ -Ixx2vpwBYzbPVYHxKosM5rPiVmcTllI9nuoSfeh9ib4foFWauOpvdmhBDqpTpKTX -u8EO2l2Z195G2RIV7TlKSxGWjR5sl/nALu1uzBeLd9zpSujzMTd1uTX9Qk/Q1S+r -vaW6bm8qqPO4jb6Wx6XIkm321nrIF6Ae25d1+Dpv/P5G4NoLd2j6/EtENC3FeR5z -oo7bA+tI8yEQRhiF0z1FlJXLD5ZbhNNWQm/j/IbzRfh8JtOFZU7ruShLvHXysW9S -9V909tr9jn8/E/Hb5N/1NVNHnZu2HIUvJvHJiHd2ucmeI9PWUMnppmE65GQ5E9xV -ZRlGEH0X85EvmHyEupkMrCC0oMv9RCq+/H8gcfpe00Hs/S+regT5p58cyYomh93v -qvuw/A06BE/wzJESuYbN9pqYpoXqXFemW1NksHEJ2w+PYMJ27WJyD5FpaXB85VaW -qMOhDfO8E3QdH8ybyKt/UgI8/tDGpFbyOlaVdIv1FXJhoLp8soAA4Djg6/KZ066N -ZFYuS8WdjpSZGP4/Lw+1yaXlzNznc/k2uHe2uXP3uFuPcHx+Dm44utxldoO1uBPy -+jzOs14+MIgOjOHMVNqAbMd8fUedLlhJMCfMtm4uz01enLNKcMrtLlPIR37Yukh1 -YEMXYpm7eU4XU+j+Jj3pDyaXtXs+p1fWfTN/cy9/Oxs4umUXQ4uHh1kObtayDJ56 -/QMxiHobjHNKuKfMxsrYEwN+QVIyVjAwMDYuMjQ1AAA9IwJniiBLRkZDAAAXt0Ja -aDQxQVkmU1lZtwytAACLf///////////////////+//////v//////////bv78// -/+AXO133uwO2xB2UxIvbKXrCqCoURUBL2ytFI82AFdcOwMhVTHtk5rD3szEVNYD4 -aIQINCaMRoTaSn7SbSMJiYmEwieTEp+psqbMCp+VNPaFNpqbBNR7UmanlPUeKfqm -j1PU0/VPU08o9Q9EeKHlPJtKbYqeTCYhN6U9T1NH6mp+lPyoGNTI/Knkyg1MggAg -CaMEyQnqZoaaRtRtJpppppoDaTR6hpphGh6mmgHpMQBpkGTTEAAaAAAA00AZDag0 -ADIBkGgABqemiRNTI0k8aU0PRGRoAZlP0UAAAGgAAAyAADQaAAAaAAAAAAAAAAAA -AaAAAAM0kgRBJ5MlPFP1Gj0jTTTUaekxNAbUGjTQMgaZANNAAAAaAADTQAAAAAAA -ANAA0AAANADQ0QAAAAAAAAAaGgAAAAAAABoA0AAA0AAAAAAAAAAAAANAAAAAkSEI -aTRpomp5DUxNNDTJPTKaep6T09Kemmo2JG0aTQ9ENogaaGhkABo0NHqaBoDTI0DC -Gj0gNAMhoDQ9QMQNAGQAaDDwyMPIMlbG1vhRBTFo6JksSupgpAjPbY0ec02IGXjb -eS+FBsh01+O4ZOaD+srUZCFaT4DRjVDLx7uKIsFtESIDUg1ZkhyCSYov05C00MtR -BdNNa/AYPGOQZWcs+VegXOPrkushFbZ3mBoRD6WamClkpBaHZrUhUl02bIfRXX4w -b3/9cW9nHDVxh2qFBxqgRKfmq7/Jc/tdJk05nVrGbckGVy2PnIy30CDhpWmqrSot -K2bOnX0NbP1iy2cd0Na0ZmbRstm4MzMzbbMySTd35F7f+zPP8DC+NJLYcakkkkRd -NZlupJt3OMFoDAD2g+N3FAMCydhIpoRHRQAdFI5nNg4ugEXHCYxkMyGCwtaJmial -y0IMlpSYYM/weXNJAhFqS0GNmvaPEtYGjbvaucMdklOTmBX1vfVAkTYB1uXCSK64 -UNIixOqRKLuRCFtqIQtgwqaFrCkIYbbewErWABa+VGADWsJXJjfx5SJViLuwiGXq -Ru6vCuwmU5CJiJz3UiBpmLv0r2wskxUhY4tzPVGQ9RMXJl65eLSNwZVwaSyGZ9Cm -A3jztQUUpFeUryBTskW95iVwRMFrhBCwZBAFJBZvhMEMNoDJJlUoIhQkAkjbExp2 -YZio+ZYeAZUwmH1qUbdQixmxf0+61+aVgJ1hwxsO1yG3hFx4pfjc09ITVht0pG8u -FtVFhPa1KE0gTRUSVXywkITucqk0Waz5Fs6qJpVHYdNrbYRFxnFsQGY1qmsTLjK6 -4QX5Rddo6krM/Bx9CqIAKq4CzVQYHrmIAd2EBhYmwVYwLvhzKIUrc2EirnGIvyuD -O4YZDSwsVTA0BpVvUOjDErkCraBoSutcKwUSSLGhVvNYHLz3klgZD++wWsa/swLw -gvNDY2De+sncOv8X2lq4HD95ZdwPuTIMXCwSbg4RrIqv+L0y6F17pqDecyQYPEj3 -iN/0BBeWZlJAyBMi5U3Q1zAlsK8IlDhaXGmvZrgISq5CfNjmUgxDeMggOKqxu4sI -OrilS49Lkl1J3u3GjXTuH+rX+4ccyFAQnizCpPClcY77F59j63S6fr5vr+y99tuO -7Ox7Wg/ljwhdyaK4xMmXczeJbx7x07htJNtC4xcQfAtvzeznLrN6MN/ILIBOI65I -qIA2D5fHHj1XN4aN6TvOjWDaSbSWqxCSCvXUpzkNJAkWXAuTwF8k5uSJvQj/rVo0 -hAhEMEIYkCRGx9AX+byIuXWlLMbbVeliHNUL5AQYmNwLFu4SkmGD+UWtBMyVHQOQ -ss0ggoVKSKOBUgnVS6ljt7WE1qXqJJ4QA1pEwYNLEaguEE1LtPNoVr5WzjbSbWPk -V9OW3y9IneUDLoIV5pAkEFTEFGFVjeTFxtpzBBfGgycBxVCdz8eESBIzsamRchAa -TQunQH8DHnpfod9QuAuRvc7JBlKUCYmCjMvynLcxIFohxCaYrDvGw4QbXZB7oWQ7 -hpoGlz23ayDfB8NrRRzdilsEQyQniu9ASLQg7RrGZnoTr1ai12IbCEUCGdFq03P5 -nBnRFAGmisQGcyykV9gKtcVMWLhCuVmXg86dndn7slUpRNSSEAU20oaWIm1maFTu -E0DT4gTbg0nuhjtz3kNOz+i7sBm0bkXjxQWuLqlZEmp60ZTyRZJDUqKSEKg6hqcy -ERxdU22CSNOO10RYUUiDVpKhPNdKTOIE1thp02sBNoNTFSht8WJtaBQ09qN3jd5r -dOLX4IA5fevRyCCzDgRXfV4wzik4KROjmxmTMglBySlIMEzcXehnDXCRiZSlvwA2 -0YsIOROcm4UrIRFxJHctJH7OdN5u1aHVHb5UaLHpv48NgmFRE56KTSoaWunqm2st -S0mrAdOiqcR12PWVbdVRJKcQ0DQuhwlAPcRtpxN3D4kbXJjToSYJIFw406G2CSaK -jQMIJPZGlQmgyFhoCSzeGS1VSq5SKKQQxs5RqKUcVUNY57YUETb4mXzV84SPngKi -nsce0mXByZq5BKUA9puHZWLNwQIYuDaJUNgG+E01E3pDYVNLKYQ0hsVesgV5gZY0 -htDsRdGtm0+iGnkN6+Ea9YJtUZNAkx2GgSoix12nTW0avTUfxR3oYcpvZ7IdtABE -UhBcjG4qZtDZsS1JQHys243vhLaDTSvvTeBiJA2tmokqECTBcSOCAGkAxMKlVAva -4IsLRaBBqhxDbcGtgdw03mFcLUaFuhtKuuEIEkUleJQwby/zwu9uvvZK4xTV+ECM -a8lmzxKmqkBggYK1+xPdbmJclm6tSZhE/OSJtCEjs+unJIQkT9hCWgBJqGMS07Eh -AJNmBiuVEVdTyjkIJkavuZmx2sJF13htgEZUCC23lZFOE6gWbM9WyYNJTM8yCQrb -0Sx3OQvBML5cRATAQkSQkAJOAhoxpQkNi4ZiEVDbdtJAME0RXNDXGHA3M3Q0mm1o -IEwbWpaM1DQCSMbGRCAu3iRIQiT6RlBpT1n3tfwvUXz3gIVlx3mEximY/kZW1kNG -sgEJIrBisaEoGYPJ+1CQUYFBw+eGEHJQBpNHjErXUJY2iWHQ30hXwFBuMSxQ2lB5 -bg+/LX3euG6HsHUB1lFvBvaiaBrITVwkCTa1d0s9CHZCiDZjbWReKyrpPE2oSa7o -LPrR4BJvys9ttjUpzETSSMxh8vsr9dXTwKBtK+1xCTGDQmNIaE29HmHdS5GSxpya -MismcAUSEgSxHBrKtgsZzduG7vHZn16l3kFkVITtENIzS2JsiBwFTDlhgexsjBHv -5HXOYxHBzoSDCcPZ0ctvkY9aS5XpoQuFYkGJgCsqjJZeUMNUEpDSbKcnUc1PifIA -CbR2UoXawBlspkEBr9HBfvUi/MUakZVOf1WKYrqSaIXce62JOyhJLq3qJBloTA0F -VbILEtM+heFmNRCFt70GJrExVJri0ArYbCRbADSGDBpBXxxb/6fo+s3C7uaL7RjM -LV2IQBNrAJrKFeJwTsPnxbAsemirUx2lk1kaxschzdK4TQNJN5wQnolIFg401OZ4 -2na11LnT3lR+1k1TMJhiAjXMk0F1ooHnYlt9LKfJ3ZIOmeY+2l9bUQHWFNGyEyfj -EAcu3kpGLq0Ez7XOS+EpAASRQTAYMATfVQibHLTT30zG732+pNe9za1JNt8sNJYn -RjWuJ6jL5ILV0rcd9vT7X9fObvcXitpvJ2XBJE+PhX2HaTkyWeF9pwnlQNrTe9hV -tzhA+ihZrDrHNmLcQjZbnv/IMubqq8egxY80t5n6vZ6U5TR6U9uZJvai1xtqAyCR -NWkW52m00rDTEuO6BA4q2RHDWwbETF55rRsWLIgNW9qJCyMHPbTM/dMBmWMQSMxz -4M2pRzt47SICxA327UqSCEERqMFybmYi3nUxePtLgHYplqRiw4ynMbXd/kiQ0LE0 -PKJSSCXA42ymziCpAxNWflzpzQdJZusahRFr6t6m+4p273/Taj7k+hZyNgBAgXAY -8F7pTts6orLb8IA6o4TOwkwQYmKvKu9VwMrE7+GUhVIAgY9a8DyQMiDBkEAwh7S1 -KgCBfao8DK1CwSS8Z3WjL5MEgt93z2koUQCD/YxMBppiCMp7SDVSmkkIHptfGpeh -t+M13Ccv1tavIASFiaQl6rBz3K4N3DSGwNkCibrvEAC0fQirOWnc4NVbcLKpFG1l -NQXF/eqdT79wq1Mvlap3QSCLhcD2D3fCkKVWid4aSjtp9FOX1Uaf7P9eT93zd9Sv -mj2yNLRUGzyI/0oONNSzmmkvJ5Cq2X2CdldIWMGZO57RJ8oyATAWTQmRmNkfh0Sx -uuR/J9oUsomVy1AEntc0dlPivkqBkBqrxU3j5PnWkaI3ZRGc0gg9spCQEISh4xEU -pMhVrnmDQLfLP8Ouqpx917MAw7hkjQk6BJFTAbXDsz3LSHIxo/gB8qrA1vbvdZZh -LtR0frJdfdppX8nAQX/TAxOQ8+H6yw8a9i7/zJEfSYIhop59N/fhcWW2F14cj2Xc -fyHaZ04lTO4uPnly91jwuFPaREuZVp8AxImIhlkxkAN61tWdWG7tEbaCgszh6VIz -ThFnHo2Vi8SQXPrXCN7J9Tc9ZYiAYqoThV/u6SYsea5aZL8deOvKBQCgZZuIxX1z -4EnfcqG176vY4VqMBIC4pMJz0WcHJYqN+j7BiwGoMBwExrIdTB7q4XIFLotcIpS0 -1MqyVsesvoQq7WObmGQXdMliMirSLcDuSx8Qy+4pIBgGDIyMp1qbonnGdcHYvU8S -O0A8s/iua5oFdNZTWvbVI4FUH9sKcLiB3/fIAF+sB4n8q6L+UCfmbPcAo/crQ6b3 -HqhDBMY9J0q/jdz9GNYZ/1fbXdkUqAQKFePhtzJDRBZba27+LPQNMCcrHMq06F1T -4QmLmkHt7LxB2pAczUO+T2O9bHEw/HWw+dYf2MoRDUw= -` - -var outOfRangeSelector = []byte{ - 0x42, 0x5a, 0x68, 0x39, 0x31, 0x41, 0x59, 0x26, - 0x53, 0x59, 0x4e, 0xec, 0xe8, 0x36, 0x00, 0x00, - 0x02, 0x51, 0x80, 0x00, 0x10, 0x40, 0x00, 0x06, - 0x44, 0x90, 0x80, 0x20, 0x00, 0x31, 0x06, 0x4c, - 0x41, 0x01, 0xa7, 0xa9, 0xa5, 0x80, 0xbb, 0x94, - 0x31, 0x17, 0x72, 0x45, 0x38, 0x50, 0x90, 0x00, - 0x00, 0x00, 0x00, -} diff --git a/src/pkg/compress/bzip2/huffman.go b/src/pkg/compress/bzip2/huffman.go deleted file mode 100644 index 75a6223d8..000000000 --- a/src/pkg/compress/bzip2/huffman.go +++ /dev/null @@ -1,251 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package bzip2 - -import "sort" - -// A huffmanTree is a binary tree which is navigated, bit-by-bit to reach a -// symbol. -type huffmanTree struct { - // nodes contains all the non-leaf nodes in the tree. nodes[0] is the - // root of the tree and nextNode contains the index of the next element - // of nodes to use when the tree is being constructed. - nodes []huffmanNode - nextNode int -} - -// A huffmanNode is a node in the tree. left and right contain indexes into the -// nodes slice of the tree. If left or right is invalidNodeValue then the child -// is a left node and its value is in leftValue/rightValue. -// -// The symbols are uint16s because bzip2 encodes not only MTF indexes in the -// tree, but also two magic values for run-length encoding and an EOF symbol. -// Thus there are more than 256 possible symbols. -type huffmanNode struct { - left, right uint16 - leftValue, rightValue uint16 -} - -// invalidNodeValue is an invalid index which marks a leaf node in the tree. -const invalidNodeValue = 0xffff - -// Decode reads bits from the given bitReader and navigates the tree until a -// symbol is found. -func (t *huffmanTree) Decode(br *bitReader) (v uint16) { - nodeIndex := uint16(0) // node 0 is the root of the tree. - - for { - node := &t.nodes[nodeIndex] - bit, ok := br.TryReadBit() - if !ok && br.ReadBit() { - bit = 1 - } - // bzip2 encodes left as a true bit. - if bit != 0 { - // left - if node.left == invalidNodeValue { - return node.leftValue - } - nodeIndex = node.left - } else { - // right - if node.right == invalidNodeValue { - return node.rightValue - } - nodeIndex = node.right - } - } -} - -// newHuffmanTree builds a Huffman tree from a slice containing the code -// lengths of each symbol. The maximum code length is 32 bits. -func newHuffmanTree(lengths []uint8) (huffmanTree, error) { - // There are many possible trees that assign the same code length to - // each symbol (consider reflecting a tree down the middle, for - // example). Since the code length assignments determine the - // efficiency of the tree, each of these trees is equally good. In - // order to minimize the amount of information needed to build a tree - // bzip2 uses a canonical tree so that it can be reconstructed given - // only the code length assignments. - - if len(lengths) < 2 { - panic("newHuffmanTree: too few symbols") - } - - var t huffmanTree - - // First we sort the code length assignments by ascending code length, - // using the symbol value to break ties. - pairs := huffmanSymbolLengthPairs(make([]huffmanSymbolLengthPair, len(lengths))) - for i, length := range lengths { - pairs[i].value = uint16(i) - pairs[i].length = length - } - - sort.Sort(pairs) - - // Now we assign codes to the symbols, starting with the longest code. - // We keep the codes packed into a uint32, at the most-significant end. - // So branches are taken from the MSB downwards. This makes it easy to - // sort them later. - code := uint32(0) - length := uint8(32) - - codes := huffmanCodes(make([]huffmanCode, len(lengths))) - for i := len(pairs) - 1; i >= 0; i-- { - if length > pairs[i].length { - // If the code length decreases we shift in order to - // zero any bits beyond the end of the code. - length >>= 32 - pairs[i].length - length <<= 32 - pairs[i].length - length = pairs[i].length - } - codes[i].code = code - codes[i].codeLen = length - codes[i].value = pairs[i].value - // We need to 'increment' the code, which means treating |code| - // like a |length| bit number. - code += 1 << (32 - length) - } - - // Now we can sort by the code so that the left half of each branch are - // grouped together, recursively. - sort.Sort(codes) - - t.nodes = make([]huffmanNode, len(codes)) - _, err := buildHuffmanNode(&t, codes, 0) - return t, err -} - -// huffmanSymbolLengthPair contains a symbol and its code length. -type huffmanSymbolLengthPair struct { - value uint16 - length uint8 -} - -// huffmanSymbolLengthPair is used to provide an interface for sorting. -type huffmanSymbolLengthPairs []huffmanSymbolLengthPair - -func (h huffmanSymbolLengthPairs) Len() int { - return len(h) -} - -func (h huffmanSymbolLengthPairs) Less(i, j int) bool { - if h[i].length < h[j].length { - return true - } - if h[i].length > h[j].length { - return false - } - if h[i].value < h[j].value { - return true - } - return false -} - -func (h huffmanSymbolLengthPairs) Swap(i, j int) { - h[i], h[j] = h[j], h[i] -} - -// huffmanCode contains a symbol, its code and code length. -type huffmanCode struct { - code uint32 - codeLen uint8 - value uint16 -} - -// huffmanCodes is used to provide an interface for sorting. -type huffmanCodes []huffmanCode - -func (n huffmanCodes) Len() int { - return len(n) -} - -func (n huffmanCodes) Less(i, j int) bool { - return n[i].code < n[j].code -} - -func (n huffmanCodes) Swap(i, j int) { - n[i], n[j] = n[j], n[i] -} - -// buildHuffmanNode takes a slice of sorted huffmanCodes and builds a node in -// the Huffman tree at the given level. It returns the index of the newly -// constructed node. -func buildHuffmanNode(t *huffmanTree, codes []huffmanCode, level uint32) (nodeIndex uint16, err error) { - test := uint32(1) << (31 - level) - - // We have to search the list of codes to find the divide between the left and right sides. - firstRightIndex := len(codes) - for i, code := range codes { - if code.code&test != 0 { - firstRightIndex = i - break - } - } - - left := codes[:firstRightIndex] - right := codes[firstRightIndex:] - - if len(left) == 0 || len(right) == 0 { - // There is a superfluous level in the Huffman tree indicating - // a bug in the encoder. However, this bug has been observed in - // the wild so we handle it. - - // If this function was called recursively then we know that - // len(codes) >= 2 because, otherwise, we would have hit the - // "leaf node" case, below, and not recursed. - // - // However, for the initial call it's possible that len(codes) - // is zero or one. Both cases are invalid because a zero length - // tree cannot encode anything and a length-1 tree can only - // encode EOF and so is superfluous. We reject both. - if len(codes) < 2 { - return 0, StructuralError("empty Huffman tree") - } - - // In this case the recursion doesn't always reduce the length - // of codes so we need to ensure termination via another - // mechanism. - if level == 31 { - // Since len(codes) >= 2 the only way that the values - // can match at all 32 bits is if they are equal, which - // is invalid. This ensures that we never enter - // infinite recursion. - return 0, StructuralError("equal symbols in Huffman tree") - } - - if len(left) == 0 { - return buildHuffmanNode(t, right, level+1) - } - return buildHuffmanNode(t, left, level+1) - } - - nodeIndex = uint16(t.nextNode) - node := &t.nodes[t.nextNode] - t.nextNode++ - - if len(left) == 1 { - // leaf node - node.left = invalidNodeValue - node.leftValue = left[0].value - } else { - node.left, err = buildHuffmanNode(t, left, level+1) - } - - if err != nil { - return - } - - if len(right) == 1 { - // leaf node - node.right = invalidNodeValue - node.rightValue = right[0].value - } else { - node.right, err = buildHuffmanNode(t, right, level+1) - } - - return -} diff --git a/src/pkg/compress/bzip2/move_to_front.go b/src/pkg/compress/bzip2/move_to_front.go deleted file mode 100644 index 526dfb34c..000000000 --- a/src/pkg/compress/bzip2/move_to_front.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package bzip2 - -// moveToFrontDecoder implements a move-to-front list. Such a list is an -// efficient way to transform a string with repeating elements into one with -// many small valued numbers, which is suitable for entropy encoding. It works -// by starting with an initial list of symbols and references symbols by their -// index into that list. When a symbol is referenced, it's moved to the front -// of the list. Thus, a repeated symbol ends up being encoded with many zeros, -// as the symbol will be at the front of the list after the first access. -type moveToFrontDecoder []byte - -// newMTFDecoder creates a move-to-front decoder with an explicit initial list -// of symbols. -func newMTFDecoder(symbols []byte) moveToFrontDecoder { - if len(symbols) > 256 { - panic("too many symbols") - } - return moveToFrontDecoder(symbols) -} - -// newMTFDecoderWithRange creates a move-to-front decoder with an initial -// symbol list of 0...n-1. -func newMTFDecoderWithRange(n int) moveToFrontDecoder { - if n > 256 { - panic("newMTFDecoderWithRange: cannot have > 256 symbols") - } - - m := make([]byte, n) - for i := 0; i < n; i++ { - m[i] = byte(i) - } - return moveToFrontDecoder(m) -} - -func (m moveToFrontDecoder) Decode(n int) (b byte) { - // Implement move-to-front with a simple copy. This approach - // beats more sophisticated approaches in benchmarking, probably - // because it has high locality of reference inside of a - // single cache line (most move-to-front operations have n < 64). - b = m[n] - copy(m[1:], m[:n]) - m[0] = b - return -} - -// First returns the symbol at the front of the list. -func (m moveToFrontDecoder) First() byte { - return m[0] -} diff --git a/src/pkg/compress/bzip2/testdata/Mark.Twain-Tom.Sawyer.txt.bz2 b/src/pkg/compress/bzip2/testdata/Mark.Twain-Tom.Sawyer.txt.bz2 deleted file mode 100644 index 0bd61a6d4..000000000 Binary files a/src/pkg/compress/bzip2/testdata/Mark.Twain-Tom.Sawyer.txt.bz2 and /dev/null differ diff --git a/src/pkg/compress/bzip2/testdata/e.txt.bz2 b/src/pkg/compress/bzip2/testdata/e.txt.bz2 deleted file mode 100644 index 65bf3b4c3..000000000 Binary files a/src/pkg/compress/bzip2/testdata/e.txt.bz2 and /dev/null differ diff --git a/src/pkg/compress/flate/copy.go b/src/pkg/compress/flate/copy.go deleted file mode 100644 index a3200a8f4..000000000 --- a/src/pkg/compress/flate/copy.go +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flate - -// forwardCopy is like the built-in copy function except that it always goes -// forward from the start, even if the dst and src overlap. -// It is equivalent to: -// for i := 0; i < n; i++ { -// mem[dst+i] = mem[src+i] -// } -func forwardCopy(mem []byte, dst, src, n int) { - if dst <= src { - copy(mem[dst:dst+n], mem[src:src+n]) - return - } - for { - if dst >= src+n { - copy(mem[dst:dst+n], mem[src:src+n]) - return - } - // There is some forward overlap. The destination - // will be filled with a repeated pattern of mem[src:src+k]. - // We copy one instance of the pattern here, then repeat. - // Each time around this loop k will double. - k := dst - src - copy(mem[dst:dst+k], mem[src:src+k]) - n -= k - dst += k - } -} diff --git a/src/pkg/compress/flate/copy_test.go b/src/pkg/compress/flate/copy_test.go deleted file mode 100644 index 2011b1547..000000000 --- a/src/pkg/compress/flate/copy_test.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flate - -import ( - "testing" -) - -func TestForwardCopy(t *testing.T) { - testCases := []struct { - dst0, dst1 int - src0, src1 int - want string - }{ - {0, 9, 0, 9, "012345678"}, - {0, 5, 4, 9, "45678"}, - {4, 9, 0, 5, "01230"}, - {1, 6, 3, 8, "34567"}, - {3, 8, 1, 6, "12121"}, - {0, 9, 3, 6, "345"}, - {3, 6, 0, 9, "012"}, - {1, 6, 0, 9, "00000"}, - {0, 4, 7, 8, "7"}, - {0, 1, 6, 8, "6"}, - {4, 4, 6, 9, ""}, - {2, 8, 6, 6, ""}, - {0, 0, 0, 0, ""}, - } - for _, tc := range testCases { - b := []byte("0123456789") - n := tc.dst1 - tc.dst0 - if tc.src1-tc.src0 < n { - n = tc.src1 - tc.src0 - } - forwardCopy(b, tc.dst0, tc.src0, n) - got := string(b[tc.dst0 : tc.dst0+n]) - if got != tc.want { - t.Errorf("dst=b[%d:%d], src=b[%d:%d]: got %q, want %q", - tc.dst0, tc.dst1, tc.src0, tc.src1, got, tc.want) - } - // Check that the bytes outside of dst[:n] were not modified. - for i, x := range b { - if i >= tc.dst0 && i < tc.dst0+n { - continue - } - if int(x) != '0'+i { - t.Errorf("dst=b[%d:%d], src=b[%d:%d]: copy overrun at b[%d]: got '%c', want '%c'", - tc.dst0, tc.dst1, tc.src0, tc.src1, i, x, '0'+i) - } - } - } -} diff --git a/src/pkg/compress/flate/deflate.go b/src/pkg/compress/flate/deflate.go deleted file mode 100644 index 8c79df0c6..000000000 --- a/src/pkg/compress/flate/deflate.go +++ /dev/null @@ -1,571 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flate - -import ( - "fmt" - "io" - "math" -) - -const ( - NoCompression = 0 - BestSpeed = 1 - fastCompression = 3 - BestCompression = 9 - DefaultCompression = -1 - logWindowSize = 15 - windowSize = 1 << logWindowSize - windowMask = windowSize - 1 - logMaxOffsetSize = 15 // Standard DEFLATE - minMatchLength = 3 // The smallest match that the compressor looks for - maxMatchLength = 258 // The longest match for the compressor - minOffsetSize = 1 // The shortest offset that makes any sense - - // The maximum number of tokens we put into a single flat block, just too - // stop things from getting too large. - maxFlateBlockTokens = 1 << 14 - maxStoreBlockSize = 65535 - hashBits = 17 - hashSize = 1 << hashBits - hashMask = (1 << hashBits) - 1 - hashShift = (hashBits + minMatchLength - 1) / minMatchLength - maxHashOffset = 1 << 24 - - skipNever = math.MaxInt32 -) - -type compressionLevel struct { - good, lazy, nice, chain, fastSkipHashing int -} - -var levels = []compressionLevel{ - {}, // 0 - // For levels 1-3 we don't bother trying with lazy matches - {3, 0, 8, 4, 4}, - {3, 0, 16, 8, 5}, - {3, 0, 32, 32, 6}, - // Levels 4-9 use increasingly more lazy matching - // and increasingly stringent conditions for "good enough". - {4, 4, 16, 16, skipNever}, - {8, 16, 32, 32, skipNever}, - {8, 16, 128, 128, skipNever}, - {8, 32, 128, 256, skipNever}, - {32, 128, 258, 1024, skipNever}, - {32, 258, 258, 4096, skipNever}, -} - -type compressor struct { - compressionLevel - - w *huffmanBitWriter - - // compression algorithm - fill func(*compressor, []byte) int // copy data to window - step func(*compressor) // process window - sync bool // requesting flush - - // Input hash chains - // hashHead[hashValue] contains the largest inputIndex with the specified hash value - // If hashHead[hashValue] is within the current window, then - // hashPrev[hashHead[hashValue] & windowMask] contains the previous index - // with the same hash value. - chainHead int - hashHead []int - hashPrev []int - hashOffset int - - // input window: unprocessed data is window[index:windowEnd] - index int - window []byte - windowEnd int - blockStart int // window index where current tokens start - byteAvailable bool // if true, still need to process window[index-1]. - - // queued output tokens - tokens []token - - // deflate state - length int - offset int - hash int - maxInsertIndex int - err error -} - -func (d *compressor) fillDeflate(b []byte) int { - if d.index >= 2*windowSize-(minMatchLength+maxMatchLength) { - // shift the window by windowSize - copy(d.window, d.window[windowSize:2*windowSize]) - d.index -= windowSize - d.windowEnd -= windowSize - if d.blockStart >= windowSize { - d.blockStart -= windowSize - } else { - d.blockStart = math.MaxInt32 - } - d.hashOffset += windowSize - if d.hashOffset > maxHashOffset { - delta := d.hashOffset - 1 - d.hashOffset -= delta - d.chainHead -= delta - for i, v := range d.hashPrev { - if v > delta { - d.hashPrev[i] -= delta - } else { - d.hashPrev[i] = 0 - } - } - for i, v := range d.hashHead { - if v > delta { - d.hashHead[i] -= delta - } else { - d.hashHead[i] = 0 - } - } - } - } - n := copy(d.window[d.windowEnd:], b) - d.windowEnd += n - return n -} - -func (d *compressor) writeBlock(tokens []token, index int, eof bool) error { - if index > 0 || eof { - var window []byte - if d.blockStart <= index { - window = d.window[d.blockStart:index] - } - d.blockStart = index - d.w.writeBlock(tokens, eof, window) - return d.w.err - } - return nil -} - -// Try to find a match starting at index whose length is greater than prevSize. -// We only look at chainCount possibilities before giving up. -func (d *compressor) findMatch(pos int, prevHead int, prevLength int, lookahead int) (length, offset int, ok bool) { - minMatchLook := maxMatchLength - if lookahead < minMatchLook { - minMatchLook = lookahead - } - - win := d.window[0 : pos+minMatchLook] - - // We quit when we get a match that's at least nice long - nice := len(win) - pos - if d.nice < nice { - nice = d.nice - } - - // If we've got a match that's good enough, only look in 1/4 the chain. - tries := d.chain - length = prevLength - if length >= d.good { - tries >>= 2 - } - - w0 := win[pos] - w1 := win[pos+1] - wEnd := win[pos+length] - minIndex := pos - windowSize - - for i := prevHead; tries > 0; tries-- { - if w0 == win[i] && w1 == win[i+1] && wEnd == win[i+length] { - // The hash function ensures that if win[i] and win[i+1] match, win[i+2] matches - - n := 3 - for pos+n < len(win) && win[i+n] == win[pos+n] { - n++ - } - if n > length && (n > 3 || pos-i <= 4096) { - length = n - offset = pos - i - ok = true - if n >= nice { - // The match is good enough that we don't try to find a better one. - break - } - wEnd = win[pos+n] - } - } - if i == minIndex { - // hashPrev[i & windowMask] has already been overwritten, so stop now. - break - } - if i = d.hashPrev[i&windowMask] - d.hashOffset; i < minIndex || i < 0 { - break - } - } - return -} - -func (d *compressor) writeStoredBlock(buf []byte) error { - if d.w.writeStoredHeader(len(buf), false); d.w.err != nil { - return d.w.err - } - d.w.writeBytes(buf) - return d.w.err -} - -func (d *compressor) initDeflate() { - d.hashHead = make([]int, hashSize) - d.hashPrev = make([]int, windowSize) - d.window = make([]byte, 2*windowSize) - d.hashOffset = 1 - d.tokens = make([]token, 0, maxFlateBlockTokens+1) - d.length = minMatchLength - 1 - d.offset = 0 - d.byteAvailable = false - d.index = 0 - d.hash = 0 - d.chainHead = -1 -} - -func (d *compressor) deflate() { - if d.windowEnd-d.index < minMatchLength+maxMatchLength && !d.sync { - return - } - - d.maxInsertIndex = d.windowEnd - (minMatchLength - 1) - if d.index < d.maxInsertIndex { - d.hash = int(d.window[d.index])< d.windowEnd { - panic("index > windowEnd") - } - lookahead := d.windowEnd - d.index - if lookahead < minMatchLength+maxMatchLength { - if !d.sync { - break Loop - } - if d.index > d.windowEnd { - panic("index > windowEnd") - } - if lookahead == 0 { - // Flush current output block if any. - if d.byteAvailable { - // There is still one pending token that needs to be flushed - d.tokens = append(d.tokens, literalToken(uint32(d.window[d.index-1]))) - d.byteAvailable = false - } - if len(d.tokens) > 0 { - if d.err = d.writeBlock(d.tokens, d.index, false); d.err != nil { - return - } - d.tokens = d.tokens[:0] - } - break Loop - } - } - if d.index < d.maxInsertIndex { - // Update the hash - d.hash = (d.hash<= minIndex && - (d.fastSkipHashing != skipNever && lookahead > minMatchLength-1 || - d.fastSkipHashing == skipNever && lookahead > prevLength && prevLength < d.lazy) { - if newLength, newOffset, ok := d.findMatch(d.index, d.chainHead-d.hashOffset, minMatchLength-1, lookahead); ok { - d.length = newLength - d.offset = newOffset - } - } - if d.fastSkipHashing != skipNever && d.length >= minMatchLength || - d.fastSkipHashing == skipNever && prevLength >= minMatchLength && d.length <= prevLength { - // There was a match at the previous step, and the current match is - // not better. Output the previous match. - if d.fastSkipHashing != skipNever { - d.tokens = append(d.tokens, matchToken(uint32(d.length-minMatchLength), uint32(d.offset-minOffsetSize))) - } else { - d.tokens = append(d.tokens, matchToken(uint32(prevLength-minMatchLength), uint32(prevOffset-minOffsetSize))) - } - // Insert in the hash table all strings up to the end of the match. - // index and index-1 are already inserted. If there is not enough - // lookahead, the last two strings are not inserted into the hash - // table. - if d.length <= d.fastSkipHashing { - var newIndex int - if d.fastSkipHashing != skipNever { - newIndex = d.index + d.length - } else { - newIndex = d.index + prevLength - 1 - } - for d.index++; d.index < newIndex; d.index++ { - if d.index < d.maxInsertIndex { - d.hash = (d.hash< 0 { - d.err = d.writeStoredBlock(d.window[:d.windowEnd]) - } - d.windowEnd = 0 -} - -func (d *compressor) write(b []byte) (n int, err error) { - n = len(b) - b = b[d.fill(d, b):] - for len(b) > 0 { - d.step(d) - b = b[d.fill(d, b):] - } - return n, d.err -} - -func (d *compressor) syncFlush() error { - d.sync = true - d.step(d) - if d.err == nil { - d.w.writeStoredHeader(0, false) - d.w.flush() - d.err = d.w.err - } - d.sync = false - return d.err -} - -func (d *compressor) init(w io.Writer, level int) (err error) { - d.w = newHuffmanBitWriter(w) - - switch { - case level == NoCompression: - d.window = make([]byte, maxStoreBlockSize) - d.fill = (*compressor).fillStore - d.step = (*compressor).store - case level == DefaultCompression: - level = 6 - fallthrough - case 1 <= level && level <= 9: - d.compressionLevel = levels[level] - d.initDeflate() - d.fill = (*compressor).fillDeflate - d.step = (*compressor).deflate - default: - return fmt.Errorf("flate: invalid compression level %d: want value in range [-1, 9]", level) - } - return nil -} - -var zeroes [32]int -var bzeroes [256]byte - -func (d *compressor) reset(w io.Writer) { - d.w.reset(w) - d.sync = false - d.err = nil - switch d.compressionLevel.chain { - case 0: - // level was NoCompression. - for i := range d.window { - d.window[i] = 0 - } - d.windowEnd = 0 - default: - d.chainHead = -1 - for s := d.hashHead; len(s) > 0; { - n := copy(s, zeroes[:]) - s = s[n:] - } - for s := d.hashPrev; len(s) > 0; s = s[len(zeroes):] { - copy(s, zeroes[:]) - } - d.hashOffset = 1 - - d.index, d.windowEnd = 0, 0 - for s := d.window; len(s) > 0; { - n := copy(s, bzeroes[:]) - s = s[n:] - } - d.blockStart, d.byteAvailable = 0, false - - d.tokens = d.tokens[:maxFlateBlockTokens+1] - for i := 0; i <= maxFlateBlockTokens; i++ { - d.tokens[i] = 0 - } - d.tokens = d.tokens[:0] - d.length = minMatchLength - 1 - d.offset = 0 - d.hash = 0 - d.maxInsertIndex = 0 - } -} - -func (d *compressor) close() error { - d.sync = true - d.step(d) - if d.err != nil { - return d.err - } - if d.w.writeStoredHeader(0, true); d.w.err != nil { - return d.w.err - } - d.w.flush() - return d.w.err -} - -// NewWriter returns a new Writer compressing data at the given level. -// Following zlib, levels range from 1 (BestSpeed) to 9 (BestCompression); -// higher levels typically run slower but compress more. Level 0 -// (NoCompression) does not attempt any compression; it only adds the -// necessary DEFLATE framing. Level -1 (DefaultCompression) uses the default -// compression level. -// -// If level is in the range [-1, 9] then the error returned will be nil. -// Otherwise the error returned will be non-nil. -func NewWriter(w io.Writer, level int) (*Writer, error) { - var dw Writer - if err := dw.d.init(w, level); err != nil { - return nil, err - } - return &dw, nil -} - -// NewWriterDict is like NewWriter but initializes the new -// Writer with a preset dictionary. The returned Writer behaves -// as if the dictionary had been written to it without producing -// any compressed output. The compressed data written to w -// can only be decompressed by a Reader initialized with the -// same dictionary. -func NewWriterDict(w io.Writer, level int, dict []byte) (*Writer, error) { - dw := &dictWriter{w, false} - zw, err := NewWriter(dw, level) - if err != nil { - return nil, err - } - zw.Write(dict) - zw.Flush() - dw.enabled = true - zw.dict = append(zw.dict, dict...) // duplicate dictionary for Reset method. - return zw, err -} - -type dictWriter struct { - w io.Writer - enabled bool -} - -func (w *dictWriter) Write(b []byte) (n int, err error) { - if w.enabled { - return w.w.Write(b) - } - return len(b), nil -} - -// A Writer takes data written to it and writes the compressed -// form of that data to an underlying writer (see NewWriter). -type Writer struct { - d compressor - dict []byte -} - -// Write writes data to w, which will eventually write the -// compressed form of data to its underlying writer. -func (w *Writer) Write(data []byte) (n int, err error) { - return w.d.write(data) -} - -// Flush flushes any pending compressed data to the underlying writer. -// It is useful mainly in compressed network protocols, to ensure that -// a remote reader has enough data to reconstruct a packet. -// Flush does not return until the data has been written. -// If the underlying writer returns an error, Flush returns that error. -// -// In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH. -func (w *Writer) Flush() error { - // For more about flushing: - // http://www.bolet.org/~pornin/deflate-flush.html - return w.d.syncFlush() -} - -// Close flushes and closes the writer. -func (w *Writer) Close() error { - return w.d.close() -} - -// Reset discards the writer's state and makes it equivalent to -// the result of NewWriter or NewWriterDict called with dst -// and w's level and dictionary. -func (w *Writer) Reset(dst io.Writer) { - if dw, ok := w.d.w.w.(*dictWriter); ok { - // w was created with NewWriterDict - dw.w = dst - w.d.reset(dw) - dw.enabled = false - w.Write(w.dict) - w.Flush() - dw.enabled = true - } else { - // w was created with NewWriter - w.d.reset(dst) - } -} diff --git a/src/pkg/compress/flate/deflate_test.go b/src/pkg/compress/flate/deflate_test.go deleted file mode 100644 index 730234c38..000000000 --- a/src/pkg/compress/flate/deflate_test.go +++ /dev/null @@ -1,490 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flate - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "reflect" - "sync" - "testing" -) - -type deflateTest struct { - in []byte - level int - out []byte -} - -type deflateInflateTest struct { - in []byte -} - -type reverseBitsTest struct { - in uint16 - bitCount uint8 - out uint16 -} - -var deflateTests = []*deflateTest{ - {[]byte{}, 0, []byte{1, 0, 0, 255, 255}}, - {[]byte{0x11}, -1, []byte{18, 4, 4, 0, 0, 255, 255}}, - {[]byte{0x11}, DefaultCompression, []byte{18, 4, 4, 0, 0, 255, 255}}, - {[]byte{0x11}, 4, []byte{18, 4, 4, 0, 0, 255, 255}}, - - {[]byte{0x11}, 0, []byte{0, 1, 0, 254, 255, 17, 1, 0, 0, 255, 255}}, - {[]byte{0x11, 0x12}, 0, []byte{0, 2, 0, 253, 255, 17, 18, 1, 0, 0, 255, 255}}, - {[]byte{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}, 0, - []byte{0, 8, 0, 247, 255, 17, 17, 17, 17, 17, 17, 17, 17, 1, 0, 0, 255, 255}, - }, - {[]byte{}, 1, []byte{1, 0, 0, 255, 255}}, - {[]byte{0x11}, 1, []byte{18, 4, 4, 0, 0, 255, 255}}, - {[]byte{0x11, 0x12}, 1, []byte{18, 20, 2, 4, 0, 0, 255, 255}}, - {[]byte{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}, 1, []byte{18, 132, 2, 64, 0, 0, 0, 255, 255}}, - {[]byte{}, 9, []byte{1, 0, 0, 255, 255}}, - {[]byte{0x11}, 9, []byte{18, 4, 4, 0, 0, 255, 255}}, - {[]byte{0x11, 0x12}, 9, []byte{18, 20, 2, 4, 0, 0, 255, 255}}, - {[]byte{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}, 9, []byte{18, 132, 2, 64, 0, 0, 0, 255, 255}}, -} - -var deflateInflateTests = []*deflateInflateTest{ - {[]byte{}}, - {[]byte{0x11}}, - {[]byte{0x11, 0x12}}, - {[]byte{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}}, - {[]byte{0x11, 0x10, 0x13, 0x41, 0x21, 0x21, 0x41, 0x13, 0x87, 0x78, 0x13}}, - {largeDataChunk()}, -} - -var reverseBitsTests = []*reverseBitsTest{ - {1, 1, 1}, - {1, 2, 2}, - {1, 3, 4}, - {1, 4, 8}, - {1, 5, 16}, - {17, 5, 17}, - {257, 9, 257}, - {29, 5, 23}, -} - -func largeDataChunk() []byte { - result := make([]byte, 100000) - for i := range result { - result[i] = byte(i * i & 0xFF) - } - return result -} - -func TestDeflate(t *testing.T) { - for _, h := range deflateTests { - var buf bytes.Buffer - w, err := NewWriter(&buf, h.level) - if err != nil { - t.Errorf("NewWriter: %v", err) - continue - } - w.Write(h.in) - w.Close() - if !bytes.Equal(buf.Bytes(), h.out) { - t.Errorf("Deflate(%d, %x) = %x, want %x", h.level, h.in, buf.Bytes(), h.out) - } - } -} - -// A sparseReader returns a stream consisting of 0s followed by 1<<16 1s. -// This tests missing hash references in a very large input. -type sparseReader struct { - l int64 - cur int64 -} - -func (r *sparseReader) Read(b []byte) (n int, err error) { - if r.cur >= r.l { - return 0, io.EOF - } - n = len(b) - cur := r.cur + int64(n) - if cur > r.l { - n -= int(cur - r.l) - cur = r.l - } - for i := range b[0:n] { - if r.cur+int64(i) >= r.l-1<<16 { - b[i] = 1 - } else { - b[i] = 0 - } - } - r.cur = cur - return -} - -func TestVeryLongSparseChunk(t *testing.T) { - if testing.Short() { - t.Skip("skipping sparse chunk during short test") - } - w, err := NewWriter(ioutil.Discard, 1) - if err != nil { - t.Errorf("NewWriter: %v", err) - return - } - if _, err = io.Copy(w, &sparseReader{l: 23E8}); err != nil { - t.Errorf("Compress failed: %v", err) - return - } -} - -type syncBuffer struct { - buf bytes.Buffer - mu sync.RWMutex - closed bool - ready chan bool -} - -func newSyncBuffer() *syncBuffer { - return &syncBuffer{ready: make(chan bool, 1)} -} - -func (b *syncBuffer) Read(p []byte) (n int, err error) { - for { - b.mu.RLock() - n, err = b.buf.Read(p) - b.mu.RUnlock() - if n > 0 || b.closed { - return - } - <-b.ready - } -} - -func (b *syncBuffer) signal() { - select { - case b.ready <- true: - default: - } -} - -func (b *syncBuffer) Write(p []byte) (n int, err error) { - n, err = b.buf.Write(p) - b.signal() - return -} - -func (b *syncBuffer) WriteMode() { - b.mu.Lock() -} - -func (b *syncBuffer) ReadMode() { - b.mu.Unlock() - b.signal() -} - -func (b *syncBuffer) Close() error { - b.closed = true - b.signal() - return nil -} - -func testSync(t *testing.T, level int, input []byte, name string) { - if len(input) == 0 { - return - } - - t.Logf("--testSync %d, %d, %s", level, len(input), name) - buf := newSyncBuffer() - buf1 := new(bytes.Buffer) - buf.WriteMode() - w, err := NewWriter(io.MultiWriter(buf, buf1), level) - if err != nil { - t.Errorf("NewWriter: %v", err) - return - } - r := NewReader(buf) - - // Write half the input and read back. - for i := 0; i < 2; i++ { - var lo, hi int - if i == 0 { - lo, hi = 0, (len(input)+1)/2 - } else { - lo, hi = (len(input)+1)/2, len(input) - } - t.Logf("#%d: write %d-%d", i, lo, hi) - if _, err := w.Write(input[lo:hi]); err != nil { - t.Errorf("testSync: write: %v", err) - return - } - if i == 0 { - if err := w.Flush(); err != nil { - t.Errorf("testSync: flush: %v", err) - return - } - } else { - if err := w.Close(); err != nil { - t.Errorf("testSync: close: %v", err) - } - } - buf.ReadMode() - out := make([]byte, hi-lo+1) - m, err := io.ReadAtLeast(r, out, hi-lo) - t.Logf("#%d: read %d", i, m) - if m != hi-lo || err != nil { - t.Errorf("testSync/%d (%d, %d, %s): read %d: %d, %v (%d left)", i, level, len(input), name, hi-lo, m, err, buf.buf.Len()) - return - } - if !bytes.Equal(input[lo:hi], out[:hi-lo]) { - t.Errorf("testSync/%d: read wrong bytes: %x vs %x", i, input[lo:hi], out[:hi-lo]) - return - } - // This test originally checked that after reading - // the first half of the input, there was nothing left - // in the read buffer (buf.buf.Len() != 0) but that is - // not necessarily the case: the write Flush may emit - // some extra framing bits that are not necessary - // to process to obtain the first half of the uncompressed - // data. The test ran correctly most of the time, because - // the background goroutine had usually read even - // those extra bits by now, but it's not a useful thing to - // check. - buf.WriteMode() - } - buf.ReadMode() - out := make([]byte, 10) - if n, err := r.Read(out); n > 0 || err != io.EOF { - t.Errorf("testSync (%d, %d, %s): final Read: %d, %v (hex: %x)", level, len(input), name, n, err, out[0:n]) - } - if buf.buf.Len() != 0 { - t.Errorf("testSync (%d, %d, %s): extra data at end", level, len(input), name) - } - r.Close() - - // stream should work for ordinary reader too - r = NewReader(buf1) - out, err = ioutil.ReadAll(r) - if err != nil { - t.Errorf("testSync: read: %s", err) - return - } - r.Close() - if !bytes.Equal(input, out) { - t.Errorf("testSync: decompress(compress(data)) != data: level=%d input=%s", level, name) - } -} - -func testToFromWithLevelAndLimit(t *testing.T, level int, input []byte, name string, limit int) { - var buffer bytes.Buffer - w, err := NewWriter(&buffer, level) - if err != nil { - t.Errorf("NewWriter: %v", err) - return - } - w.Write(input) - w.Close() - if limit > 0 && buffer.Len() > limit { - t.Errorf("level: %d, len(compress(data)) = %d > limit = %d", level, buffer.Len(), limit) - return - } - r := NewReader(&buffer) - out, err := ioutil.ReadAll(r) - if err != nil { - t.Errorf("read: %s", err) - return - } - r.Close() - if !bytes.Equal(input, out) { - t.Errorf("decompress(compress(data)) != data: level=%d input=%s", level, name) - return - } - testSync(t, level, input, name) -} - -func testToFromWithLimit(t *testing.T, input []byte, name string, limit [10]int) { - for i := 0; i < 10; i++ { - testToFromWithLevelAndLimit(t, i, input, name, limit[i]) - } -} - -func TestDeflateInflate(t *testing.T) { - for i, h := range deflateInflateTests { - testToFromWithLimit(t, h.in, fmt.Sprintf("#%d", i), [10]int{}) - } -} - -func TestReverseBits(t *testing.T) { - for _, h := range reverseBitsTests { - if v := reverseBits(h.in, h.bitCount); v != h.out { - t.Errorf("reverseBits(%v,%v) = %v, want %v", - h.in, h.bitCount, v, h.out) - } - } -} - -type deflateInflateStringTest struct { - filename string - label string - limit [10]int -} - -var deflateInflateStringTests = []deflateInflateStringTest{ - { - "../testdata/e.txt", - "2.718281828...", - [...]int{100018, 50650, 50960, 51150, 50930, 50790, 50790, 50790, 50790, 50790}, - }, - { - "../testdata/Mark.Twain-Tom.Sawyer.txt", - "Mark.Twain-Tom.Sawyer", - [...]int{407330, 187598, 180361, 172974, 169160, 163476, 160936, 160506, 160295, 160295}, - }, -} - -func TestDeflateInflateString(t *testing.T) { - for _, test := range deflateInflateStringTests { - gold, err := ioutil.ReadFile(test.filename) - if err != nil { - t.Error(err) - } - testToFromWithLimit(t, gold, test.label, test.limit) - if testing.Short() { - break - } - } -} - -func TestReaderDict(t *testing.T) { - const ( - dict = "hello world" - text = "hello again world" - ) - var b bytes.Buffer - w, err := NewWriter(&b, 5) - if err != nil { - t.Fatalf("NewWriter: %v", err) - } - w.Write([]byte(dict)) - w.Flush() - b.Reset() - w.Write([]byte(text)) - w.Close() - - r := NewReaderDict(&b, []byte(dict)) - data, err := ioutil.ReadAll(r) - if err != nil { - t.Fatal(err) - } - if string(data) != "hello again world" { - t.Fatalf("read returned %q want %q", string(data), text) - } -} - -func TestWriterDict(t *testing.T) { - const ( - dict = "hello world" - text = "hello again world" - ) - var b bytes.Buffer - w, err := NewWriter(&b, 5) - if err != nil { - t.Fatalf("NewWriter: %v", err) - } - w.Write([]byte(dict)) - w.Flush() - b.Reset() - w.Write([]byte(text)) - w.Close() - - var b1 bytes.Buffer - w, _ = NewWriterDict(&b1, 5, []byte(dict)) - w.Write([]byte(text)) - w.Close() - - if !bytes.Equal(b1.Bytes(), b.Bytes()) { - t.Fatalf("writer wrote %q want %q", b1.Bytes(), b.Bytes()) - } -} - -// See http://code.google.com/p/go/issues/detail?id=2508 -func TestRegression2508(t *testing.T) { - if testing.Short() { - t.Logf("test disabled with -short") - return - } - w, err := NewWriter(ioutil.Discard, 1) - if err != nil { - t.Fatalf("NewWriter: %v", err) - } - buf := make([]byte, 1024) - for i := 0; i < 131072; i++ { - if _, err := w.Write(buf); err != nil { - t.Fatalf("writer failed: %v", err) - } - } - w.Close() -} - -func TestWriterReset(t *testing.T) { - for level := 0; level <= 9; level++ { - if testing.Short() && level > 1 { - break - } - w, err := NewWriter(ioutil.Discard, level) - if err != nil { - t.Fatalf("NewWriter: %v", err) - } - buf := []byte("hello world") - for i := 0; i < 1024; i++ { - w.Write(buf) - } - w.Reset(ioutil.Discard) - - wref, err := NewWriter(ioutil.Discard, level) - if err != nil { - t.Fatalf("NewWriter: %v", err) - } - - // DeepEqual doesn't compare functions. - w.d.fill, wref.d.fill = nil, nil - w.d.step, wref.d.step = nil, nil - if !reflect.DeepEqual(w, wref) { - t.Errorf("level %d Writer not reset after Reset", level) - } - } - testResetOutput(t, func(w io.Writer) (*Writer, error) { return NewWriter(w, NoCompression) }) - testResetOutput(t, func(w io.Writer) (*Writer, error) { return NewWriter(w, DefaultCompression) }) - testResetOutput(t, func(w io.Writer) (*Writer, error) { return NewWriter(w, BestCompression) }) - dict := []byte("we are the world") - testResetOutput(t, func(w io.Writer) (*Writer, error) { return NewWriterDict(w, NoCompression, dict) }) - testResetOutput(t, func(w io.Writer) (*Writer, error) { return NewWriterDict(w, DefaultCompression, dict) }) - testResetOutput(t, func(w io.Writer) (*Writer, error) { return NewWriterDict(w, BestCompression, dict) }) -} - -func testResetOutput(t *testing.T, newWriter func(w io.Writer) (*Writer, error)) { - buf := new(bytes.Buffer) - w, err := newWriter(buf) - if err != nil { - t.Fatalf("NewWriter: %v", err) - } - b := []byte("hello world") - for i := 0; i < 1024; i++ { - w.Write(b) - } - w.Close() - out1 := buf.String() - - buf2 := new(bytes.Buffer) - w.Reset(buf2) - for i := 0; i < 1024; i++ { - w.Write(b) - } - w.Close() - out2 := buf2.String() - - if out1 != out2 { - t.Errorf("got %q, expected %q", out2, out1) - } - t.Logf("got %d bytes", len(out1)) -} diff --git a/src/pkg/compress/flate/fixedhuff.go b/src/pkg/compress/flate/fixedhuff.go deleted file mode 100644 index 7df8b9a29..000000000 --- a/src/pkg/compress/flate/fixedhuff.go +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flate - -// autogenerated by go run gen.go -output fixedhuff.go, DO NOT EDIT - -var fixedHuffmanDecoder = huffmanDecoder{ - 7, - [huffmanNumChunks]uint32{ - 0x1007, 0x0508, 0x0108, 0x1188, 0x1107, 0x0708, 0x0308, 0x0c09, - 0x1087, 0x0608, 0x0208, 0x0a09, 0x0008, 0x0808, 0x0408, 0x0e09, - 0x1047, 0x0588, 0x0188, 0x0909, 0x1147, 0x0788, 0x0388, 0x0d09, - 0x10c7, 0x0688, 0x0288, 0x0b09, 0x0088, 0x0888, 0x0488, 0x0f09, - 0x1027, 0x0548, 0x0148, 0x11c8, 0x1127, 0x0748, 0x0348, 0x0c89, - 0x10a7, 0x0648, 0x0248, 0x0a89, 0x0048, 0x0848, 0x0448, 0x0e89, - 0x1067, 0x05c8, 0x01c8, 0x0989, 0x1167, 0x07c8, 0x03c8, 0x0d89, - 0x10e7, 0x06c8, 0x02c8, 0x0b89, 0x00c8, 0x08c8, 0x04c8, 0x0f89, - 0x1017, 0x0528, 0x0128, 0x11a8, 0x1117, 0x0728, 0x0328, 0x0c49, - 0x1097, 0x0628, 0x0228, 0x0a49, 0x0028, 0x0828, 0x0428, 0x0e49, - 0x1057, 0x05a8, 0x01a8, 0x0949, 0x1157, 0x07a8, 0x03a8, 0x0d49, - 0x10d7, 0x06a8, 0x02a8, 0x0b49, 0x00a8, 0x08a8, 0x04a8, 0x0f49, - 0x1037, 0x0568, 0x0168, 0x11e8, 0x1137, 0x0768, 0x0368, 0x0cc9, - 0x10b7, 0x0668, 0x0268, 0x0ac9, 0x0068, 0x0868, 0x0468, 0x0ec9, - 0x1077, 0x05e8, 0x01e8, 0x09c9, 0x1177, 0x07e8, 0x03e8, 0x0dc9, - 0x10f7, 0x06e8, 0x02e8, 0x0bc9, 0x00e8, 0x08e8, 0x04e8, 0x0fc9, - 0x1007, 0x0518, 0x0118, 0x1198, 0x1107, 0x0718, 0x0318, 0x0c29, - 0x1087, 0x0618, 0x0218, 0x0a29, 0x0018, 0x0818, 0x0418, 0x0e29, - 0x1047, 0x0598, 0x0198, 0x0929, 0x1147, 0x0798, 0x0398, 0x0d29, - 0x10c7, 0x0698, 0x0298, 0x0b29, 0x0098, 0x0898, 0x0498, 0x0f29, - 0x1027, 0x0558, 0x0158, 0x11d8, 0x1127, 0x0758, 0x0358, 0x0ca9, - 0x10a7, 0x0658, 0x0258, 0x0aa9, 0x0058, 0x0858, 0x0458, 0x0ea9, - 0x1067, 0x05d8, 0x01d8, 0x09a9, 0x1167, 0x07d8, 0x03d8, 0x0da9, - 0x10e7, 0x06d8, 0x02d8, 0x0ba9, 0x00d8, 0x08d8, 0x04d8, 0x0fa9, - 0x1017, 0x0538, 0x0138, 0x11b8, 0x1117, 0x0738, 0x0338, 0x0c69, - 0x1097, 0x0638, 0x0238, 0x0a69, 0x0038, 0x0838, 0x0438, 0x0e69, - 0x1057, 0x05b8, 0x01b8, 0x0969, 0x1157, 0x07b8, 0x03b8, 0x0d69, - 0x10d7, 0x06b8, 0x02b8, 0x0b69, 0x00b8, 0x08b8, 0x04b8, 0x0f69, - 0x1037, 0x0578, 0x0178, 0x11f8, 0x1137, 0x0778, 0x0378, 0x0ce9, - 0x10b7, 0x0678, 0x0278, 0x0ae9, 0x0078, 0x0878, 0x0478, 0x0ee9, - 0x1077, 0x05f8, 0x01f8, 0x09e9, 0x1177, 0x07f8, 0x03f8, 0x0de9, - 0x10f7, 0x06f8, 0x02f8, 0x0be9, 0x00f8, 0x08f8, 0x04f8, 0x0fe9, - 0x1007, 0x0508, 0x0108, 0x1188, 0x1107, 0x0708, 0x0308, 0x0c19, - 0x1087, 0x0608, 0x0208, 0x0a19, 0x0008, 0x0808, 0x0408, 0x0e19, - 0x1047, 0x0588, 0x0188, 0x0919, 0x1147, 0x0788, 0x0388, 0x0d19, - 0x10c7, 0x0688, 0x0288, 0x0b19, 0x0088, 0x0888, 0x0488, 0x0f19, - 0x1027, 0x0548, 0x0148, 0x11c8, 0x1127, 0x0748, 0x0348, 0x0c99, - 0x10a7, 0x0648, 0x0248, 0x0a99, 0x0048, 0x0848, 0x0448, 0x0e99, - 0x1067, 0x05c8, 0x01c8, 0x0999, 0x1167, 0x07c8, 0x03c8, 0x0d99, - 0x10e7, 0x06c8, 0x02c8, 0x0b99, 0x00c8, 0x08c8, 0x04c8, 0x0f99, - 0x1017, 0x0528, 0x0128, 0x11a8, 0x1117, 0x0728, 0x0328, 0x0c59, - 0x1097, 0x0628, 0x0228, 0x0a59, 0x0028, 0x0828, 0x0428, 0x0e59, - 0x1057, 0x05a8, 0x01a8, 0x0959, 0x1157, 0x07a8, 0x03a8, 0x0d59, - 0x10d7, 0x06a8, 0x02a8, 0x0b59, 0x00a8, 0x08a8, 0x04a8, 0x0f59, - 0x1037, 0x0568, 0x0168, 0x11e8, 0x1137, 0x0768, 0x0368, 0x0cd9, - 0x10b7, 0x0668, 0x0268, 0x0ad9, 0x0068, 0x0868, 0x0468, 0x0ed9, - 0x1077, 0x05e8, 0x01e8, 0x09d9, 0x1177, 0x07e8, 0x03e8, 0x0dd9, - 0x10f7, 0x06e8, 0x02e8, 0x0bd9, 0x00e8, 0x08e8, 0x04e8, 0x0fd9, - 0x1007, 0x0518, 0x0118, 0x1198, 0x1107, 0x0718, 0x0318, 0x0c39, - 0x1087, 0x0618, 0x0218, 0x0a39, 0x0018, 0x0818, 0x0418, 0x0e39, - 0x1047, 0x0598, 0x0198, 0x0939, 0x1147, 0x0798, 0x0398, 0x0d39, - 0x10c7, 0x0698, 0x0298, 0x0b39, 0x0098, 0x0898, 0x0498, 0x0f39, - 0x1027, 0x0558, 0x0158, 0x11d8, 0x1127, 0x0758, 0x0358, 0x0cb9, - 0x10a7, 0x0658, 0x0258, 0x0ab9, 0x0058, 0x0858, 0x0458, 0x0eb9, - 0x1067, 0x05d8, 0x01d8, 0x09b9, 0x1167, 0x07d8, 0x03d8, 0x0db9, - 0x10e7, 0x06d8, 0x02d8, 0x0bb9, 0x00d8, 0x08d8, 0x04d8, 0x0fb9, - 0x1017, 0x0538, 0x0138, 0x11b8, 0x1117, 0x0738, 0x0338, 0x0c79, - 0x1097, 0x0638, 0x0238, 0x0a79, 0x0038, 0x0838, 0x0438, 0x0e79, - 0x1057, 0x05b8, 0x01b8, 0x0979, 0x1157, 0x07b8, 0x03b8, 0x0d79, - 0x10d7, 0x06b8, 0x02b8, 0x0b79, 0x00b8, 0x08b8, 0x04b8, 0x0f79, - 0x1037, 0x0578, 0x0178, 0x11f8, 0x1137, 0x0778, 0x0378, 0x0cf9, - 0x10b7, 0x0678, 0x0278, 0x0af9, 0x0078, 0x0878, 0x0478, 0x0ef9, - 0x1077, 0x05f8, 0x01f8, 0x09f9, 0x1177, 0x07f8, 0x03f8, 0x0df9, - 0x10f7, 0x06f8, 0x02f8, 0x0bf9, 0x00f8, 0x08f8, 0x04f8, 0x0ff9, - }, - nil, 0, -} diff --git a/src/pkg/compress/flate/flate_test.go b/src/pkg/compress/flate/flate_test.go deleted file mode 100644 index 068766323..000000000 --- a/src/pkg/compress/flate/flate_test.go +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This test tests some internals of the flate package. -// The tests in package compress/gzip serve as the -// end-to-end test of the decompressor. - -package flate - -import ( - "bytes" - "testing" -) - -func TestUncompressedSource(t *testing.T) { - decoder := NewReader(bytes.NewReader([]byte{0x01, 0x01, 0x00, 0xfe, 0xff, 0x11})) - output := make([]byte, 1) - n, error := decoder.Read(output) - if n != 1 || error != nil { - t.Fatalf("decoder.Read() = %d, %v, want 1, nil", n, error) - } - if output[0] != 0x11 { - t.Errorf("output[0] = %x, want 0x11", output[0]) - } -} - -// The following test should not panic. -func TestIssue5915(t *testing.T) { - bits := []int{4, 0, 0, 6, 4, 3, 2, 3, 3, 4, 4, 5, 0, 0, 0, 0, 5, 5, 6, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 6, 0, 11, 0, 8, 0, 6, 6, 10, 8} - h := new(huffmanDecoder) - ok := h.init(bits) - if ok == true { - t.Fatalf("Given sequence of bits is bad, and should not succeed.") - } -} - -// The following test should not panic. -func TestIssue5962(t *testing.T) { - bits := []int{4, 0, 0, 6, 4, 3, 2, 3, 3, 4, 4, 5, 0, 0, 0, 0, - 5, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 11} - h := new(huffmanDecoder) - ok := h.init(bits) - if ok == true { - t.Fatalf("Given sequence of bits is bad, and should not succeed.") - } -} - -// The following test should not panic. -func TestIssue6255(t *testing.T) { - bits1 := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 11} - bits2 := []int{11, 13} - h := new(huffmanDecoder) - if !h.init(bits1) { - t.Fatalf("Given sequence of bits is good and should succeed.") - } - if h.init(bits2) { - t.Fatalf("Given sequence of bits is bad and should not succeed.") - } -} diff --git a/src/pkg/compress/flate/gen.go b/src/pkg/compress/flate/gen.go deleted file mode 100644 index 6288ecddd..000000000 --- a/src/pkg/compress/flate/gen.go +++ /dev/null @@ -1,190 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// This program generates fixedhuff.go -// Invoke as -// -// go run gen.go -output fixedhuff.go - -package main - -import ( - "bytes" - "flag" - "fmt" - "go/format" - "io/ioutil" - "log" -) - -var filename = flag.String("output", "fixedhuff.go", "output file name") - -const maxCodeLen = 16 - -// Note: the definition of the huffmanDecoder struct is copied from -// inflate.go, as it is private to the implementation. - -// chunk & 15 is number of bits -// chunk >> 4 is value, including table link - -const ( - huffmanChunkBits = 9 - huffmanNumChunks = 1 << huffmanChunkBits - huffmanCountMask = 15 - huffmanValueShift = 4 -) - -type huffmanDecoder struct { - min int // the minimum code length - chunks [huffmanNumChunks]uint32 // chunks as described above - links [][]uint32 // overflow links - linkMask uint32 // mask the width of the link table -} - -// Initialize Huffman decoding tables from array of code lengths. -func (h *huffmanDecoder) init(bits []int) bool { - // Count number of codes of each length, - // compute min and max length. - var count [maxCodeLen]int - var min, max int - for _, n := range bits { - if n == 0 { - continue - } - if min == 0 || n < min { - min = n - } - if n > max { - max = n - } - count[n]++ - } - if max == 0 { - return false - } - - h.min = min - var linkBits uint - var numLinks int - if max > huffmanChunkBits { - linkBits = uint(max) - huffmanChunkBits - numLinks = 1 << linkBits - h.linkMask = uint32(numLinks - 1) - } - code := 0 - var nextcode [maxCodeLen]int - for i := min; i <= max; i++ { - if i == huffmanChunkBits+1 { - // create link tables - link := code >> 1 - h.links = make([][]uint32, huffmanNumChunks-link) - for j := uint(link); j < huffmanNumChunks; j++ { - reverse := int(reverseByte[j>>8]) | int(reverseByte[j&0xff])<<8 - reverse >>= uint(16 - huffmanChunkBits) - off := j - uint(link) - h.chunks[reverse] = uint32(off<>8]) | int(reverseByte[code&0xff])<<8 - reverse >>= uint(16 - n) - if n <= huffmanChunkBits { - for off := reverse; off < huffmanNumChunks; off += 1 << uint(n) { - h.chunks[off] = chunk - } - } else { - linktab := h.links[h.chunks[reverse&(huffmanNumChunks-1)]>>huffmanValueShift] - reverse >>= huffmanChunkBits - for off := reverse; off < numLinks; off += 1 << uint(n-huffmanChunkBits) { - linktab[off] = chunk - } - } - } - return true -} - -func main() { - flag.Parse() - - var h huffmanDecoder - var bits [288]int - initReverseByte() - for i := 0; i < 144; i++ { - bits[i] = 8 - } - for i := 144; i < 256; i++ { - bits[i] = 9 - } - for i := 256; i < 280; i++ { - bits[i] = 7 - } - for i := 280; i < 288; i++ { - bits[i] = 8 - } - h.init(bits[:]) - - var buf bytes.Buffer - - fmt.Fprintf(&buf, `// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file.`+"\n\n") - - fmt.Fprintln(&buf, "package flate") - fmt.Fprintln(&buf) - fmt.Fprintln(&buf, "// autogenerated by go run gen.go -output fixedhuff.go, DO NOT EDIT") - fmt.Fprintln(&buf) - fmt.Fprintln(&buf, "var fixedHuffmanDecoder = huffmanDecoder{") - fmt.Fprintf(&buf, "\t%d,\n", h.min) - fmt.Fprintln(&buf, "\t[huffmanNumChunks]uint32{") - for i := 0; i < huffmanNumChunks; i++ { - if i&7 == 0 { - fmt.Fprintf(&buf, "\t\t") - } else { - fmt.Fprintf(&buf, " ") - } - fmt.Fprintf(&buf, "0x%04x,", h.chunks[i]) - if i&7 == 7 { - fmt.Fprintln(&buf) - } - } - fmt.Fprintln(&buf, "\t},") - fmt.Fprintln(&buf, "\tnil, 0,") - fmt.Fprintln(&buf, "}") - - data, err := format.Source(buf.Bytes()) - if err != nil { - log.Fatal(err) - } - err = ioutil.WriteFile(*filename, data, 0644) - if err != nil { - log.Fatal(err) - } -} - -var reverseByte [256]byte - -func initReverseByte() { - for x := 0; x < 256; x++ { - var result byte - for i := uint(0); i < 8; i++ { - result |= byte(((x >> i) & 1) << (7 - i)) - } - reverseByte[x] = result - } -} diff --git a/src/pkg/compress/flate/huffman_bit_writer.go b/src/pkg/compress/flate/huffman_bit_writer.go deleted file mode 100644 index b182a710b..000000000 --- a/src/pkg/compress/flate/huffman_bit_writer.go +++ /dev/null @@ -1,517 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flate - -import ( - "io" - "math" -) - -const ( - // The largest offset code. - offsetCodeCount = 30 - - // The special code used to mark the end of a block. - endBlockMarker = 256 - - // The first length code. - lengthCodesStart = 257 - - // The number of codegen codes. - codegenCodeCount = 19 - badCode = 255 -) - -// The number of extra bits needed by length code X - LENGTH_CODES_START. -var lengthExtraBits = []int8{ - /* 257 */ 0, 0, 0, - /* 260 */ 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, - /* 270 */ 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, - /* 280 */ 4, 5, 5, 5, 5, 0, -} - -// The length indicated by length code X - LENGTH_CODES_START. -var lengthBase = []uint32{ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, - 12, 14, 16, 20, 24, 28, 32, 40, 48, 56, - 64, 80, 96, 112, 128, 160, 192, 224, 255, -} - -// offset code word extra bits. -var offsetExtraBits = []int8{ - 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, - 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, - 9, 9, 10, 10, 11, 11, 12, 12, 13, 13, - /* extended window */ - 14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, -} - -var offsetBase = []uint32{ - /* normal deflate */ - 0x000000, 0x000001, 0x000002, 0x000003, 0x000004, - 0x000006, 0x000008, 0x00000c, 0x000010, 0x000018, - 0x000020, 0x000030, 0x000040, 0x000060, 0x000080, - 0x0000c0, 0x000100, 0x000180, 0x000200, 0x000300, - 0x000400, 0x000600, 0x000800, 0x000c00, 0x001000, - 0x001800, 0x002000, 0x003000, 0x004000, 0x006000, - - /* extended window */ - 0x008000, 0x00c000, 0x010000, 0x018000, 0x020000, - 0x030000, 0x040000, 0x060000, 0x080000, 0x0c0000, - 0x100000, 0x180000, 0x200000, 0x300000, -} - -// The odd order in which the codegen code sizes are written. -var codegenOrder = []uint32{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15} - -type huffmanBitWriter struct { - w io.Writer - // Data waiting to be written is bytes[0:nbytes] - // and then the low nbits of bits. - bits uint32 - nbits uint32 - bytes [64]byte - nbytes int - literalFreq []int32 - offsetFreq []int32 - codegen []uint8 - codegenFreq []int32 - literalEncoding *huffmanEncoder - offsetEncoding *huffmanEncoder - codegenEncoding *huffmanEncoder - err error -} - -func newHuffmanBitWriter(w io.Writer) *huffmanBitWriter { - return &huffmanBitWriter{ - w: w, - literalFreq: make([]int32, maxLit), - offsetFreq: make([]int32, offsetCodeCount), - codegen: make([]uint8, maxLit+offsetCodeCount+1), - codegenFreq: make([]int32, codegenCodeCount), - literalEncoding: newHuffmanEncoder(maxLit), - offsetEncoding: newHuffmanEncoder(offsetCodeCount), - codegenEncoding: newHuffmanEncoder(codegenCodeCount), - } -} - -func (w *huffmanBitWriter) reset(writer io.Writer) { - w.w = writer - w.bits, w.nbits, w.nbytes, w.err = 0, 0, 0, nil - w.bytes = [64]byte{} - for i := range w.codegen { - w.codegen[i] = 0 - } - for _, s := range [...][]int32{w.literalFreq, w.offsetFreq, w.codegenFreq} { - for i := range s { - s[i] = 0 - } - } - for _, enc := range [...]*huffmanEncoder{ - w.literalEncoding, - w.offsetEncoding, - w.codegenEncoding} { - for i := range enc.code { - enc.code[i] = 0 - } - for i := range enc.codeBits { - enc.codeBits[i] = 0 - } - } -} - -func (w *huffmanBitWriter) flushBits() { - if w.err != nil { - w.nbits = 0 - return - } - bits := w.bits - w.bits >>= 16 - w.nbits -= 16 - n := w.nbytes - w.bytes[n] = byte(bits) - w.bytes[n+1] = byte(bits >> 8) - if n += 2; n >= len(w.bytes) { - _, w.err = w.w.Write(w.bytes[0:]) - n = 0 - } - w.nbytes = n -} - -func (w *huffmanBitWriter) flush() { - if w.err != nil { - w.nbits = 0 - return - } - n := w.nbytes - if w.nbits > 8 { - w.bytes[n] = byte(w.bits) - w.bits >>= 8 - w.nbits -= 8 - n++ - } - if w.nbits > 0 { - w.bytes[n] = byte(w.bits) - w.nbits = 0 - n++ - } - w.bits = 0 - _, w.err = w.w.Write(w.bytes[0:n]) - w.nbytes = 0 -} - -func (w *huffmanBitWriter) writeBits(b, nb int32) { - w.bits |= uint32(b) << w.nbits - if w.nbits += uint32(nb); w.nbits >= 16 { - w.flushBits() - } -} - -func (w *huffmanBitWriter) writeBytes(bytes []byte) { - if w.err != nil { - return - } - n := w.nbytes - if w.nbits == 8 { - w.bytes[n] = byte(w.bits) - w.nbits = 0 - n++ - } - if w.nbits != 0 { - w.err = InternalError("writeBytes with unfinished bits") - return - } - if n != 0 { - _, w.err = w.w.Write(w.bytes[0:n]) - if w.err != nil { - return - } - } - w.nbytes = 0 - _, w.err = w.w.Write(bytes) -} - -// RFC 1951 3.2.7 specifies a special run-length encoding for specifying -// the literal and offset lengths arrays (which are concatenated into a single -// array). This method generates that run-length encoding. -// -// The result is written into the codegen array, and the frequencies -// of each code is written into the codegenFreq array. -// Codes 0-15 are single byte codes. Codes 16-18 are followed by additional -// information. Code badCode is an end marker -// -// numLiterals The number of literals in literalEncoding -// numOffsets The number of offsets in offsetEncoding -func (w *huffmanBitWriter) generateCodegen(numLiterals int, numOffsets int) { - for i := range w.codegenFreq { - w.codegenFreq[i] = 0 - } - // Note that we are using codegen both as a temporary variable for holding - // a copy of the frequencies, and as the place where we put the result. - // This is fine because the output is always shorter than the input used - // so far. - codegen := w.codegen // cache - // Copy the concatenated code sizes to codegen. Put a marker at the end. - copy(codegen[0:numLiterals], w.literalEncoding.codeBits) - copy(codegen[numLiterals:numLiterals+numOffsets], w.offsetEncoding.codeBits) - codegen[numLiterals+numOffsets] = badCode - - size := codegen[0] - count := 1 - outIndex := 0 - for inIndex := 1; size != badCode; inIndex++ { - // INVARIANT: We have seen "count" copies of size that have not yet - // had output generated for them. - nextSize := codegen[inIndex] - if nextSize == size { - count++ - continue - } - // We need to generate codegen indicating "count" of size. - if size != 0 { - codegen[outIndex] = size - outIndex++ - w.codegenFreq[size]++ - count-- - for count >= 3 { - n := 6 - if n > count { - n = count - } - codegen[outIndex] = 16 - outIndex++ - codegen[outIndex] = uint8(n - 3) - outIndex++ - w.codegenFreq[16]++ - count -= n - } - } else { - for count >= 11 { - n := 138 - if n > count { - n = count - } - codegen[outIndex] = 18 - outIndex++ - codegen[outIndex] = uint8(n - 11) - outIndex++ - w.codegenFreq[18]++ - count -= n - } - if count >= 3 { - // count >= 3 && count <= 10 - codegen[outIndex] = 17 - outIndex++ - codegen[outIndex] = uint8(count - 3) - outIndex++ - w.codegenFreq[17]++ - count = 0 - } - } - count-- - for ; count >= 0; count-- { - codegen[outIndex] = size - outIndex++ - w.codegenFreq[size]++ - } - // Set up invariant for next time through the loop. - size = nextSize - count = 1 - } - // Marker indicating the end of the codegen. - codegen[outIndex] = badCode -} - -func (w *huffmanBitWriter) writeCode(code *huffmanEncoder, literal uint32) { - if w.err != nil { - return - } - w.writeBits(int32(code.code[literal]), int32(code.codeBits[literal])) -} - -// Write the header of a dynamic Huffman block to the output stream. -// -// numLiterals The number of literals specified in codegen -// numOffsets The number of offsets specified in codegen -// numCodegens The number of codegens used in codegen -func (w *huffmanBitWriter) writeDynamicHeader(numLiterals int, numOffsets int, numCodegens int, isEof bool) { - if w.err != nil { - return - } - var firstBits int32 = 4 - if isEof { - firstBits = 5 - } - w.writeBits(firstBits, 3) - w.writeBits(int32(numLiterals-257), 5) - w.writeBits(int32(numOffsets-1), 5) - w.writeBits(int32(numCodegens-4), 4) - - for i := 0; i < numCodegens; i++ { - value := w.codegenEncoding.codeBits[codegenOrder[i]] - w.writeBits(int32(value), 3) - } - - i := 0 - for { - var codeWord int = int(w.codegen[i]) - i++ - if codeWord == badCode { - break - } - // The low byte contains the actual code to generate. - w.writeCode(w.codegenEncoding, uint32(codeWord)) - - switch codeWord { - case 16: - w.writeBits(int32(w.codegen[i]), 2) - i++ - break - case 17: - w.writeBits(int32(w.codegen[i]), 3) - i++ - break - case 18: - w.writeBits(int32(w.codegen[i]), 7) - i++ - break - } - } -} - -func (w *huffmanBitWriter) writeStoredHeader(length int, isEof bool) { - if w.err != nil { - return - } - var flag int32 - if isEof { - flag = 1 - } - w.writeBits(flag, 3) - w.flush() - w.writeBits(int32(length), 16) - w.writeBits(int32(^uint16(length)), 16) -} - -func (w *huffmanBitWriter) writeFixedHeader(isEof bool) { - if w.err != nil { - return - } - // Indicate that we are a fixed Huffman block - var value int32 = 2 - if isEof { - value = 3 - } - w.writeBits(value, 3) -} - -func (w *huffmanBitWriter) writeBlock(tokens []token, eof bool, input []byte) { - if w.err != nil { - return - } - for i := range w.literalFreq { - w.literalFreq[i] = 0 - } - for i := range w.offsetFreq { - w.offsetFreq[i] = 0 - } - - n := len(tokens) - tokens = tokens[0 : n+1] - tokens[n] = endBlockMarker - - for _, t := range tokens { - switch t.typ() { - case literalType: - w.literalFreq[t.literal()]++ - case matchType: - length := t.length() - offset := t.offset() - w.literalFreq[lengthCodesStart+lengthCode(length)]++ - w.offsetFreq[offsetCode(offset)]++ - } - } - - // get the number of literals - numLiterals := len(w.literalFreq) - for w.literalFreq[numLiterals-1] == 0 { - numLiterals-- - } - // get the number of offsets - numOffsets := len(w.offsetFreq) - for numOffsets > 0 && w.offsetFreq[numOffsets-1] == 0 { - numOffsets-- - } - if numOffsets == 0 { - // We haven't found a single match. If we want to go with the dynamic encoding, - // we should count at least one offset to be sure that the offset huffman tree could be encoded. - w.offsetFreq[0] = 1 - numOffsets = 1 - } - - w.literalEncoding.generate(w.literalFreq, 15) - w.offsetEncoding.generate(w.offsetFreq, 15) - - storedBytes := 0 - if input != nil { - storedBytes = len(input) - } - var extraBits int64 - var storedSize int64 = math.MaxInt64 - if storedBytes <= maxStoreBlockSize && input != nil { - storedSize = int64((storedBytes + 5) * 8) - // We only bother calculating the costs of the extra bits required by - // the length of offset fields (which will be the same for both fixed - // and dynamic encoding), if we need to compare those two encodings - // against stored encoding. - for lengthCode := lengthCodesStart + 8; lengthCode < numLiterals; lengthCode++ { - // First eight length codes have extra size = 0. - extraBits += int64(w.literalFreq[lengthCode]) * int64(lengthExtraBits[lengthCode-lengthCodesStart]) - } - for offsetCode := 4; offsetCode < numOffsets; offsetCode++ { - // First four offset codes have extra size = 0. - extraBits += int64(w.offsetFreq[offsetCode]) * int64(offsetExtraBits[offsetCode]) - } - } - - // Figure out smallest code. - // Fixed Huffman baseline. - var size = int64(3) + - fixedLiteralEncoding.bitLength(w.literalFreq) + - fixedOffsetEncoding.bitLength(w.offsetFreq) + - extraBits - var literalEncoding = fixedLiteralEncoding - var offsetEncoding = fixedOffsetEncoding - - // Dynamic Huffman? - var numCodegens int - - // Generate codegen and codegenFrequencies, which indicates how to encode - // the literalEncoding and the offsetEncoding. - w.generateCodegen(numLiterals, numOffsets) - w.codegenEncoding.generate(w.codegenFreq, 7) - numCodegens = len(w.codegenFreq) - for numCodegens > 4 && w.codegenFreq[codegenOrder[numCodegens-1]] == 0 { - numCodegens-- - } - dynamicHeader := int64(3+5+5+4+(3*numCodegens)) + - w.codegenEncoding.bitLength(w.codegenFreq) + - int64(extraBits) + - int64(w.codegenFreq[16]*2) + - int64(w.codegenFreq[17]*3) + - int64(w.codegenFreq[18]*7) - dynamicSize := dynamicHeader + - w.literalEncoding.bitLength(w.literalFreq) + - w.offsetEncoding.bitLength(w.offsetFreq) - - if dynamicSize < size { - size = dynamicSize - literalEncoding = w.literalEncoding - offsetEncoding = w.offsetEncoding - } - - // Stored bytes? - if storedSize < size { - w.writeStoredHeader(storedBytes, eof) - w.writeBytes(input[0:storedBytes]) - return - } - - // Huffman. - if literalEncoding == fixedLiteralEncoding { - w.writeFixedHeader(eof) - } else { - w.writeDynamicHeader(numLiterals, numOffsets, numCodegens, eof) - } - for _, t := range tokens { - switch t.typ() { - case literalType: - w.writeCode(literalEncoding, t.literal()) - break - case matchType: - // Write the length - length := t.length() - lengthCode := lengthCode(length) - w.writeCode(literalEncoding, lengthCode+lengthCodesStart) - extraLengthBits := int32(lengthExtraBits[lengthCode]) - if extraLengthBits > 0 { - extraLength := int32(length - lengthBase[lengthCode]) - w.writeBits(extraLength, extraLengthBits) - } - // Write the offset - offset := t.offset() - offsetCode := offsetCode(offset) - w.writeCode(offsetEncoding, offsetCode) - extraOffsetBits := int32(offsetExtraBits[offsetCode]) - if extraOffsetBits > 0 { - extraOffset := int32(offset - offsetBase[offsetCode]) - w.writeBits(extraOffset, extraOffsetBits) - } - break - default: - panic("unknown token type: " + string(t)) - } - } -} diff --git a/src/pkg/compress/flate/huffman_code.go b/src/pkg/compress/flate/huffman_code.go deleted file mode 100644 index 3b9fce466..000000000 --- a/src/pkg/compress/flate/huffman_code.go +++ /dev/null @@ -1,323 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flate - -import ( - "math" - "sort" -) - -type huffmanEncoder struct { - codeBits []uint8 - code []uint16 -} - -type literalNode struct { - literal uint16 - freq int32 -} - -// A levelInfo describes the state of the constructed tree for a given depth. -type levelInfo struct { - // Our level. for better printing - level int32 - - // The frequency of the last node at this level - lastFreq int32 - - // The frequency of the next character to add to this level - nextCharFreq int32 - - // The frequency of the next pair (from level below) to add to this level. - // Only valid if the "needed" value of the next lower level is 0. - nextPairFreq int32 - - // The number of chains remaining to generate for this level before moving - // up to the next level - needed int32 -} - -func maxNode() literalNode { return literalNode{math.MaxUint16, math.MaxInt32} } - -func newHuffmanEncoder(size int) *huffmanEncoder { - return &huffmanEncoder{make([]uint8, size), make([]uint16, size)} -} - -// Generates a HuffmanCode corresponding to the fixed literal table -func generateFixedLiteralEncoding() *huffmanEncoder { - h := newHuffmanEncoder(maxLit) - codeBits := h.codeBits - code := h.code - var ch uint16 - for ch = 0; ch < maxLit; ch++ { - var bits uint16 - var size uint8 - switch { - case ch < 144: - // size 8, 000110000 .. 10111111 - bits = ch + 48 - size = 8 - break - case ch < 256: - // size 9, 110010000 .. 111111111 - bits = ch + 400 - 144 - size = 9 - break - case ch < 280: - // size 7, 0000000 .. 0010111 - bits = ch - 256 - size = 7 - break - default: - // size 8, 11000000 .. 11000111 - bits = ch + 192 - 280 - size = 8 - } - codeBits[ch] = size - code[ch] = reverseBits(bits, size) - } - return h -} - -func generateFixedOffsetEncoding() *huffmanEncoder { - h := newHuffmanEncoder(30) - codeBits := h.codeBits - code := h.code - for ch := uint16(0); ch < 30; ch++ { - codeBits[ch] = 5 - code[ch] = reverseBits(ch, 5) - } - return h -} - -var fixedLiteralEncoding *huffmanEncoder = generateFixedLiteralEncoding() -var fixedOffsetEncoding *huffmanEncoder = generateFixedOffsetEncoding() - -func (h *huffmanEncoder) bitLength(freq []int32) int64 { - var total int64 - for i, f := range freq { - if f != 0 { - total += int64(f) * int64(h.codeBits[i]) - } - } - return total -} - -const maxBitsLimit = 16 - -// Return the number of literals assigned to each bit size in the Huffman encoding -// -// This method is only called when list.length >= 3 -// The cases of 0, 1, and 2 literals are handled by special case code. -// -// list An array of the literals with non-zero frequencies -// and their associated frequencies. The array is in order of increasing -// frequency, and has as its last element a special element with frequency -// MaxInt32 -// maxBits The maximum number of bits that should be used to encode any literal. -// Must be less than 16. -// return An integer array in which array[i] indicates the number of literals -// that should be encoded in i bits. -func (h *huffmanEncoder) bitCounts(list []literalNode, maxBits int32) []int32 { - if maxBits >= maxBitsLimit { - panic("flate: maxBits too large") - } - n := int32(len(list)) - list = list[0 : n+1] - list[n] = maxNode() - - // The tree can't have greater depth than n - 1, no matter what. This - // saves a little bit of work in some small cases - if maxBits > n-1 { - maxBits = n - 1 - } - - // Create information about each of the levels. - // A bogus "Level 0" whose sole purpose is so that - // level1.prev.needed==0. This makes level1.nextPairFreq - // be a legitimate value that never gets chosen. - var levels [maxBitsLimit]levelInfo - // leafCounts[i] counts the number of literals at the left - // of ancestors of the rightmost node at level i. - // leafCounts[i][j] is the number of literals at the left - // of the level j ancestor. - var leafCounts [maxBitsLimit][maxBitsLimit]int32 - - for level := int32(1); level <= maxBits; level++ { - // For every level, the first two items are the first two characters. - // We initialize the levels as if we had already figured this out. - levels[level] = levelInfo{ - level: level, - lastFreq: list[1].freq, - nextCharFreq: list[2].freq, - nextPairFreq: list[0].freq + list[1].freq, - } - leafCounts[level][level] = 2 - if level == 1 { - levels[level].nextPairFreq = math.MaxInt32 - } - } - - // We need a total of 2*n - 2 items at top level and have already generated 2. - levels[maxBits].needed = 2*n - 4 - - level := maxBits - for { - l := &levels[level] - if l.nextPairFreq == math.MaxInt32 && l.nextCharFreq == math.MaxInt32 { - // We've run out of both leafs and pairs. - // End all calculations for this level. - // To make sure we never come back to this level or any lower level, - // set nextPairFreq impossibly large. - l.needed = 0 - levels[level+1].nextPairFreq = math.MaxInt32 - level++ - continue - } - - prevFreq := l.lastFreq - if l.nextCharFreq < l.nextPairFreq { - // The next item on this row is a leaf node. - n := leafCounts[level][level] + 1 - l.lastFreq = l.nextCharFreq - // Lower leafCounts are the same of the previous node. - leafCounts[level][level] = n - l.nextCharFreq = list[n].freq - } else { - // The next item on this row is a pair from the previous row. - // nextPairFreq isn't valid until we generate two - // more values in the level below - l.lastFreq = l.nextPairFreq - // Take leaf counts from the lower level, except counts[level] remains the same. - copy(leafCounts[level][:level], leafCounts[level-1][:level]) - levels[l.level-1].needed = 2 - } - - if l.needed--; l.needed == 0 { - // We've done everything we need to do for this level. - // Continue calculating one level up. Fill in nextPairFreq - // of that level with the sum of the two nodes we've just calculated on - // this level. - if l.level == maxBits { - // All done! - break - } - levels[l.level+1].nextPairFreq = prevFreq + l.lastFreq - level++ - } else { - // If we stole from below, move down temporarily to replenish it. - for levels[level-1].needed > 0 { - level-- - } - } - } - - // Somethings is wrong if at the end, the top level is null or hasn't used - // all of the leaves. - if leafCounts[maxBits][maxBits] != n { - panic("leafCounts[maxBits][maxBits] != n") - } - - bitCount := make([]int32, maxBits+1) - bits := 1 - counts := &leafCounts[maxBits] - for level := maxBits; level > 0; level-- { - // chain.leafCount gives the number of literals requiring at least "bits" - // bits to encode. - bitCount[bits] = counts[level] - counts[level-1] - bits++ - } - return bitCount -} - -// Look at the leaves and assign them a bit count and an encoding as specified -// in RFC 1951 3.2.2 -func (h *huffmanEncoder) assignEncodingAndSize(bitCount []int32, list []literalNode) { - code := uint16(0) - for n, bits := range bitCount { - code <<= 1 - if n == 0 || bits == 0 { - continue - } - // The literals list[len(list)-bits] .. list[len(list)-bits] - // are encoded using "bits" bits, and get the values - // code, code + 1, .... The code values are - // assigned in literal order (not frequency order). - chunk := list[len(list)-int(bits):] - sortByLiteral(chunk) - for _, node := range chunk { - h.codeBits[node.literal] = uint8(n) - h.code[node.literal] = reverseBits(code, uint8(n)) - code++ - } - list = list[0 : len(list)-int(bits)] - } -} - -// Update this Huffman Code object to be the minimum code for the specified frequency count. -// -// freq An array of frequencies, in which frequency[i] gives the frequency of literal i. -// maxBits The maximum number of bits to use for any literal. -func (h *huffmanEncoder) generate(freq []int32, maxBits int32) { - list := make([]literalNode, len(freq)+1) - // Number of non-zero literals - count := 0 - // Set list to be the set of all non-zero literals and their frequencies - for i, f := range freq { - if f != 0 { - list[count] = literalNode{uint16(i), f} - count++ - } else { - h.codeBits[i] = 0 - } - } - // If freq[] is shorter than codeBits[], fill rest of codeBits[] with zeros - h.codeBits = h.codeBits[0:len(freq)] - list = list[0:count] - if count <= 2 { - // Handle the small cases here, because they are awkward for the general case code. With - // two or fewer literals, everything has bit length 1. - for i, node := range list { - // "list" is in order of increasing literal value. - h.codeBits[node.literal] = 1 - h.code[node.literal] = uint16(i) - } - return - } - sortByFreq(list) - - // Get the number of literals for each bit count - bitCount := h.bitCounts(list, maxBits) - // And do the assignment - h.assignEncodingAndSize(bitCount, list) -} - -type literalNodeSorter struct { - a []literalNode - less func(i, j int) bool -} - -func (s literalNodeSorter) Len() int { return len(s.a) } - -func (s literalNodeSorter) Less(i, j int) bool { - return s.less(i, j) -} - -func (s literalNodeSorter) Swap(i, j int) { s.a[i], s.a[j] = s.a[j], s.a[i] } - -func sortByFreq(a []literalNode) { - s := &literalNodeSorter{a, func(i, j int) bool { - if a[i].freq == a[j].freq { - return a[i].literal < a[j].literal - } - return a[i].freq < a[j].freq - }} - sort.Sort(s) -} - -func sortByLiteral(a []literalNode) { - s := &literalNodeSorter{a, func(i, j int) bool { return a[i].literal < a[j].literal }} - sort.Sort(s) -} diff --git a/src/pkg/compress/flate/inflate.go b/src/pkg/compress/flate/inflate.go deleted file mode 100644 index 769ef4299..000000000 --- a/src/pkg/compress/flate/inflate.go +++ /dev/null @@ -1,710 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:generate go run gen.go -output fixedhuff.go - -// Package flate implements the DEFLATE compressed data format, described in -// RFC 1951. The gzip and zlib packages implement access to DEFLATE-based file -// formats. -package flate - -import ( - "bufio" - "io" - "strconv" -) - -const ( - maxCodeLen = 16 // max length of Huffman code - maxHist = 32768 // max history required - // The next three numbers come from the RFC, section 3.2.7. - maxLit = 286 - maxDist = 32 - numCodes = 19 // number of codes in Huffman meta-code -) - -// A CorruptInputError reports the presence of corrupt input at a given offset. -type CorruptInputError int64 - -func (e CorruptInputError) Error() string { - return "flate: corrupt input before offset " + strconv.FormatInt(int64(e), 10) -} - -// An InternalError reports an error in the flate code itself. -type InternalError string - -func (e InternalError) Error() string { return "flate: internal error: " + string(e) } - -// A ReadError reports an error encountered while reading input. -type ReadError struct { - Offset int64 // byte offset where error occurred - Err error // error returned by underlying Read -} - -func (e *ReadError) Error() string { - return "flate: read error at offset " + strconv.FormatInt(e.Offset, 10) + ": " + e.Err.Error() -} - -// A WriteError reports an error encountered while writing output. -type WriteError struct { - Offset int64 // byte offset where error occurred - Err error // error returned by underlying Write -} - -func (e *WriteError) Error() string { - return "flate: write error at offset " + strconv.FormatInt(e.Offset, 10) + ": " + e.Err.Error() -} - -// Note that much of the implementation of huffmanDecoder is also copied -// into gen.go (in package main) for the purpose of precomputing the -// fixed huffman tables so they can be included statically. - -// The data structure for decoding Huffman tables is based on that of -// zlib. There is a lookup table of a fixed bit width (huffmanChunkBits), -// For codes smaller than the table width, there are multiple entries -// (each combination of trailing bits has the same value). For codes -// larger than the table width, the table contains a link to an overflow -// table. The width of each entry in the link table is the maximum code -// size minus the chunk width. - -// Note that you can do a lookup in the table even without all bits -// filled. Since the extra bits are zero, and the DEFLATE Huffman codes -// have the property that shorter codes come before longer ones, the -// bit length estimate in the result is a lower bound on the actual -// number of bits. - -// chunk & 15 is number of bits -// chunk >> 4 is value, including table link - -const ( - huffmanChunkBits = 9 - huffmanNumChunks = 1 << huffmanChunkBits - huffmanCountMask = 15 - huffmanValueShift = 4 -) - -type huffmanDecoder struct { - min int // the minimum code length - chunks [huffmanNumChunks]uint32 // chunks as described above - links [][]uint32 // overflow links - linkMask uint32 // mask the width of the link table -} - -// Initialize Huffman decoding tables from array of code lengths. -func (h *huffmanDecoder) init(bits []int) bool { - if h.min != 0 { - *h = huffmanDecoder{} - } - - // Count number of codes of each length, - // compute min and max length. - var count [maxCodeLen]int - var min, max int - for _, n := range bits { - if n == 0 { - continue - } - if min == 0 || n < min { - min = n - } - if n > max { - max = n - } - count[n]++ - } - if max == 0 { - return false - } - - h.min = min - var linkBits uint - var numLinks int - if max > huffmanChunkBits { - linkBits = uint(max) - huffmanChunkBits - numLinks = 1 << linkBits - h.linkMask = uint32(numLinks - 1) - } - code := 0 - var nextcode [maxCodeLen]int - for i := min; i <= max; i++ { - if i == huffmanChunkBits+1 { - // create link tables - link := code >> 1 - if huffmanNumChunks < link { - return false - } - h.links = make([][]uint32, huffmanNumChunks-link) - for j := uint(link); j < huffmanNumChunks; j++ { - reverse := int(reverseByte[j>>8]) | int(reverseByte[j&0xff])<<8 - reverse >>= uint(16 - huffmanChunkBits) - off := j - uint(link) - h.chunks[reverse] = uint32(off<>8]) | int(reverseByte[code&0xff])<<8 - reverse >>= uint(16 - n) - if n <= huffmanChunkBits { - for off := reverse; off < huffmanNumChunks; off += 1 << uint(n) { - h.chunks[off] = chunk - } - } else { - value := h.chunks[reverse&(huffmanNumChunks-1)] >> huffmanValueShift - if value >= uint32(len(h.links)) { - return false - } - linktab := h.links[value] - reverse >>= huffmanChunkBits - for off := reverse; off < numLinks; off += 1 << uint(n-huffmanChunkBits) { - linktab[off] = chunk - } - } - } - return true -} - -// The actual read interface needed by NewReader. -// If the passed in io.Reader does not also have ReadByte, -// the NewReader will introduce its own buffering. -type Reader interface { - io.Reader - io.ByteReader -} - -// Decompress state. -type decompressor struct { - // Input source. - r Reader - roffset int64 - woffset int64 - - // Input bits, in top of b. - b uint32 - nb uint - - // Huffman decoders for literal/length, distance. - h1, h2 huffmanDecoder - - // Length arrays used to define Huffman codes. - bits *[maxLit + maxDist]int - codebits *[numCodes]int - - // Output history, buffer. - hist *[maxHist]byte - hp int // current output position in buffer - hw int // have written hist[0:hw] already - hfull bool // buffer has filled at least once - - // Temporary buffer (avoids repeated allocation). - buf [4]byte - - // Next step in the decompression, - // and decompression state. - step func(*decompressor) - final bool - err error - toRead []byte - hl, hd *huffmanDecoder - copyLen int - copyDist int -} - -func (f *decompressor) nextBlock() { - if f.final { - if f.hw != f.hp { - f.flush((*decompressor).nextBlock) - return - } - f.err = io.EOF - return - } - for f.nb < 1+2 { - if f.err = f.moreBits(); f.err != nil { - return - } - } - f.final = f.b&1 == 1 - f.b >>= 1 - typ := f.b & 3 - f.b >>= 2 - f.nb -= 1 + 2 - switch typ { - case 0: - f.dataBlock() - case 1: - // compressed, fixed Huffman tables - f.hl = &fixedHuffmanDecoder - f.hd = nil - f.huffmanBlock() - case 2: - // compressed, dynamic Huffman tables - if f.err = f.readHuffman(); f.err != nil { - break - } - f.hl = &f.h1 - f.hd = &f.h2 - f.huffmanBlock() - default: - // 3 is reserved. - f.err = CorruptInputError(f.roffset) - } -} - -func (f *decompressor) Read(b []byte) (int, error) { - for { - if len(f.toRead) > 0 { - n := copy(b, f.toRead) - f.toRead = f.toRead[n:] - return n, nil - } - if f.err != nil { - return 0, f.err - } - f.step(f) - } -} - -func (f *decompressor) Close() error { - if f.err == io.EOF { - return nil - } - return f.err -} - -// RFC 1951 section 3.2.7. -// Compression with dynamic Huffman codes - -var codeOrder = [...]int{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15} - -func (f *decompressor) readHuffman() error { - // HLIT[5], HDIST[5], HCLEN[4]. - for f.nb < 5+5+4 { - if err := f.moreBits(); err != nil { - return err - } - } - nlit := int(f.b&0x1F) + 257 - if nlit > maxLit { - return CorruptInputError(f.roffset) - } - f.b >>= 5 - ndist := int(f.b&0x1F) + 1 - // maxDist is 32, so ndist is always valid. - f.b >>= 5 - nclen := int(f.b&0xF) + 4 - // numCodes is 19, so nclen is always valid. - f.b >>= 4 - f.nb -= 5 + 5 + 4 - - // (HCLEN+4)*3 bits: code lengths in the magic codeOrder order. - for i := 0; i < nclen; i++ { - for f.nb < 3 { - if err := f.moreBits(); err != nil { - return err - } - } - f.codebits[codeOrder[i]] = int(f.b & 0x7) - f.b >>= 3 - f.nb -= 3 - } - for i := nclen; i < len(codeOrder); i++ { - f.codebits[codeOrder[i]] = 0 - } - if !f.h1.init(f.codebits[0:]) { - return CorruptInputError(f.roffset) - } - - // HLIT + 257 code lengths, HDIST + 1 code lengths, - // using the code length Huffman code. - for i, n := 0, nlit+ndist; i < n; { - x, err := f.huffSym(&f.h1) - if err != nil { - return err - } - if x < 16 { - // Actual length. - f.bits[i] = x - i++ - continue - } - // Repeat previous length or zero. - var rep int - var nb uint - var b int - switch x { - default: - return InternalError("unexpected length code") - case 16: - rep = 3 - nb = 2 - if i == 0 { - return CorruptInputError(f.roffset) - } - b = f.bits[i-1] - case 17: - rep = 3 - nb = 3 - b = 0 - case 18: - rep = 11 - nb = 7 - b = 0 - } - for f.nb < nb { - if err := f.moreBits(); err != nil { - return err - } - } - rep += int(f.b & uint32(1<>= nb - f.nb -= nb - if i+rep > n { - return CorruptInputError(f.roffset) - } - for j := 0; j < rep; j++ { - f.bits[i] = b - i++ - } - } - - if !f.h1.init(f.bits[0:nlit]) || !f.h2.init(f.bits[nlit:nlit+ndist]) { - return CorruptInputError(f.roffset) - } - - return nil -} - -// Decode a single Huffman block from f. -// hl and hd are the Huffman states for the lit/length values -// and the distance values, respectively. If hd == nil, using the -// fixed distance encoding associated with fixed Huffman blocks. -func (f *decompressor) huffmanBlock() { - for { - v, err := f.huffSym(f.hl) - if err != nil { - f.err = err - return - } - var n uint // number of bits extra - var length int - switch { - case v < 256: - f.hist[f.hp] = byte(v) - f.hp++ - if f.hp == len(f.hist) { - // After the flush, continue this loop. - f.flush((*decompressor).huffmanBlock) - return - } - continue - case v == 256: - // Done with huffman block; read next block. - f.step = (*decompressor).nextBlock - return - // otherwise, reference to older data - case v < 265: - length = v - (257 - 3) - n = 0 - case v < 269: - length = v*2 - (265*2 - 11) - n = 1 - case v < 273: - length = v*4 - (269*4 - 19) - n = 2 - case v < 277: - length = v*8 - (273*8 - 35) - n = 3 - case v < 281: - length = v*16 - (277*16 - 67) - n = 4 - case v < 285: - length = v*32 - (281*32 - 131) - n = 5 - default: - length = 258 - n = 0 - } - if n > 0 { - for f.nb < n { - if err = f.moreBits(); err != nil { - f.err = err - return - } - } - length += int(f.b & uint32(1<>= n - f.nb -= n - } - - var dist int - if f.hd == nil { - for f.nb < 5 { - if err = f.moreBits(); err != nil { - f.err = err - return - } - } - dist = int(reverseByte[(f.b&0x1F)<<3]) - f.b >>= 5 - f.nb -= 5 - } else { - if dist, err = f.huffSym(f.hd); err != nil { - f.err = err - return - } - } - - switch { - case dist < 4: - dist++ - case dist >= 30: - f.err = CorruptInputError(f.roffset) - return - default: - nb := uint(dist-2) >> 1 - // have 1 bit in bottom of dist, need nb more. - extra := (dist & 1) << nb - for f.nb < nb { - if err = f.moreBits(); err != nil { - f.err = err - return - } - } - extra |= int(f.b & uint32(1<>= nb - f.nb -= nb - dist = 1<<(nb+1) + 1 + extra - } - - // Copy history[-dist:-dist+length] into output. - if dist > len(f.hist) { - f.err = InternalError("bad history distance") - return - } - - // No check on length; encoding can be prescient. - if !f.hfull && dist > f.hp { - f.err = CorruptInputError(f.roffset) - return - } - - f.copyLen, f.copyDist = length, dist - if f.copyHist() { - return - } - } -} - -// copyHist copies f.copyLen bytes from f.hist (f.copyDist bytes ago) to itself. -// It reports whether the f.hist buffer is full. -func (f *decompressor) copyHist() bool { - p := f.hp - f.copyDist - if p < 0 { - p += len(f.hist) - } - for f.copyLen > 0 { - n := f.copyLen - if x := len(f.hist) - f.hp; n > x { - n = x - } - if x := len(f.hist) - p; n > x { - n = x - } - forwardCopy(f.hist[:], f.hp, p, n) - p += n - f.hp += n - f.copyLen -= n - if f.hp == len(f.hist) { - // After flush continue copying out of history. - f.flush((*decompressor).copyHuff) - return true - } - if p == len(f.hist) { - p = 0 - } - } - return false -} - -func (f *decompressor) copyHuff() { - if f.copyHist() { - return - } - f.huffmanBlock() -} - -// Copy a single uncompressed data block from input to output. -func (f *decompressor) dataBlock() { - // Uncompressed. - // Discard current half-byte. - f.nb = 0 - f.b = 0 - - // Length then ones-complement of length. - nr, err := io.ReadFull(f.r, f.buf[0:4]) - f.roffset += int64(nr) - if err != nil { - f.err = &ReadError{f.roffset, err} - return - } - n := int(f.buf[0]) | int(f.buf[1])<<8 - nn := int(f.buf[2]) | int(f.buf[3])<<8 - if uint16(nn) != uint16(^n) { - f.err = CorruptInputError(f.roffset) - return - } - - if n == 0 { - // 0-length block means sync - f.flush((*decompressor).nextBlock) - return - } - - f.copyLen = n - f.copyData() -} - -// copyData copies f.copyLen bytes from the underlying reader into f.hist. -// It pauses for reads when f.hist is full. -func (f *decompressor) copyData() { - n := f.copyLen - for n > 0 { - m := len(f.hist) - f.hp - if m > n { - m = n - } - m, err := io.ReadFull(f.r, f.hist[f.hp:f.hp+m]) - f.roffset += int64(m) - if err != nil { - f.err = &ReadError{f.roffset, err} - return - } - n -= m - f.hp += m - if f.hp == len(f.hist) { - f.copyLen = n - f.flush((*decompressor).copyData) - return - } - } - f.step = (*decompressor).nextBlock -} - -func (f *decompressor) setDict(dict []byte) { - if len(dict) > len(f.hist) { - // Will only remember the tail. - dict = dict[len(dict)-len(f.hist):] - } - - f.hp = copy(f.hist[:], dict) - if f.hp == len(f.hist) { - f.hp = 0 - f.hfull = true - } - f.hw = f.hp -} - -func (f *decompressor) moreBits() error { - c, err := f.r.ReadByte() - if err != nil { - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - return err - } - f.roffset++ - f.b |= uint32(c) << f.nb - f.nb += 8 - return nil -} - -// Read the next Huffman-encoded symbol from f according to h. -func (f *decompressor) huffSym(h *huffmanDecoder) (int, error) { - n := uint(h.min) - for { - for f.nb < n { - if err := f.moreBits(); err != nil { - return 0, err - } - } - chunk := h.chunks[f.b&(huffmanNumChunks-1)] - n = uint(chunk & huffmanCountMask) - if n > huffmanChunkBits { - chunk = h.links[chunk>>huffmanValueShift][(f.b>>huffmanChunkBits)&h.linkMask] - n = uint(chunk & huffmanCountMask) - if n == 0 { - f.err = CorruptInputError(f.roffset) - return 0, f.err - } - } - if n <= f.nb { - f.b >>= n - f.nb -= n - return int(chunk >> huffmanValueShift), nil - } - } -} - -// Flush any buffered output to the underlying writer. -func (f *decompressor) flush(step func(*decompressor)) { - f.toRead = f.hist[f.hw:f.hp] - f.woffset += int64(f.hp - f.hw) - f.hw = f.hp - if f.hp == len(f.hist) { - f.hp = 0 - f.hw = 0 - f.hfull = true - } - f.step = step -} - -func makeReader(r io.Reader) Reader { - if rr, ok := r.(Reader); ok { - return rr - } - return bufio.NewReader(r) -} - -// NewReader returns a new ReadCloser that can be used -// to read the uncompressed version of r. It is the caller's -// responsibility to call Close on the ReadCloser when -// finished reading. -func NewReader(r io.Reader) io.ReadCloser { - var f decompressor - f.bits = new([maxLit + maxDist]int) - f.codebits = new([numCodes]int) - f.r = makeReader(r) - f.hist = new([maxHist]byte) - f.step = (*decompressor).nextBlock - return &f -} - -// NewReaderDict is like NewReader but initializes the reader -// with a preset dictionary. The returned Reader behaves as if -// the uncompressed data stream started with the given dictionary, -// which has already been read. NewReaderDict is typically used -// to read data compressed by NewWriterDict. -func NewReaderDict(r io.Reader, dict []byte) io.ReadCloser { - var f decompressor - f.r = makeReader(r) - f.hist = new([maxHist]byte) - f.bits = new([maxLit + maxDist]int) - f.codebits = new([numCodes]int) - f.step = (*decompressor).nextBlock - f.setDict(dict) - return &f -} diff --git a/src/pkg/compress/flate/reader_test.go b/src/pkg/compress/flate/reader_test.go deleted file mode 100644 index a62ef741d..000000000 --- a/src/pkg/compress/flate/reader_test.go +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flate - -import ( - "bytes" - "io" - "io/ioutil" - "runtime" - "strings" - "testing" -) - -func TestNlitOutOfRange(t *testing.T) { - // Trying to decode this bogus flate data, which has a Huffman table - // with nlit=288, should not panic. - io.Copy(ioutil.Discard, NewReader(strings.NewReader( - "\xfc\xfe\x36\xe7\x5e\x1c\xef\xb3\x55\x58\x77\xb6\x56\xb5\x43\xf4"+ - "\x6f\xf2\xd2\xe6\x3d\x99\xa0\x85\x8c\x48\xeb\xf8\xda\x83\x04\x2a"+ - "\x75\xc4\xf8\x0f\x12\x11\xb9\xb4\x4b\x09\xa0\xbe\x8b\x91\x4c"))) -} - -const ( - digits = iota - twain -) - -var testfiles = []string{ - // Digits is the digits of the irrational number e. Its decimal representation - // does not repeat, but there are only 10 possible digits, so it should be - // reasonably compressible. - digits: "../testdata/e.txt", - // Twain is Project Gutenberg's edition of Mark Twain's classic English novel. - twain: "../testdata/Mark.Twain-Tom.Sawyer.txt", -} - -func benchmarkDecode(b *testing.B, testfile, level, n int) { - b.ReportAllocs() - b.StopTimer() - b.SetBytes(int64(n)) - buf0, err := ioutil.ReadFile(testfiles[testfile]) - if err != nil { - b.Fatal(err) - } - if len(buf0) == 0 { - b.Fatalf("test file %q has no data", testfiles[testfile]) - } - compressed := new(bytes.Buffer) - w, err := NewWriter(compressed, level) - if err != nil { - b.Fatal(err) - } - for i := 0; i < n; i += len(buf0) { - if len(buf0) > n-i { - buf0 = buf0[:n-i] - } - io.Copy(w, bytes.NewReader(buf0)) - } - w.Close() - buf1 := compressed.Bytes() - buf0, compressed, w = nil, nil, nil - runtime.GC() - b.StartTimer() - for i := 0; i < b.N; i++ { - io.Copy(ioutil.Discard, NewReader(bytes.NewReader(buf1))) - } -} - -// These short names are so that gofmt doesn't break the BenchmarkXxx function -// bodies below over multiple lines. -const ( - speed = BestSpeed - default_ = DefaultCompression - compress = BestCompression -) - -func BenchmarkDecodeDigitsSpeed1e4(b *testing.B) { benchmarkDecode(b, digits, speed, 1e4) } -func BenchmarkDecodeDigitsSpeed1e5(b *testing.B) { benchmarkDecode(b, digits, speed, 1e5) } -func BenchmarkDecodeDigitsSpeed1e6(b *testing.B) { benchmarkDecode(b, digits, speed, 1e6) } -func BenchmarkDecodeDigitsDefault1e4(b *testing.B) { benchmarkDecode(b, digits, default_, 1e4) } -func BenchmarkDecodeDigitsDefault1e5(b *testing.B) { benchmarkDecode(b, digits, default_, 1e5) } -func BenchmarkDecodeDigitsDefault1e6(b *testing.B) { benchmarkDecode(b, digits, default_, 1e6) } -func BenchmarkDecodeDigitsCompress1e4(b *testing.B) { benchmarkDecode(b, digits, compress, 1e4) } -func BenchmarkDecodeDigitsCompress1e5(b *testing.B) { benchmarkDecode(b, digits, compress, 1e5) } -func BenchmarkDecodeDigitsCompress1e6(b *testing.B) { benchmarkDecode(b, digits, compress, 1e6) } -func BenchmarkDecodeTwainSpeed1e4(b *testing.B) { benchmarkDecode(b, twain, speed, 1e4) } -func BenchmarkDecodeTwainSpeed1e5(b *testing.B) { benchmarkDecode(b, twain, speed, 1e5) } -func BenchmarkDecodeTwainSpeed1e6(b *testing.B) { benchmarkDecode(b, twain, speed, 1e6) } -func BenchmarkDecodeTwainDefault1e4(b *testing.B) { benchmarkDecode(b, twain, default_, 1e4) } -func BenchmarkDecodeTwainDefault1e5(b *testing.B) { benchmarkDecode(b, twain, default_, 1e5) } -func BenchmarkDecodeTwainDefault1e6(b *testing.B) { benchmarkDecode(b, twain, default_, 1e6) } -func BenchmarkDecodeTwainCompress1e4(b *testing.B) { benchmarkDecode(b, twain, compress, 1e4) } -func BenchmarkDecodeTwainCompress1e5(b *testing.B) { benchmarkDecode(b, twain, compress, 1e5) } -func BenchmarkDecodeTwainCompress1e6(b *testing.B) { benchmarkDecode(b, twain, compress, 1e6) } diff --git a/src/pkg/compress/flate/reverse_bits.go b/src/pkg/compress/flate/reverse_bits.go deleted file mode 100644 index c1a02720d..000000000 --- a/src/pkg/compress/flate/reverse_bits.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flate - -var reverseByte = [256]byte{ - 0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0, - 0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0, - 0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8, - 0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8, - 0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4, - 0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4, - 0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec, - 0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc, - 0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2, - 0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2, - 0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea, - 0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa, - 0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6, - 0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6, - 0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee, - 0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe, - 0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1, - 0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1, - 0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9, - 0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9, - 0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5, - 0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5, - 0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed, - 0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd, - 0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3, - 0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3, - 0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb, - 0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb, - 0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7, - 0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7, - 0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef, - 0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff, -} - -func reverseUint16(v uint16) uint16 { - return uint16(reverseByte[v>>8]) | uint16(reverseByte[v&0xFF])<<8 -} - -func reverseBits(number uint16, bitLength byte) uint16 { - return reverseUint16(number << uint8(16-bitLength)) -} diff --git a/src/pkg/compress/flate/token.go b/src/pkg/compress/flate/token.go deleted file mode 100644 index 4d4917687..000000000 --- a/src/pkg/compress/flate/token.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flate - -const ( - // 2 bits: type 0 = literal 1=EOF 2=Match 3=Unused - // 8 bits: xlength = length - MIN_MATCH_LENGTH - // 22 bits xoffset = offset - MIN_OFFSET_SIZE, or literal - lengthShift = 22 - offsetMask = 1< pair into a match token. -func matchToken(xlength uint32, xoffset uint32) token { - return token(matchType + xlength<> lengthShift) } - -func lengthCode(len uint32) uint32 { return lengthCodes[len] } - -// Returns the offset code corresponding to a specific offset -func offsetCode(off uint32) uint32 { - const n = uint32(len(offsetCodes)) - switch { - case off < n: - return offsetCodes[off] - case off>>7 < n: - return offsetCodes[off>>7] + 14 - default: - return offsetCodes[off>>14] + 28 - } -} diff --git a/src/pkg/compress/flate/writer_test.go b/src/pkg/compress/flate/writer_test.go deleted file mode 100644 index 58431774e..000000000 --- a/src/pkg/compress/flate/writer_test.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package flate - -import ( - "io/ioutil" - "runtime" - "testing" -) - -func benchmarkEncoder(b *testing.B, testfile, level, n int) { - b.StopTimer() - b.SetBytes(int64(n)) - buf0, err := ioutil.ReadFile(testfiles[testfile]) - if err != nil { - b.Fatal(err) - } - if len(buf0) == 0 { - b.Fatalf("test file %q has no data", testfiles[testfile]) - } - buf1 := make([]byte, n) - for i := 0; i < n; i += len(buf0) { - if len(buf0) > n-i { - buf0 = buf0[:n-i] - } - copy(buf1[i:], buf0) - } - buf0 = nil - runtime.GC() - b.StartTimer() - for i := 0; i < b.N; i++ { - w, err := NewWriter(ioutil.Discard, level) - if err != nil { - b.Fatal(err) - } - w.Write(buf1) - w.Close() - } -} - -func BenchmarkEncodeDigitsSpeed1e4(b *testing.B) { benchmarkEncoder(b, digits, speed, 1e4) } -func BenchmarkEncodeDigitsSpeed1e5(b *testing.B) { benchmarkEncoder(b, digits, speed, 1e5) } -func BenchmarkEncodeDigitsSpeed1e6(b *testing.B) { benchmarkEncoder(b, digits, speed, 1e6) } -func BenchmarkEncodeDigitsDefault1e4(b *testing.B) { benchmarkEncoder(b, digits, default_, 1e4) } -func BenchmarkEncodeDigitsDefault1e5(b *testing.B) { benchmarkEncoder(b, digits, default_, 1e5) } -func BenchmarkEncodeDigitsDefault1e6(b *testing.B) { benchmarkEncoder(b, digits, default_, 1e6) } -func BenchmarkEncodeDigitsCompress1e4(b *testing.B) { benchmarkEncoder(b, digits, compress, 1e4) } -func BenchmarkEncodeDigitsCompress1e5(b *testing.B) { benchmarkEncoder(b, digits, compress, 1e5) } -func BenchmarkEncodeDigitsCompress1e6(b *testing.B) { benchmarkEncoder(b, digits, compress, 1e6) } -func BenchmarkEncodeTwainSpeed1e4(b *testing.B) { benchmarkEncoder(b, twain, speed, 1e4) } -func BenchmarkEncodeTwainSpeed1e5(b *testing.B) { benchmarkEncoder(b, twain, speed, 1e5) } -func BenchmarkEncodeTwainSpeed1e6(b *testing.B) { benchmarkEncoder(b, twain, speed, 1e6) } -func BenchmarkEncodeTwainDefault1e4(b *testing.B) { benchmarkEncoder(b, twain, default_, 1e4) } -func BenchmarkEncodeTwainDefault1e5(b *testing.B) { benchmarkEncoder(b, twain, default_, 1e5) } -func BenchmarkEncodeTwainDefault1e6(b *testing.B) { benchmarkEncoder(b, twain, default_, 1e6) } -func BenchmarkEncodeTwainCompress1e4(b *testing.B) { benchmarkEncoder(b, twain, compress, 1e4) } -func BenchmarkEncodeTwainCompress1e5(b *testing.B) { benchmarkEncoder(b, twain, compress, 1e5) } -func BenchmarkEncodeTwainCompress1e6(b *testing.B) { benchmarkEncoder(b, twain, compress, 1e6) } diff --git a/src/pkg/compress/gzip/gunzip.go b/src/pkg/compress/gzip/gunzip.go deleted file mode 100644 index 4f398b194..000000000 --- a/src/pkg/compress/gzip/gunzip.go +++ /dev/null @@ -1,255 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package gzip implements reading and writing of gzip format compressed files, -// as specified in RFC 1952. -package gzip - -import ( - "bufio" - "compress/flate" - "errors" - "hash" - "hash/crc32" - "io" - "time" -) - -const ( - gzipID1 = 0x1f - gzipID2 = 0x8b - gzipDeflate = 8 - flagText = 1 << 0 - flagHdrCrc = 1 << 1 - flagExtra = 1 << 2 - flagName = 1 << 3 - flagComment = 1 << 4 -) - -func makeReader(r io.Reader) flate.Reader { - if rr, ok := r.(flate.Reader); ok { - return rr - } - return bufio.NewReader(r) -} - -var ( - // ErrChecksum is returned when reading GZIP data that has an invalid checksum. - ErrChecksum = errors.New("gzip: invalid checksum") - // ErrHeader is returned when reading GZIP data that has an invalid header. - ErrHeader = errors.New("gzip: invalid header") -) - -// The gzip file stores a header giving metadata about the compressed file. -// That header is exposed as the fields of the Writer and Reader structs. -type Header struct { - Comment string // comment - Extra []byte // "extra data" - ModTime time.Time // modification time - Name string // file name - OS byte // operating system type -} - -// A Reader is an io.Reader that can be read to retrieve -// uncompressed data from a gzip-format compressed file. -// -// In general, a gzip file can be a concatenation of gzip files, -// each with its own header. Reads from the Reader -// return the concatenation of the uncompressed data of each. -// Only the first header is recorded in the Reader fields. -// -// Gzip files store a length and checksum of the uncompressed data. -// The Reader will return a ErrChecksum when Read -// reaches the end of the uncompressed data if it does not -// have the expected length or checksum. Clients should treat data -// returned by Read as tentative until they receive the io.EOF -// marking the end of the data. -type Reader struct { - Header - r flate.Reader - decompressor io.ReadCloser - digest hash.Hash32 - size uint32 - flg byte - buf [512]byte - err error -} - -// NewReader creates a new Reader reading the given reader. -// The implementation buffers input and may read more data than necessary from r. -// It is the caller's responsibility to call Close on the Reader when done. -func NewReader(r io.Reader) (*Reader, error) { - z := new(Reader) - z.r = makeReader(r) - z.digest = crc32.NewIEEE() - if err := z.readHeader(true); err != nil { - return nil, err - } - return z, nil -} - -// Reset discards the Reader z's state and makes it equivalent to the -// result of its original state from NewReader, but reading from r instead. -// This permits reusing a Reader rather than allocating a new one. -func (z *Reader) Reset(r io.Reader) error { - z.r = makeReader(r) - if z.digest == nil { - z.digest = crc32.NewIEEE() - } else { - z.digest.Reset() - } - z.size = 0 - z.err = nil - return z.readHeader(true) -} - -// GZIP (RFC 1952) is little-endian, unlike ZLIB (RFC 1950). -func get4(p []byte) uint32 { - return uint32(p[0]) | uint32(p[1])<<8 | uint32(p[2])<<16 | uint32(p[3])<<24 -} - -func (z *Reader) readString() (string, error) { - var err error - needconv := false - for i := 0; ; i++ { - if i >= len(z.buf) { - return "", ErrHeader - } - z.buf[i], err = z.r.ReadByte() - if err != nil { - return "", err - } - if z.buf[i] > 0x7f { - needconv = true - } - if z.buf[i] == 0 { - // GZIP (RFC 1952) specifies that strings are NUL-terminated ISO 8859-1 (Latin-1). - if needconv { - s := make([]rune, 0, i) - for _, v := range z.buf[0:i] { - s = append(s, rune(v)) - } - return string(s), nil - } - return string(z.buf[0:i]), nil - } - } -} - -func (z *Reader) read2() (uint32, error) { - _, err := io.ReadFull(z.r, z.buf[0:2]) - if err != nil { - return 0, err - } - return uint32(z.buf[0]) | uint32(z.buf[1])<<8, nil -} - -func (z *Reader) readHeader(save bool) error { - _, err := io.ReadFull(z.r, z.buf[0:10]) - if err != nil { - return err - } - if z.buf[0] != gzipID1 || z.buf[1] != gzipID2 || z.buf[2] != gzipDeflate { - return ErrHeader - } - z.flg = z.buf[3] - if save { - z.ModTime = time.Unix(int64(get4(z.buf[4:8])), 0) - // z.buf[8] is xfl, ignored - z.OS = z.buf[9] - } - z.digest.Reset() - z.digest.Write(z.buf[0:10]) - - if z.flg&flagExtra != 0 { - n, err := z.read2() - if err != nil { - return err - } - data := make([]byte, n) - if _, err = io.ReadFull(z.r, data); err != nil { - return err - } - if save { - z.Extra = data - } - } - - var s string - if z.flg&flagName != 0 { - if s, err = z.readString(); err != nil { - return err - } - if save { - z.Name = s - } - } - - if z.flg&flagComment != 0 { - if s, err = z.readString(); err != nil { - return err - } - if save { - z.Comment = s - } - } - - if z.flg&flagHdrCrc != 0 { - n, err := z.read2() - if err != nil { - return err - } - sum := z.digest.Sum32() & 0xFFFF - if n != sum { - return ErrHeader - } - } - - z.digest.Reset() - z.decompressor = flate.NewReader(z.r) - return nil -} - -func (z *Reader) Read(p []byte) (n int, err error) { - if z.err != nil { - return 0, z.err - } - if len(p) == 0 { - return 0, nil - } - - n, err = z.decompressor.Read(p) - z.digest.Write(p[0:n]) - z.size += uint32(n) - if n != 0 || err != io.EOF { - z.err = err - return - } - - // Finished file; check checksum + size. - if _, err := io.ReadFull(z.r, z.buf[0:8]); err != nil { - z.err = err - return 0, err - } - crc32, isize := get4(z.buf[0:4]), get4(z.buf[4:8]) - sum := z.digest.Sum32() - if sum != crc32 || isize != z.size { - z.err = ErrChecksum - return 0, z.err - } - - // File is ok; is there another? - if err = z.readHeader(false); err != nil { - z.err = err - return - } - - // Yes. Reset and read from it. - z.digest.Reset() - z.size = 0 - return z.Read(p) -} - -// Close closes the Reader. It does not close the underlying io.Reader. -func (z *Reader) Close() error { return z.decompressor.Close() } diff --git a/src/pkg/compress/gzip/gunzip_test.go b/src/pkg/compress/gzip/gunzip_test.go deleted file mode 100644 index 2471038f5..000000000 --- a/src/pkg/compress/gzip/gunzip_test.go +++ /dev/null @@ -1,369 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gzip - -import ( - "bytes" - "io" - "io/ioutil" - "os" - "testing" - "time" -) - -type gunzipTest struct { - name string - desc string - raw string - gzip []byte - err error -} - -var gunzipTests = []gunzipTest{ - { // has 1 empty fixed-huffman block - "empty.txt", - "empty.txt", - "", - []byte{ - 0x1f, 0x8b, 0x08, 0x08, 0xf7, 0x5e, 0x14, 0x4a, - 0x00, 0x03, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, - 0x74, 0x78, 0x74, 0x00, 0x03, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - }, - nil, - }, - { // has 1 non-empty fixed huffman block - "hello.txt", - "hello.txt", - "hello world\n", - []byte{ - 0x1f, 0x8b, 0x08, 0x08, 0xc8, 0x58, 0x13, 0x4a, - 0x00, 0x03, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x2e, - 0x74, 0x78, 0x74, 0x00, 0xcb, 0x48, 0xcd, 0xc9, - 0xc9, 0x57, 0x28, 0xcf, 0x2f, 0xca, 0x49, 0xe1, - 0x02, 0x00, 0x2d, 0x3b, 0x08, 0xaf, 0x0c, 0x00, - 0x00, 0x00, - }, - nil, - }, - { // concatenation - "hello.txt", - "hello.txt x2", - "hello world\n" + - "hello world\n", - []byte{ - 0x1f, 0x8b, 0x08, 0x08, 0xc8, 0x58, 0x13, 0x4a, - 0x00, 0x03, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x2e, - 0x74, 0x78, 0x74, 0x00, 0xcb, 0x48, 0xcd, 0xc9, - 0xc9, 0x57, 0x28, 0xcf, 0x2f, 0xca, 0x49, 0xe1, - 0x02, 0x00, 0x2d, 0x3b, 0x08, 0xaf, 0x0c, 0x00, - 0x00, 0x00, - 0x1f, 0x8b, 0x08, 0x08, 0xc8, 0x58, 0x13, 0x4a, - 0x00, 0x03, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x2e, - 0x74, 0x78, 0x74, 0x00, 0xcb, 0x48, 0xcd, 0xc9, - 0xc9, 0x57, 0x28, 0xcf, 0x2f, 0xca, 0x49, 0xe1, - 0x02, 0x00, 0x2d, 0x3b, 0x08, 0xaf, 0x0c, 0x00, - 0x00, 0x00, - }, - nil, - }, - { // has a fixed huffman block with some length-distance pairs - "shesells.txt", - "shesells.txt", - "she sells seashells by the seashore\n", - []byte{ - 0x1f, 0x8b, 0x08, 0x08, 0x72, 0x66, 0x8b, 0x4a, - 0x00, 0x03, 0x73, 0x68, 0x65, 0x73, 0x65, 0x6c, - 0x6c, 0x73, 0x2e, 0x74, 0x78, 0x74, 0x00, 0x2b, - 0xce, 0x48, 0x55, 0x28, 0x4e, 0xcd, 0xc9, 0x29, - 0x06, 0x92, 0x89, 0xc5, 0x19, 0x60, 0x56, 0x52, - 0xa5, 0x42, 0x09, 0x58, 0x18, 0x28, 0x90, 0x5f, - 0x94, 0xca, 0x05, 0x00, 0x76, 0xb0, 0x3b, 0xeb, - 0x24, 0x00, 0x00, 0x00, - }, - nil, - }, - { // has dynamic huffman blocks - "gettysburg", - "gettysburg", - " Four score and seven years ago our fathers brought forth on\n" + - "this continent, a new nation, conceived in Liberty, and dedicated\n" + - "to the proposition that all men are created equal.\n" + - " Now we are engaged in a great Civil War, testing whether that\n" + - "nation, or any nation so conceived and so dedicated, can long\n" + - "endure.\n" + - " We are met on a great battle-field of that war.\n" + - " We have come to dedicate a portion of that field, as a final\n" + - "resting place for those who here gave their lives that that\n" + - "nation might live. It is altogether fitting and proper that\n" + - "we should do this.\n" + - " But, in a larger sense, we can not dedicate — we can not\n" + - "consecrate — we can not hallow — this ground.\n" + - " The brave men, living and dead, who struggled here, have\n" + - "consecrated it, far above our poor power to add or detract.\n" + - "The world will little note, nor long remember what we say here,\n" + - "but it can never forget what they did here.\n" + - " It is for us the living, rather, to be dedicated here to the\n" + - "unfinished work which they who fought here have thus far so\n" + - "nobly advanced. It is rather for us to be here dedicated to\n" + - "the great task remaining before us — that from these honored\n" + - "dead we take increased devotion to that cause for which they\n" + - "gave the last full measure of devotion —\n" + - " that we here highly resolve that these dead shall not have\n" + - "died in vain — that this nation, under God, shall have a new\n" + - "birth of freedom — and that government of the people, by the\n" + - "people, for the people, shall not perish from this earth.\n" + - "\n" + - "Abraham Lincoln, November 19, 1863, Gettysburg, Pennsylvania\n", - []byte{ - 0x1f, 0x8b, 0x08, 0x08, 0xd1, 0x12, 0x2b, 0x4a, - 0x00, 0x03, 0x67, 0x65, 0x74, 0x74, 0x79, 0x73, - 0x62, 0x75, 0x72, 0x67, 0x00, 0x65, 0x54, 0xcd, - 0x6e, 0xd4, 0x30, 0x10, 0xbe, 0xfb, 0x29, 0xe6, - 0x01, 0x42, 0xa5, 0x0a, 0x09, 0xc1, 0x11, 0x90, - 0x40, 0x48, 0xa8, 0xe2, 0x80, 0xd4, 0xf3, 0x24, - 0x9e, 0x24, 0x56, 0xbd, 0x9e, 0xc5, 0x76, 0x76, - 0x95, 0x1b, 0x0f, 0xc1, 0x13, 0xf2, 0x24, 0x7c, - 0x63, 0x77, 0x9b, 0x4a, 0x5c, 0xaa, 0x6e, 0x6c, - 0xcf, 0x7c, 0x7f, 0x33, 0x44, 0x5f, 0x74, 0xcb, - 0x54, 0x26, 0xcd, 0x42, 0x9c, 0x3c, 0x15, 0xb9, - 0x48, 0xa2, 0x5d, 0x38, 0x17, 0xe2, 0x45, 0xc9, - 0x4e, 0x67, 0xae, 0xab, 0xe0, 0xf7, 0x98, 0x75, - 0x5b, 0xd6, 0x4a, 0xb3, 0xe6, 0xba, 0x92, 0x26, - 0x57, 0xd7, 0x50, 0x68, 0xd2, 0x54, 0x43, 0x92, - 0x54, 0x07, 0x62, 0x4a, 0x72, 0xa5, 0xc4, 0x35, - 0x68, 0x1a, 0xec, 0x60, 0x92, 0x70, 0x11, 0x4f, - 0x21, 0xd1, 0xf7, 0x30, 0x4a, 0xae, 0xfb, 0xd0, - 0x9a, 0x78, 0xf1, 0x61, 0xe2, 0x2a, 0xde, 0x55, - 0x25, 0xd4, 0xa6, 0x73, 0xd6, 0xb3, 0x96, 0x60, - 0xef, 0xf0, 0x9b, 0x2b, 0x71, 0x8c, 0x74, 0x02, - 0x10, 0x06, 0xac, 0x29, 0x8b, 0xdd, 0x25, 0xf9, - 0xb5, 0x71, 0xbc, 0x73, 0x44, 0x0f, 0x7a, 0xa5, - 0xab, 0xb4, 0x33, 0x49, 0x0b, 0x2f, 0xbd, 0x03, - 0xd3, 0x62, 0x17, 0xe9, 0x73, 0xb8, 0x84, 0x48, - 0x8f, 0x9c, 0x07, 0xaa, 0x52, 0x00, 0x6d, 0xa1, - 0xeb, 0x2a, 0xc6, 0xa0, 0x95, 0x76, 0x37, 0x78, - 0x9a, 0x81, 0x65, 0x7f, 0x46, 0x4b, 0x45, 0x5f, - 0xe1, 0x6d, 0x42, 0xe8, 0x01, 0x13, 0x5c, 0x38, - 0x51, 0xd4, 0xb4, 0x38, 0x49, 0x7e, 0xcb, 0x62, - 0x28, 0x1e, 0x3b, 0x82, 0x93, 0x54, 0x48, 0xf1, - 0xd2, 0x7d, 0xe4, 0x5a, 0xa3, 0xbc, 0x99, 0x83, - 0x44, 0x4f, 0x3a, 0x77, 0x36, 0x57, 0xce, 0xcf, - 0x2f, 0x56, 0xbe, 0x80, 0x90, 0x9e, 0x84, 0xea, - 0x51, 0x1f, 0x8f, 0xcf, 0x90, 0xd4, 0x60, 0xdc, - 0x5e, 0xb4, 0xf7, 0x10, 0x0b, 0x26, 0xe0, 0xff, - 0xc4, 0xd1, 0xe5, 0x67, 0x2e, 0xe7, 0xc8, 0x93, - 0x98, 0x05, 0xb8, 0xa8, 0x45, 0xc0, 0x4d, 0x09, - 0xdc, 0x84, 0x16, 0x2b, 0x0d, 0x9a, 0x21, 0x53, - 0x04, 0x8b, 0xd2, 0x0b, 0xbd, 0xa2, 0x4c, 0xa7, - 0x60, 0xee, 0xd9, 0xe1, 0x1d, 0xd1, 0xb7, 0x4a, - 0x30, 0x8f, 0x63, 0xd5, 0xa5, 0x8b, 0x33, 0x87, - 0xda, 0x1a, 0x18, 0x79, 0xf3, 0xe3, 0xa6, 0x17, - 0x94, 0x2e, 0xab, 0x6e, 0xa0, 0xe3, 0xcd, 0xac, - 0x50, 0x8c, 0xca, 0xa7, 0x0d, 0x76, 0x37, 0xd1, - 0x23, 0xe7, 0x05, 0x57, 0x8b, 0xa4, 0x22, 0x83, - 0xd9, 0x62, 0x52, 0x25, 0xad, 0x07, 0xbb, 0xbf, - 0xbf, 0xff, 0xbc, 0xfa, 0xee, 0x20, 0x73, 0x91, - 0x29, 0xff, 0x7f, 0x02, 0x71, 0x62, 0x84, 0xb5, - 0xf6, 0xb5, 0x25, 0x6b, 0x41, 0xde, 0x92, 0xb7, - 0x76, 0x3f, 0x91, 0x91, 0x31, 0x1b, 0x41, 0x84, - 0x62, 0x30, 0x0a, 0x37, 0xa4, 0x5e, 0x18, 0x3a, - 0x99, 0x08, 0xa5, 0xe6, 0x6d, 0x59, 0x22, 0xec, - 0x33, 0x39, 0x86, 0x26, 0xf5, 0xab, 0x66, 0xc8, - 0x08, 0x20, 0xcf, 0x0c, 0xd7, 0x47, 0x45, 0x21, - 0x0b, 0xf6, 0x59, 0xd5, 0xfe, 0x5c, 0x8d, 0xaa, - 0x12, 0x7b, 0x6f, 0xa1, 0xf0, 0x52, 0x33, 0x4f, - 0xf5, 0xce, 0x59, 0xd3, 0xab, 0x66, 0x10, 0xbf, - 0x06, 0xc4, 0x31, 0x06, 0x73, 0xd6, 0x80, 0xa2, - 0x78, 0xc2, 0x45, 0xcb, 0x03, 0x65, 0x39, 0xc9, - 0x09, 0xd1, 0x06, 0x04, 0x33, 0x1a, 0x5a, 0xf1, - 0xde, 0x01, 0xb8, 0x71, 0x83, 0xc4, 0xb5, 0xb3, - 0xc3, 0x54, 0x65, 0x33, 0x0d, 0x5a, 0xf7, 0x9b, - 0x90, 0x7c, 0x27, 0x1f, 0x3a, 0x58, 0xa3, 0xd8, - 0xfd, 0x30, 0x5f, 0xb7, 0xd2, 0x66, 0xa2, 0x93, - 0x1c, 0x28, 0xb7, 0xe9, 0x1b, 0x0c, 0xe1, 0x28, - 0x47, 0x26, 0xbb, 0xe9, 0x7d, 0x7e, 0xdc, 0x96, - 0x10, 0x92, 0x50, 0x56, 0x7c, 0x06, 0xe2, 0x27, - 0xb4, 0x08, 0xd3, 0xda, 0x7b, 0x98, 0x34, 0x73, - 0x9f, 0xdb, 0xf6, 0x62, 0xed, 0x31, 0x41, 0x13, - 0xd3, 0xa2, 0xa8, 0x4b, 0x3a, 0xc6, 0x1d, 0xe4, - 0x2f, 0x8c, 0xf8, 0xfb, 0x97, 0x64, 0xf4, 0xb6, - 0x2f, 0x80, 0x5a, 0xf3, 0x56, 0xe0, 0x40, 0x50, - 0xd5, 0x19, 0xd0, 0x1e, 0xfc, 0xca, 0xe5, 0xc9, - 0xd4, 0x60, 0x00, 0x81, 0x2e, 0xa3, 0xcc, 0xb6, - 0x52, 0xf0, 0xb4, 0xdb, 0x69, 0x99, 0xce, 0x7a, - 0x32, 0x4c, 0x08, 0xed, 0xaa, 0x10, 0x10, 0xe3, - 0x6f, 0xee, 0x99, 0x68, 0x95, 0x9f, 0x04, 0x71, - 0xb2, 0x49, 0x2f, 0x62, 0xa6, 0x5e, 0xb4, 0xef, - 0x02, 0xed, 0x4f, 0x27, 0xde, 0x4a, 0x0f, 0xfd, - 0xc1, 0xcc, 0xdd, 0x02, 0x8f, 0x08, 0x16, 0x54, - 0xdf, 0xda, 0xca, 0xe0, 0x82, 0xf1, 0xb4, 0x31, - 0x7a, 0xa9, 0x81, 0xfe, 0x90, 0xb7, 0x3e, 0xdb, - 0xd3, 0x35, 0xc0, 0x20, 0x80, 0x33, 0x46, 0x4a, - 0x63, 0xab, 0xd1, 0x0d, 0x29, 0xd2, 0xe2, 0x84, - 0xb8, 0xdb, 0xfa, 0xe9, 0x89, 0x44, 0x86, 0x7c, - 0xe8, 0x0b, 0xe6, 0x02, 0x6a, 0x07, 0x9b, 0x96, - 0xd0, 0xdb, 0x2e, 0x41, 0x4c, 0xa1, 0xd5, 0x57, - 0x45, 0x14, 0xfb, 0xe3, 0xa6, 0x72, 0x5b, 0x87, - 0x6e, 0x0c, 0x6d, 0x5b, 0xce, 0xe0, 0x2f, 0xe2, - 0x21, 0x81, 0x95, 0xb0, 0xe8, 0xb6, 0x32, 0x0b, - 0xb2, 0x98, 0x13, 0x52, 0x5d, 0xfb, 0xec, 0x63, - 0x17, 0x8a, 0x9e, 0x23, 0x22, 0x36, 0xee, 0xcd, - 0xda, 0xdb, 0xcf, 0x3e, 0xf1, 0xc7, 0xf1, 0x01, - 0x12, 0x93, 0x0a, 0xeb, 0x6f, 0xf2, 0x02, 0x15, - 0x96, 0x77, 0x5d, 0xef, 0x9c, 0xfb, 0x88, 0x91, - 0x59, 0xf9, 0x84, 0xdd, 0x9b, 0x26, 0x8d, 0x80, - 0xf9, 0x80, 0x66, 0x2d, 0xac, 0xf7, 0x1f, 0x06, - 0xba, 0x7f, 0xff, 0xee, 0xed, 0x40, 0x5f, 0xa5, - 0xd6, 0xbd, 0x8c, 0x5b, 0x46, 0xd2, 0x7e, 0x48, - 0x4a, 0x65, 0x8f, 0x08, 0x42, 0x60, 0xf7, 0x0f, - 0xb9, 0x16, 0x0b, 0x0c, 0x1a, 0x06, 0x00, 0x00, - }, - nil, - }, - { // has 1 non-empty fixed huffman block then garbage - "hello.txt", - "hello.txt + garbage", - "hello world\n", - []byte{ - 0x1f, 0x8b, 0x08, 0x08, 0xc8, 0x58, 0x13, 0x4a, - 0x00, 0x03, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x2e, - 0x74, 0x78, 0x74, 0x00, 0xcb, 0x48, 0xcd, 0xc9, - 0xc9, 0x57, 0x28, 0xcf, 0x2f, 0xca, 0x49, 0xe1, - 0x02, 0x00, 0x2d, 0x3b, 0x08, 0xaf, 0x0c, 0x00, - 0x00, 0x00, 'g', 'a', 'r', 'b', 'a', 'g', 'e', '!', '!', '!', - }, - ErrHeader, - }, - { // has 1 non-empty fixed huffman block not enough header - "hello.txt", - "hello.txt + garbage", - "hello world\n", - []byte{ - 0x1f, 0x8b, 0x08, 0x08, 0xc8, 0x58, 0x13, 0x4a, - 0x00, 0x03, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x2e, - 0x74, 0x78, 0x74, 0x00, 0xcb, 0x48, 0xcd, 0xc9, - 0xc9, 0x57, 0x28, 0xcf, 0x2f, 0xca, 0x49, 0xe1, - 0x02, 0x00, 0x2d, 0x3b, 0x08, 0xaf, 0x0c, 0x00, - 0x00, 0x00, gzipID1, - }, - io.ErrUnexpectedEOF, - }, - { // has 1 non-empty fixed huffman block but corrupt checksum - "hello.txt", - "hello.txt + corrupt checksum", - "hello world\n", - []byte{ - 0x1f, 0x8b, 0x08, 0x08, 0xc8, 0x58, 0x13, 0x4a, - 0x00, 0x03, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x2e, - 0x74, 0x78, 0x74, 0x00, 0xcb, 0x48, 0xcd, 0xc9, - 0xc9, 0x57, 0x28, 0xcf, 0x2f, 0xca, 0x49, 0xe1, - 0x02, 0x00, 0xff, 0xff, 0xff, 0xff, 0x0c, 0x00, - 0x00, 0x00, - }, - ErrChecksum, - }, - { // has 1 non-empty fixed huffman block but corrupt size - "hello.txt", - "hello.txt + corrupt size", - "hello world\n", - []byte{ - 0x1f, 0x8b, 0x08, 0x08, 0xc8, 0x58, 0x13, 0x4a, - 0x00, 0x03, 0x68, 0x65, 0x6c, 0x6c, 0x6f, 0x2e, - 0x74, 0x78, 0x74, 0x00, 0xcb, 0x48, 0xcd, 0xc9, - 0xc9, 0x57, 0x28, 0xcf, 0x2f, 0xca, 0x49, 0xe1, - 0x02, 0x00, 0x2d, 0x3b, 0x08, 0xaf, 0xff, 0x00, - 0x00, 0x00, - }, - ErrChecksum, - }, -} - -func TestDecompressor(t *testing.T) { - b := new(bytes.Buffer) - for _, tt := range gunzipTests { - in := bytes.NewReader(tt.gzip) - gzip, err := NewReader(in) - if err != nil { - t.Errorf("%s: NewReader: %s", tt.name, err) - continue - } - defer gzip.Close() - if tt.name != gzip.Name { - t.Errorf("%s: got name %s", tt.name, gzip.Name) - } - b.Reset() - n, err := io.Copy(b, gzip) - if err != tt.err { - t.Errorf("%s: io.Copy: %v want %v", tt.name, err, tt.err) - } - s := b.String() - if s != tt.raw { - t.Errorf("%s: got %d-byte %q want %d-byte %q", tt.name, n, s, len(tt.raw), tt.raw) - } - - // Test Reader Reset. - in = bytes.NewReader(tt.gzip) - err = gzip.Reset(in) - if err != nil { - t.Errorf("%s: Reset: %s", tt.name, err) - continue - } - if tt.name != gzip.Name { - t.Errorf("%s: got name %s", tt.name, gzip.Name) - } - b.Reset() - n, err = io.Copy(b, gzip) - if err != tt.err { - t.Errorf("%s: io.Copy: %v want %v", tt.name, err, tt.err) - } - s = b.String() - if s != tt.raw { - t.Errorf("%s: got %d-byte %q want %d-byte %q", tt.name, n, s, len(tt.raw), tt.raw) - } - } -} - -func TestIssue6550(t *testing.T) { - f, err := os.Open("testdata/issue6550.gz") - if err != nil { - t.Fatal(err) - } - gzip, err := NewReader(f) - if err != nil { - t.Fatalf("NewReader(testdata/issue6550.gz): %v", err) - } - defer gzip.Close() - done := make(chan bool, 1) - go func() { - _, err := io.Copy(ioutil.Discard, gzip) - if err == nil { - t.Errorf("Copy succeeded") - } else { - t.Logf("Copy failed (correctly): %v", err) - } - done <- true - }() - select { - case <-time.After(1 * time.Second): - t.Errorf("Copy hung") - case <-done: - // ok - } -} - -func TestInitialReset(t *testing.T) { - var r Reader - if err := r.Reset(bytes.NewReader(gunzipTests[1].gzip)); err != nil { - t.Error(err) - } - var buf bytes.Buffer - if _, err := io.Copy(&buf, &r); err != nil { - t.Error(err) - } - if s := buf.String(); s != gunzipTests[1].raw { - t.Errorf("got %q want %q", s, gunzipTests[1].raw) - } -} diff --git a/src/pkg/compress/gzip/gzip.go b/src/pkg/compress/gzip/gzip.go deleted file mode 100644 index 5131d128e..000000000 --- a/src/pkg/compress/gzip/gzip.go +++ /dev/null @@ -1,272 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gzip - -import ( - "compress/flate" - "errors" - "fmt" - "hash" - "hash/crc32" - "io" -) - -// These constants are copied from the flate package, so that code that imports -// "compress/gzip" does not also have to import "compress/flate". -const ( - NoCompression = flate.NoCompression - BestSpeed = flate.BestSpeed - BestCompression = flate.BestCompression - DefaultCompression = flate.DefaultCompression -) - -// A Writer is an io.WriteCloser. -// Writes to a Writer are compressed and written to w. -type Writer struct { - Header - w io.Writer - level int - wroteHeader bool - compressor *flate.Writer - digest hash.Hash32 - size uint32 - closed bool - buf [10]byte - err error -} - -// NewWriter returns a new Writer. -// Writes to the returned writer are compressed and written to w. -// -// It is the caller's responsibility to call Close on the WriteCloser when done. -// Writes may be buffered and not flushed until Close. -// -// Callers that wish to set the fields in Writer.Header must do so before -// the first call to Write or Close. The Comment and Name header fields are -// UTF-8 strings in Go, but the underlying format requires NUL-terminated ISO -// 8859-1 (Latin-1). NUL or non-Latin-1 runes in those strings will lead to an -// error on Write. -func NewWriter(w io.Writer) *Writer { - z, _ := NewWriterLevel(w, DefaultCompression) - return z -} - -// NewWriterLevel is like NewWriter but specifies the compression level instead -// of assuming DefaultCompression. -// -// The compression level can be DefaultCompression, NoCompression, or any -// integer value between BestSpeed and BestCompression inclusive. The error -// returned will be nil if the level is valid. -func NewWriterLevel(w io.Writer, level int) (*Writer, error) { - if level < DefaultCompression || level > BestCompression { - return nil, fmt.Errorf("gzip: invalid compression level: %d", level) - } - z := new(Writer) - z.init(w, level) - return z, nil -} - -func (z *Writer) init(w io.Writer, level int) { - digest := z.digest - if digest != nil { - digest.Reset() - } else { - digest = crc32.NewIEEE() - } - compressor := z.compressor - if compressor != nil { - compressor.Reset(w) - } - *z = Writer{ - Header: Header{ - OS: 255, // unknown - }, - w: w, - level: level, - digest: digest, - compressor: compressor, - } -} - -// Reset discards the Writer z's state and makes it equivalent to the -// result of its original state from NewWriter or NewWriterLevel, but -// writing to w instead. This permits reusing a Writer rather than -// allocating a new one. -func (z *Writer) Reset(w io.Writer) { - z.init(w, z.level) -} - -// GZIP (RFC 1952) is little-endian, unlike ZLIB (RFC 1950). -func put2(p []byte, v uint16) { - p[0] = uint8(v >> 0) - p[1] = uint8(v >> 8) -} - -func put4(p []byte, v uint32) { - p[0] = uint8(v >> 0) - p[1] = uint8(v >> 8) - p[2] = uint8(v >> 16) - p[3] = uint8(v >> 24) -} - -// writeBytes writes a length-prefixed byte slice to z.w. -func (z *Writer) writeBytes(b []byte) error { - if len(b) > 0xffff { - return errors.New("gzip.Write: Extra data is too large") - } - put2(z.buf[0:2], uint16(len(b))) - _, err := z.w.Write(z.buf[0:2]) - if err != nil { - return err - } - _, err = z.w.Write(b) - return err -} - -// writeString writes a UTF-8 string s in GZIP's format to z.w. -// GZIP (RFC 1952) specifies that strings are NUL-terminated ISO 8859-1 (Latin-1). -func (z *Writer) writeString(s string) (err error) { - // GZIP stores Latin-1 strings; error if non-Latin-1; convert if non-ASCII. - needconv := false - for _, v := range s { - if v == 0 || v > 0xff { - return errors.New("gzip.Write: non-Latin-1 header string") - } - if v > 0x7f { - needconv = true - } - } - if needconv { - b := make([]byte, 0, len(s)) - for _, v := range s { - b = append(b, byte(v)) - } - _, err = z.w.Write(b) - } else { - _, err = io.WriteString(z.w, s) - } - if err != nil { - return err - } - // GZIP strings are NUL-terminated. - z.buf[0] = 0 - _, err = z.w.Write(z.buf[0:1]) - return err -} - -// Write writes a compressed form of p to the underlying io.Writer. The -// compressed bytes are not necessarily flushed until the Writer is closed. -func (z *Writer) Write(p []byte) (int, error) { - if z.err != nil { - return 0, z.err - } - var n int - // Write the GZIP header lazily. - if !z.wroteHeader { - z.wroteHeader = true - z.buf[0] = gzipID1 - z.buf[1] = gzipID2 - z.buf[2] = gzipDeflate - z.buf[3] = 0 - if z.Extra != nil { - z.buf[3] |= 0x04 - } - if z.Name != "" { - z.buf[3] |= 0x08 - } - if z.Comment != "" { - z.buf[3] |= 0x10 - } - put4(z.buf[4:8], uint32(z.ModTime.Unix())) - if z.level == BestCompression { - z.buf[8] = 2 - } else if z.level == BestSpeed { - z.buf[8] = 4 - } else { - z.buf[8] = 0 - } - z.buf[9] = z.OS - n, z.err = z.w.Write(z.buf[0:10]) - if z.err != nil { - return n, z.err - } - if z.Extra != nil { - z.err = z.writeBytes(z.Extra) - if z.err != nil { - return n, z.err - } - } - if z.Name != "" { - z.err = z.writeString(z.Name) - if z.err != nil { - return n, z.err - } - } - if z.Comment != "" { - z.err = z.writeString(z.Comment) - if z.err != nil { - return n, z.err - } - } - if z.compressor == nil { - z.compressor, _ = flate.NewWriter(z.w, z.level) - } - } - z.size += uint32(len(p)) - z.digest.Write(p) - n, z.err = z.compressor.Write(p) - return n, z.err -} - -// Flush flushes any pending compressed data to the underlying writer. -// -// It is useful mainly in compressed network protocols, to ensure that -// a remote reader has enough data to reconstruct a packet. Flush does -// not return until the data has been written. If the underlying -// writer returns an error, Flush returns that error. -// -// In the terminology of the zlib library, Flush is equivalent to Z_SYNC_FLUSH. -func (z *Writer) Flush() error { - if z.err != nil { - return z.err - } - if z.closed { - return nil - } - if !z.wroteHeader { - z.Write(nil) - if z.err != nil { - return z.err - } - } - z.err = z.compressor.Flush() - return z.err -} - -// Close closes the Writer, flushing any unwritten data to the underlying -// io.Writer, but does not close the underlying io.Writer. -func (z *Writer) Close() error { - if z.err != nil { - return z.err - } - if z.closed { - return nil - } - z.closed = true - if !z.wroteHeader { - z.Write(nil) - if z.err != nil { - return z.err - } - } - z.err = z.compressor.Close() - if z.err != nil { - return z.err - } - put4(z.buf[0:4], z.digest.Sum32()) - put4(z.buf[4:8], z.size) - _, z.err = z.w.Write(z.buf[0:8]) - return z.err -} diff --git a/src/pkg/compress/gzip/gzip_test.go b/src/pkg/compress/gzip/gzip_test.go deleted file mode 100644 index 09271b24e..000000000 --- a/src/pkg/compress/gzip/gzip_test.go +++ /dev/null @@ -1,231 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gzip - -import ( - "bufio" - "bytes" - "io/ioutil" - "testing" - "time" -) - -// TestEmpty tests that an empty payload still forms a valid GZIP stream. -func TestEmpty(t *testing.T) { - buf := new(bytes.Buffer) - - if err := NewWriter(buf).Close(); err != nil { - t.Fatalf("Writer.Close: %v", err) - } - - r, err := NewReader(buf) - if err != nil { - t.Fatalf("NewReader: %v", err) - } - b, err := ioutil.ReadAll(r) - if err != nil { - t.Fatalf("ReadAll: %v", err) - } - if len(b) != 0 { - t.Fatalf("got %d bytes, want 0", len(b)) - } - if err := r.Close(); err != nil { - t.Fatalf("Reader.Close: %v", err) - } -} - -// TestRoundTrip tests that gzipping and then gunzipping is the identity -// function. -func TestRoundTrip(t *testing.T) { - buf := new(bytes.Buffer) - - w := NewWriter(buf) - w.Comment = "comment" - w.Extra = []byte("extra") - w.ModTime = time.Unix(1e8, 0) - w.Name = "name" - if _, err := w.Write([]byte("payload")); err != nil { - t.Fatalf("Write: %v", err) - } - if err := w.Close(); err != nil { - t.Fatalf("Writer.Close: %v", err) - } - - r, err := NewReader(buf) - if err != nil { - t.Fatalf("NewReader: %v", err) - } - b, err := ioutil.ReadAll(r) - if err != nil { - t.Fatalf("ReadAll: %v", err) - } - if string(b) != "payload" { - t.Fatalf("payload is %q, want %q", string(b), "payload") - } - if r.Comment != "comment" { - t.Fatalf("comment is %q, want %q", r.Comment, "comment") - } - if string(r.Extra) != "extra" { - t.Fatalf("extra is %q, want %q", r.Extra, "extra") - } - if r.ModTime.Unix() != 1e8 { - t.Fatalf("mtime is %d, want %d", r.ModTime.Unix(), uint32(1e8)) - } - if r.Name != "name" { - t.Fatalf("name is %q, want %q", r.Name, "name") - } - if err := r.Close(); err != nil { - t.Fatalf("Reader.Close: %v", err) - } -} - -// TestLatin1 tests the internal functions for converting to and from Latin-1. -func TestLatin1(t *testing.T) { - latin1 := []byte{0xc4, 'u', 0xdf, 'e', 'r', 'u', 'n', 'g', 0} - utf8 := "Äußerung" - z := Reader{r: bufio.NewReader(bytes.NewReader(latin1))} - s, err := z.readString() - if err != nil { - t.Fatalf("readString: %v", err) - } - if s != utf8 { - t.Fatalf("read latin-1: got %q, want %q", s, utf8) - } - - buf := bytes.NewBuffer(make([]byte, 0, len(latin1))) - c := Writer{w: buf} - if err = c.writeString(utf8); err != nil { - t.Fatalf("writeString: %v", err) - } - s = buf.String() - if s != string(latin1) { - t.Fatalf("write utf-8: got %q, want %q", s, string(latin1)) - } -} - -// TestLatin1RoundTrip tests that metadata that is representable in Latin-1 -// survives a round trip. -func TestLatin1RoundTrip(t *testing.T) { - testCases := []struct { - name string - ok bool - }{ - {"", true}, - {"ASCII is OK", true}, - {"unless it contains a NUL\x00", false}, - {"no matter where \x00 occurs", false}, - {"\x00\x00\x00", false}, - {"Látin-1 also passes (U+00E1)", true}, - {"but LĀtin Extended-A (U+0100) does not", false}, - {"neither does 日本語", false}, - {"invalid UTF-8 also \xffails", false}, - {"\x00 as does Látin-1 with NUL", false}, - } - for _, tc := range testCases { - buf := new(bytes.Buffer) - - w := NewWriter(buf) - w.Name = tc.name - err := w.Close() - if (err == nil) != tc.ok { - t.Errorf("Writer.Close: name = %q, err = %v", tc.name, err) - continue - } - if !tc.ok { - continue - } - - r, err := NewReader(buf) - if err != nil { - t.Errorf("NewReader: %v", err) - continue - } - _, err = ioutil.ReadAll(r) - if err != nil { - t.Errorf("ReadAll: %v", err) - continue - } - if r.Name != tc.name { - t.Errorf("name is %q, want %q", r.Name, tc.name) - continue - } - if err := r.Close(); err != nil { - t.Errorf("Reader.Close: %v", err) - continue - } - } -} - -func TestWriterFlush(t *testing.T) { - buf := new(bytes.Buffer) - - w := NewWriter(buf) - w.Comment = "comment" - w.Extra = []byte("extra") - w.ModTime = time.Unix(1e8, 0) - w.Name = "name" - - n0 := buf.Len() - if n0 != 0 { - t.Fatalf("buffer size = %d before writes; want 0", n0) - } - - if err := w.Flush(); err != nil { - t.Fatal(err) - } - - n1 := buf.Len() - if n1 == 0 { - t.Fatal("no data after first flush") - } - - w.Write([]byte("x")) - - n2 := buf.Len() - if n1 != n2 { - t.Fatalf("after writing a single byte, size changed from %d to %d; want no change", n1, n2) - } - - if err := w.Flush(); err != nil { - t.Fatal(err) - } - - n3 := buf.Len() - if n2 == n3 { - t.Fatal("Flush didn't flush any data") - } -} - -// Multiple gzip files concatenated form a valid gzip file. -func TestConcat(t *testing.T) { - var buf bytes.Buffer - w := NewWriter(&buf) - w.Write([]byte("hello ")) - w.Close() - w = NewWriter(&buf) - w.Write([]byte("world\n")) - w.Close() - - r, err := NewReader(&buf) - data, err := ioutil.ReadAll(r) - if string(data) != "hello world\n" || err != nil { - t.Fatalf("ReadAll = %q, %v, want %q, nil", data, err, "hello world") - } -} - -func TestWriterReset(t *testing.T) { - buf := new(bytes.Buffer) - buf2 := new(bytes.Buffer) - z := NewWriter(buf) - msg := []byte("hello world") - z.Write(msg) - z.Close() - z.Reset(buf2) - z.Write(msg) - z.Close() - if buf.String() != buf2.String() { - t.Errorf("buf2 %q != original buf of %q", buf2.String(), buf.String()) - } -} diff --git a/src/pkg/compress/gzip/testdata/issue6550.gz b/src/pkg/compress/gzip/testdata/issue6550.gz deleted file mode 100644 index 57972b636..000000000 Binary files a/src/pkg/compress/gzip/testdata/issue6550.gz and /dev/null differ diff --git a/src/pkg/compress/lzw/reader.go b/src/pkg/compress/lzw/reader.go deleted file mode 100644 index cd90c9c63..000000000 --- a/src/pkg/compress/lzw/reader.go +++ /dev/null @@ -1,257 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package lzw implements the Lempel-Ziv-Welch compressed data format, -// described in T. A. Welch, ``A Technique for High-Performance Data -// Compression'', Computer, 17(6) (June 1984), pp 8-19. -// -// In particular, it implements LZW as used by the GIF and PDF file -// formats, which means variable-width codes up to 12 bits and the first -// two non-literal codes are a clear code and an EOF code. -// -// The TIFF file format uses a similar but incompatible version of the LZW -// algorithm. See the code.google.com/p/go.image/tiff/lzw package for an -// implementation. -package lzw - -// TODO(nigeltao): check that PDF uses LZW in the same way as GIF, -// modulo LSB/MSB packing order. - -import ( - "bufio" - "errors" - "fmt" - "io" -) - -// Order specifies the bit ordering in an LZW data stream. -type Order int - -const ( - // LSB means Least Significant Bits first, as used in the GIF file format. - LSB Order = iota - // MSB means Most Significant Bits first, as used in the TIFF and PDF - // file formats. - MSB -) - -const ( - maxWidth = 12 - decoderInvalidCode = 0xffff - flushBuffer = 1 << maxWidth -) - -// decoder is the state from which the readXxx method converts a byte -// stream into a code stream. -type decoder struct { - r io.ByteReader - bits uint32 - nBits uint - width uint - read func(*decoder) (uint16, error) // readLSB or readMSB - litWidth int // width in bits of literal codes - err error - - // The first 1<= 1<>= d.width - d.nBits -= d.width - return code, nil -} - -// readMSB returns the next code for "Most Significant Bits first" data. -func (d *decoder) readMSB() (uint16, error) { - for d.nBits < d.width { - x, err := d.r.ReadByte() - if err != nil { - return 0, err - } - d.bits |= uint32(x) << (24 - d.nBits) - d.nBits += 8 - } - code := uint16(d.bits >> (32 - d.width)) - d.bits <<= d.width - d.nBits -= d.width - return code, nil -} - -func (d *decoder) Read(b []byte) (int, error) { - for { - if len(d.toRead) > 0 { - n := copy(b, d.toRead) - d.toRead = d.toRead[n:] - return n, nil - } - if d.err != nil { - return 0, d.err - } - d.decode() - } -} - -// decode decompresses bytes from r and leaves them in d.toRead. -// read specifies how to decode bytes into codes. -// litWidth is the width in bits of literal codes. -func (d *decoder) decode() { - // Loop over the code stream, converting codes into decompressed bytes. - for { - code, err := d.read(d) - if err != nil { - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - d.err = err - return - } - switch { - case code < d.clear: - // We have a literal code. - d.output[d.o] = uint8(code) - d.o++ - if d.last != decoderInvalidCode { - // Save what the hi code expands to. - d.suffix[d.hi] = uint8(code) - d.prefix[d.hi] = d.last - } - case code == d.clear: - d.width = 1 + uint(d.litWidth) - d.hi = d.eof - d.overflow = 1 << d.width - d.last = decoderInvalidCode - continue - case code == d.eof: - d.flush() - d.err = io.EOF - return - case code <= d.hi: - c, i := code, len(d.output)-1 - if code == d.hi { - // code == hi is a special case which expands to the last expansion - // followed by the head of the last expansion. To find the head, we walk - // the prefix chain until we find a literal code. - c = d.last - for c >= d.clear { - c = d.prefix[c] - } - d.output[i] = uint8(c) - i-- - c = d.last - } - // Copy the suffix chain into output and then write that to w. - for c >= d.clear { - d.output[i] = d.suffix[c] - i-- - c = d.prefix[c] - } - d.output[i] = uint8(c) - d.o += copy(d.output[d.o:], d.output[i:]) - if d.last != decoderInvalidCode { - // Save what the hi code expands to. - d.suffix[d.hi] = uint8(c) - d.prefix[d.hi] = d.last - } - default: - d.err = errors.New("lzw: invalid code") - return - } - d.last, d.hi = code, d.hi+1 - if d.hi >= d.overflow { - if d.width == maxWidth { - d.last = decoderInvalidCode - } else { - d.width++ - d.overflow <<= 1 - } - } - if d.o >= flushBuffer { - d.flush() - return - } - } -} - -func (d *decoder) flush() { - d.toRead = d.output[:d.o] - d.o = 0 -} - -var errClosed = errors.New("compress/lzw: reader/writer is closed") - -func (d *decoder) Close() error { - d.err = errClosed // in case any Reads come along - return nil -} - -// NewReader creates a new io.ReadCloser. -// Reads from the returned io.ReadCloser read and decompress data from r. -// It is the caller's responsibility to call Close on the ReadCloser when -// finished reading. -// The number of bits to use for literal codes, litWidth, must be in the -// range [2,8] and is typically 8. -func NewReader(r io.Reader, order Order, litWidth int) io.ReadCloser { - d := new(decoder) - switch order { - case LSB: - d.read = (*decoder).readLSB - case MSB: - d.read = (*decoder).readMSB - default: - d.err = errors.New("lzw: unknown order") - return d - } - if litWidth < 2 || 8 < litWidth { - d.err = fmt.Errorf("lzw: litWidth %d out of range", litWidth) - return d - } - if br, ok := r.(io.ByteReader); ok { - d.r = br - } else { - d.r = bufio.NewReader(r) - } - d.litWidth = litWidth - d.width = 1 + uint(litWidth) - d.clear = uint16(1) << uint(litWidth) - d.eof, d.hi = d.clear+1, d.clear+1 - d.overflow = uint16(1) << d.width - d.last = decoderInvalidCode - - return d -} diff --git a/src/pkg/compress/lzw/reader_test.go b/src/pkg/compress/lzw/reader_test.go deleted file mode 100644 index 9006c91c2..000000000 --- a/src/pkg/compress/lzw/reader_test.go +++ /dev/null @@ -1,152 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package lzw - -import ( - "bytes" - "io" - "io/ioutil" - "runtime" - "strconv" - "strings" - "testing" -) - -type lzwTest struct { - desc string - raw string - compressed string - err error -} - -var lzwTests = []lzwTest{ - { - "empty;LSB;8", - "", - "\x01\x01", - nil, - }, - { - "empty;MSB;8", - "", - "\x80\x80", - nil, - }, - { - "tobe;LSB;7", - "TOBEORNOTTOBEORTOBEORNOT", - "\x54\x4f\x42\x45\x4f\x52\x4e\x4f\x54\x82\x84\x86\x8b\x85\x87\x89\x81", - nil, - }, - { - "tobe;LSB;8", - "TOBEORNOTTOBEORTOBEORNOT", - "\x54\x9e\x08\x29\xf2\x44\x8a\x93\x27\x54\x04\x12\x34\xb8\xb0\xe0\xc1\x84\x01\x01", - nil, - }, - { - "tobe;MSB;7", - "TOBEORNOTTOBEORTOBEORNOT", - "\x54\x4f\x42\x45\x4f\x52\x4e\x4f\x54\x82\x84\x86\x8b\x85\x87\x89\x81", - nil, - }, - { - "tobe;MSB;8", - "TOBEORNOTTOBEORTOBEORNOT", - "\x2a\x13\xc8\x44\x52\x79\x48\x9c\x4f\x2a\x40\xa0\x90\x68\x5c\x16\x0f\x09\x80\x80", - nil, - }, - { - "tobe-truncated;LSB;8", - "TOBEORNOTTOBEORTOBEORNOT", - "\x54\x9e\x08\x29\xf2\x44\x8a\x93\x27\x54\x04", - io.ErrUnexpectedEOF, - }, - // This example comes from http://en.wikipedia.org/wiki/Graphics_Interchange_Format. - { - "gif;LSB;8", - "\x28\xff\xff\xff\x28\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff", - "\x00\x51\xfc\x1b\x28\x70\xa0\xc1\x83\x01\x01", - nil, - }, - // This example comes from http://compgroups.net/comp.lang.ruby/Decompressing-LZW-compression-from-PDF-file - { - "pdf;MSB;8", - "-----A---B", - "\x80\x0b\x60\x50\x22\x0c\x0c\x85\x01", - nil, - }, -} - -func TestReader(t *testing.T) { - var b bytes.Buffer - for _, tt := range lzwTests { - d := strings.Split(tt.desc, ";") - var order Order - switch d[1] { - case "LSB": - order = LSB - case "MSB": - order = MSB - default: - t.Errorf("%s: bad order %q", tt.desc, d[1]) - } - litWidth, _ := strconv.Atoi(d[2]) - rc := NewReader(strings.NewReader(tt.compressed), order, litWidth) - defer rc.Close() - b.Reset() - n, err := io.Copy(&b, rc) - if err != nil { - if err != tt.err { - t.Errorf("%s: io.Copy: %v want %v", tt.desc, err, tt.err) - } - continue - } - s := b.String() - if s != tt.raw { - t.Errorf("%s: got %d-byte %q want %d-byte %q", tt.desc, n, s, len(tt.raw), tt.raw) - } - } -} - -func benchmarkDecoder(b *testing.B, n int) { - b.StopTimer() - b.SetBytes(int64(n)) - buf0, err := ioutil.ReadFile("../testdata/e.txt") - if err != nil { - b.Fatal(err) - } - if len(buf0) == 0 { - b.Fatalf("test file has no data") - } - compressed := new(bytes.Buffer) - w := NewWriter(compressed, LSB, 8) - for i := 0; i < n; i += len(buf0) { - if len(buf0) > n-i { - buf0 = buf0[:n-i] - } - w.Write(buf0) - } - w.Close() - buf1 := compressed.Bytes() - buf0, compressed, w = nil, nil, nil - runtime.GC() - b.StartTimer() - for i := 0; i < b.N; i++ { - io.Copy(ioutil.Discard, NewReader(bytes.NewReader(buf1), LSB, 8)) - } -} - -func BenchmarkDecoder1e4(b *testing.B) { - benchmarkDecoder(b, 1e4) -} - -func BenchmarkDecoder1e5(b *testing.B) { - benchmarkDecoder(b, 1e5) -} - -func BenchmarkDecoder1e6(b *testing.B) { - benchmarkDecoder(b, 1e6) -} diff --git a/src/pkg/compress/lzw/writer.go b/src/pkg/compress/lzw/writer.go deleted file mode 100644 index 961b25f94..000000000 --- a/src/pkg/compress/lzw/writer.go +++ /dev/null @@ -1,262 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package lzw - -import ( - "bufio" - "errors" - "fmt" - "io" -) - -// A writer is a buffered, flushable writer. -type writer interface { - io.ByteWriter - Flush() error -} - -// An errWriteCloser is an io.WriteCloser that always returns a given error. -type errWriteCloser struct { - err error -} - -func (e *errWriteCloser) Write([]byte) (int, error) { - return 0, e.err -} - -func (e *errWriteCloser) Close() error { - return e.err -} - -const ( - // A code is a 12 bit value, stored as a uint32 when encoding to avoid - // type conversions when shifting bits. - maxCode = 1<<12 - 1 - invalidCode = 1<<32 - 1 - // There are 1<<12 possible codes, which is an upper bound on the number of - // valid hash table entries at any given point in time. tableSize is 4x that. - tableSize = 4 * 1 << 12 - tableMask = tableSize - 1 - // A hash table entry is a uint32. Zero is an invalid entry since the - // lower 12 bits of a valid entry must be a non-literal code. - invalidEntry = 0 -) - -// encoder is LZW compressor. -type encoder struct { - // w is the writer that compressed bytes are written to. - w writer - // order, write, bits, nBits and width are the state for - // converting a code stream into a byte stream. - order Order - write func(*encoder, uint32) error - bits uint32 - nBits uint - width uint - // litWidth is the width in bits of literal codes. - litWidth uint - // hi is the code implied by the next code emission. - // overflow is the code at which hi overflows the code width. - hi, overflow uint32 - // savedCode is the accumulated code at the end of the most recent Write - // call. It is equal to invalidCode if there was no such call. - savedCode uint32 - // err is the first error encountered during writing. Closing the encoder - // will make any future Write calls return errClosed - err error - // table is the hash table from 20-bit keys to 12-bit values. Each table - // entry contains key<<12|val and collisions resolve by linear probing. - // The keys consist of a 12-bit code prefix and an 8-bit byte suffix. - // The values are a 12-bit code. - table [tableSize]uint32 -} - -// writeLSB writes the code c for "Least Significant Bits first" data. -func (e *encoder) writeLSB(c uint32) error { - e.bits |= c << e.nBits - e.nBits += e.width - for e.nBits >= 8 { - if err := e.w.WriteByte(uint8(e.bits)); err != nil { - return err - } - e.bits >>= 8 - e.nBits -= 8 - } - return nil -} - -// writeMSB writes the code c for "Most Significant Bits first" data. -func (e *encoder) writeMSB(c uint32) error { - e.bits |= c << (32 - e.width - e.nBits) - e.nBits += e.width - for e.nBits >= 8 { - if err := e.w.WriteByte(uint8(e.bits >> 24)); err != nil { - return err - } - e.bits <<= 8 - e.nBits -= 8 - } - return nil -} - -// errOutOfCodes is an internal error that means that the encoder has run out -// of unused codes and a clear code needs to be sent next. -var errOutOfCodes = errors.New("lzw: out of codes") - -// incHi increments e.hi and checks for both overflow and running out of -// unused codes. In the latter case, incHi sends a clear code, resets the -// encoder state and returns errOutOfCodes. -func (e *encoder) incHi() error { - e.hi++ - if e.hi == e.overflow { - e.width++ - e.overflow <<= 1 - } - if e.hi == maxCode { - clear := uint32(1) << e.litWidth - if err := e.write(e, clear); err != nil { - return err - } - e.width = uint(e.litWidth) + 1 - e.hi = clear + 1 - e.overflow = clear << 1 - for i := range e.table { - e.table[i] = invalidEntry - } - return errOutOfCodes - } - return nil -} - -// Write writes a compressed representation of p to e's underlying writer. -func (e *encoder) Write(p []byte) (n int, err error) { - if e.err != nil { - return 0, e.err - } - if len(p) == 0 { - return 0, nil - } - n = len(p) - litMask := uint32(1<>12 ^ key) & tableMask - for h, t := hash, e.table[hash]; t != invalidEntry; { - if key == t>>12 { - code = t & maxCode - continue loop - } - h = (h + 1) & tableMask - t = e.table[h] - } - // Otherwise, write the current code, and literal becomes the start of - // the next emitted code. - if e.err = e.write(e, code); e.err != nil { - return 0, e.err - } - code = literal - // Increment e.hi, the next implied code. If we run out of codes, reset - // the encoder state (including clearing the hash table) and continue. - if err1 := e.incHi(); err1 != nil { - if err1 == errOutOfCodes { - continue - } - e.err = err1 - return 0, e.err - } - // Otherwise, insert key -> e.hi into the map that e.table represents. - for { - if e.table[hash] == invalidEntry { - e.table[hash] = (key << 12) | e.hi - break - } - hash = (hash + 1) & tableMask - } - } - e.savedCode = code - return n, nil -} - -// Close closes the encoder, flushing any pending output. It does not close or -// flush e's underlying writer. -func (e *encoder) Close() error { - if e.err != nil { - if e.err == errClosed { - return nil - } - return e.err - } - // Make any future calls to Write return errClosed. - e.err = errClosed - // Write the savedCode if valid. - if e.savedCode != invalidCode { - if err := e.write(e, e.savedCode); err != nil { - return err - } - if err := e.incHi(); err != nil && err != errOutOfCodes { - return err - } - } - // Write the eof code. - eof := uint32(1)< 0 { - if e.order == MSB { - e.bits >>= 24 - } - if err := e.w.WriteByte(uint8(e.bits)); err != nil { - return err - } - } - return e.w.Flush() -} - -// NewWriter creates a new io.WriteCloser. -// Writes to the returned io.WriteCloser are compressed and written to w. -// It is the caller's responsibility to call Close on the WriteCloser when -// finished writing. -// The number of bits to use for literal codes, litWidth, must be in the -// range [2,8] and is typically 8. -func NewWriter(w io.Writer, order Order, litWidth int) io.WriteCloser { - var write func(*encoder, uint32) error - switch order { - case LSB: - write = (*encoder).writeLSB - case MSB: - write = (*encoder).writeMSB - default: - return &errWriteCloser{errors.New("lzw: unknown order")} - } - if litWidth < 2 || 8 < litWidth { - return &errWriteCloser{fmt.Errorf("lzw: litWidth %d out of range", litWidth)} - } - bw, ok := w.(writer) - if !ok { - bw = bufio.NewWriter(w) - } - lw := uint(litWidth) - return &encoder{ - w: bw, - order: order, - write: write, - width: 1 + lw, - litWidth: lw, - hi: 1< n-i { - buf0 = buf0[:n-i] - } - copy(buf1[i:], buf0) - } - buf0 = nil - runtime.GC() - b.StartTimer() - for i := 0; i < b.N; i++ { - w := NewWriter(ioutil.Discard, LSB, 8) - w.Write(buf1) - w.Close() - } -} - -func BenchmarkEncoder1e4(b *testing.B) { - benchmarkEncoder(b, 1e4) -} - -func BenchmarkEncoder1e5(b *testing.B) { - benchmarkEncoder(b, 1e5) -} - -func BenchmarkEncoder1e6(b *testing.B) { - benchmarkEncoder(b, 1e6) -} diff --git a/src/pkg/compress/testdata/Mark.Twain-Tom.Sawyer.txt b/src/pkg/compress/testdata/Mark.Twain-Tom.Sawyer.txt deleted file mode 100644 index c97da7ecc..000000000 --- a/src/pkg/compress/testdata/Mark.Twain-Tom.Sawyer.txt +++ /dev/null @@ -1,8858 +0,0 @@ -The Project Gutenberg EBook of The Adventures of Tom Sawyer, Complete -by Mark Twain (Samuel Clemens) - -This eBook is for the use of anyone anywhere at no cost and with -almost no restrictions whatsoever. You may copy it, give it away or -re-use it under the terms of the Project Gutenberg License included -with this eBook or online at www.gutenberg.net - - -Title: The Adventures of Tom Sawyer, Complete - -Author: Mark Twain (Samuel Clemens) - -Release Date: August 20, 2006 [EBook #74] -[Last updated: May 3, 2011] - -Language: English - - -*** START OF THIS PROJECT GUTENBERG EBOOK TOM SAWYER *** - - - - -Produced by David Widger. The previous edition was updated by Jose -Menendez. - - - - - - THE ADVENTURES OF TOM SAWYER - BY - MARK TWAIN - (Samuel Langhorne Clemens) - - - - - P R E F A C E - -MOST of the adventures recorded in this book really occurred; one or -two were experiences of my own, the rest those of boys who were -schoolmates of mine. Huck Finn is drawn from life; Tom Sawyer also, but -not from an individual--he is a combination of the characteristics of -three boys whom I knew, and therefore belongs to the composite order of -architecture. - -The odd superstitions touched upon were all prevalent among children -and slaves in the West at the period of this story--that is to say, -thirty or forty years ago. - -Although my book is intended mainly for the entertainment of boys and -girls, I hope it will not be shunned by men and women on that account, -for part of my plan has been to try to pleasantly remind adults of what -they once were themselves, and of how they felt and thought and talked, -and what queer enterprises they sometimes engaged in. - - THE AUTHOR. - -HARTFORD, 1876. - - - - T O M S A W Y E R - - - -CHAPTER I - -"TOM!" - -No answer. - -"TOM!" - -No answer. - -"What's gone with that boy, I wonder? You TOM!" - -No answer. - -The old lady pulled her spectacles down and looked over them about the -room; then she put them up and looked out under them. She seldom or -never looked THROUGH them for so small a thing as a boy; they were her -state pair, the pride of her heart, and were built for "style," not -service--she could have seen through a pair of stove-lids just as well. -She looked perplexed for a moment, and then said, not fiercely, but -still loud enough for the furniture to hear: - -"Well, I lay if I get hold of you I'll--" - -She did not finish, for by this time she was bending down and punching -under the bed with the broom, and so she needed breath to punctuate the -punches with. She resurrected nothing but the cat. - -"I never did see the beat of that boy!" - -She went to the open door and stood in it and looked out among the -tomato vines and "jimpson" weeds that constituted the garden. No Tom. -So she lifted up her voice at an angle calculated for distance and -shouted: - -"Y-o-u-u TOM!" - -There was a slight noise behind her and she turned just in time to -seize a small boy by the slack of his roundabout and arrest his flight. - -"There! I might 'a' thought of that closet. What you been doing in -there?" - -"Nothing." - -"Nothing! Look at your hands. And look at your mouth. What IS that -truck?" - -"I don't know, aunt." - -"Well, I know. It's jam--that's what it is. Forty times I've said if -you didn't let that jam alone I'd skin you. Hand me that switch." - -The switch hovered in the air--the peril was desperate-- - -"My! Look behind you, aunt!" - -The old lady whirled round, and snatched her skirts out of danger. The -lad fled on the instant, scrambled up the high board-fence, and -disappeared over it. - -His aunt Polly stood surprised a moment, and then broke into a gentle -laugh. - -"Hang the boy, can't I never learn anything? Ain't he played me tricks -enough like that for me to be looking out for him by this time? But old -fools is the biggest fools there is. Can't learn an old dog new tricks, -as the saying is. But my goodness, he never plays them alike, two days, -and how is a body to know what's coming? He 'pears to know just how -long he can torment me before I get my dander up, and he knows if he -can make out to put me off for a minute or make me laugh, it's all down -again and I can't hit him a lick. I ain't doing my duty by that boy, -and that's the Lord's truth, goodness knows. Spare the rod and spile -the child, as the Good Book says. I'm a laying up sin and suffering for -us both, I know. He's full of the Old Scratch, but laws-a-me! he's my -own dead sister's boy, poor thing, and I ain't got the heart to lash -him, somehow. Every time I let him off, my conscience does hurt me so, -and every time I hit him my old heart most breaks. Well-a-well, man -that is born of woman is of few days and full of trouble, as the -Scripture says, and I reckon it's so. He'll play hookey this evening, * -and [* Southwestern for "afternoon"] I'll just be obleeged to make him -work, to-morrow, to punish him. It's mighty hard to make him work -Saturdays, when all the boys is having holiday, but he hates work more -than he hates anything else, and I've GOT to do some of my duty by him, -or I'll be the ruination of the child." - -Tom did play hookey, and he had a very good time. He got back home -barely in season to help Jim, the small colored boy, saw next-day's -wood and split the kindlings before supper--at least he was there in -time to tell his adventures to Jim while Jim did three-fourths of the -work. Tom's younger brother (or rather half-brother) Sid was already -through with his part of the work (picking up chips), for he was a -quiet boy, and had no adventurous, troublesome ways. - -While Tom was eating his supper, and stealing sugar as opportunity -offered, Aunt Polly asked him questions that were full of guile, and -very deep--for she wanted to trap him into damaging revealments. Like -many other simple-hearted souls, it was her pet vanity to believe she -was endowed with a talent for dark and mysterious diplomacy, and she -loved to contemplate her most transparent devices as marvels of low -cunning. Said she: - -"Tom, it was middling warm in school, warn't it?" - -"Yes'm." - -"Powerful warm, warn't it?" - -"Yes'm." - -"Didn't you want to go in a-swimming, Tom?" - -A bit of a scare shot through Tom--a touch of uncomfortable suspicion. -He searched Aunt Polly's face, but it told him nothing. So he said: - -"No'm--well, not very much." - -The old lady reached out her hand and felt Tom's shirt, and said: - -"But you ain't too warm now, though." And it flattered her to reflect -that she had discovered that the shirt was dry without anybody knowing -that that was what she had in her mind. But in spite of her, Tom knew -where the wind lay, now. So he forestalled what might be the next move: - -"Some of us pumped on our heads--mine's damp yet. See?" - -Aunt Polly was vexed to think she had overlooked that bit of -circumstantial evidence, and missed a trick. Then she had a new -inspiration: - -"Tom, you didn't have to undo your shirt collar where I sewed it, to -pump on your head, did you? Unbutton your jacket!" - -The trouble vanished out of Tom's face. He opened his jacket. His -shirt collar was securely sewed. - -"Bother! Well, go 'long with you. I'd made sure you'd played hookey -and been a-swimming. But I forgive ye, Tom. I reckon you're a kind of a -singed cat, as the saying is--better'n you look. THIS time." - -She was half sorry her sagacity had miscarried, and half glad that Tom -had stumbled into obedient conduct for once. - -But Sidney said: - -"Well, now, if I didn't think you sewed his collar with white thread, -but it's black." - -"Why, I did sew it with white! Tom!" - -But Tom did not wait for the rest. As he went out at the door he said: - -"Siddy, I'll lick you for that." - -In a safe place Tom examined two large needles which were thrust into -the lapels of his jacket, and had thread bound about them--one needle -carried white thread and the other black. He said: - -"She'd never noticed if it hadn't been for Sid. Confound it! sometimes -she sews it with white, and sometimes she sews it with black. I wish to -geeminy she'd stick to one or t'other--I can't keep the run of 'em. But -I bet you I'll lam Sid for that. I'll learn him!" - -He was not the Model Boy of the village. He knew the model boy very -well though--and loathed him. - -Within two minutes, or even less, he had forgotten all his troubles. -Not because his troubles were one whit less heavy and bitter to him -than a man's are to a man, but because a new and powerful interest bore -them down and drove them out of his mind for the time--just as men's -misfortunes are forgotten in the excitement of new enterprises. This -new interest was a valued novelty in whistling, which he had just -acquired from a negro, and he was suffering to practise it undisturbed. -It consisted in a peculiar bird-like turn, a sort of liquid warble, -produced by touching the tongue to the roof of the mouth at short -intervals in the midst of the music--the reader probably remembers how -to do it, if he has ever been a boy. Diligence and attention soon gave -him the knack of it, and he strode down the street with his mouth full -of harmony and his soul full of gratitude. He felt much as an -astronomer feels who has discovered a new planet--no doubt, as far as -strong, deep, unalloyed pleasure is concerned, the advantage was with -the boy, not the astronomer. - -The summer evenings were long. It was not dark, yet. Presently Tom -checked his whistle. A stranger was before him--a boy a shade larger -than himself. A new-comer of any age or either sex was an impressive -curiosity in the poor little shabby village of St. Petersburg. This boy -was well dressed, too--well dressed on a week-day. This was simply -astounding. His cap was a dainty thing, his close-buttoned blue cloth -roundabout was new and natty, and so were his pantaloons. He had shoes -on--and it was only Friday. He even wore a necktie, a bright bit of -ribbon. He had a citified air about him that ate into Tom's vitals. The -more Tom stared at the splendid marvel, the higher he turned up his -nose at his finery and the shabbier and shabbier his own outfit seemed -to him to grow. Neither boy spoke. If one moved, the other moved--but -only sidewise, in a circle; they kept face to face and eye to eye all -the time. Finally Tom said: - -"I can lick you!" - -"I'd like to see you try it." - -"Well, I can do it." - -"No you can't, either." - -"Yes I can." - -"No you can't." - -"I can." - -"You can't." - -"Can!" - -"Can't!" - -An uncomfortable pause. Then Tom said: - -"What's your name?" - -"'Tisn't any of your business, maybe." - -"Well I 'low I'll MAKE it my business." - -"Well why don't you?" - -"If you say much, I will." - -"Much--much--MUCH. There now." - -"Oh, you think you're mighty smart, DON'T you? I could lick you with -one hand tied behind me, if I wanted to." - -"Well why don't you DO it? You SAY you can do it." - -"Well I WILL, if you fool with me." - -"Oh yes--I've seen whole families in the same fix." - -"Smarty! You think you're SOME, now, DON'T you? Oh, what a hat!" - -"You can lump that hat if you don't like it. I dare you to knock it -off--and anybody that'll take a dare will suck eggs." - -"You're a liar!" - -"You're another." - -"You're a fighting liar and dasn't take it up." - -"Aw--take a walk!" - -"Say--if you give me much more of your sass I'll take and bounce a -rock off'n your head." - -"Oh, of COURSE you will." - -"Well I WILL." - -"Well why don't you DO it then? What do you keep SAYING you will for? -Why don't you DO it? It's because you're afraid." - -"I AIN'T afraid." - -"You are." - -"I ain't." - -"You are." - -Another pause, and more eying and sidling around each other. Presently -they were shoulder to shoulder. Tom said: - -"Get away from here!" - -"Go away yourself!" - -"I won't." - -"I won't either." - -So they stood, each with a foot placed at an angle as a brace, and -both shoving with might and main, and glowering at each other with -hate. But neither could get an advantage. After struggling till both -were hot and flushed, each relaxed his strain with watchful caution, -and Tom said: - -"You're a coward and a pup. I'll tell my big brother on you, and he -can thrash you with his little finger, and I'll make him do it, too." - -"What do I care for your big brother? I've got a brother that's bigger -than he is--and what's more, he can throw him over that fence, too." -[Both brothers were imaginary.] - -"That's a lie." - -"YOUR saying so don't make it so." - -Tom drew a line in the dust with his big toe, and said: - -"I dare you to step over that, and I'll lick you till you can't stand -up. Anybody that'll take a dare will steal sheep." - -The new boy stepped over promptly, and said: - -"Now you said you'd do it, now let's see you do it." - -"Don't you crowd me now; you better look out." - -"Well, you SAID you'd do it--why don't you do it?" - -"By jingo! for two cents I WILL do it." - -The new boy took two broad coppers out of his pocket and held them out -with derision. Tom struck them to the ground. In an instant both boys -were rolling and tumbling in the dirt, gripped together like cats; and -for the space of a minute they tugged and tore at each other's hair and -clothes, punched and scratched each other's nose, and covered -themselves with dust and glory. Presently the confusion took form, and -through the fog of battle Tom appeared, seated astride the new boy, and -pounding him with his fists. "Holler 'nuff!" said he. - -The boy only struggled to free himself. He was crying--mainly from rage. - -"Holler 'nuff!"--and the pounding went on. - -At last the stranger got out a smothered "'Nuff!" and Tom let him up -and said: - -"Now that'll learn you. Better look out who you're fooling with next -time." - -The new boy went off brushing the dust from his clothes, sobbing, -snuffling, and occasionally looking back and shaking his head and -threatening what he would do to Tom the "next time he caught him out." -To which Tom responded with jeers, and started off in high feather, and -as soon as his back was turned the new boy snatched up a stone, threw -it and hit him between the shoulders and then turned tail and ran like -an antelope. Tom chased the traitor home, and thus found out where he -lived. He then held a position at the gate for some time, daring the -enemy to come outside, but the enemy only made faces at him through the -window and declined. At last the enemy's mother appeared, and called -Tom a bad, vicious, vulgar child, and ordered him away. So he went -away; but he said he "'lowed" to "lay" for that boy. - -He got home pretty late that night, and when he climbed cautiously in -at the window, he uncovered an ambuscade, in the person of his aunt; -and when she saw the state his clothes were in her resolution to turn -his Saturday holiday into captivity at hard labor became adamantine in -its firmness. - - - -CHAPTER II - -SATURDAY morning was come, and all the summer world was bright and -fresh, and brimming with life. There was a song in every heart; and if -the heart was young the music issued at the lips. There was cheer in -every face and a spring in every step. The locust-trees were in bloom -and the fragrance of the blossoms filled the air. Cardiff Hill, beyond -the village and above it, was green with vegetation and it lay just far -enough away to seem a Delectable Land, dreamy, reposeful, and inviting. - -Tom appeared on the sidewalk with a bucket of whitewash and a -long-handled brush. He surveyed the fence, and all gladness left him and -a deep melancholy settled down upon his spirit. Thirty yards of board -fence nine feet high. Life to him seemed hollow, and existence but a -burden. Sighing, he dipped his brush and passed it along the topmost -plank; repeated the operation; did it again; compared the insignificant -whitewashed streak with the far-reaching continent of unwhitewashed -fence, and sat down on a tree-box discouraged. Jim came skipping out at -the gate with a tin pail, and singing Buffalo Gals. Bringing water from -the town pump had always been hateful work in Tom's eyes, before, but -now it did not strike him so. He remembered that there was company at -the pump. White, mulatto, and negro boys and girls were always there -waiting their turns, resting, trading playthings, quarrelling, -fighting, skylarking. And he remembered that although the pump was only -a hundred and fifty yards off, Jim never got back with a bucket of -water under an hour--and even then somebody generally had to go after -him. Tom said: - -"Say, Jim, I'll fetch the water if you'll whitewash some." - -Jim shook his head and said: - -"Can't, Mars Tom. Ole missis, she tole me I got to go an' git dis -water an' not stop foolin' roun' wid anybody. She say she spec' Mars -Tom gwine to ax me to whitewash, an' so she tole me go 'long an' 'tend -to my own business--she 'lowed SHE'D 'tend to de whitewashin'." - -"Oh, never you mind what she said, Jim. That's the way she always -talks. Gimme the bucket--I won't be gone only a a minute. SHE won't -ever know." - -"Oh, I dasn't, Mars Tom. Ole missis she'd take an' tar de head off'n -me. 'Deed she would." - -"SHE! She never licks anybody--whacks 'em over the head with her -thimble--and who cares for that, I'd like to know. She talks awful, but -talk don't hurt--anyways it don't if she don't cry. Jim, I'll give you -a marvel. I'll give you a white alley!" - -Jim began to waver. - -"White alley, Jim! And it's a bully taw." - -"My! Dat's a mighty gay marvel, I tell you! But Mars Tom I's powerful -'fraid ole missis--" - -"And besides, if you will I'll show you my sore toe." - -Jim was only human--this attraction was too much for him. He put down -his pail, took the white alley, and bent over the toe with absorbing -interest while the bandage was being unwound. In another moment he was -flying down the street with his pail and a tingling rear, Tom was -whitewashing with vigor, and Aunt Polly was retiring from the field -with a slipper in her hand and triumph in her eye. - -But Tom's energy did not last. He began to think of the fun he had -planned for this day, and his sorrows multiplied. Soon the free boys -would come tripping along on all sorts of delicious expeditions, and -they would make a world of fun of him for having to work--the very -thought of it burnt him like fire. He got out his worldly wealth and -examined it--bits of toys, marbles, and trash; enough to buy an -exchange of WORK, maybe, but not half enough to buy so much as half an -hour of pure freedom. So he returned his straitened means to his -pocket, and gave up the idea of trying to buy the boys. At this dark -and hopeless moment an inspiration burst upon him! Nothing less than a -great, magnificent inspiration. - -He took up his brush and went tranquilly to work. Ben Rogers hove in -sight presently--the very boy, of all boys, whose ridicule he had been -dreading. Ben's gait was the hop-skip-and-jump--proof enough that his -heart was light and his anticipations high. He was eating an apple, and -giving a long, melodious whoop, at intervals, followed by a deep-toned -ding-dong-dong, ding-dong-dong, for he was personating a steamboat. As -he drew near, he slackened speed, took the middle of the street, leaned -far over to starboard and rounded to ponderously and with laborious -pomp and circumstance--for he was personating the Big Missouri, and -considered himself to be drawing nine feet of water. He was boat and -captain and engine-bells combined, so he had to imagine himself -standing on his own hurricane-deck giving the orders and executing them: - -"Stop her, sir! Ting-a-ling-ling!" The headway ran almost out, and he -drew up slowly toward the sidewalk. - -"Ship up to back! Ting-a-ling-ling!" His arms straightened and -stiffened down his sides. - -"Set her back on the stabboard! Ting-a-ling-ling! Chow! ch-chow-wow! -Chow!" His right hand, meantime, describing stately circles--for it was -representing a forty-foot wheel. - -"Let her go back on the labboard! Ting-a-lingling! Chow-ch-chow-chow!" -The left hand began to describe circles. - -"Stop the stabboard! Ting-a-ling-ling! Stop the labboard! Come ahead -on the stabboard! Stop her! Let your outside turn over slow! -Ting-a-ling-ling! Chow-ow-ow! Get out that head-line! LIVELY now! -Come--out with your spring-line--what're you about there! Take a turn -round that stump with the bight of it! Stand by that stage, now--let her -go! Done with the engines, sir! Ting-a-ling-ling! SH'T! S'H'T! SH'T!" -(trying the gauge-cocks). - -Tom went on whitewashing--paid no attention to the steamboat. Ben -stared a moment and then said: "Hi-YI! YOU'RE up a stump, ain't you!" - -No answer. Tom surveyed his last touch with the eye of an artist, then -he gave his brush another gentle sweep and surveyed the result, as -before. Ben ranged up alongside of him. Tom's mouth watered for the -apple, but he stuck to his work. Ben said: - -"Hello, old chap, you got to work, hey?" - -Tom wheeled suddenly and said: - -"Why, it's you, Ben! I warn't noticing." - -"Say--I'm going in a-swimming, I am. Don't you wish you could? But of -course you'd druther WORK--wouldn't you? Course you would!" - -Tom contemplated the boy a bit, and said: - -"What do you call work?" - -"Why, ain't THAT work?" - -Tom resumed his whitewashing, and answered carelessly: - -"Well, maybe it is, and maybe it ain't. All I know, is, it suits Tom -Sawyer." - -"Oh come, now, you don't mean to let on that you LIKE it?" - -The brush continued to move. - -"Like it? Well, I don't see why I oughtn't to like it. Does a boy get -a chance to whitewash a fence every day?" - -That put the thing in a new light. Ben stopped nibbling his apple. Tom -swept his brush daintily back and forth--stepped back to note the -effect--added a touch here and there--criticised the effect again--Ben -watching every move and getting more and more interested, more and more -absorbed. Presently he said: - -"Say, Tom, let ME whitewash a little." - -Tom considered, was about to consent; but he altered his mind: - -"No--no--I reckon it wouldn't hardly do, Ben. You see, Aunt Polly's -awful particular about this fence--right here on the street, you know ---but if it was the back fence I wouldn't mind and SHE wouldn't. Yes, -she's awful particular about this fence; it's got to be done very -careful; I reckon there ain't one boy in a thousand, maybe two -thousand, that can do it the way it's got to be done." - -"No--is that so? Oh come, now--lemme just try. Only just a little--I'd -let YOU, if you was me, Tom." - -"Ben, I'd like to, honest injun; but Aunt Polly--well, Jim wanted to -do it, but she wouldn't let him; Sid wanted to do it, and she wouldn't -let Sid. Now don't you see how I'm fixed? If you was to tackle this -fence and anything was to happen to it--" - -"Oh, shucks, I'll be just as careful. Now lemme try. Say--I'll give -you the core of my apple." - -"Well, here--No, Ben, now don't. I'm afeard--" - -"I'll give you ALL of it!" - -Tom gave up the brush with reluctance in his face, but alacrity in his -heart. And while the late steamer Big Missouri worked and sweated in -the sun, the retired artist sat on a barrel in the shade close by, -dangled his legs, munched his apple, and planned the slaughter of more -innocents. There was no lack of material; boys happened along every -little while; they came to jeer, but remained to whitewash. By the time -Ben was fagged out, Tom had traded the next chance to Billy Fisher for -a kite, in good repair; and when he played out, Johnny Miller bought in -for a dead rat and a string to swing it with--and so on, and so on, -hour after hour. And when the middle of the afternoon came, from being -a poor poverty-stricken boy in the morning, Tom was literally rolling -in wealth. He had besides the things before mentioned, twelve marbles, -part of a jews-harp, a piece of blue bottle-glass to look through, a -spool cannon, a key that wouldn't unlock anything, a fragment of chalk, -a glass stopper of a decanter, a tin soldier, a couple of tadpoles, six -fire-crackers, a kitten with only one eye, a brass doorknob, a -dog-collar--but no dog--the handle of a knife, four pieces of -orange-peel, and a dilapidated old window sash. - -He had had a nice, good, idle time all the while--plenty of company ---and the fence had three coats of whitewash on it! If he hadn't run out -of whitewash he would have bankrupted every boy in the village. - -Tom said to himself that it was not such a hollow world, after all. He -had discovered a great law of human action, without knowing it--namely, -that in order to make a man or a boy covet a thing, it is only -necessary to make the thing difficult to attain. If he had been a great -and wise philosopher, like the writer of this book, he would now have -comprehended that Work consists of whatever a body is OBLIGED to do, -and that Play consists of whatever a body is not obliged to do. And -this would help him to understand why constructing artificial flowers -or performing on a tread-mill is work, while rolling ten-pins or -climbing Mont Blanc is only amusement. There are wealthy gentlemen in -England who drive four-horse passenger-coaches twenty or thirty miles -on a daily line, in the summer, because the privilege costs them -considerable money; but if they were offered wages for the service, -that would turn it into work and then they would resign. - -The boy mused awhile over the substantial change which had taken place -in his worldly circumstances, and then wended toward headquarters to -report. - - - -CHAPTER III - -TOM presented himself before Aunt Polly, who was sitting by an open -window in a pleasant rearward apartment, which was bedroom, -breakfast-room, dining-room, and library, combined. The balmy summer -air, the restful quiet, the odor of the flowers, and the drowsing murmur -of the bees had had their effect, and she was nodding over her knitting ---for she had no company but the cat, and it was asleep in her lap. Her -spectacles were propped up on her gray head for safety. She had thought -that of course Tom had deserted long ago, and she wondered at seeing him -place himself in her power again in this intrepid way. He said: "Mayn't -I go and play now, aunt?" - -"What, a'ready? How much have you done?" - -"It's all done, aunt." - -"Tom, don't lie to me--I can't bear it." - -"I ain't, aunt; it IS all done." - -Aunt Polly placed small trust in such evidence. She went out to see -for herself; and she would have been content to find twenty per cent. -of Tom's statement true. When she found the entire fence whitewashed, -and not only whitewashed but elaborately coated and recoated, and even -a streak added to the ground, her astonishment was almost unspeakable. -She said: - -"Well, I never! There's no getting round it, you can work when you're -a mind to, Tom." And then she diluted the compliment by adding, "But -it's powerful seldom you're a mind to, I'm bound to say. Well, go 'long -and play; but mind you get back some time in a week, or I'll tan you." - -She was so overcome by the splendor of his achievement that she took -him into the closet and selected a choice apple and delivered it to -him, along with an improving lecture upon the added value and flavor a -treat took to itself when it came without sin through virtuous effort. -And while she closed with a happy Scriptural flourish, he "hooked" a -doughnut. - -Then he skipped out, and saw Sid just starting up the outside stairway -that led to the back rooms on the second floor. Clods were handy and -the air was full of them in a twinkling. They raged around Sid like a -hail-storm; and before Aunt Polly could collect her surprised faculties -and sally to the rescue, six or seven clods had taken personal effect, -and Tom was over the fence and gone. There was a gate, but as a general -thing he was too crowded for time to make use of it. His soul was at -peace, now that he had settled with Sid for calling attention to his -black thread and getting him into trouble. - -Tom skirted the block, and came round into a muddy alley that led by -the back of his aunt's cow-stable. He presently got safely beyond the -reach of capture and punishment, and hastened toward the public square -of the village, where two "military" companies of boys had met for -conflict, according to previous appointment. Tom was General of one of -these armies, Joe Harper (a bosom friend) General of the other. These -two great commanders did not condescend to fight in person--that being -better suited to the still smaller fry--but sat together on an eminence -and conducted the field operations by orders delivered through -aides-de-camp. Tom's army won a great victory, after a long and -hard-fought battle. Then the dead were counted, prisoners exchanged, -the terms of the next disagreement agreed upon, and the day for the -necessary battle appointed; after which the armies fell into line and -marched away, and Tom turned homeward alone. - -As he was passing by the house where Jeff Thatcher lived, he saw a new -girl in the garden--a lovely little blue-eyed creature with yellow hair -plaited into two long-tails, white summer frock and embroidered -pantalettes. The fresh-crowned hero fell without firing a shot. A -certain Amy Lawrence vanished out of his heart and left not even a -memory of herself behind. He had thought he loved her to distraction; -he had regarded his passion as adoration; and behold it was only a poor -little evanescent partiality. He had been months winning her; she had -confessed hardly a week ago; he had been the happiest and the proudest -boy in the world only seven short days, and here in one instant of time -she had gone out of his heart like a casual stranger whose visit is -done. - -He worshipped this new angel with furtive eye, till he saw that she -had discovered him; then he pretended he did not know she was present, -and began to "show off" in all sorts of absurd boyish ways, in order to -win her admiration. He kept up this grotesque foolishness for some -time; but by-and-by, while he was in the midst of some dangerous -gymnastic performances, he glanced aside and saw that the little girl -was wending her way toward the house. Tom came up to the fence and -leaned on it, grieving, and hoping she would tarry yet awhile longer. -She halted a moment on the steps and then moved toward the door. Tom -heaved a great sigh as she put her foot on the threshold. But his face -lit up, right away, for she tossed a pansy over the fence a moment -before she disappeared. - -The boy ran around and stopped within a foot or two of the flower, and -then shaded his eyes with his hand and began to look down street as if -he had discovered something of interest going on in that direction. -Presently he picked up a straw and began trying to balance it on his -nose, with his head tilted far back; and as he moved from side to side, -in his efforts, he edged nearer and nearer toward the pansy; finally -his bare foot rested upon it, his pliant toes closed upon it, and he -hopped away with the treasure and disappeared round the corner. But -only for a minute--only while he could button the flower inside his -jacket, next his heart--or next his stomach, possibly, for he was not -much posted in anatomy, and not hypercritical, anyway. - -He returned, now, and hung about the fence till nightfall, "showing -off," as before; but the girl never exhibited herself again, though Tom -comforted himself a little with the hope that she had been near some -window, meantime, and been aware of his attentions. Finally he strode -home reluctantly, with his poor head full of visions. - -All through supper his spirits were so high that his aunt wondered -"what had got into the child." He took a good scolding about clodding -Sid, and did not seem to mind it in the least. He tried to steal sugar -under his aunt's very nose, and got his knuckles rapped for it. He said: - -"Aunt, you don't whack Sid when he takes it." - -"Well, Sid don't torment a body the way you do. You'd be always into -that sugar if I warn't watching you." - -Presently she stepped into the kitchen, and Sid, happy in his -immunity, reached for the sugar-bowl--a sort of glorying over Tom which -was wellnigh unbearable. But Sid's fingers slipped and the bowl dropped -and broke. Tom was in ecstasies. In such ecstasies that he even -controlled his tongue and was silent. He said to himself that he would -not speak a word, even when his aunt came in, but would sit perfectly -still till she asked who did the mischief; and then he would tell, and -there would be nothing so good in the world as to see that pet model -"catch it." He was so brimful of exultation that he could hardly hold -himself when the old lady came back and stood above the wreck -discharging lightnings of wrath from over her spectacles. He said to -himself, "Now it's coming!" And the next instant he was sprawling on -the floor! The potent palm was uplifted to strike again when Tom cried -out: - -"Hold on, now, what 'er you belting ME for?--Sid broke it!" - -Aunt Polly paused, perplexed, and Tom looked for healing pity. But -when she got her tongue again, she only said: - -"Umf! Well, you didn't get a lick amiss, I reckon. You been into some -other audacious mischief when I wasn't around, like enough." - -Then her conscience reproached her, and she yearned to say something -kind and loving; but she judged that this would be construed into a -confession that she had been in the wrong, and discipline forbade that. -So she kept silence, and went about her affairs with a troubled heart. -Tom sulked in a corner and exalted his woes. He knew that in her heart -his aunt was on her knees to him, and he was morosely gratified by the -consciousness of it. He would hang out no signals, he would take notice -of none. He knew that a yearning glance fell upon him, now and then, -through a film of tears, but he refused recognition of it. He pictured -himself lying sick unto death and his aunt bending over him beseeching -one little forgiving word, but he would turn his face to the wall, and -die with that word unsaid. Ah, how would she feel then? And he pictured -himself brought home from the river, dead, with his curls all wet, and -his sore heart at rest. How she would throw herself upon him, and how -her tears would fall like rain, and her lips pray God to give her back -her boy and she would never, never abuse him any more! But he would lie -there cold and white and make no sign--a poor little sufferer, whose -griefs were at an end. He so worked upon his feelings with the pathos -of these dreams, that he had to keep swallowing, he was so like to -choke; and his eyes swam in a blur of water, which overflowed when he -winked, and ran down and trickled from the end of his nose. And such a -luxury to him was this petting of his sorrows, that he could not bear -to have any worldly cheeriness or any grating delight intrude upon it; -it was too sacred for such contact; and so, presently, when his cousin -Mary danced in, all alive with the joy of seeing home again after an -age-long visit of one week to the country, he got up and moved in -clouds and darkness out at one door as she brought song and sunshine in -at the other. - -He wandered far from the accustomed haunts of boys, and sought -desolate places that were in harmony with his spirit. A log raft in the -river invited him, and he seated himself on its outer edge and -contemplated the dreary vastness of the stream, wishing, the while, -that he could only be drowned, all at once and unconsciously, without -undergoing the uncomfortable routine devised by nature. Then he thought -of his flower. He got it out, rumpled and wilted, and it mightily -increased his dismal felicity. He wondered if she would pity him if she -knew? Would she cry, and wish that she had a right to put her arms -around his neck and comfort him? Or would she turn coldly away like all -the hollow world? This picture brought such an agony of pleasurable -suffering that he worked it over and over again in his mind and set it -up in new and varied lights, till he wore it threadbare. At last he -rose up sighing and departed in the darkness. - -About half-past nine or ten o'clock he came along the deserted street -to where the Adored Unknown lived; he paused a moment; no sound fell -upon his listening ear; a candle was casting a dull glow upon the -curtain of a second-story window. Was the sacred presence there? He -climbed the fence, threaded his stealthy way through the plants, till -he stood under that window; he looked up at it long, and with emotion; -then he laid him down on the ground under it, disposing himself upon -his back, with his hands clasped upon his breast and holding his poor -wilted flower. And thus he would die--out in the cold world, with no -shelter over his homeless head, no friendly hand to wipe the -death-damps from his brow, no loving face to bend pityingly over him -when the great agony came. And thus SHE would see him when she looked -out upon the glad morning, and oh! would she drop one little tear upon -his poor, lifeless form, would she heave one little sigh to see a bright -young life so rudely blighted, so untimely cut down? - -The window went up, a maid-servant's discordant voice profaned the -holy calm, and a deluge of water drenched the prone martyr's remains! - -The strangling hero sprang up with a relieving snort. There was a whiz -as of a missile in the air, mingled with the murmur of a curse, a sound -as of shivering glass followed, and a small, vague form went over the -fence and shot away in the gloom. - -Not long after, as Tom, all undressed for bed, was surveying his -drenched garments by the light of a tallow dip, Sid woke up; but if he -had any dim idea of making any "references to allusions," he thought -better of it and held his peace, for there was danger in Tom's eye. - -Tom turned in without the added vexation of prayers, and Sid made -mental note of the omission. - - - -CHAPTER IV - -THE sun rose upon a tranquil world, and beamed down upon the peaceful -village like a benediction. Breakfast over, Aunt Polly had family -worship: it began with a prayer built from the ground up of solid -courses of Scriptural quotations, welded together with a thin mortar of -originality; and from the summit of this she delivered a grim chapter -of the Mosaic Law, as from Sinai. - -Then Tom girded up his loins, so to speak, and went to work to "get -his verses." Sid had learned his lesson days before. Tom bent all his -energies to the memorizing of five verses, and he chose part of the -Sermon on the Mount, because he could find no verses that were shorter. -At the end of half an hour Tom had a vague general idea of his lesson, -but no more, for his mind was traversing the whole field of human -thought, and his hands were busy with distracting recreations. Mary -took his book to hear him recite, and he tried to find his way through -the fog: - -"Blessed are the--a--a--" - -"Poor"-- - -"Yes--poor; blessed are the poor--a--a--" - -"In spirit--" - -"In spirit; blessed are the poor in spirit, for they--they--" - -"THEIRS--" - -"For THEIRS. Blessed are the poor in spirit, for theirs is the kingdom -of heaven. Blessed are they that mourn, for they--they--" - -"Sh--" - -"For they--a--" - -"S, H, A--" - -"For they S, H--Oh, I don't know what it is!" - -"SHALL!" - -"Oh, SHALL! for they shall--for they shall--a--a--shall mourn--a--a-- -blessed are they that shall--they that--a--they that shall mourn, for -they shall--a--shall WHAT? Why don't you tell me, Mary?--what do you -want to be so mean for?" - -"Oh, Tom, you poor thick-headed thing, I'm not teasing you. I wouldn't -do that. You must go and learn it again. Don't you be discouraged, Tom, -you'll manage it--and if you do, I'll give you something ever so nice. -There, now, that's a good boy." - -"All right! What is it, Mary, tell me what it is." - -"Never you mind, Tom. You know if I say it's nice, it is nice." - -"You bet you that's so, Mary. All right, I'll tackle it again." - -And he did "tackle it again"--and under the double pressure of -curiosity and prospective gain he did it with such spirit that he -accomplished a shining success. Mary gave him a brand-new "Barlow" -knife worth twelve and a half cents; and the convulsion of delight that -swept his system shook him to his foundations. True, the knife would -not cut anything, but it was a "sure-enough" Barlow, and there was -inconceivable grandeur in that--though where the Western boys ever got -the idea that such a weapon could possibly be counterfeited to its -injury is an imposing mystery and will always remain so, perhaps. Tom -contrived to scarify the cupboard with it, and was arranging to begin -on the bureau, when he was called off to dress for Sunday-school. - -Mary gave him a tin basin of water and a piece of soap, and he went -outside the door and set the basin on a little bench there; then he -dipped the soap in the water and laid it down; turned up his sleeves; -poured out the water on the ground, gently, and then entered the -kitchen and began to wipe his face diligently on the towel behind the -door. But Mary removed the towel and said: - -"Now ain't you ashamed, Tom. You mustn't be so bad. Water won't hurt -you." - -Tom was a trifle disconcerted. The basin was refilled, and this time -he stood over it a little while, gathering resolution; took in a big -breath and began. When he entered the kitchen presently, with both eyes -shut and groping for the towel with his hands, an honorable testimony -of suds and water was dripping from his face. But when he emerged from -the towel, he was not yet satisfactory, for the clean territory stopped -short at his chin and his jaws, like a mask; below and beyond this line -there was a dark expanse of unirrigated soil that spread downward in -front and backward around his neck. Mary took him in hand, and when she -was done with him he was a man and a brother, without distinction of -color, and his saturated hair was neatly brushed, and its short curls -wrought into a dainty and symmetrical general effect. [He privately -smoothed out the curls, with labor and difficulty, and plastered his -hair close down to his head; for he held curls to be effeminate, and -his own filled his life with bitterness.] Then Mary got out a suit of -his clothing that had been used only on Sundays during two years--they -were simply called his "other clothes"--and so by that we know the -size of his wardrobe. The girl "put him to rights" after he had dressed -himself; she buttoned his neat roundabout up to his chin, turned his -vast shirt collar down over his shoulders, brushed him off and crowned -him with his speckled straw hat. He now looked exceedingly improved and -uncomfortable. He was fully as uncomfortable as he looked; for there -was a restraint about whole clothes and cleanliness that galled him. He -hoped that Mary would forget his shoes, but the hope was blighted; she -coated them thoroughly with tallow, as was the custom, and brought them -out. He lost his temper and said he was always being made to do -everything he didn't want to do. But Mary said, persuasively: - -"Please, Tom--that's a good boy." - -So he got into the shoes snarling. Mary was soon ready, and the three -children set out for Sunday-school--a place that Tom hated with his -whole heart; but Sid and Mary were fond of it. - -Sabbath-school hours were from nine to half-past ten; and then church -service. Two of the children always remained for the sermon -voluntarily, and the other always remained too--for stronger reasons. -The church's high-backed, uncushioned pews would seat about three -hundred persons; the edifice was but a small, plain affair, with a sort -of pine board tree-box on top of it for a steeple. At the door Tom -dropped back a step and accosted a Sunday-dressed comrade: - -"Say, Billy, got a yaller ticket?" - -"Yes." - -"What'll you take for her?" - -"What'll you give?" - -"Piece of lickrish and a fish-hook." - -"Less see 'em." - -Tom exhibited. They were satisfactory, and the property changed hands. -Then Tom traded a couple of white alleys for three red tickets, and -some small trifle or other for a couple of blue ones. He waylaid other -boys as they came, and went on buying tickets of various colors ten or -fifteen minutes longer. He entered the church, now, with a swarm of -clean and noisy boys and girls, proceeded to his seat and started a -quarrel with the first boy that came handy. The teacher, a grave, -elderly man, interfered; then turned his back a moment and Tom pulled a -boy's hair in the next bench, and was absorbed in his book when the boy -turned around; stuck a pin in another boy, presently, in order to hear -him say "Ouch!" and got a new reprimand from his teacher. Tom's whole -class were of a pattern--restless, noisy, and troublesome. When they -came to recite their lessons, not one of them knew his verses -perfectly, but had to be prompted all along. However, they worried -through, and each got his reward--in small blue tickets, each with a -passage of Scripture on it; each blue ticket was pay for two verses of -the recitation. Ten blue tickets equalled a red one, and could be -exchanged for it; ten red tickets equalled a yellow one; for ten yellow -tickets the superintendent gave a very plainly bound Bible (worth forty -cents in those easy times) to the pupil. How many of my readers would -have the industry and application to memorize two thousand verses, even -for a Dore Bible? And yet Mary had acquired two Bibles in this way--it -was the patient work of two years--and a boy of German parentage had -won four or five. He once recited three thousand verses without -stopping; but the strain upon his mental faculties was too great, and -he was little better than an idiot from that day forth--a grievous -misfortune for the school, for on great occasions, before company, the -superintendent (as Tom expressed it) had always made this boy come out -and "spread himself." Only the older pupils managed to keep their -tickets and stick to their tedious work long enough to get a Bible, and -so the delivery of one of these prizes was a rare and noteworthy -circumstance; the successful pupil was so great and conspicuous for -that day that on the spot every scholar's heart was fired with a fresh -ambition that often lasted a couple of weeks. It is possible that Tom's -mental stomach had never really hungered for one of those prizes, but -unquestionably his entire being had for many a day longed for the glory -and the eclat that came with it. - -In due course the superintendent stood up in front of the pulpit, with -a closed hymn-book in his hand and his forefinger inserted between its -leaves, and commanded attention. When a Sunday-school superintendent -makes his customary little speech, a hymn-book in the hand is as -necessary as is the inevitable sheet of music in the hand of a singer -who stands forward on the platform and sings a solo at a concert ---though why, is a mystery: for neither the hymn-book nor the sheet of -music is ever referred to by the sufferer. This superintendent was a -slim creature of thirty-five, with a sandy goatee and short sandy hair; -he wore a stiff standing-collar whose upper edge almost reached his -ears and whose sharp points curved forward abreast the corners of his -mouth--a fence that compelled a straight lookout ahead, and a turning -of the whole body when a side view was required; his chin was propped -on a spreading cravat which was as broad and as long as a bank-note, -and had fringed ends; his boot toes were turned sharply up, in the -fashion of the day, like sleigh-runners--an effect patiently and -laboriously produced by the young men by sitting with their toes -pressed against a wall for hours together. Mr. Walters was very earnest -of mien, and very sincere and honest at heart; and he held sacred -things and places in such reverence, and so separated them from worldly -matters, that unconsciously to himself his Sunday-school voice had -acquired a peculiar intonation which was wholly absent on week-days. He -began after this fashion: - -"Now, children, I want you all to sit up just as straight and pretty -as you can and give me all your attention for a minute or two. There ---that is it. That is the way good little boys and girls should do. I see -one little girl who is looking out of the window--I am afraid she -thinks I am out there somewhere--perhaps up in one of the trees making -a speech to the little birds. [Applausive titter.] I want to tell you -how good it makes me feel to see so many bright, clean little faces -assembled in a place like this, learning to do right and be good." And -so forth and so on. It is not necessary to set down the rest of the -oration. It was of a pattern which does not vary, and so it is familiar -to us all. - -The latter third of the speech was marred by the resumption of fights -and other recreations among certain of the bad boys, and by fidgetings -and whisperings that extended far and wide, washing even to the bases -of isolated and incorruptible rocks like Sid and Mary. But now every -sound ceased suddenly, with the subsidence of Mr. Walters' voice, and -the conclusion of the speech was received with a burst of silent -gratitude. - -A good part of the whispering had been occasioned by an event which -was more or less rare--the entrance of visitors: lawyer Thatcher, -accompanied by a very feeble and aged man; a fine, portly, middle-aged -gentleman with iron-gray hair; and a dignified lady who was doubtless -the latter's wife. The lady was leading a child. Tom had been restless -and full of chafings and repinings; conscience-smitten, too--he could -not meet Amy Lawrence's eye, he could not brook her loving gaze. But -when he saw this small new-comer his soul was all ablaze with bliss in -a moment. The next moment he was "showing off" with all his might ---cuffing boys, pulling hair, making faces--in a word, using every art -that seemed likely to fascinate a girl and win her applause. His -exaltation had but one alloy--the memory of his humiliation in this -angel's garden--and that record in sand was fast washing out, under -the waves of happiness that were sweeping over it now. - -The visitors were given the highest seat of honor, and as soon as Mr. -Walters' speech was finished, he introduced them to the school. The -middle-aged man turned out to be a prodigious personage--no less a one -than the county judge--altogether the most august creation these -children had ever looked upon--and they wondered what kind of material -he was made of--and they half wanted to hear him roar, and were half -afraid he might, too. He was from Constantinople, twelve miles away--so -he had travelled, and seen the world--these very eyes had looked upon -the county court-house--which was said to have a tin roof. The awe -which these reflections inspired was attested by the impressive silence -and the ranks of staring eyes. This was the great Judge Thatcher, -brother of their own lawyer. Jeff Thatcher immediately went forward, to -be familiar with the great man and be envied by the school. It would -have been music to his soul to hear the whisperings: - -"Look at him, Jim! He's a going up there. Say--look! he's a going to -shake hands with him--he IS shaking hands with him! By jings, don't you -wish you was Jeff?" - -Mr. Walters fell to "showing off," with all sorts of official -bustlings and activities, giving orders, delivering judgments, -discharging directions here, there, everywhere that he could find a -target. The librarian "showed off"--running hither and thither with his -arms full of books and making a deal of the splutter and fuss that -insect authority delights in. The young lady teachers "showed off" ---bending sweetly over pupils that were lately being boxed, lifting -pretty warning fingers at bad little boys and patting good ones -lovingly. The young gentlemen teachers "showed off" with small -scoldings and other little displays of authority and fine attention to -discipline--and most of the teachers, of both sexes, found business up -at the library, by the pulpit; and it was business that frequently had -to be done over again two or three times (with much seeming vexation). -The little girls "showed off" in various ways, and the little boys -"showed off" with such diligence that the air was thick with paper wads -and the murmur of scufflings. And above it all the great man sat and -beamed a majestic judicial smile upon all the house, and warmed himself -in the sun of his own grandeur--for he was "showing off," too. - -There was only one thing wanting to make Mr. Walters' ecstasy -complete, and that was a chance to deliver a Bible-prize and exhibit a -prodigy. Several pupils had a few yellow tickets, but none had enough ---he had been around among the star pupils inquiring. He would have given -worlds, now, to have that German lad back again with a sound mind. - -And now at this moment, when hope was dead, Tom Sawyer came forward -with nine yellow tickets, nine red tickets, and ten blue ones, and -demanded a Bible. This was a thunderbolt out of a clear sky. Walters -was not expecting an application from this source for the next ten -years. But there was no getting around it--here were the certified -checks, and they were good for their face. Tom was therefore elevated -to a place with the Judge and the other elect, and the great news was -announced from headquarters. It was the most stunning surprise of the -decade, and so profound was the sensation that it lifted the new hero -up to the judicial one's altitude, and the school had two marvels to -gaze upon in place of one. The boys were all eaten up with envy--but -those that suffered the bitterest pangs were those who perceived too -late that they themselves had contributed to this hated splendor by -trading tickets to Tom for the wealth he had amassed in selling -whitewashing privileges. These despised themselves, as being the dupes -of a wily fraud, a guileful snake in the grass. - -The prize was delivered to Tom with as much effusion as the -superintendent could pump up under the circumstances; but it lacked -somewhat of the true gush, for the poor fellow's instinct taught him -that there was a mystery here that could not well bear the light, -perhaps; it was simply preposterous that this boy had warehoused two -thousand sheaves of Scriptural wisdom on his premises--a dozen would -strain his capacity, without a doubt. - -Amy Lawrence was proud and glad, and she tried to make Tom see it in -her face--but he wouldn't look. She wondered; then she was just a grain -troubled; next a dim suspicion came and went--came again; she watched; -a furtive glance told her worlds--and then her heart broke, and she was -jealous, and angry, and the tears came and she hated everybody. Tom -most of all (she thought). - -Tom was introduced to the Judge; but his tongue was tied, his breath -would hardly come, his heart quaked--partly because of the awful -greatness of the man, but mainly because he was her parent. He would -have liked to fall down and worship him, if it were in the dark. The -Judge put his hand on Tom's head and called him a fine little man, and -asked him what his name was. The boy stammered, gasped, and got it out: - -"Tom." - -"Oh, no, not Tom--it is--" - -"Thomas." - -"Ah, that's it. I thought there was more to it, maybe. That's very -well. But you've another one I daresay, and you'll tell it to me, won't -you?" - -"Tell the gentleman your other name, Thomas," said Walters, "and say -sir. You mustn't forget your manners." - -"Thomas Sawyer--sir." - -"That's it! That's a good boy. Fine boy. Fine, manly little fellow. -Two thousand verses is a great many--very, very great many. And you -never can be sorry for the trouble you took to learn them; for -knowledge is worth more than anything there is in the world; it's what -makes great men and good men; you'll be a great man and a good man -yourself, some day, Thomas, and then you'll look back and say, It's all -owing to the precious Sunday-school privileges of my boyhood--it's all -owing to my dear teachers that taught me to learn--it's all owing to -the good superintendent, who encouraged me, and watched over me, and -gave me a beautiful Bible--a splendid elegant Bible--to keep and have -it all for my own, always--it's all owing to right bringing up! That is -what you will say, Thomas--and you wouldn't take any money for those -two thousand verses--no indeed you wouldn't. And now you wouldn't mind -telling me and this lady some of the things you've learned--no, I know -you wouldn't--for we are proud of little boys that learn. Now, no -doubt you know the names of all the twelve disciples. Won't you tell us -the names of the first two that were appointed?" - -Tom was tugging at a button-hole and looking sheepish. He blushed, -now, and his eyes fell. Mr. Walters' heart sank within him. He said to -himself, it is not possible that the boy can answer the simplest -question--why DID the Judge ask him? Yet he felt obliged to speak up -and say: - -"Answer the gentleman, Thomas--don't be afraid." - -Tom still hung fire. - -"Now I know you'll tell me," said the lady. "The names of the first -two disciples were--" - -"DAVID AND GOLIAH!" - -Let us draw the curtain of charity over the rest of the scene. - - - -CHAPTER V - -ABOUT half-past ten the cracked bell of the small church began to -ring, and presently the people began to gather for the morning sermon. -The Sunday-school children distributed themselves about the house and -occupied pews with their parents, so as to be under supervision. Aunt -Polly came, and Tom and Sid and Mary sat with her--Tom being placed -next the aisle, in order that he might be as far away from the open -window and the seductive outside summer scenes as possible. The crowd -filed up the aisles: the aged and needy postmaster, who had seen better -days; the mayor and his wife--for they had a mayor there, among other -unnecessaries; the justice of the peace; the widow Douglass, fair, -smart, and forty, a generous, good-hearted soul and well-to-do, her -hill mansion the only palace in the town, and the most hospitable and -much the most lavish in the matter of festivities that St. Petersburg -could boast; the bent and venerable Major and Mrs. Ward; lawyer -Riverson, the new notable from a distance; next the belle of the -village, followed by a troop of lawn-clad and ribbon-decked young -heart-breakers; then all the young clerks in town in a body--for they -had stood in the vestibule sucking their cane-heads, a circling wall of -oiled and simpering admirers, till the last girl had run their gantlet; -and last of all came the Model Boy, Willie Mufferson, taking as heedful -care of his mother as if she were cut glass. He always brought his -mother to church, and was the pride of all the matrons. The boys all -hated him, he was so good. And besides, he had been "thrown up to them" -so much. His white handkerchief was hanging out of his pocket behind, as -usual on Sundays--accidentally. Tom had no handkerchief, and he looked -upon boys who had as snobs. - -The congregation being fully assembled, now, the bell rang once more, -to warn laggards and stragglers, and then a solemn hush fell upon the -church which was only broken by the tittering and whispering of the -choir in the gallery. The choir always tittered and whispered all -through service. There was once a church choir that was not ill-bred, -but I have forgotten where it was, now. It was a great many years ago, -and I can scarcely remember anything about it, but I think it was in -some foreign country. - -The minister gave out the hymn, and read it through with a relish, in -a peculiar style which was much admired in that part of the country. -His voice began on a medium key and climbed steadily up till it reached -a certain point, where it bore with strong emphasis upon the topmost -word and then plunged down as if from a spring-board: - - Shall I be car-ri-ed toe the skies, on flow'ry BEDS of ease, - - Whilst others fight to win the prize, and sail thro' BLOODY seas? - -He was regarded as a wonderful reader. At church "sociables" he was -always called upon to read poetry; and when he was through, the ladies -would lift up their hands and let them fall helplessly in their laps, -and "wall" their eyes, and shake their heads, as much as to say, "Words -cannot express it; it is too beautiful, TOO beautiful for this mortal -earth." - -After the hymn had been sung, the Rev. Mr. Sprague turned himself into -a bulletin-board, and read off "notices" of meetings and societies and -things till it seemed that the list would stretch out to the crack of -doom--a queer custom which is still kept up in America, even in cities, -away here in this age of abundant newspapers. Often, the less there is -to justify a traditional custom, the harder it is to get rid of it. - -And now the minister prayed. A good, generous prayer it was, and went -into details: it pleaded for the church, and the little children of the -church; for the other churches of the village; for the village itself; -for the county; for the State; for the State officers; for the United -States; for the churches of the United States; for Congress; for the -President; for the officers of the Government; for poor sailors, tossed -by stormy seas; for the oppressed millions groaning under the heel of -European monarchies and Oriental despotisms; for such as have the light -and the good tidings, and yet have not eyes to see nor ears to hear -withal; for the heathen in the far islands of the sea; and closed with -a supplication that the words he was about to speak might find grace -and favor, and be as seed sown in fertile ground, yielding in time a -grateful harvest of good. Amen. - -There was a rustling of dresses, and the standing congregation sat -down. The boy whose history this book relates did not enjoy the prayer, -he only endured it--if he even did that much. He was restive all -through it; he kept tally of the details of the prayer, unconsciously ---for he was not listening, but he knew the ground of old, and the -clergyman's regular route over it--and when a little trifle of new -matter was interlarded, his ear detected it and his whole nature -resented it; he considered additions unfair, and scoundrelly. In the -midst of the prayer a fly had lit on the back of the pew in front of -him and tortured his spirit by calmly rubbing its hands together, -embracing its head with its arms, and polishing it so vigorously that -it seemed to almost part company with the body, and the slender thread -of a neck was exposed to view; scraping its wings with its hind legs -and smoothing them to its body as if they had been coat-tails; going -through its whole toilet as tranquilly as if it knew it was perfectly -safe. As indeed it was; for as sorely as Tom's hands itched to grab for -it they did not dare--he believed his soul would be instantly destroyed -if he did such a thing while the prayer was going on. But with the -closing sentence his hand began to curve and steal forward; and the -instant the "Amen" was out the fly was a prisoner of war. His aunt -detected the act and made him let it go. - -The minister gave out his text and droned along monotonously through -an argument that was so prosy that many a head by and by began to nod ---and yet it was an argument that dealt in limitless fire and brimstone -and thinned the predestined elect down to a company so small as to be -hardly worth the saving. Tom counted the pages of the sermon; after -church he always knew how many pages there had been, but he seldom knew -anything else about the discourse. However, this time he was really -interested for a little while. The minister made a grand and moving -picture of the assembling together of the world's hosts at the -millennium when the lion and the lamb should lie down together and a -little child should lead them. But the pathos, the lesson, the moral of -the great spectacle were lost upon the boy; he only thought of the -conspicuousness of the principal character before the on-looking -nations; his face lit with the thought, and he said to himself that he -wished he could be that child, if it was a tame lion. - -Now he lapsed into suffering again, as the dry argument was resumed. -Presently he bethought him of a treasure he had and got it out. It was -a large black beetle with formidable jaws--a "pinchbug," he called it. -It was in a percussion-cap box. The first thing the beetle did was to -take him by the finger. A natural fillip followed, the beetle went -floundering into the aisle and lit on its back, and the hurt finger -went into the boy's mouth. The beetle lay there working its helpless -legs, unable to turn over. Tom eyed it, and longed for it; but it was -safe out of his reach. Other people uninterested in the sermon found -relief in the beetle, and they eyed it too. Presently a vagrant poodle -dog came idling along, sad at heart, lazy with the summer softness and -the quiet, weary of captivity, sighing for change. He spied the beetle; -the drooping tail lifted and wagged. He surveyed the prize; walked -around it; smelt at it from a safe distance; walked around it again; -grew bolder, and took a closer smell; then lifted his lip and made a -gingerly snatch at it, just missing it; made another, and another; -began to enjoy the diversion; subsided to his stomach with the beetle -between his paws, and continued his experiments; grew weary at last, -and then indifferent and absent-minded. His head nodded, and little by -little his chin descended and touched the enemy, who seized it. There -was a sharp yelp, a flirt of the poodle's head, and the beetle fell a -couple of yards away, and lit on its back once more. The neighboring -spectators shook with a gentle inward joy, several faces went behind -fans and handkerchiefs, and Tom was entirely happy. The dog looked -foolish, and probably felt so; but there was resentment in his heart, -too, and a craving for revenge. So he went to the beetle and began a -wary attack on it again; jumping at it from every point of a circle, -lighting with his fore-paws within an inch of the creature, making even -closer snatches at it with his teeth, and jerking his head till his -ears flapped again. But he grew tired once more, after a while; tried -to amuse himself with a fly but found no relief; followed an ant -around, with his nose close to the floor, and quickly wearied of that; -yawned, sighed, forgot the beetle entirely, and sat down on it. Then -there was a wild yelp of agony and the poodle went sailing up the -aisle; the yelps continued, and so did the dog; he crossed the house in -front of the altar; he flew down the other aisle; he crossed before the -doors; he clamored up the home-stretch; his anguish grew with his -progress, till presently he was but a woolly comet moving in its orbit -with the gleam and the speed of light. At last the frantic sufferer -sheered from its course, and sprang into its master's lap; he flung it -out of the window, and the voice of distress quickly thinned away and -died in the distance. - -By this time the whole church was red-faced and suffocating with -suppressed laughter, and the sermon had come to a dead standstill. The -discourse was resumed presently, but it went lame and halting, all -possibility of impressiveness being at an end; for even the gravest -sentiments were constantly being received with a smothered burst of -unholy mirth, under cover of some remote pew-back, as if the poor -parson had said a rarely facetious thing. It was a genuine relief to -the whole congregation when the ordeal was over and the benediction -pronounced. - -Tom Sawyer went home quite cheerful, thinking to himself that there -was some satisfaction about divine service when there was a bit of -variety in it. He had but one marring thought; he was willing that the -dog should play with his pinchbug, but he did not think it was upright -in him to carry it off. - - - -CHAPTER VI - -MONDAY morning found Tom Sawyer miserable. Monday morning always found -him so--because it began another week's slow suffering in school. He -generally began that day with wishing he had had no intervening -holiday, it made the going into captivity and fetters again so much -more odious. - -Tom lay thinking. Presently it occurred to him that he wished he was -sick; then he could stay home from school. Here was a vague -possibility. He canvassed his system. No ailment was found, and he -investigated again. This time he thought he could detect colicky -symptoms, and he began to encourage them with considerable hope. But -they soon grew feeble, and presently died wholly away. He reflected -further. Suddenly he discovered something. One of his upper front teeth -was loose. This was lucky; he was about to begin to groan, as a -"starter," as he called it, when it occurred to him that if he came -into court with that argument, his aunt would pull it out, and that -would hurt. So he thought he would hold the tooth in reserve for the -present, and seek further. Nothing offered for some little time, and -then he remembered hearing the doctor tell about a certain thing that -laid up a patient for two or three weeks and threatened to make him -lose a finger. So the boy eagerly drew his sore toe from under the -sheet and held it up for inspection. But now he did not know the -necessary symptoms. However, it seemed well worth while to chance it, -so he fell to groaning with considerable spirit. - -But Sid slept on unconscious. - -Tom groaned louder, and fancied that he began to feel pain in the toe. - -No result from Sid. - -Tom was panting with his exertions by this time. He took a rest and -then swelled himself up and fetched a succession of admirable groans. - -Sid snored on. - -Tom was aggravated. He said, "Sid, Sid!" and shook him. This course -worked well, and Tom began to groan again. Sid yawned, stretched, then -brought himself up on his elbow with a snort, and began to stare at -Tom. Tom went on groaning. Sid said: - -"Tom! Say, Tom!" [No response.] "Here, Tom! TOM! What is the matter, -Tom?" And he shook him and looked in his face anxiously. - -Tom moaned out: - -"Oh, don't, Sid. Don't joggle me." - -"Why, what's the matter, Tom? I must call auntie." - -"No--never mind. It'll be over by and by, maybe. Don't call anybody." - -"But I must! DON'T groan so, Tom, it's awful. How long you been this -way?" - -"Hours. Ouch! Oh, don't stir so, Sid, you'll kill me." - -"Tom, why didn't you wake me sooner? Oh, Tom, DON'T! It makes my -flesh crawl to hear you. Tom, what is the matter?" - -"I forgive you everything, Sid. [Groan.] Everything you've ever done -to me. When I'm gone--" - -"Oh, Tom, you ain't dying, are you? Don't, Tom--oh, don't. Maybe--" - -"I forgive everybody, Sid. [Groan.] Tell 'em so, Sid. And Sid, you -give my window-sash and my cat with one eye to that new girl that's -come to town, and tell her--" - -But Sid had snatched his clothes and gone. Tom was suffering in -reality, now, so handsomely was his imagination working, and so his -groans had gathered quite a genuine tone. - -Sid flew down-stairs and said: - -"Oh, Aunt Polly, come! Tom's dying!" - -"Dying!" - -"Yes'm. Don't wait--come quick!" - -"Rubbage! I don't believe it!" - -But she fled up-stairs, nevertheless, with Sid and Mary at her heels. -And her face grew white, too, and her lip trembled. When she reached -the bedside she gasped out: - -"You, Tom! Tom, what's the matter with you?" - -"Oh, auntie, I'm--" - -"What's the matter with you--what is the matter with you, child?" - -"Oh, auntie, my sore toe's mortified!" - -The old lady sank down into a chair and laughed a little, then cried a -little, then did both together. This restored her and she said: - -"Tom, what a turn you did give me. Now you shut up that nonsense and -climb out of this." - -The groans ceased and the pain vanished from the toe. The boy felt a -little foolish, and he said: - -"Aunt Polly, it SEEMED mortified, and it hurt so I never minded my -tooth at all." - -"Your tooth, indeed! What's the matter with your tooth?" - -"One of them's loose, and it aches perfectly awful." - -"There, there, now, don't begin that groaning again. Open your mouth. -Well--your tooth IS loose, but you're not going to die about that. -Mary, get me a silk thread, and a chunk of fire out of the kitchen." - -Tom said: - -"Oh, please, auntie, don't pull it out. It don't hurt any more. I wish -I may never stir if it does. Please don't, auntie. I don't want to stay -home from school." - -"Oh, you don't, don't you? So all this row was because you thought -you'd get to stay home from school and go a-fishing? Tom, Tom, I love -you so, and you seem to try every way you can to break my old heart -with your outrageousness." By this time the dental instruments were -ready. The old lady made one end of the silk thread fast to Tom's tooth -with a loop and tied the other to the bedpost. Then she seized the -chunk of fire and suddenly thrust it almost into the boy's face. The -tooth hung dangling by the bedpost, now. - -But all trials bring their compensations. As Tom wended to school -after breakfast, he was the envy of every boy he met because the gap in -his upper row of teeth enabled him to expectorate in a new and -admirable way. He gathered quite a following of lads interested in the -exhibition; and one that had cut his finger and had been a centre of -fascination and homage up to this time, now found himself suddenly -without an adherent, and shorn of his glory. His heart was heavy, and -he said with a disdain which he did not feel that it wasn't anything to -spit like Tom Sawyer; but another boy said, "Sour grapes!" and he -wandered away a dismantled hero. - -Shortly Tom came upon the juvenile pariah of the village, Huckleberry -Finn, son of the town drunkard. Huckleberry was cordially hated and -dreaded by all the mothers of the town, because he was idle and lawless -and vulgar and bad--and because all their children admired him so, and -delighted in his forbidden society, and wished they dared to be like -him. Tom was like the rest of the respectable boys, in that he envied -Huckleberry his gaudy outcast condition, and was under strict orders -not to play with him. So he played with him every time he got a chance. -Huckleberry was always dressed in the cast-off clothes of full-grown -men, and they were in perennial bloom and fluttering with rags. His hat -was a vast ruin with a wide crescent lopped out of its brim; his coat, -when he wore one, hung nearly to his heels and had the rearward buttons -far down the back; but one suspender supported his trousers; the seat -of the trousers bagged low and contained nothing, the fringed legs -dragged in the dirt when not rolled up. - -Huckleberry came and went, at his own free will. He slept on doorsteps -in fine weather and in empty hogsheads in wet; he did not have to go to -school or to church, or call any being master or obey anybody; he could -go fishing or swimming when and where he chose, and stay as long as it -suited him; nobody forbade him to fight; he could sit up as late as he -pleased; he was always the first boy that went barefoot in the spring -and the last to resume leather in the fall; he never had to wash, nor -put on clean clothes; he could swear wonderfully. In a word, everything -that goes to make life precious that boy had. So thought every -harassed, hampered, respectable boy in St. Petersburg. - -Tom hailed the romantic outcast: - -"Hello, Huckleberry!" - -"Hello yourself, and see how you like it." - -"What's that you got?" - -"Dead cat." - -"Lemme see him, Huck. My, he's pretty stiff. Where'd you get him?" - -"Bought him off'n a boy." - -"What did you give?" - -"I give a blue ticket and a bladder that I got at the slaughter-house." - -"Where'd you get the blue ticket?" - -"Bought it off'n Ben Rogers two weeks ago for a hoop-stick." - -"Say--what is dead cats good for, Huck?" - -"Good for? Cure warts with." - -"No! Is that so? I know something that's better." - -"I bet you don't. What is it?" - -"Why, spunk-water." - -"Spunk-water! I wouldn't give a dern for spunk-water." - -"You wouldn't, wouldn't you? D'you ever try it?" - -"No, I hain't. But Bob Tanner did." - -"Who told you so!" - -"Why, he told Jeff Thatcher, and Jeff told Johnny Baker, and Johnny -told Jim Hollis, and Jim told Ben Rogers, and Ben told a nigger, and -the nigger told me. There now!" - -"Well, what of it? They'll all lie. Leastways all but the nigger. I -don't know HIM. But I never see a nigger that WOULDN'T lie. Shucks! Now -you tell me how Bob Tanner done it, Huck." - -"Why, he took and dipped his hand in a rotten stump where the -rain-water was." - -"In the daytime?" - -"Certainly." - -"With his face to the stump?" - -"Yes. Least I reckon so." - -"Did he say anything?" - -"I don't reckon he did. I don't know." - -"Aha! Talk about trying to cure warts with spunk-water such a blame -fool way as that! Why, that ain't a-going to do any good. You got to go -all by yourself, to the middle of the woods, where you know there's a -spunk-water stump, and just as it's midnight you back up against the -stump and jam your hand in and say: - - 'Barley-corn, barley-corn, injun-meal shorts, - Spunk-water, spunk-water, swaller these warts,' - -and then walk away quick, eleven steps, with your eyes shut, and then -turn around three times and walk home without speaking to anybody. -Because if you speak the charm's busted." - -"Well, that sounds like a good way; but that ain't the way Bob Tanner -done." - -"No, sir, you can bet he didn't, becuz he's the wartiest boy in this -town; and he wouldn't have a wart on him if he'd knowed how to work -spunk-water. I've took off thousands of warts off of my hands that way, -Huck. I play with frogs so much that I've always got considerable many -warts. Sometimes I take 'em off with a bean." - -"Yes, bean's good. I've done that." - -"Have you? What's your way?" - -"You take and split the bean, and cut the wart so as to get some -blood, and then you put the blood on one piece of the bean and take and -dig a hole and bury it 'bout midnight at the crossroads in the dark of -the moon, and then you burn up the rest of the bean. You see that piece -that's got the blood on it will keep drawing and drawing, trying to -fetch the other piece to it, and so that helps the blood to draw the -wart, and pretty soon off she comes." - -"Yes, that's it, Huck--that's it; though when you're burying it if you -say 'Down bean; off wart; come no more to bother me!' it's better. -That's the way Joe Harper does, and he's been nearly to Coonville and -most everywheres. But say--how do you cure 'em with dead cats?" - -"Why, you take your cat and go and get in the graveyard 'long about -midnight when somebody that was wicked has been buried; and when it's -midnight a devil will come, or maybe two or three, but you can't see -'em, you can only hear something like the wind, or maybe hear 'em talk; -and when they're taking that feller away, you heave your cat after 'em -and say, 'Devil follow corpse, cat follow devil, warts follow cat, I'm -done with ye!' That'll fetch ANY wart." - -"Sounds right. D'you ever try it, Huck?" - -"No, but old Mother Hopkins told me." - -"Well, I reckon it's so, then. Becuz they say she's a witch." - -"Say! Why, Tom, I KNOW she is. She witched pap. Pap says so his own -self. He come along one day, and he see she was a-witching him, so he -took up a rock, and if she hadn't dodged, he'd a got her. Well, that -very night he rolled off'n a shed wher' he was a layin drunk, and broke -his arm." - -"Why, that's awful. How did he know she was a-witching him?" - -"Lord, pap can tell, easy. Pap says when they keep looking at you -right stiddy, they're a-witching you. Specially if they mumble. Becuz -when they mumble they're saying the Lord's Prayer backards." - -"Say, Hucky, when you going to try the cat?" - -"To-night. I reckon they'll come after old Hoss Williams to-night." - -"But they buried him Saturday. Didn't they get him Saturday night?" - -"Why, how you talk! How could their charms work till midnight?--and -THEN it's Sunday. Devils don't slosh around much of a Sunday, I don't -reckon." - -"I never thought of that. That's so. Lemme go with you?" - -"Of course--if you ain't afeard." - -"Afeard! 'Tain't likely. Will you meow?" - -"Yes--and you meow back, if you get a chance. Last time, you kep' me -a-meowing around till old Hays went to throwing rocks at me and says -'Dern that cat!' and so I hove a brick through his window--but don't -you tell." - -"I won't. I couldn't meow that night, becuz auntie was watching me, -but I'll meow this time. Say--what's that?" - -"Nothing but a tick." - -"Where'd you get him?" - -"Out in the woods." - -"What'll you take for him?" - -"I don't know. I don't want to sell him." - -"All right. It's a mighty small tick, anyway." - -"Oh, anybody can run a tick down that don't belong to them. I'm -satisfied with it. It's a good enough tick for me." - -"Sho, there's ticks a plenty. I could have a thousand of 'em if I -wanted to." - -"Well, why don't you? Becuz you know mighty well you can't. This is a -pretty early tick, I reckon. It's the first one I've seen this year." - -"Say, Huck--I'll give you my tooth for him." - -"Less see it." - -Tom got out a bit of paper and carefully unrolled it. Huckleberry -viewed it wistfully. The temptation was very strong. At last he said: - -"Is it genuwyne?" - -Tom lifted his lip and showed the vacancy. - -"Well, all right," said Huckleberry, "it's a trade." - -Tom enclosed the tick in the percussion-cap box that had lately been -the pinchbug's prison, and the boys separated, each feeling wealthier -than before. - -When Tom reached the little isolated frame schoolhouse, he strode in -briskly, with the manner of one who had come with all honest speed. -He hung his hat on a peg and flung himself into his seat with -business-like alacrity. The master, throned on high in his great -splint-bottom arm-chair, was dozing, lulled by the drowsy hum of study. -The interruption roused him. - -"Thomas Sawyer!" - -Tom knew that when his name was pronounced in full, it meant trouble. - -"Sir!" - -"Come up here. Now, sir, why are you late again, as usual?" - -Tom was about to take refuge in a lie, when he saw two long tails of -yellow hair hanging down a back that he recognized by the electric -sympathy of love; and by that form was THE ONLY VACANT PLACE on the -girls' side of the schoolhouse. He instantly said: - -"I STOPPED TO TALK WITH HUCKLEBERRY FINN!" - -The master's pulse stood still, and he stared helplessly. The buzz of -study ceased. The pupils wondered if this foolhardy boy had lost his -mind. The master said: - -"You--you did what?" - -"Stopped to talk with Huckleberry Finn." - -There was no mistaking the words. - -"Thomas Sawyer, this is the most astounding confession I have ever -listened to. No mere ferule will answer for this offence. Take off your -jacket." - -The master's arm performed until it was tired and the stock of -switches notably diminished. Then the order followed: - -"Now, sir, go and sit with the girls! And let this be a warning to you." - -The titter that rippled around the room appeared to abash the boy, but -in reality that result was caused rather more by his worshipful awe of -his unknown idol and the dread pleasure that lay in his high good -fortune. He sat down upon the end of the pine bench and the girl -hitched herself away from him with a toss of her head. Nudges and winks -and whispers traversed the room, but Tom sat still, with his arms upon -the long, low desk before him, and seemed to study his book. - -By and by attention ceased from him, and the accustomed school murmur -rose upon the dull air once more. Presently the boy began to steal -furtive glances at the girl. She observed it, "made a mouth" at him and -gave him the back of her head for the space of a minute. When she -cautiously faced around again, a peach lay before her. She thrust it -away. Tom gently put it back. She thrust it away again, but with less -animosity. Tom patiently returned it to its place. Then she let it -remain. Tom scrawled on his slate, "Please take it--I got more." The -girl glanced at the words, but made no sign. Now the boy began to draw -something on the slate, hiding his work with his left hand. For a time -the girl refused to notice; but her human curiosity presently began to -manifest itself by hardly perceptible signs. The boy worked on, -apparently unconscious. The girl made a sort of noncommittal attempt to -see, but the boy did not betray that he was aware of it. At last she -gave in and hesitatingly whispered: - -"Let me see it." - -Tom partly uncovered a dismal caricature of a house with two gable -ends to it and a corkscrew of smoke issuing from the chimney. Then the -girl's interest began to fasten itself upon the work and she forgot -everything else. When it was finished, she gazed a moment, then -whispered: - -"It's nice--make a man." - -The artist erected a man in the front yard, that resembled a derrick. -He could have stepped over the house; but the girl was not -hypercritical; she was satisfied with the monster, and whispered: - -"It's a beautiful man--now make me coming along." - -Tom drew an hour-glass with a full moon and straw limbs to it and -armed the spreading fingers with a portentous fan. The girl said: - -"It's ever so nice--I wish I could draw." - -"It's easy," whispered Tom, "I'll learn you." - -"Oh, will you? When?" - -"At noon. Do you go home to dinner?" - -"I'll stay if you will." - -"Good--that's a whack. What's your name?" - -"Becky Thatcher. What's yours? Oh, I know. It's Thomas Sawyer." - -"That's the name they lick me by. I'm Tom when I'm good. You call me -Tom, will you?" - -"Yes." - -Now Tom began to scrawl something on the slate, hiding the words from -the girl. But she was not backward this time. She begged to see. Tom -said: - -"Oh, it ain't anything." - -"Yes it is." - -"No it ain't. You don't want to see." - -"Yes I do, indeed I do. Please let me." - -"You'll tell." - -"No I won't--deed and deed and double deed won't." - -"You won't tell anybody at all? Ever, as long as you live?" - -"No, I won't ever tell ANYbody. Now let me." - -"Oh, YOU don't want to see!" - -"Now that you treat me so, I WILL see." And she put her small hand -upon his and a little scuffle ensued, Tom pretending to resist in -earnest but letting his hand slip by degrees till these words were -revealed: "I LOVE YOU." - -"Oh, you bad thing!" And she hit his hand a smart rap, but reddened -and looked pleased, nevertheless. - -Just at this juncture the boy felt a slow, fateful grip closing on his -ear, and a steady lifting impulse. In that wise he was borne across the -house and deposited in his own seat, under a peppering fire of giggles -from the whole school. Then the master stood over him during a few -awful moments, and finally moved away to his throne without saying a -word. But although Tom's ear tingled, his heart was jubilant. - -As the school quieted down Tom made an honest effort to study, but the -turmoil within him was too great. In turn he took his place in the -reading class and made a botch of it; then in the geography class and -turned lakes into mountains, mountains into rivers, and rivers into -continents, till chaos was come again; then in the spelling class, and -got "turned down," by a succession of mere baby words, till he brought -up at the foot and yielded up the pewter medal which he had worn with -ostentation for months. - - - -CHAPTER VII - -THE harder Tom tried to fasten his mind on his book, the more his -ideas wandered. So at last, with a sigh and a yawn, he gave it up. It -seemed to him that the noon recess would never come. The air was -utterly dead. There was not a breath stirring. It was the sleepiest of -sleepy days. The drowsing murmur of the five and twenty studying -scholars soothed the soul like the spell that is in the murmur of bees. -Away off in the flaming sunshine, Cardiff Hill lifted its soft green -sides through a shimmering veil of heat, tinted with the purple of -distance; a few birds floated on lazy wing high in the air; no other -living thing was visible but some cows, and they were asleep. Tom's -heart ached to be free, or else to have something of interest to do to -pass the dreary time. His hand wandered into his pocket and his face -lit up with a glow of gratitude that was prayer, though he did not know -it. Then furtively the percussion-cap box came out. He released the -tick and put him on the long flat desk. The creature probably glowed -with a gratitude that amounted to prayer, too, at this moment, but it -was premature: for when he started thankfully to travel off, Tom turned -him aside with a pin and made him take a new direction. - -Tom's bosom friend sat next him, suffering just as Tom had been, and -now he was deeply and gratefully interested in this entertainment in an -instant. This bosom friend was Joe Harper. The two boys were sworn -friends all the week, and embattled enemies on Saturdays. Joe took a -pin out of his lapel and began to assist in exercising the prisoner. -The sport grew in interest momently. Soon Tom said that they were -interfering with each other, and neither getting the fullest benefit of -the tick. So he put Joe's slate on the desk and drew a line down the -middle of it from top to bottom. - -"Now," said he, "as long as he is on your side you can stir him up and -I'll let him alone; but if you let him get away and get on my side, -you're to leave him alone as long as I can keep him from crossing over." - -"All right, go ahead; start him up." - -The tick escaped from Tom, presently, and crossed the equator. Joe -harassed him awhile, and then he got away and crossed back again. This -change of base occurred often. While one boy was worrying the tick with -absorbing interest, the other would look on with interest as strong, -the two heads bowed together over the slate, and the two souls dead to -all things else. At last luck seemed to settle and abide with Joe. The -tick tried this, that, and the other course, and got as excited and as -anxious as the boys themselves, but time and again just as he would -have victory in his very grasp, so to speak, and Tom's fingers would be -twitching to begin, Joe's pin would deftly head him off, and keep -possession. At last Tom could stand it no longer. The temptation was -too strong. So he reached out and lent a hand with his pin. Joe was -angry in a moment. Said he: - -"Tom, you let him alone." - -"I only just want to stir him up a little, Joe." - -"No, sir, it ain't fair; you just let him alone." - -"Blame it, I ain't going to stir him much." - -"Let him alone, I tell you." - -"I won't!" - -"You shall--he's on my side of the line." - -"Look here, Joe Harper, whose is that tick?" - -"I don't care whose tick he is--he's on my side of the line, and you -sha'n't touch him." - -"Well, I'll just bet I will, though. He's my tick and I'll do what I -blame please with him, or die!" - -A tremendous whack came down on Tom's shoulders, and its duplicate on -Joe's; and for the space of two minutes the dust continued to fly from -the two jackets and the whole school to enjoy it. The boys had been too -absorbed to notice the hush that had stolen upon the school awhile -before when the master came tiptoeing down the room and stood over -them. He had contemplated a good part of the performance before he -contributed his bit of variety to it. - -When school broke up at noon, Tom flew to Becky Thatcher, and -whispered in her ear: - -"Put on your bonnet and let on you're going home; and when you get to -the corner, give the rest of 'em the slip, and turn down through the -lane and come back. I'll go the other way and come it over 'em the same -way." - -So the one went off with one group of scholars, and the other with -another. In a little while the two met at the bottom of the lane, and -when they reached the school they had it all to themselves. Then they -sat together, with a slate before them, and Tom gave Becky the pencil -and held her hand in his, guiding it, and so created another surprising -house. When the interest in art began to wane, the two fell to talking. -Tom was swimming in bliss. He said: - -"Do you love rats?" - -"No! I hate them!" - -"Well, I do, too--LIVE ones. But I mean dead ones, to swing round your -head with a string." - -"No, I don't care for rats much, anyway. What I like is chewing-gum." - -"Oh, I should say so! I wish I had some now." - -"Do you? I've got some. I'll let you chew it awhile, but you must give -it back to me." - -That was agreeable, so they chewed it turn about, and dangled their -legs against the bench in excess of contentment. - -"Was you ever at a circus?" said Tom. - -"Yes, and my pa's going to take me again some time, if I'm good." - -"I been to the circus three or four times--lots of times. Church ain't -shucks to a circus. There's things going on at a circus all the time. -I'm going to be a clown in a circus when I grow up." - -"Oh, are you! That will be nice. They're so lovely, all spotted up." - -"Yes, that's so. And they get slathers of money--most a dollar a day, -Ben Rogers says. Say, Becky, was you ever engaged?" - -"What's that?" - -"Why, engaged to be married." - -"No." - -"Would you like to?" - -"I reckon so. I don't know. What is it like?" - -"Like? Why it ain't like anything. You only just tell a boy you won't -ever have anybody but him, ever ever ever, and then you kiss and that's -all. Anybody can do it." - -"Kiss? What do you kiss for?" - -"Why, that, you know, is to--well, they always do that." - -"Everybody?" - -"Why, yes, everybody that's in love with each other. Do you remember -what I wrote on the slate?" - -"Ye--yes." - -"What was it?" - -"I sha'n't tell you." - -"Shall I tell YOU?" - -"Ye--yes--but some other time." - -"No, now." - -"No, not now--to-morrow." - -"Oh, no, NOW. Please, Becky--I'll whisper it, I'll whisper it ever so -easy." - -Becky hesitating, Tom took silence for consent, and passed his arm -about her waist and whispered the tale ever so softly, with his mouth -close to her ear. And then he added: - -"Now you whisper it to me--just the same." - -She resisted, for a while, and then said: - -"You turn your face away so you can't see, and then I will. But you -mustn't ever tell anybody--WILL you, Tom? Now you won't, WILL you?" - -"No, indeed, indeed I won't. Now, Becky." - -He turned his face away. She bent timidly around till her breath -stirred his curls and whispered, "I--love--you!" - -Then she sprang away and ran around and around the desks and benches, -with Tom after her, and took refuge in a corner at last, with her -little white apron to her face. Tom clasped her about her neck and -pleaded: - -"Now, Becky, it's all done--all over but the kiss. Don't you be afraid -of that--it ain't anything at all. Please, Becky." And he tugged at her -apron and the hands. - -By and by she gave up, and let her hands drop; her face, all glowing -with the struggle, came up and submitted. Tom kissed the red lips and -said: - -"Now it's all done, Becky. And always after this, you know, you ain't -ever to love anybody but me, and you ain't ever to marry anybody but -me, ever never and forever. Will you?" - -"No, I'll never love anybody but you, Tom, and I'll never marry -anybody but you--and you ain't to ever marry anybody but me, either." - -"Certainly. Of course. That's PART of it. And always coming to school -or when we're going home, you're to walk with me, when there ain't -anybody looking--and you choose me and I choose you at parties, because -that's the way you do when you're engaged." - -"It's so nice. I never heard of it before." - -"Oh, it's ever so gay! Why, me and Amy Lawrence--" - -The big eyes told Tom his blunder and he stopped, confused. - -"Oh, Tom! Then I ain't the first you've ever been engaged to!" - -The child began to cry. Tom said: - -"Oh, don't cry, Becky, I don't care for her any more." - -"Yes, you do, Tom--you know you do." - -Tom tried to put his arm about her neck, but she pushed him away and -turned her face to the wall, and went on crying. Tom tried again, with -soothing words in his mouth, and was repulsed again. Then his pride was -up, and he strode away and went outside. He stood about, restless and -uneasy, for a while, glancing at the door, every now and then, hoping -she would repent and come to find him. But she did not. Then he began -to feel badly and fear that he was in the wrong. It was a hard struggle -with him to make new advances, now, but he nerved himself to it and -entered. She was still standing back there in the corner, sobbing, with -her face to the wall. Tom's heart smote him. He went to her and stood a -moment, not knowing exactly how to proceed. Then he said hesitatingly: - -"Becky, I--I don't care for anybody but you." - -No reply--but sobs. - -"Becky"--pleadingly. "Becky, won't you say something?" - -More sobs. - -Tom got out his chiefest jewel, a brass knob from the top of an -andiron, and passed it around her so that she could see it, and said: - -"Please, Becky, won't you take it?" - -She struck it to the floor. Then Tom marched out of the house and over -the hills and far away, to return to school no more that day. Presently -Becky began to suspect. She ran to the door; he was not in sight; she -flew around to the play-yard; he was not there. Then she called: - -"Tom! Come back, Tom!" - -She listened intently, but there was no answer. She had no companions -but silence and loneliness. So she sat down to cry again and upbraid -herself; and by this time the scholars began to gather again, and she -had to hide her griefs and still her broken heart and take up the cross -of a long, dreary, aching afternoon, with none among the strangers -about her to exchange sorrows with. - - - -CHAPTER VIII - -TOM dodged hither and thither through lanes until he was well out of -the track of returning scholars, and then fell into a moody jog. He -crossed a small "branch" two or three times, because of a prevailing -juvenile superstition that to cross water baffled pursuit. Half an hour -later he was disappearing behind the Douglas mansion on the summit of -Cardiff Hill, and the schoolhouse was hardly distinguishable away off -in the valley behind him. He entered a dense wood, picked his pathless -way to the centre of it, and sat down on a mossy spot under a spreading -oak. There was not even a zephyr stirring; the dead noonday heat had -even stilled the songs of the birds; nature lay in a trance that was -broken by no sound but the occasional far-off hammering of a -woodpecker, and this seemed to render the pervading silence and sense -of loneliness the more profound. The boy's soul was steeped in -melancholy; his feelings were in happy accord with his surroundings. He -sat long with his elbows on his knees and his chin in his hands, -meditating. It seemed to him that life was but a trouble, at best, and -he more than half envied Jimmy Hodges, so lately released; it must be -very peaceful, he thought, to lie and slumber and dream forever and -ever, with the wind whispering through the trees and caressing the -grass and the flowers over the grave, and nothing to bother and grieve -about, ever any more. If he only had a clean Sunday-school record he -could be willing to go, and be done with it all. Now as to this girl. -What had he done? Nothing. He had meant the best in the world, and been -treated like a dog--like a very dog. She would be sorry some day--maybe -when it was too late. Ah, if he could only die TEMPORARILY! - -But the elastic heart of youth cannot be compressed into one -constrained shape long at a time. Tom presently began to drift -insensibly back into the concerns of this life again. What if he turned -his back, now, and disappeared mysteriously? What if he went away--ever -so far away, into unknown countries beyond the seas--and never came -back any more! How would she feel then! The idea of being a clown -recurred to him now, only to fill him with disgust. For frivolity and -jokes and spotted tights were an offense, when they intruded themselves -upon a spirit that was exalted into the vague august realm of the -romantic. No, he would be a soldier, and return after long years, all -war-worn and illustrious. No--better still, he would join the Indians, -and hunt buffaloes and go on the warpath in the mountain ranges and the -trackless great plains of the Far West, and away in the future come -back a great chief, bristling with feathers, hideous with paint, and -prance into Sunday-school, some drowsy summer morning, with a -bloodcurdling war-whoop, and sear the eyeballs of all his companions -with unappeasable envy. But no, there was something gaudier even than -this. He would be a pirate! That was it! NOW his future lay plain -before him, and glowing with unimaginable splendor. How his name would -fill the world, and make people shudder! How gloriously he would go -plowing the dancing seas, in his long, low, black-hulled racer, the -Spirit of the Storm, with his grisly flag flying at the fore! And at -the zenith of his fame, how he would suddenly appear at the old village -and stalk into church, brown and weather-beaten, in his black velvet -doublet and trunks, his great jack-boots, his crimson sash, his belt -bristling with horse-pistols, his crime-rusted cutlass at his side, his -slouch hat with waving plumes, his black flag unfurled, with the skull -and crossbones on it, and hear with swelling ecstasy the whisperings, -"It's Tom Sawyer the Pirate!--the Black Avenger of the Spanish Main!" - -Yes, it was settled; his career was determined. He would run away from -home and enter upon it. He would start the very next morning. Therefore -he must now begin to get ready. He would collect his resources -together. He went to a rotten log near at hand and began to dig under -one end of it with his Barlow knife. He soon struck wood that sounded -hollow. He put his hand there and uttered this incantation impressively: - -"What hasn't come here, come! What's here, stay here!" - -Then he scraped away the dirt, and exposed a pine shingle. He took it -up and disclosed a shapely little treasure-house whose bottom and sides -were of shingles. In it lay a marble. Tom's astonishment was boundless! -He scratched his head with a perplexed air, and said: - -"Well, that beats anything!" - -Then he tossed the marble away pettishly, and stood cogitating. The -truth was, that a superstition of his had failed, here, which he and -all his comrades had always looked upon as infallible. If you buried a -marble with certain necessary incantations, and left it alone a -fortnight, and then opened the place with the incantation he had just -used, you would find that all the marbles you had ever lost had -gathered themselves together there, meantime, no matter how widely they -had been separated. But now, this thing had actually and unquestionably -failed. Tom's whole structure of faith was shaken to its foundations. -He had many a time heard of this thing succeeding but never of its -failing before. It did not occur to him that he had tried it several -times before, himself, but could never find the hiding-places -afterward. He puzzled over the matter some time, and finally decided -that some witch had interfered and broken the charm. He thought he -would satisfy himself on that point; so he searched around till he -found a small sandy spot with a little funnel-shaped depression in it. -He laid himself down and put his mouth close to this depression and -called-- - -"Doodle-bug, doodle-bug, tell me what I want to know! Doodle-bug, -doodle-bug, tell me what I want to know!" - -The sand began to work, and presently a small black bug appeared for a -second and then darted under again in a fright. - -"He dasn't tell! So it WAS a witch that done it. I just knowed it." - -He well knew the futility of trying to contend against witches, so he -gave up discouraged. But it occurred to him that he might as well have -the marble he had just thrown away, and therefore he went and made a -patient search for it. But he could not find it. Now he went back to -his treasure-house and carefully placed himself just as he had been -standing when he tossed the marble away; then he took another marble -from his pocket and tossed it in the same way, saying: - -"Brother, go find your brother!" - -He watched where it stopped, and went there and looked. But it must -have fallen short or gone too far; so he tried twice more. The last -repetition was successful. The two marbles lay within a foot of each -other. - -Just here the blast of a toy tin trumpet came faintly down the green -aisles of the forest. Tom flung off his jacket and trousers, turned a -suspender into a belt, raked away some brush behind the rotten log, -disclosing a rude bow and arrow, a lath sword and a tin trumpet, and in -a moment had seized these things and bounded away, barelegged, with -fluttering shirt. He presently halted under a great elm, blew an -answering blast, and then began to tiptoe and look warily out, this way -and that. He said cautiously--to an imaginary company: - -"Hold, my merry men! Keep hid till I blow." - -Now appeared Joe Harper, as airily clad and elaborately armed as Tom. -Tom called: - -"Hold! Who comes here into Sherwood Forest without my pass?" - -"Guy of Guisborne wants no man's pass. Who art thou that--that--" - -"Dares to hold such language," said Tom, prompting--for they talked -"by the book," from memory. - -"Who art thou that dares to hold such language?" - -"I, indeed! I am Robin Hood, as thy caitiff carcase soon shall know." - -"Then art thou indeed that famous outlaw? Right gladly will I dispute -with thee the passes of the merry wood. Have at thee!" - -They took their lath swords, dumped their other traps on the ground, -struck a fencing attitude, foot to foot, and began a grave, careful -combat, "two up and two down." Presently Tom said: - -"Now, if you've got the hang, go it lively!" - -So they "went it lively," panting and perspiring with the work. By and -by Tom shouted: - -"Fall! fall! Why don't you fall?" - -"I sha'n't! Why don't you fall yourself? You're getting the worst of -it." - -"Why, that ain't anything. I can't fall; that ain't the way it is in -the book. The book says, 'Then with one back-handed stroke he slew poor -Guy of Guisborne.' You're to turn around and let me hit you in the -back." - -There was no getting around the authorities, so Joe turned, received -the whack and fell. - -"Now," said Joe, getting up, "you got to let me kill YOU. That's fair." - -"Why, I can't do that, it ain't in the book." - -"Well, it's blamed mean--that's all." - -"Well, say, Joe, you can be Friar Tuck or Much the miller's son, and -lam me with a quarter-staff; or I'll be the Sheriff of Nottingham and -you be Robin Hood a little while and kill me." - -This was satisfactory, and so these adventures were carried out. Then -Tom became Robin Hood again, and was allowed by the treacherous nun to -bleed his strength away through his neglected wound. And at last Joe, -representing a whole tribe of weeping outlaws, dragged him sadly forth, -gave his bow into his feeble hands, and Tom said, "Where this arrow -falls, there bury poor Robin Hood under the greenwood tree." Then he -shot the arrow and fell back and would have died, but he lit on a -nettle and sprang up too gaily for a corpse. - -The boys dressed themselves, hid their accoutrements, and went off -grieving that there were no outlaws any more, and wondering what modern -civilization could claim to have done to compensate for their loss. -They said they would rather be outlaws a year in Sherwood Forest than -President of the United States forever. - - - -CHAPTER IX - -AT half-past nine, that night, Tom and Sid were sent to bed, as usual. -They said their prayers, and Sid was soon asleep. Tom lay awake and -waited, in restless impatience. When it seemed to him that it must be -nearly daylight, he heard the clock strike ten! This was despair. He -would have tossed and fidgeted, as his nerves demanded, but he was -afraid he might wake Sid. So he lay still, and stared up into the dark. -Everything was dismally still. By and by, out of the stillness, little, -scarcely perceptible noises began to emphasize themselves. The ticking -of the clock began to bring itself into notice. Old beams began to -crack mysteriously. The stairs creaked faintly. Evidently spirits were -abroad. A measured, muffled snore issued from Aunt Polly's chamber. And -now the tiresome chirping of a cricket that no human ingenuity could -locate, began. Next the ghastly ticking of a deathwatch in the wall at -the bed's head made Tom shudder--it meant that somebody's days were -numbered. Then the howl of a far-off dog rose on the night air, and was -answered by a fainter howl from a remoter distance. Tom was in an -agony. At last he was satisfied that time had ceased and eternity -begun; he began to doze, in spite of himself; the clock chimed eleven, -but he did not hear it. And then there came, mingling with his -half-formed dreams, a most melancholy caterwauling. The raising of a -neighboring window disturbed him. A cry of "Scat! you devil!" and the -crash of an empty bottle against the back of his aunt's woodshed -brought him wide awake, and a single minute later he was dressed and -out of the window and creeping along the roof of the "ell" on all -fours. He "meow'd" with caution once or twice, as he went; then jumped -to the roof of the woodshed and thence to the ground. Huckleberry Finn -was there, with his dead cat. The boys moved off and disappeared in the -gloom. At the end of half an hour they were wading through the tall -grass of the graveyard. - -It was a graveyard of the old-fashioned Western kind. It was on a -hill, about a mile and a half from the village. It had a crazy board -fence around it, which leaned inward in places, and outward the rest of -the time, but stood upright nowhere. Grass and weeds grew rank over the -whole cemetery. All the old graves were sunken in, there was not a -tombstone on the place; round-topped, worm-eaten boards staggered over -the graves, leaning for support and finding none. "Sacred to the memory -of" So-and-So had been painted on them once, but it could no longer -have been read, on the most of them, now, even if there had been light. - -A faint wind moaned through the trees, and Tom feared it might be the -spirits of the dead, complaining at being disturbed. The boys talked -little, and only under their breath, for the time and the place and the -pervading solemnity and silence oppressed their spirits. They found the -sharp new heap they were seeking, and ensconced themselves within the -protection of three great elms that grew in a bunch within a few feet -of the grave. - -Then they waited in silence for what seemed a long time. The hooting -of a distant owl was all the sound that troubled the dead stillness. -Tom's reflections grew oppressive. He must force some talk. So he said -in a whisper: - -"Hucky, do you believe the dead people like it for us to be here?" - -Huckleberry whispered: - -"I wisht I knowed. It's awful solemn like, AIN'T it?" - -"I bet it is." - -There was a considerable pause, while the boys canvassed this matter -inwardly. Then Tom whispered: - -"Say, Hucky--do you reckon Hoss Williams hears us talking?" - -"O' course he does. Least his sperrit does." - -Tom, after a pause: - -"I wish I'd said Mister Williams. But I never meant any harm. -Everybody calls him Hoss." - -"A body can't be too partic'lar how they talk 'bout these-yer dead -people, Tom." - -This was a damper, and conversation died again. - -Presently Tom seized his comrade's arm and said: - -"Sh!" - -"What is it, Tom?" And the two clung together with beating hearts. - -"Sh! There 'tis again! Didn't you hear it?" - -"I--" - -"There! Now you hear it." - -"Lord, Tom, they're coming! They're coming, sure. What'll we do?" - -"I dono. Think they'll see us?" - -"Oh, Tom, they can see in the dark, same as cats. I wisht I hadn't -come." - -"Oh, don't be afeard. I don't believe they'll bother us. We ain't -doing any harm. If we keep perfectly still, maybe they won't notice us -at all." - -"I'll try to, Tom, but, Lord, I'm all of a shiver." - -"Listen!" - -The boys bent their heads together and scarcely breathed. A muffled -sound of voices floated up from the far end of the graveyard. - -"Look! See there!" whispered Tom. "What is it?" - -"It's devil-fire. Oh, Tom, this is awful." - -Some vague figures approached through the gloom, swinging an -old-fashioned tin lantern that freckled the ground with innumerable -little spangles of light. Presently Huckleberry whispered with a -shudder: - -"It's the devils sure enough. Three of 'em! Lordy, Tom, we're goners! -Can you pray?" - -"I'll try, but don't you be afeard. They ain't going to hurt us. 'Now -I lay me down to sleep, I--'" - -"Sh!" - -"What is it, Huck?" - -"They're HUMANS! One of 'em is, anyway. One of 'em's old Muff Potter's -voice." - -"No--'tain't so, is it?" - -"I bet I know it. Don't you stir nor budge. He ain't sharp enough to -notice us. Drunk, the same as usual, likely--blamed old rip!" - -"All right, I'll keep still. Now they're stuck. Can't find it. Here -they come again. Now they're hot. Cold again. Hot again. Red hot! -They're p'inted right, this time. Say, Huck, I know another o' them -voices; it's Injun Joe." - -"That's so--that murderin' half-breed! I'd druther they was devils a -dern sight. What kin they be up to?" - -The whisper died wholly out, now, for the three men had reached the -grave and stood within a few feet of the boys' hiding-place. - -"Here it is," said the third voice; and the owner of it held the -lantern up and revealed the face of young Doctor Robinson. - -Potter and Injun Joe were carrying a handbarrow with a rope and a -couple of shovels on it. They cast down their load and began to open -the grave. The doctor put the lantern at the head of the grave and came -and sat down with his back against one of the elm trees. He was so -close the boys could have touched him. - -"Hurry, men!" he said, in a low voice; "the moon might come out at any -moment." - -They growled a response and went on digging. For some time there was -no noise but the grating sound of the spades discharging their freight -of mould and gravel. It was very monotonous. Finally a spade struck -upon the coffin with a dull woody accent, and within another minute or -two the men had hoisted it out on the ground. They pried off the lid -with their shovels, got out the body and dumped it rudely on the -ground. The moon drifted from behind the clouds and exposed the pallid -face. The barrow was got ready and the corpse placed on it, covered -with a blanket, and bound to its place with the rope. Potter took out a -large spring-knife and cut off the dangling end of the rope and then -said: - -"Now the cussed thing's ready, Sawbones, and you'll just out with -another five, or here she stays." - -"That's the talk!" said Injun Joe. - -"Look here, what does this mean?" said the doctor. "You required your -pay in advance, and I've paid you." - -"Yes, and you done more than that," said Injun Joe, approaching the -doctor, who was now standing. "Five years ago you drove me away from -your father's kitchen one night, when I come to ask for something to -eat, and you said I warn't there for any good; and when I swore I'd get -even with you if it took a hundred years, your father had me jailed for -a vagrant. Did you think I'd forget? The Injun blood ain't in me for -nothing. And now I've GOT you, and you got to SETTLE, you know!" - -He was threatening the doctor, with his fist in his face, by this -time. The doctor struck out suddenly and stretched the ruffian on the -ground. Potter dropped his knife, and exclaimed: - -"Here, now, don't you hit my pard!" and the next moment he had -grappled with the doctor and the two were struggling with might and -main, trampling the grass and tearing the ground with their heels. -Injun Joe sprang to his feet, his eyes flaming with passion, snatched -up Potter's knife, and went creeping, catlike and stooping, round and -round about the combatants, seeking an opportunity. All at once the -doctor flung himself free, seized the heavy headboard of Williams' -grave and felled Potter to the earth with it--and in the same instant -the half-breed saw his chance and drove the knife to the hilt in the -young man's breast. He reeled and fell partly upon Potter, flooding him -with his blood, and in the same moment the clouds blotted out the -dreadful spectacle and the two frightened boys went speeding away in -the dark. - -Presently, when the moon emerged again, Injun Joe was standing over -the two forms, contemplating them. The doctor murmured inarticulately, -gave a long gasp or two and was still. The half-breed muttered: - -"THAT score is settled--damn you." - -Then he robbed the body. After which he put the fatal knife in -Potter's open right hand, and sat down on the dismantled coffin. Three ---four--five minutes passed, and then Potter began to stir and moan. His -hand closed upon the knife; he raised it, glanced at it, and let it -fall, with a shudder. Then he sat up, pushing the body from him, and -gazed at it, and then around him, confusedly. His eyes met Joe's. - -"Lord, how is this, Joe?" he said. - -"It's a dirty business," said Joe, without moving. - -"What did you do it for?" - -"I! I never done it!" - -"Look here! That kind of talk won't wash." - -Potter trembled and grew white. - -"I thought I'd got sober. I'd no business to drink to-night. But it's -in my head yet--worse'n when we started here. I'm all in a muddle; -can't recollect anything of it, hardly. Tell me, Joe--HONEST, now, old -feller--did I do it? Joe, I never meant to--'pon my soul and honor, I -never meant to, Joe. Tell me how it was, Joe. Oh, it's awful--and him -so young and promising." - -"Why, you two was scuffling, and he fetched you one with the headboard -and you fell flat; and then up you come, all reeling and staggering -like, and snatched the knife and jammed it into him, just as he fetched -you another awful clip--and here you've laid, as dead as a wedge til -now." - -"Oh, I didn't know what I was a-doing. I wish I may die this minute if -I did. It was all on account of the whiskey and the excitement, I -reckon. I never used a weepon in my life before, Joe. I've fought, but -never with weepons. They'll all say that. Joe, don't tell! Say you -won't tell, Joe--that's a good feller. I always liked you, Joe, and -stood up for you, too. Don't you remember? You WON'T tell, WILL you, -Joe?" And the poor creature dropped on his knees before the stolid -murderer, and clasped his appealing hands. - -"No, you've always been fair and square with me, Muff Potter, and I -won't go back on you. There, now, that's as fair as a man can say." - -"Oh, Joe, you're an angel. I'll bless you for this the longest day I -live." And Potter began to cry. - -"Come, now, that's enough of that. This ain't any time for blubbering. -You be off yonder way and I'll go this. Move, now, and don't leave any -tracks behind you." - -Potter started on a trot that quickly increased to a run. The -half-breed stood looking after him. He muttered: - -"If he's as much stunned with the lick and fuddled with the rum as he -had the look of being, he won't think of the knife till he's gone so -far he'll be afraid to come back after it to such a place by himself ---chicken-heart!" - -Two or three minutes later the murdered man, the blanketed corpse, the -lidless coffin, and the open grave were under no inspection but the -moon's. The stillness was complete again, too. - - - -CHAPTER X - -THE two boys flew on and on, toward the village, speechless with -horror. They glanced backward over their shoulders from time to time, -apprehensively, as if they feared they might be followed. Every stump -that started up in their path seemed a man and an enemy, and made them -catch their breath; and as they sped by some outlying cottages that lay -near the village, the barking of the aroused watch-dogs seemed to give -wings to their feet. - -"If we can only get to the old tannery before we break down!" -whispered Tom, in short catches between breaths. "I can't stand it much -longer." - -Huckleberry's hard pantings were his only reply, and the boys fixed -their eyes on the goal of their hopes and bent to their work to win it. -They gained steadily on it, and at last, breast to breast, they burst -through the open door and fell grateful and exhausted in the sheltering -shadows beyond. By and by their pulses slowed down, and Tom whispered: - -"Huckleberry, what do you reckon'll come of this?" - -"If Doctor Robinson dies, I reckon hanging'll come of it." - -"Do you though?" - -"Why, I KNOW it, Tom." - -Tom thought a while, then he said: - -"Who'll tell? We?" - -"What are you talking about? S'pose something happened and Injun Joe -DIDN'T hang? Why, he'd kill us some time or other, just as dead sure as -we're a laying here." - -"That's just what I was thinking to myself, Huck." - -"If anybody tells, let Muff Potter do it, if he's fool enough. He's -generally drunk enough." - -Tom said nothing--went on thinking. Presently he whispered: - -"Huck, Muff Potter don't know it. How can he tell?" - -"What's the reason he don't know it?" - -"Because he'd just got that whack when Injun Joe done it. D'you reckon -he could see anything? D'you reckon he knowed anything?" - -"By hokey, that's so, Tom!" - -"And besides, look-a-here--maybe that whack done for HIM!" - -"No, 'taint likely, Tom. He had liquor in him; I could see that; and -besides, he always has. Well, when pap's full, you might take and belt -him over the head with a church and you couldn't phase him. He says so, -his own self. So it's the same with Muff Potter, of course. But if a -man was dead sober, I reckon maybe that whack might fetch him; I dono." - -After another reflective silence, Tom said: - -"Hucky, you sure you can keep mum?" - -"Tom, we GOT to keep mum. You know that. That Injun devil wouldn't -make any more of drownding us than a couple of cats, if we was to -squeak 'bout this and they didn't hang him. Now, look-a-here, Tom, less -take and swear to one another--that's what we got to do--swear to keep -mum." - -"I'm agreed. It's the best thing. Would you just hold hands and swear -that we--" - -"Oh no, that wouldn't do for this. That's good enough for little -rubbishy common things--specially with gals, cuz THEY go back on you -anyway, and blab if they get in a huff--but there orter be writing -'bout a big thing like this. And blood." - -Tom's whole being applauded this idea. It was deep, and dark, and -awful; the hour, the circumstances, the surroundings, were in keeping -with it. He picked up a clean pine shingle that lay in the moonlight, -took a little fragment of "red keel" out of his pocket, got the moon on -his work, and painfully scrawled these lines, emphasizing each slow -down-stroke by clamping his tongue between his teeth, and letting up -the pressure on the up-strokes. [See next page.] - - "Huck Finn and - Tom Sawyer swears - they will keep mum - about This and They - wish They may Drop - down dead in Their - Tracks if They ever - Tell and Rot." - -Huckleberry was filled with admiration of Tom's facility in writing, -and the sublimity of his language. He at once took a pin from his lapel -and was going to prick his flesh, but Tom said: - -"Hold on! Don't do that. A pin's brass. It might have verdigrease on -it." - -"What's verdigrease?" - -"It's p'ison. That's what it is. You just swaller some of it once ---you'll see." - -So Tom unwound the thread from one of his needles, and each boy -pricked the ball of his thumb and squeezed out a drop of blood. In -time, after many squeezes, Tom managed to sign his initials, using the -ball of his little finger for a pen. Then he showed Huckleberry how to -make an H and an F, and the oath was complete. They buried the shingle -close to the wall, with some dismal ceremonies and incantations, and -the fetters that bound their tongues were considered to be locked and -the key thrown away. - -A figure crept stealthily through a break in the other end of the -ruined building, now, but they did not notice it. - -"Tom," whispered Huckleberry, "does this keep us from EVER telling ---ALWAYS?" - -"Of course it does. It don't make any difference WHAT happens, we got -to keep mum. We'd drop down dead--don't YOU know that?" - -"Yes, I reckon that's so." - -They continued to whisper for some little time. Presently a dog set up -a long, lugubrious howl just outside--within ten feet of them. The boys -clasped each other suddenly, in an agony of fright. - -"Which of us does he mean?" gasped Huckleberry. - -"I dono--peep through the crack. Quick!" - -"No, YOU, Tom!" - -"I can't--I can't DO it, Huck!" - -"Please, Tom. There 'tis again!" - -"Oh, lordy, I'm thankful!" whispered Tom. "I know his voice. It's Bull -Harbison." * - -[* If Mr. Harbison owned a slave named Bull, Tom would have spoken of -him as "Harbison's Bull," but a son or a dog of that name was "Bull -Harbison."] - -"Oh, that's good--I tell you, Tom, I was most scared to death; I'd a -bet anything it was a STRAY dog." - -The dog howled again. The boys' hearts sank once more. - -"Oh, my! that ain't no Bull Harbison!" whispered Huckleberry. "DO, Tom!" - -Tom, quaking with fear, yielded, and put his eye to the crack. His -whisper was hardly audible when he said: - -"Oh, Huck, IT S A STRAY DOG!" - -"Quick, Tom, quick! Who does he mean?" - -"Huck, he must mean us both--we're right together." - -"Oh, Tom, I reckon we're goners. I reckon there ain't no mistake 'bout -where I'LL go to. I been so wicked." - -"Dad fetch it! This comes of playing hookey and doing everything a -feller's told NOT to do. I might a been good, like Sid, if I'd a tried ---but no, I wouldn't, of course. But if ever I get off this time, I lay -I'll just WALLER in Sunday-schools!" And Tom began to snuffle a little. - -"YOU bad!" and Huckleberry began to snuffle too. "Consound it, Tom -Sawyer, you're just old pie, 'longside o' what I am. Oh, LORDY, lordy, -lordy, I wisht I only had half your chance." - -Tom choked off and whispered: - -"Look, Hucky, look! He's got his BACK to us!" - -Hucky looked, with joy in his heart. - -"Well, he has, by jingoes! Did he before?" - -"Yes, he did. But I, like a fool, never thought. Oh, this is bully, -you know. NOW who can he mean?" - -The howling stopped. Tom pricked up his ears. - -"Sh! What's that?" he whispered. - -"Sounds like--like hogs grunting. No--it's somebody snoring, Tom." - -"That IS it! Where 'bouts is it, Huck?" - -"I bleeve it's down at 'tother end. Sounds so, anyway. Pap used to -sleep there, sometimes, 'long with the hogs, but laws bless you, he -just lifts things when HE snores. Besides, I reckon he ain't ever -coming back to this town any more." - -The spirit of adventure rose in the boys' souls once more. - -"Hucky, do you das't to go if I lead?" - -"I don't like to, much. Tom, s'pose it's Injun Joe!" - -Tom quailed. But presently the temptation rose up strong again and the -boys agreed to try, with the understanding that they would take to -their heels if the snoring stopped. So they went tiptoeing stealthily -down, the one behind the other. When they had got to within five steps -of the snorer, Tom stepped on a stick, and it broke with a sharp snap. -The man moaned, writhed a little, and his face came into the moonlight. -It was Muff Potter. The boys' hearts had stood still, and their hopes -too, when the man moved, but their fears passed away now. They tiptoed -out, through the broken weather-boarding, and stopped at a little -distance to exchange a parting word. That long, lugubrious howl rose on -the night air again! They turned and saw the strange dog standing -within a few feet of where Potter was lying, and FACING Potter, with -his nose pointing heavenward. - -"Oh, geeminy, it's HIM!" exclaimed both boys, in a breath. - -"Say, Tom--they say a stray dog come howling around Johnny Miller's -house, 'bout midnight, as much as two weeks ago; and a whippoorwill -come in and lit on the banisters and sung, the very same evening; and -there ain't anybody dead there yet." - -"Well, I know that. And suppose there ain't. Didn't Gracie Miller fall -in the kitchen fire and burn herself terrible the very next Saturday?" - -"Yes, but she ain't DEAD. And what's more, she's getting better, too." - -"All right, you wait and see. She's a goner, just as dead sure as Muff -Potter's a goner. That's what the niggers say, and they know all about -these kind of things, Huck." - -Then they separated, cogitating. When Tom crept in at his bedroom -window the night was almost spent. He undressed with excessive caution, -and fell asleep congratulating himself that nobody knew of his -escapade. He was not aware that the gently-snoring Sid was awake, and -had been so for an hour. - -When Tom awoke, Sid was dressed and gone. There was a late look in the -light, a late sense in the atmosphere. He was startled. Why had he not -been called--persecuted till he was up, as usual? The thought filled -him with bodings. Within five minutes he was dressed and down-stairs, -feeling sore and drowsy. The family were still at table, but they had -finished breakfast. There was no voice of rebuke; but there were -averted eyes; there was a silence and an air of solemnity that struck a -chill to the culprit's heart. He sat down and tried to seem gay, but it -was up-hill work; it roused no smile, no response, and he lapsed into -silence and let his heart sink down to the depths. - -After breakfast his aunt took him aside, and Tom almost brightened in -the hope that he was going to be flogged; but it was not so. His aunt -wept over him and asked him how he could go and break her old heart so; -and finally told him to go on, and ruin himself and bring her gray -hairs with sorrow to the grave, for it was no use for her to try any -more. This was worse than a thousand whippings, and Tom's heart was -sorer now than his body. He cried, he pleaded for forgiveness, promised -to reform over and over again, and then received his dismissal, feeling -that he had won but an imperfect forgiveness and established but a -feeble confidence. - -He left the presence too miserable to even feel revengeful toward Sid; -and so the latter's prompt retreat through the back gate was -unnecessary. He moped to school gloomy and sad, and took his flogging, -along with Joe Harper, for playing hookey the day before, with the air -of one whose heart was busy with heavier woes and wholly dead to -trifles. Then he betook himself to his seat, rested his elbows on his -desk and his jaws in his hands, and stared at the wall with the stony -stare of suffering that has reached the limit and can no further go. -His elbow was pressing against some hard substance. After a long time -he slowly and sadly changed his position, and took up this object with -a sigh. It was in a paper. He unrolled it. A long, lingering, colossal -sigh followed, and his heart broke. It was his brass andiron knob! - -This final feather broke the camel's back. - - - -CHAPTER XI - -CLOSE upon the hour of noon the whole village was suddenly electrified -with the ghastly news. No need of the as yet undreamed-of telegraph; -the tale flew from man to man, from group to group, from house to -house, with little less than telegraphic speed. Of course the -schoolmaster gave holiday for that afternoon; the town would have -thought strangely of him if he had not. - -A gory knife had been found close to the murdered man, and it had been -recognized by somebody as belonging to Muff Potter--so the story ran. -And it was said that a belated citizen had come upon Potter washing -himself in the "branch" about one or two o'clock in the morning, and -that Potter had at once sneaked off--suspicious circumstances, -especially the washing which was not a habit with Potter. It was also -said that the town had been ransacked for this "murderer" (the public -are not slow in the matter of sifting evidence and arriving at a -verdict), but that he could not be found. Horsemen had departed down -all the roads in every direction, and the Sheriff "was confident" that -he would be captured before night. - -All the town was drifting toward the graveyard. Tom's heartbreak -vanished and he joined the procession, not because he would not a -thousand times rather go anywhere else, but because an awful, -unaccountable fascination drew him on. Arrived at the dreadful place, -he wormed his small body through the crowd and saw the dismal -spectacle. It seemed to him an age since he was there before. Somebody -pinched his arm. He turned, and his eyes met Huckleberry's. Then both -looked elsewhere at once, and wondered if anybody had noticed anything -in their mutual glance. But everybody was talking, and intent upon the -grisly spectacle before them. - -"Poor fellow!" "Poor young fellow!" "This ought to be a lesson to -grave robbers!" "Muff Potter'll hang for this if they catch him!" This -was the drift of remark; and the minister said, "It was a judgment; His -hand is here." - -Now Tom shivered from head to heel; for his eye fell upon the stolid -face of Injun Joe. At this moment the crowd began to sway and struggle, -and voices shouted, "It's him! it's him! he's coming himself!" - -"Who? Who?" from twenty voices. - -"Muff Potter!" - -"Hallo, he's stopped!--Look out, he's turning! Don't let him get away!" - -People in the branches of the trees over Tom's head said he wasn't -trying to get away--he only looked doubtful and perplexed. - -"Infernal impudence!" said a bystander; "wanted to come and take a -quiet look at his work, I reckon--didn't expect any company." - -The crowd fell apart, now, and the Sheriff came through, -ostentatiously leading Potter by the arm. The poor fellow's face was -haggard, and his eyes showed the fear that was upon him. When he stood -before the murdered man, he shook as with a palsy, and he put his face -in his hands and burst into tears. - -"I didn't do it, friends," he sobbed; "'pon my word and honor I never -done it." - -"Who's accused you?" shouted a voice. - -This shot seemed to carry home. Potter lifted his face and looked -around him with a pathetic hopelessness in his eyes. He saw Injun Joe, -and exclaimed: - -"Oh, Injun Joe, you promised me you'd never--" - -"Is that your knife?" and it was thrust before him by the Sheriff. - -Potter would have fallen if they had not caught him and eased him to -the ground. Then he said: - -"Something told me 't if I didn't come back and get--" He shuddered; -then waved his nerveless hand with a vanquished gesture and said, "Tell -'em, Joe, tell 'em--it ain't any use any more." - -Then Huckleberry and Tom stood dumb and staring, and heard the -stony-hearted liar reel off his serene statement, they expecting every -moment that the clear sky would deliver God's lightnings upon his head, -and wondering to see how long the stroke was delayed. And when he had -finished and still stood alive and whole, their wavering impulse to -break their oath and save the poor betrayed prisoner's life faded and -vanished away, for plainly this miscreant had sold himself to Satan and -it would be fatal to meddle with the property of such a power as that. - -"Why didn't you leave? What did you want to come here for?" somebody -said. - -"I couldn't help it--I couldn't help it," Potter moaned. "I wanted to -run away, but I couldn't seem to come anywhere but here." And he fell -to sobbing again. - -Injun Joe repeated his statement, just as calmly, a few minutes -afterward on the inquest, under oath; and the boys, seeing that the -lightnings were still withheld, were confirmed in their belief that Joe -had sold himself to the devil. He was now become, to them, the most -balefully interesting object they had ever looked upon, and they could -not take their fascinated eyes from his face. - -They inwardly resolved to watch him nights, when opportunity should -offer, in the hope of getting a glimpse of his dread master. - -Injun Joe helped to raise the body of the murdered man and put it in a -wagon for removal; and it was whispered through the shuddering crowd -that the wound bled a little! The boys thought that this happy -circumstance would turn suspicion in the right direction; but they were -disappointed, for more than one villager remarked: - -"It was within three feet of Muff Potter when it done it." - -Tom's fearful secret and gnawing conscience disturbed his sleep for as -much as a week after this; and at breakfast one morning Sid said: - -"Tom, you pitch around and talk in your sleep so much that you keep me -awake half the time." - -Tom blanched and dropped his eyes. - -"It's a bad sign," said Aunt Polly, gravely. "What you got on your -mind, Tom?" - -"Nothing. Nothing 't I know of." But the boy's hand shook so that he -spilled his coffee. - -"And you do talk such stuff," Sid said. "Last night you said, 'It's -blood, it's blood, that's what it is!' You said that over and over. And -you said, 'Don't torment me so--I'll tell!' Tell WHAT? What is it -you'll tell?" - -Everything was swimming before Tom. There is no telling what might -have happened, now, but luckily the concern passed out of Aunt Polly's -face and she came to Tom's relief without knowing it. She said: - -"Sho! It's that dreadful murder. I dream about it most every night -myself. Sometimes I dream it's me that done it." - -Mary said she had been affected much the same way. Sid seemed -satisfied. Tom got out of the presence as quick as he plausibly could, -and after that he complained of toothache for a week, and tied up his -jaws every night. He never knew that Sid lay nightly watching, and -frequently slipped the bandage free and then leaned on his elbow -listening a good while at a time, and afterward slipped the bandage -back to its place again. Tom's distress of mind wore off gradually and -the toothache grew irksome and was discarded. If Sid really managed to -make anything out of Tom's disjointed mutterings, he kept it to himself. - -It seemed to Tom that his schoolmates never would get done holding -inquests on dead cats, and thus keeping his trouble present to his -mind. Sid noticed that Tom never was coroner at one of these inquiries, -though it had been his habit to take the lead in all new enterprises; -he noticed, too, that Tom never acted as a witness--and that was -strange; and Sid did not overlook the fact that Tom even showed a -marked aversion to these inquests, and always avoided them when he -could. Sid marvelled, but said nothing. However, even inquests went out -of vogue at last, and ceased to torture Tom's conscience. - -Every day or two, during this time of sorrow, Tom watched his -opportunity and went to the little grated jail-window and smuggled such -small comforts through to the "murderer" as he could get hold of. The -jail was a trifling little brick den that stood in a marsh at the edge -of the village, and no guards were afforded for it; indeed, it was -seldom occupied. These offerings greatly helped to ease Tom's -conscience. - -The villagers had a strong desire to tar-and-feather Injun Joe and -ride him on a rail, for body-snatching, but so formidable was his -character that nobody could be found who was willing to take the lead -in the matter, so it was dropped. He had been careful to begin both of -his inquest-statements with the fight, without confessing the -grave-robbery that preceded it; therefore it was deemed wisest not -to try the case in the courts at present. - - - -CHAPTER XII - -ONE of the reasons why Tom's mind had drifted away from its secret -troubles was, that it had found a new and weighty matter to interest -itself about. Becky Thatcher had stopped coming to school. Tom had -struggled with his pride a few days, and tried to "whistle her down the -wind," but failed. He began to find himself hanging around her father's -house, nights, and feeling very miserable. She was ill. What if she -should die! There was distraction in the thought. He no longer took an -interest in war, nor even in piracy. The charm of life was gone; there -was nothing but dreariness left. He put his hoop away, and his bat; -there was no joy in them any more. His aunt was concerned. She began to -try all manner of remedies on him. She was one of those people who are -infatuated with patent medicines and all new-fangled methods of -producing health or mending it. She was an inveterate experimenter in -these things. When something fresh in this line came out she was in a -fever, right away, to try it; not on herself, for she was never ailing, -but on anybody else that came handy. She was a subscriber for all the -"Health" periodicals and phrenological frauds; and the solemn ignorance -they were inflated with was breath to her nostrils. All the "rot" they -contained about ventilation, and how to go to bed, and how to get up, -and what to eat, and what to drink, and how much exercise to take, and -what frame of mind to keep one's self in, and what sort of clothing to -wear, was all gospel to her, and she never observed that her -health-journals of the current month customarily upset everything they -had recommended the month before. She was as simple-hearted and honest -as the day was long, and so she was an easy victim. She gathered -together her quack periodicals and her quack medicines, and thus armed -with death, went about on her pale horse, metaphorically speaking, with -"hell following after." But she never suspected that she was not an -angel of healing and the balm of Gilead in disguise, to the suffering -neighbors. - -The water treatment was new, now, and Tom's low condition was a -windfall to her. She had him out at daylight every morning, stood him -up in the woodshed and drowned him with a deluge of cold water; then -she scrubbed him down with a towel like a file, and so brought him to; -then she rolled him up in a wet sheet and put him away under blankets -till she sweated his soul clean and "the yellow stains of it came -through his pores"--as Tom said. - -Yet notwithstanding all this, the boy grew more and more melancholy -and pale and dejected. She added hot baths, sitz baths, shower baths, -and plunges. The boy remained as dismal as a hearse. She began to -assist the water with a slim oatmeal diet and blister-plasters. She -calculated his capacity as she would a jug's, and filled him up every -day with quack cure-alls. - -Tom had become indifferent to persecution by this time. This phase -filled the old lady's heart with consternation. This indifference must -be broken up at any cost. Now she heard of Pain-killer for the first -time. She ordered a lot at once. She tasted it and was filled with -gratitude. It was simply fire in a liquid form. She dropped the water -treatment and everything else, and pinned her faith to Pain-killer. She -gave Tom a teaspoonful and watched with the deepest anxiety for the -result. Her troubles were instantly at rest, her soul at peace again; -for the "indifference" was broken up. The boy could not have shown a -wilder, heartier interest, if she had built a fire under him. - -Tom felt that it was time to wake up; this sort of life might be -romantic enough, in his blighted condition, but it was getting to have -too little sentiment and too much distracting variety about it. So he -thought over various plans for relief, and finally hit pon that of -professing to be fond of Pain-killer. He asked for it so often that he -became a nuisance, and his aunt ended by telling him to help himself -and quit bothering her. If it had been Sid, she would have had no -misgivings to alloy her delight; but since it was Tom, she watched the -bottle clandestinely. She found that the medicine did really diminish, -but it did not occur to her that the boy was mending the health of a -crack in the sitting-room floor with it. - -One day Tom was in the act of dosing the crack when his aunt's yellow -cat came along, purring, eying the teaspoon avariciously, and begging -for a taste. Tom said: - -"Don't ask for it unless you want it, Peter." - -But Peter signified that he did want it. - -"You better make sure." - -Peter was sure. - -"Now you've asked for it, and I'll give it to you, because there ain't -anything mean about me; but if you find you don't like it, you mustn't -blame anybody but your own self." - -Peter was agreeable. So Tom pried his mouth open and poured down the -Pain-killer. Peter sprang a couple of yards in the air, and then -delivered a war-whoop and set off round and round the room, banging -against furniture, upsetting flower-pots, and making general havoc. -Next he rose on his hind feet and pranced around, in a frenzy of -enjoyment, with his head over his shoulder and his voice proclaiming -his unappeasable happiness. Then he went tearing around the house again -spreading chaos and destruction in his path. Aunt Polly entered in time -to see him throw a few double summersets, deliver a final mighty -hurrah, and sail through the open window, carrying the rest of the -flower-pots with him. The old lady stood petrified with astonishment, -peering over her glasses; Tom lay on the floor expiring with laughter. - -"Tom, what on earth ails that cat?" - -"I don't know, aunt," gasped the boy. - -"Why, I never see anything like it. What did make him act so?" - -"Deed I don't know, Aunt Polly; cats always act so when they're having -a good time." - -"They do, do they?" There was something in the tone that made Tom -apprehensive. - -"Yes'm. That is, I believe they do." - -"You DO?" - -"Yes'm." - -The old lady was bending down, Tom watching, with interest emphasized -by anxiety. Too late he divined her "drift." The handle of the telltale -teaspoon was visible under the bed-valance. Aunt Polly took it, held it -up. Tom winced, and dropped his eyes. Aunt Polly raised him by the -usual handle--his ear--and cracked his head soundly with her thimble. - -"Now, sir, what did you want to treat that poor dumb beast so, for?" - -"I done it out of pity for him--because he hadn't any aunt." - -"Hadn't any aunt!--you numskull. What has that got to do with it?" - -"Heaps. Because if he'd had one she'd a burnt him out herself! She'd a -roasted his bowels out of him 'thout any more feeling than if he was a -human!" - -Aunt Polly felt a sudden pang of remorse. This was putting the thing -in a new light; what was cruelty to a cat MIGHT be cruelty to a boy, -too. She began to soften; she felt sorry. Her eyes watered a little, -and she put her hand on Tom's head and said gently: - -"I was meaning for the best, Tom. And, Tom, it DID do you good." - -Tom looked up in her face with just a perceptible twinkle peeping -through his gravity. - -"I know you was meaning for the best, aunty, and so was I with Peter. -It done HIM good, too. I never see him get around so since--" - -"Oh, go 'long with you, Tom, before you aggravate me again. And you -try and see if you can't be a good boy, for once, and you needn't take -any more medicine." - -Tom reached school ahead of time. It was noticed that this strange -thing had been occurring every day latterly. And now, as usual of late, -he hung about the gate of the schoolyard instead of playing with his -comrades. He was sick, he said, and he looked it. He tried to seem to -be looking everywhere but whither he really was looking--down the road. -Presently Jeff Thatcher hove in sight, and Tom's face lighted; he gazed -a moment, and then turned sorrowfully away. When Jeff arrived, Tom -accosted him; and "led up" warily to opportunities for remark about -Becky, but the giddy lad never could see the bait. Tom watched and -watched, hoping whenever a frisking frock came in sight, and hating the -owner of it as soon as he saw she was not the right one. At last frocks -ceased to appear, and he dropped hopelessly into the dumps; he entered -the empty schoolhouse and sat down to suffer. Then one more frock -passed in at the gate, and Tom's heart gave a great bound. The next -instant he was out, and "going on" like an Indian; yelling, laughing, -chasing boys, jumping over the fence at risk of life and limb, throwing -handsprings, standing on his head--doing all the heroic things he could -conceive of, and keeping a furtive eye out, all the while, to see if -Becky Thatcher was noticing. But she seemed to be unconscious of it -all; she never looked. Could it be possible that she was not aware that -he was there? He carried his exploits to her immediate vicinity; came -war-whooping around, snatched a boy's cap, hurled it to the roof of the -schoolhouse, broke through a group of boys, tumbling them in every -direction, and fell sprawling, himself, under Becky's nose, almost -upsetting her--and she turned, with her nose in the air, and he heard -her say: "Mf! some people think they're mighty smart--always showing -off!" - -Tom's cheeks burned. He gathered himself up and sneaked off, crushed -and crestfallen. - - - -CHAPTER XIII - -TOM'S mind was made up now. He was gloomy and desperate. He was a -forsaken, friendless boy, he said; nobody loved him; when they found -out what they had driven him to, perhaps they would be sorry; he had -tried to do right and get along, but they would not let him; since -nothing would do them but to be rid of him, let it be so; and let them -blame HIM for the consequences--why shouldn't they? What right had the -friendless to complain? Yes, they had forced him to it at last: he -would lead a life of crime. There was no choice. - -By this time he was far down Meadow Lane, and the bell for school to -"take up" tinkled faintly upon his ear. He sobbed, now, to think he -should never, never hear that old familiar sound any more--it was very -hard, but it was forced on him; since he was driven out into the cold -world, he must submit--but he forgave them. Then the sobs came thick -and fast. - -Just at this point he met his soul's sworn comrade, Joe Harper ---hard-eyed, and with evidently a great and dismal purpose in his heart. -Plainly here were "two souls with but a single thought." Tom, wiping -his eyes with his sleeve, began to blubber out something about a -resolution to escape from hard usage and lack of sympathy at home by -roaming abroad into the great world never to return; and ended by -hoping that Joe would not forget him. - -But it transpired that this was a request which Joe had just been -going to make of Tom, and had come to hunt him up for that purpose. His -mother had whipped him for drinking some cream which he had never -tasted and knew nothing about; it was plain that she was tired of him -and wished him to go; if she felt that way, there was nothing for him -to do but succumb; he hoped she would be happy, and never regret having -driven her poor boy out into the unfeeling world to suffer and die. - -As the two boys walked sorrowing along, they made a new compact to -stand by each other and be brothers and never separate till death -relieved them of their troubles. Then they began to lay their plans. -Joe was for being a hermit, and living on crusts in a remote cave, and -dying, some time, of cold and want and grief; but after listening to -Tom, he conceded that there were some conspicuous advantages about a -life of crime, and so he consented to be a pirate. - -Three miles below St. Petersburg, at a point where the Mississippi -River was a trifle over a mile wide, there was a long, narrow, wooded -island, with a shallow bar at the head of it, and this offered well as -a rendezvous. It was not inhabited; it lay far over toward the further -shore, abreast a dense and almost wholly unpeopled forest. So Jackson's -Island was chosen. Who were to be the subjects of their piracies was a -matter that did not occur to them. Then they hunted up Huckleberry -Finn, and he joined them promptly, for all careers were one to him; he -was indifferent. They presently separated to meet at a lonely spot on -the river-bank two miles above the village at the favorite hour--which -was midnight. There was a small log raft there which they meant to -capture. Each would bring hooks and lines, and such provision as he -could steal in the most dark and mysterious way--as became outlaws. And -before the afternoon was done, they had all managed to enjoy the sweet -glory of spreading the fact that pretty soon the town would "hear -something." All who got this vague hint were cautioned to "be mum and -wait." - -About midnight Tom arrived with a boiled ham and a few trifles, -and stopped in a dense undergrowth on a small bluff overlooking the -meeting-place. It was starlight, and very still. The mighty river lay -like an ocean at rest. Tom listened a moment, but no sound disturbed the -quiet. Then he gave a low, distinct whistle. It was answered from under -the bluff. Tom whistled twice more; these signals were answered in the -same way. Then a guarded voice said: - -"Who goes there?" - -"Tom Sawyer, the Black Avenger of the Spanish Main. Name your names." - -"Huck Finn the Red-Handed, and Joe Harper the Terror of the Seas." Tom -had furnished these titles, from his favorite literature. - -"'Tis well. Give the countersign." - -Two hoarse whispers delivered the same awful word simultaneously to -the brooding night: - -"BLOOD!" - -Then Tom tumbled his ham over the bluff and let himself down after it, -tearing both skin and clothes to some extent in the effort. There was -an easy, comfortable path along the shore under the bluff, but it -lacked the advantages of difficulty and danger so valued by a pirate. - -The Terror of the Seas had brought a side of bacon, and had about worn -himself out with getting it there. Finn the Red-Handed had stolen a -skillet and a quantity of half-cured leaf tobacco, and had also brought -a few corn-cobs to make pipes with. But none of the pirates smoked or -"chewed" but himself. The Black Avenger of the Spanish Main said it -would never do to start without some fire. That was a wise thought; -matches were hardly known there in that day. They saw a fire -smouldering upon a great raft a hundred yards above, and they went -stealthily thither and helped themselves to a chunk. They made an -imposing adventure of it, saying, "Hist!" every now and then, and -suddenly halting with finger on lip; moving with hands on imaginary -dagger-hilts; and giving orders in dismal whispers that if "the foe" -stirred, to "let him have it to the hilt," because "dead men tell no -tales." They knew well enough that the raftsmen were all down at the -village laying in stores or having a spree, but still that was no -excuse for their conducting this thing in an unpiratical way. - -They shoved off, presently, Tom in command, Huck at the after oar and -Joe at the forward. Tom stood amidships, gloomy-browed, and with folded -arms, and gave his orders in a low, stern whisper: - -"Luff, and bring her to the wind!" - -"Aye-aye, sir!" - -"Steady, steady-y-y-y!" - -"Steady it is, sir!" - -"Let her go off a point!" - -"Point it is, sir!" - -As the boys steadily and monotonously drove the raft toward mid-stream -it was no doubt understood that these orders were given only for -"style," and were not intended to mean anything in particular. - -"What sail's she carrying?" - -"Courses, tops'ls, and flying-jib, sir." - -"Send the r'yals up! Lay out aloft, there, half a dozen of ye ---foretopmaststuns'l! Lively, now!" - -"Aye-aye, sir!" - -"Shake out that maintogalans'l! Sheets and braces! NOW my hearties!" - -"Aye-aye, sir!" - -"Hellum-a-lee--hard a port! Stand by to meet her when she comes! Port, -port! NOW, men! With a will! Stead-y-y-y!" - -"Steady it is, sir!" - -The raft drew beyond the middle of the river; the boys pointed her -head right, and then lay on their oars. The river was not high, so -there was not more than a two or three mile current. Hardly a word was -said during the next three-quarters of an hour. Now the raft was -passing before the distant town. Two or three glimmering lights showed -where it lay, peacefully sleeping, beyond the vague vast sweep of -star-gemmed water, unconscious of the tremendous event that was happening. -The Black Avenger stood still with folded arms, "looking his last" upon -the scene of his former joys and his later sufferings, and wishing -"she" could see him now, abroad on the wild sea, facing peril and death -with dauntless heart, going to his doom with a grim smile on his lips. -It was but a small strain on his imagination to remove Jackson's Island -beyond eyeshot of the village, and so he "looked his last" with a -broken and satisfied heart. The other pirates were looking their last, -too; and they all looked so long that they came near letting the -current drift them out of the range of the island. But they discovered -the danger in time, and made shift to avert it. About two o'clock in -the morning the raft grounded on the bar two hundred yards above the -head of the island, and they waded back and forth until they had landed -their freight. Part of the little raft's belongings consisted of an old -sail, and this they spread over a nook in the bushes for a tent to -shelter their provisions; but they themselves would sleep in the open -air in good weather, as became outlaws. - -They built a fire against the side of a great log twenty or thirty -steps within the sombre depths of the forest, and then cooked some -bacon in the frying-pan for supper, and used up half of the corn "pone" -stock they had brought. It seemed glorious sport to be feasting in that -wild, free way in the virgin forest of an unexplored and uninhabited -island, far from the haunts of men, and they said they never would -return to civilization. The climbing fire lit up their faces and threw -its ruddy glare upon the pillared tree-trunks of their forest temple, -and upon the varnished foliage and festooning vines. - -When the last crisp slice of bacon was gone, and the last allowance of -corn pone devoured, the boys stretched themselves out on the grass, -filled with contentment. They could have found a cooler place, but they -would not deny themselves such a romantic feature as the roasting -camp-fire. - -"AIN'T it gay?" said Joe. - -"It's NUTS!" said Tom. "What would the boys say if they could see us?" - -"Say? Well, they'd just die to be here--hey, Hucky!" - -"I reckon so," said Huckleberry; "anyways, I'm suited. I don't want -nothing better'n this. I don't ever get enough to eat, gen'ally--and -here they can't come and pick at a feller and bullyrag him so." - -"It's just the life for me," said Tom. "You don't have to get up, -mornings, and you don't have to go to school, and wash, and all that -blame foolishness. You see a pirate don't have to do ANYTHING, Joe, -when he's ashore, but a hermit HE has to be praying considerable, and -then he don't have any fun, anyway, all by himself that way." - -"Oh yes, that's so," said Joe, "but I hadn't thought much about it, -you know. I'd a good deal rather be a pirate, now that I've tried it." - -"You see," said Tom, "people don't go much on hermits, nowadays, like -they used to in old times, but a pirate's always respected. And a -hermit's got to sleep on the hardest place he can find, and put -sackcloth and ashes on his head, and stand out in the rain, and--" - -"What does he put sackcloth and ashes on his head for?" inquired Huck. - -"I dono. But they've GOT to do it. Hermits always do. You'd have to do -that if you was a hermit." - -"Dern'd if I would," said Huck. - -"Well, what would you do?" - -"I dono. But I wouldn't do that." - -"Why, Huck, you'd HAVE to. How'd you get around it?" - -"Why, I just wouldn't stand it. I'd run away." - -"Run away! Well, you WOULD be a nice old slouch of a hermit. You'd be -a disgrace." - -The Red-Handed made no response, being better employed. He had -finished gouging out a cob, and now he fitted a weed stem to it, loaded -it with tobacco, and was pressing a coal to the charge and blowing a -cloud of fragrant smoke--he was in the full bloom of luxurious -contentment. The other pirates envied him this majestic vice, and -secretly resolved to acquire it shortly. Presently Huck said: - -"What does pirates have to do?" - -Tom said: - -"Oh, they have just a bully time--take ships and burn them, and get -the money and bury it in awful places in their island where there's -ghosts and things to watch it, and kill everybody in the ships--make -'em walk a plank." - -"And they carry the women to the island," said Joe; "they don't kill -the women." - -"No," assented Tom, "they don't kill the women--they're too noble. And -the women's always beautiful, too. - -"And don't they wear the bulliest clothes! Oh no! All gold and silver -and di'monds," said Joe, with enthusiasm. - -"Who?" said Huck. - -"Why, the pirates." - -Huck scanned his own clothing forlornly. - -"I reckon I ain't dressed fitten for a pirate," said he, with a -regretful pathos in his voice; "but I ain't got none but these." - -But the other boys told him the fine clothes would come fast enough, -after they should have begun their adventures. They made him understand -that his poor rags would do to begin with, though it was customary for -wealthy pirates to start with a proper wardrobe. - -Gradually their talk died out and drowsiness began to steal upon the -eyelids of the little waifs. The pipe dropped from the fingers of the -Red-Handed, and he slept the sleep of the conscience-free and the -weary. The Terror of the Seas and the Black Avenger of the Spanish Main -had more difficulty in getting to sleep. They said their prayers -inwardly, and lying down, since there was nobody there with authority -to make them kneel and recite aloud; in truth, they had a mind not to -say them at all, but they were afraid to proceed to such lengths as -that, lest they might call down a sudden and special thunderbolt from -heaven. Then at once they reached and hovered upon the imminent verge -of sleep--but an intruder came, now, that would not "down." It was -conscience. They began to feel a vague fear that they had been doing -wrong to run away; and next they thought of the stolen meat, and then -the real torture came. They tried to argue it away by reminding -conscience that they had purloined sweetmeats and apples scores of -times; but conscience was not to be appeased by such thin -plausibilities; it seemed to them, in the end, that there was no -getting around the stubborn fact that taking sweetmeats was only -"hooking," while taking bacon and hams and such valuables was plain -simple stealing--and there was a command against that in the Bible. So -they inwardly resolved that so long as they remained in the business, -their piracies should not again be sullied with the crime of stealing. -Then conscience granted a truce, and these curiously inconsistent -pirates fell peacefully to sleep. - - - -CHAPTER XIV - -WHEN Tom awoke in the morning, he wondered where he was. He sat up and -rubbed his eyes and looked around. Then he comprehended. It was the -cool gray dawn, and there was a delicious sense of repose and peace in -the deep pervading calm and silence of the woods. Not a leaf stirred; -not a sound obtruded upon great Nature's meditation. Beaded dewdrops -stood upon the leaves and grasses. A white layer of ashes covered the -fire, and a thin blue breath of smoke rose straight into the air. Joe -and Huck still slept. - -Now, far away in the woods a bird called; another answered; presently -the hammering of a woodpecker was heard. Gradually the cool dim gray of -the morning whitened, and as gradually sounds multiplied and life -manifested itself. The marvel of Nature shaking off sleep and going to -work unfolded itself to the musing boy. A little green worm came -crawling over a dewy leaf, lifting two-thirds of his body into the air -from time to time and "sniffing around," then proceeding again--for he -was measuring, Tom said; and when the worm approached him, of its own -accord, he sat as still as a stone, with his hopes rising and falling, -by turns, as the creature still came toward him or seemed inclined to -go elsewhere; and when at last it considered a painful moment with its -curved body in the air and then came decisively down upon Tom's leg and -began a journey over him, his whole heart was glad--for that meant that -he was going to have a new suit of clothes--without the shadow of a -doubt a gaudy piratical uniform. Now a procession of ants appeared, -from nowhere in particular, and went about their labors; one struggled -manfully by with a dead spider five times as big as itself in its arms, -and lugged it straight up a tree-trunk. A brown spotted lady-bug -climbed the dizzy height of a grass blade, and Tom bent down close to -it and said, "Lady-bug, lady-bug, fly away home, your house is on fire, -your children's alone," and she took wing and went off to see about it ---which did not surprise the boy, for he knew of old that this insect was -credulous about conflagrations, and he had practised upon its -simplicity more than once. A tumblebug came next, heaving sturdily at -its ball, and Tom touched the creature, to see it shut its legs against -its body and pretend to be dead. The birds were fairly rioting by this -time. A catbird, the Northern mocker, lit in a tree over Tom's head, -and trilled out her imitations of her neighbors in a rapture of -enjoyment; then a shrill jay swept down, a flash of blue flame, and -stopped on a twig almost within the boy's reach, cocked his head to one -side and eyed the strangers with a consuming curiosity; a gray squirrel -and a big fellow of the "fox" kind came skurrying along, sitting up at -intervals to inspect and chatter at the boys, for the wild things had -probably never seen a human being before and scarcely knew whether to -be afraid or not. All Nature was wide awake and stirring, now; long -lances of sunlight pierced down through the dense foliage far and near, -and a few butterflies came fluttering upon the scene. - -Tom stirred up the other pirates and they all clattered away with a -shout, and in a minute or two were stripped and chasing after and -tumbling over each other in the shallow limpid water of the white -sandbar. They felt no longing for the little village sleeping in the -distance beyond the majestic waste of water. A vagrant current or a -slight rise in the river had carried off their raft, but this only -gratified them, since its going was something like burning the bridge -between them and civilization. - -They came back to camp wonderfully refreshed, glad-hearted, and -ravenous; and they soon had the camp-fire blazing up again. Huck found -a spring of clear cold water close by, and the boys made cups of broad -oak or hickory leaves, and felt that water, sweetened with such a -wildwood charm as that, would be a good enough substitute for coffee. -While Joe was slicing bacon for breakfast, Tom and Huck asked him to -hold on a minute; they stepped to a promising nook in the river-bank -and threw in their lines; almost immediately they had reward. Joe had -not had time to get impatient before they were back again with some -handsome bass, a couple of sun-perch and a small catfish--provisions -enough for quite a family. They fried the fish with the bacon, and were -astonished; for no fish had ever seemed so delicious before. They did -not know that the quicker a fresh-water fish is on the fire after he is -caught the better he is; and they reflected little upon what a sauce -open-air sleeping, open-air exercise, bathing, and a large ingredient -of hunger make, too. - -They lay around in the shade, after breakfast, while Huck had a smoke, -and then went off through the woods on an exploring expedition. They -tramped gayly along, over decaying logs, through tangled underbrush, -among solemn monarchs of the forest, hung from their crowns to the -ground with a drooping regalia of grape-vines. Now and then they came -upon snug nooks carpeted with grass and jeweled with flowers. - -They found plenty of things to be delighted with, but nothing to be -astonished at. They discovered that the island was about three miles -long and a quarter of a mile wide, and that the shore it lay closest to -was only separated from it by a narrow channel hardly two hundred yards -wide. They took a swim about every hour, so it was close upon the -middle of the afternoon when they got back to camp. They were too -hungry to stop to fish, but they fared sumptuously upon cold ham, and -then threw themselves down in the shade to talk. But the talk soon -began to drag, and then died. The stillness, the solemnity that brooded -in the woods, and the sense of loneliness, began to tell upon the -spirits of the boys. They fell to thinking. A sort of undefined longing -crept upon them. This took dim shape, presently--it was budding -homesickness. Even Finn the Red-Handed was dreaming of his doorsteps -and empty hogsheads. But they were all ashamed of their weakness, and -none was brave enough to speak his thought. - -For some time, now, the boys had been dully conscious of a peculiar -sound in the distance, just as one sometimes is of the ticking of a -clock which he takes no distinct note of. But now this mysterious sound -became more pronounced, and forced a recognition. The boys started, -glanced at each other, and then each assumed a listening attitude. -There was a long silence, profound and unbroken; then a deep, sullen -boom came floating down out of the distance. - -"What is it!" exclaimed Joe, under his breath. - -"I wonder," said Tom in a whisper. - -"'Tain't thunder," said Huckleberry, in an awed tone, "becuz thunder--" - -"Hark!" said Tom. "Listen--don't talk." - -They waited a time that seemed an age, and then the same muffled boom -troubled the solemn hush. - -"Let's go and see." - -They sprang to their feet and hurried to the shore toward the town. -They parted the bushes on the bank and peered out over the water. The -little steam ferryboat was about a mile below the village, drifting -with the current. Her broad deck seemed crowded with people. There were -a great many skiffs rowing about or floating with the stream in the -neighborhood of the ferryboat, but the boys could not determine what -the men in them were doing. Presently a great jet of white smoke burst -from the ferryboat's side, and as it expanded and rose in a lazy cloud, -that same dull throb of sound was borne to the listeners again. - -"I know now!" exclaimed Tom; "somebody's drownded!" - -"That's it!" said Huck; "they done that last summer, when Bill Turner -got drownded; they shoot a cannon over the water, and that makes him -come up to the top. Yes, and they take loaves of bread and put -quicksilver in 'em and set 'em afloat, and wherever there's anybody -that's drownded, they'll float right there and stop." - -"Yes, I've heard about that," said Joe. "I wonder what makes the bread -do that." - -"Oh, it ain't the bread, so much," said Tom; "I reckon it's mostly -what they SAY over it before they start it out." - -"But they don't say anything over it," said Huck. "I've seen 'em and -they don't." - -"Well, that's funny," said Tom. "But maybe they say it to themselves. -Of COURSE they do. Anybody might know that." - -The other boys agreed that there was reason in what Tom said, because -an ignorant lump of bread, uninstructed by an incantation, could not be -expected to act very intelligently when set upon an errand of such -gravity. - -"By jings, I wish I was over there, now," said Joe. - -"I do too" said Huck "I'd give heaps to know who it is." - -The boys still listened and watched. Presently a revealing thought -flashed through Tom's mind, and he exclaimed: - -"Boys, I know who's drownded--it's us!" - -They felt like heroes in an instant. Here was a gorgeous triumph; they -were missed; they were mourned; hearts were breaking on their account; -tears were being shed; accusing memories of unkindness to these poor -lost lads were rising up, and unavailing regrets and remorse were being -indulged; and best of all, the departed were the talk of the whole -town, and the envy of all the boys, as far as this dazzling notoriety -was concerned. This was fine. It was worth while to be a pirate, after -all. - -As twilight drew on, the ferryboat went back to her accustomed -business and the skiffs disappeared. The pirates returned to camp. They -were jubilant with vanity over their new grandeur and the illustrious -trouble they were making. They caught fish, cooked supper and ate it, -and then fell to guessing at what the village was thinking and saying -about them; and the pictures they drew of the public distress on their -account were gratifying to look upon--from their point of view. But -when the shadows of night closed them in, they gradually ceased to -talk, and sat gazing into the fire, with their minds evidently -wandering elsewhere. The excitement was gone, now, and Tom and Joe -could not keep back thoughts of certain persons at home who were not -enjoying this fine frolic as much as they were. Misgivings came; they -grew troubled and unhappy; a sigh or two escaped, unawares. By and by -Joe timidly ventured upon a roundabout "feeler" as to how the others -might look upon a return to civilization--not right now, but-- - -Tom withered him with derision! Huck, being uncommitted as yet, joined -in with Tom, and the waverer quickly "explained," and was glad to get -out of the scrape with as little taint of chicken-hearted homesickness -clinging to his garments as he could. Mutiny was effectually laid to -rest for the moment. - -As the night deepened, Huck began to nod, and presently to snore. Joe -followed next. Tom lay upon his elbow motionless, for some time, -watching the two intently. At last he got up cautiously, on his knees, -and went searching among the grass and the flickering reflections flung -by the camp-fire. He picked up and inspected several large -semi-cylinders of the thin white bark of a sycamore, and finally chose -two which seemed to suit him. Then he knelt by the fire and painfully -wrote something upon each of these with his "red keel"; one he rolled up -and put in his jacket pocket, and the other he put in Joe's hat and -removed it to a little distance from the owner. And he also put into the -hat certain schoolboy treasures of almost inestimable value--among them -a lump of chalk, an India-rubber ball, three fishhooks, and one of that -kind of marbles known as a "sure 'nough crystal." Then he tiptoed his -way cautiously among the trees till he felt that he was out of hearing, -and straightway broke into a keen run in the direction of the sandbar. - - - -CHAPTER XV - -A FEW minutes later Tom was in the shoal water of the bar, wading -toward the Illinois shore. Before the depth reached his middle he was -half-way over; the current would permit no more wading, now, so he -struck out confidently to swim the remaining hundred yards. He swam -quartering upstream, but still was swept downward rather faster than he -had expected. However, he reached the shore finally, and drifted along -till he found a low place and drew himself out. He put his hand on his -jacket pocket, found his piece of bark safe, and then struck through -the woods, following the shore, with streaming garments. Shortly before -ten o'clock he came out into an open place opposite the village, and -saw the ferryboat lying in the shadow of the trees and the high bank. -Everything was quiet under the blinking stars. He crept down the bank, -watching with all his eyes, slipped into the water, swam three or four -strokes and climbed into the skiff that did "yawl" duty at the boat's -stern. He laid himself down under the thwarts and waited, panting. - -Presently the cracked bell tapped and a voice gave the order to "cast -off." A minute or two later the skiff's head was standing high up, -against the boat's swell, and the voyage was begun. Tom felt happy in -his success, for he knew it was the boat's last trip for the night. At -the end of a long twelve or fifteen minutes the wheels stopped, and Tom -slipped overboard and swam ashore in the dusk, landing fifty yards -downstream, out of danger of possible stragglers. - -He flew along unfrequented alleys, and shortly found himself at his -aunt's back fence. He climbed over, approached the "ell," and looked in -at the sitting-room window, for a light was burning there. There sat -Aunt Polly, Sid, Mary, and Joe Harper's mother, grouped together, -talking. They were by the bed, and the bed was between them and the -door. Tom went to the door and began to softly lift the latch; then he -pressed gently and the door yielded a crack; he continued pushing -cautiously, and quaking every time it creaked, till he judged he might -squeeze through on his knees; so he put his head through and began, -warily. - -"What makes the candle blow so?" said Aunt Polly. Tom hurried up. -"Why, that door's open, I believe. Why, of course it is. No end of -strange things now. Go 'long and shut it, Sid." - -Tom disappeared under the bed just in time. He lay and "breathed" -himself for a time, and then crept to where he could almost touch his -aunt's foot. - -"But as I was saying," said Aunt Polly, "he warn't BAD, so to say ---only mischEEvous. Only just giddy, and harum-scarum, you know. He -warn't any more responsible than a colt. HE never meant any harm, and -he was the best-hearted boy that ever was"--and she began to cry. - -"It was just so with my Joe--always full of his devilment, and up to -every kind of mischief, but he was just as unselfish and kind as he -could be--and laws bless me, to think I went and whipped him for taking -that cream, never once recollecting that I throwed it out myself -because it was sour, and I never to see him again in this world, never, -never, never, poor abused boy!" And Mrs. Harper sobbed as if her heart -would break. - -"I hope Tom's better off where he is," said Sid, "but if he'd been -better in some ways--" - -"SID!" Tom felt the glare of the old lady's eye, though he could not -see it. "Not a word against my Tom, now that he's gone! God'll take -care of HIM--never you trouble YOURself, sir! Oh, Mrs. Harper, I don't -know how to give him up! I don't know how to give him up! He was such a -comfort to me, although he tormented my old heart out of me, 'most." - -"The Lord giveth and the Lord hath taken away--Blessed be the name of -the Lord! But it's so hard--Oh, it's so hard! Only last Saturday my -Joe busted a firecracker right under my nose and I knocked him -sprawling. Little did I know then, how soon--Oh, if it was to do over -again I'd hug him and bless him for it." - -"Yes, yes, yes, I know just how you feel, Mrs. Harper, I know just -exactly how you feel. No longer ago than yesterday noon, my Tom took -and filled the cat full of Pain-killer, and I did think the cretur -would tear the house down. And God forgive me, I cracked Tom's head -with my thimble, poor boy, poor dead boy. But he's out of all his -troubles now. And the last words I ever heard him say was to reproach--" - -But this memory was too much for the old lady, and she broke entirely -down. Tom was snuffling, now, himself--and more in pity of himself than -anybody else. He could hear Mary crying, and putting in a kindly word -for him from time to time. He began to have a nobler opinion of himself -than ever before. Still, he was sufficiently touched by his aunt's -grief to long to rush out from under the bed and overwhelm her with -joy--and the theatrical gorgeousness of the thing appealed strongly to -his nature, too, but he resisted and lay still. - -He went on listening, and gathered by odds and ends that it was -conjectured at first that the boys had got drowned while taking a swim; -then the small raft had been missed; next, certain boys said the -missing lads had promised that the village should "hear something" -soon; the wise-heads had "put this and that together" and decided that -the lads had gone off on that raft and would turn up at the next town -below, presently; but toward noon the raft had been found, lodged -against the Missouri shore some five or six miles below the village ---and then hope perished; they must be drowned, else hunger would have -driven them home by nightfall if not sooner. It was believed that the -search for the bodies had been a fruitless effort merely because the -drowning must have occurred in mid-channel, since the boys, being good -swimmers, would otherwise have escaped to shore. This was Wednesday -night. If the bodies continued missing until Sunday, all hope would be -given over, and the funerals would be preached on that morning. Tom -shuddered. - -Mrs. Harper gave a sobbing good-night and turned to go. Then with a -mutual impulse the two bereaved women flung themselves into each -other's arms and had a good, consoling cry, and then parted. Aunt Polly -was tender far beyond her wont, in her good-night to Sid and Mary. Sid -snuffled a bit and Mary went off crying with all her heart. - -Aunt Polly knelt down and prayed for Tom so touchingly, so -appealingly, and with such measureless love in her words and her old -trembling voice, that he was weltering in tears again, long before she -was through. - -He had to keep still long after she went to bed, for she kept making -broken-hearted ejaculations from time to time, tossing unrestfully, and -turning over. But at last she was still, only moaning a little in her -sleep. Now the boy stole out, rose gradually by the bedside, shaded the -candle-light with his hand, and stood regarding her. His heart was full -of pity for her. He took out his sycamore scroll and placed it by the -candle. But something occurred to him, and he lingered considering. His -face lighted with a happy solution of his thought; he put the bark -hastily in his pocket. Then he bent over and kissed the faded lips, and -straightway made his stealthy exit, latching the door behind him. - -He threaded his way back to the ferry landing, found nobody at large -there, and walked boldly on board the boat, for he knew she was -tenantless except that there was a watchman, who always turned in and -slept like a graven image. He untied the skiff at the stern, slipped -into it, and was soon rowing cautiously upstream. When he had pulled a -mile above the village, he started quartering across and bent himself -stoutly to his work. He hit the landing on the other side neatly, for -this was a familiar bit of work to him. He was moved to capture the -skiff, arguing that it might be considered a ship and therefore -legitimate prey for a pirate, but he knew a thorough search would be -made for it and that might end in revelations. So he stepped ashore and -entered the woods. - -He sat down and took a long rest, torturing himself meanwhile to keep -awake, and then started warily down the home-stretch. The night was far -spent. It was broad daylight before he found himself fairly abreast the -island bar. He rested again until the sun was well up and gilding the -great river with its splendor, and then he plunged into the stream. A -little later he paused, dripping, upon the threshold of the camp, and -heard Joe say: - -"No, Tom's true-blue, Huck, and he'll come back. He won't desert. He -knows that would be a disgrace to a pirate, and Tom's too proud for -that sort of thing. He's up to something or other. Now I wonder what?" - -"Well, the things is ours, anyway, ain't they?" - -"Pretty near, but not yet, Huck. The writing says they are if he ain't -back here to breakfast." - -"Which he is!" exclaimed Tom, with fine dramatic effect, stepping -grandly into camp. - -A sumptuous breakfast of bacon and fish was shortly provided, and as -the boys set to work upon it, Tom recounted (and adorned) his -adventures. They were a vain and boastful company of heroes when the -tale was done. Then Tom hid himself away in a shady nook to sleep till -noon, and the other pirates got ready to fish and explore. - - - -CHAPTER XVI - -AFTER dinner all the gang turned out to hunt for turtle eggs on the -bar. They went about poking sticks into the sand, and when they found a -soft place they went down on their knees and dug with their hands. -Sometimes they would take fifty or sixty eggs out of one hole. They -were perfectly round white things a trifle smaller than an English -walnut. They had a famous fried-egg feast that night, and another on -Friday morning. - -After breakfast they went whooping and prancing out on the bar, and -chased each other round and round, shedding clothes as they went, until -they were naked, and then continued the frolic far away up the shoal -water of the bar, against the stiff current, which latter tripped their -legs from under them from time to time and greatly increased the fun. -And now and then they stooped in a group and splashed water in each -other's faces with their palms, gradually approaching each other, with -averted faces to avoid the strangling sprays, and finally gripping and -struggling till the best man ducked his neighbor, and then they all -went under in a tangle of white legs and arms and came up blowing, -sputtering, laughing, and gasping for breath at one and the same time. - -When they were well exhausted, they would run out and sprawl on the -dry, hot sand, and lie there and cover themselves up with it, and by -and by break for the water again and go through the original -performance once more. Finally it occurred to them that their naked -skin represented flesh-colored "tights" very fairly; so they drew a -ring in the sand and had a circus--with three clowns in it, for none -would yield this proudest post to his neighbor. - -Next they got their marbles and played "knucks" and "ring-taw" and -"keeps" till that amusement grew stale. Then Joe and Huck had another -swim, but Tom would not venture, because he found that in kicking off -his trousers he had kicked his string of rattlesnake rattles off his -ankle, and he wondered how he had escaped cramp so long without the -protection of this mysterious charm. He did not venture again until he -had found it, and by that time the other boys were tired and ready to -rest. They gradually wandered apart, dropped into the "dumps," and fell -to gazing longingly across the wide river to where the village lay -drowsing in the sun. Tom found himself writing "BECKY" in the sand with -his big toe; he scratched it out, and was angry with himself for his -weakness. But he wrote it again, nevertheless; he could not help it. He -erased it once more and then took himself out of temptation by driving -the other boys together and joining them. - -But Joe's spirits had gone down almost beyond resurrection. He was so -homesick that he could hardly endure the misery of it. The tears lay -very near the surface. Huck was melancholy, too. Tom was downhearted, -but tried hard not to show it. He had a secret which he was not ready -to tell, yet, but if this mutinous depression was not broken up soon, -he would have to bring it out. He said, with a great show of -cheerfulness: - -"I bet there's been pirates on this island before, boys. We'll explore -it again. They've hid treasures here somewhere. How'd you feel to light -on a rotten chest full of gold and silver--hey?" - -But it roused only faint enthusiasm, which faded out, with no reply. -Tom tried one or two other seductions; but they failed, too. It was -discouraging work. Joe sat poking up the sand with a stick and looking -very gloomy. Finally he said: - -"Oh, boys, let's give it up. I want to go home. It's so lonesome." - -"Oh no, Joe, you'll feel better by and by," said Tom. "Just think of -the fishing that's here." - -"I don't care for fishing. I want to go home." - -"But, Joe, there ain't such another swimming-place anywhere." - -"Swimming's no good. I don't seem to care for it, somehow, when there -ain't anybody to say I sha'n't go in. I mean to go home." - -"Oh, shucks! Baby! You want to see your mother, I reckon." - -"Yes, I DO want to see my mother--and you would, too, if you had one. -I ain't any more baby than you are." And Joe snuffled a little. - -"Well, we'll let the cry-baby go home to his mother, won't we, Huck? -Poor thing--does it want to see its mother? And so it shall. You like -it here, don't you, Huck? We'll stay, won't we?" - -Huck said, "Y-e-s"--without any heart in it. - -"I'll never speak to you again as long as I live," said Joe, rising. -"There now!" And he moved moodily away and began to dress himself. - -"Who cares!" said Tom. "Nobody wants you to. Go 'long home and get -laughed at. Oh, you're a nice pirate. Huck and me ain't cry-babies. -We'll stay, won't we, Huck? Let him go if he wants to. I reckon we can -get along without him, per'aps." - -But Tom was uneasy, nevertheless, and was alarmed to see Joe go -sullenly on with his dressing. And then it was discomforting to see -Huck eying Joe's preparations so wistfully, and keeping up such an -ominous silence. Presently, without a parting word, Joe began to wade -off toward the Illinois shore. Tom's heart began to sink. He glanced at -Huck. Huck could not bear the look, and dropped his eyes. Then he said: - -"I want to go, too, Tom. It was getting so lonesome anyway, and now -it'll be worse. Let's us go, too, Tom." - -"I won't! You can all go, if you want to. I mean to stay." - -"Tom, I better go." - -"Well, go 'long--who's hendering you." - -Huck began to pick up his scattered clothes. He said: - -"Tom, I wisht you'd come, too. Now you think it over. We'll wait for -you when we get to shore." - -"Well, you'll wait a blame long time, that's all." - -Huck started sorrowfully away, and Tom stood looking after him, with a -strong desire tugging at his heart to yield his pride and go along too. -He hoped the boys would stop, but they still waded slowly on. It -suddenly dawned on Tom that it was become very lonely and still. He -made one final struggle with his pride, and then darted after his -comrades, yelling: - -"Wait! Wait! I want to tell you something!" - -They presently stopped and turned around. When he got to where they -were, he began unfolding his secret, and they listened moodily till at -last they saw the "point" he was driving at, and then they set up a -war-whoop of applause and said it was "splendid!" and said if he had -told them at first, they wouldn't have started away. He made a plausible -excuse; but his real reason had been the fear that not even the secret -would keep them with him any very great length of time, and so he had -meant to hold it in reserve as a last seduction. - -The lads came gayly back and went at their sports again with a will, -chattering all the time about Tom's stupendous plan and admiring the -genius of it. After a dainty egg and fish dinner, Tom said he wanted to -learn to smoke, now. Joe caught at the idea and said he would like to -try, too. So Huck made pipes and filled them. These novices had never -smoked anything before but cigars made of grape-vine, and they "bit" -the tongue, and were not considered manly anyway. - -Now they stretched themselves out on their elbows and began to puff, -charily, and with slender confidence. The smoke had an unpleasant -taste, and they gagged a little, but Tom said: - -"Why, it's just as easy! If I'd a knowed this was all, I'd a learnt -long ago." - -"So would I," said Joe. "It's just nothing." - -"Why, many a time I've looked at people smoking, and thought well I -wish I could do that; but I never thought I could," said Tom. - -"That's just the way with me, hain't it, Huck? You've heard me talk -just that way--haven't you, Huck? I'll leave it to Huck if I haven't." - -"Yes--heaps of times," said Huck. - -"Well, I have too," said Tom; "oh, hundreds of times. Once down by the -slaughter-house. Don't you remember, Huck? Bob Tanner was there, and -Johnny Miller, and Jeff Thatcher, when I said it. Don't you remember, -Huck, 'bout me saying that?" - -"Yes, that's so," said Huck. "That was the day after I lost a white -alley. No, 'twas the day before." - -"There--I told you so," said Tom. "Huck recollects it." - -"I bleeve I could smoke this pipe all day," said Joe. "I don't feel -sick." - -"Neither do I," said Tom. "I could smoke it all day. But I bet you -Jeff Thatcher couldn't." - -"Jeff Thatcher! Why, he'd keel over just with two draws. Just let him -try it once. HE'D see!" - -"I bet he would. And Johnny Miller--I wish could see Johnny Miller -tackle it once." - -"Oh, don't I!" said Joe. "Why, I bet you Johnny Miller couldn't any -more do this than nothing. Just one little snifter would fetch HIM." - -"'Deed it would, Joe. Say--I wish the boys could see us now." - -"So do I." - -"Say--boys, don't say anything about it, and some time when they're -around, I'll come up to you and say, 'Joe, got a pipe? I want a smoke.' -And you'll say, kind of careless like, as if it warn't anything, you'll -say, 'Yes, I got my OLD pipe, and another one, but my tobacker ain't -very good.' And I'll say, 'Oh, that's all right, if it's STRONG -enough.' And then you'll out with the pipes, and we'll light up just as -ca'm, and then just see 'em look!" - -"By jings, that'll be gay, Tom! I wish it was NOW!" - -"So do I! And when we tell 'em we learned when we was off pirating, -won't they wish they'd been along?" - -"Oh, I reckon not! I'll just BET they will!" - -So the talk ran on. But presently it began to flag a trifle, and grow -disjointed. The silences widened; the expectoration marvellously -increased. Every pore inside the boys' cheeks became a spouting -fountain; they could scarcely bail out the cellars under their tongues -fast enough to prevent an inundation; little overflowings down their -throats occurred in spite of all they could do, and sudden retchings -followed every time. Both boys were looking very pale and miserable, -now. Joe's pipe dropped from his nerveless fingers. Tom's followed. -Both fountains were going furiously and both pumps bailing with might -and main. Joe said feebly: - -"I've lost my knife. I reckon I better go and find it." - -Tom said, with quivering lips and halting utterance: - -"I'll help you. You go over that way and I'll hunt around by the -spring. No, you needn't come, Huck--we can find it." - -So Huck sat down again, and waited an hour. Then he found it lonesome, -and went to find his comrades. They were wide apart in the woods, both -very pale, both fast asleep. But something informed him that if they -had had any trouble they had got rid of it. - -They were not talkative at supper that night. They had a humble look, -and when Huck prepared his pipe after the meal and was going to prepare -theirs, they said no, they were not feeling very well--something they -ate at dinner had disagreed with them. - -About midnight Joe awoke, and called the boys. There was a brooding -oppressiveness in the air that seemed to bode something. The boys -huddled themselves together and sought the friendly companionship of -the fire, though the dull dead heat of the breathless atmosphere was -stifling. They sat still, intent and waiting. The solemn hush -continued. Beyond the light of the fire everything was swallowed up in -the blackness of darkness. Presently there came a quivering glow that -vaguely revealed the foliage for a moment and then vanished. By and by -another came, a little stronger. Then another. Then a faint moan came -sighing through the branches of the forest and the boys felt a fleeting -breath upon their cheeks, and shuddered with the fancy that the Spirit -of the Night had gone by. There was a pause. Now a weird flash turned -night into day and showed every little grass-blade, separate and -distinct, that grew about their feet. And it showed three white, -startled faces, too. A deep peal of thunder went rolling and tumbling -down the heavens and lost itself in sullen rumblings in the distance. A -sweep of chilly air passed by, rustling all the leaves and snowing the -flaky ashes broadcast about the fire. Another fierce glare lit up the -forest and an instant crash followed that seemed to rend the tree-tops -right over the boys' heads. They clung together in terror, in the thick -gloom that followed. A few big rain-drops fell pattering upon the -leaves. - -"Quick! boys, go for the tent!" exclaimed Tom. - -They sprang away, stumbling over roots and among vines in the dark, no -two plunging in the same direction. A furious blast roared through the -trees, making everything sing as it went. One blinding flash after -another came, and peal on peal of deafening thunder. And now a -drenching rain poured down and the rising hurricane drove it in sheets -along the ground. The boys cried out to each other, but the roaring -wind and the booming thunder-blasts drowned their voices utterly. -However, one by one they straggled in at last and took shelter under -the tent, cold, scared, and streaming with water; but to have company -in misery seemed something to be grateful for. They could not talk, the -old sail flapped so furiously, even if the other noises would have -allowed them. The tempest rose higher and higher, and presently the -sail tore loose from its fastenings and went winging away on the blast. -The boys seized each others' hands and fled, with many tumblings and -bruises, to the shelter of a great oak that stood upon the river-bank. -Now the battle was at its highest. Under the ceaseless conflagration of -lightning that flamed in the skies, everything below stood out in -clean-cut and shadowless distinctness: the bending trees, the billowy -river, white with foam, the driving spray of spume-flakes, the dim -outlines of the high bluffs on the other side, glimpsed through the -drifting cloud-rack and the slanting veil of rain. Every little while -some giant tree yielded the fight and fell crashing through the younger -growth; and the unflagging thunder-peals came now in ear-splitting -explosive bursts, keen and sharp, and unspeakably appalling. The storm -culminated in one matchless effort that seemed likely to tear the island -to pieces, burn it up, drown it to the tree-tops, blow it away, and -deafen every creature in it, all at one and the same moment. It was a -wild night for homeless young heads to be out in. - -But at last the battle was done, and the forces retired with weaker -and weaker threatenings and grumblings, and peace resumed her sway. The -boys went back to camp, a good deal awed; but they found there was -still something to be thankful for, because the great sycamore, the -shelter of their beds, was a ruin, now, blasted by the lightnings, and -they were not under it when the catastrophe happened. - -Everything in camp was drenched, the camp-fire as well; for they were -but heedless lads, like their generation, and had made no provision -against rain. Here was matter for dismay, for they were soaked through -and chilled. They were eloquent in their distress; but they presently -discovered that the fire had eaten so far up under the great log it had -been built against (where it curved upward and separated itself from -the ground), that a handbreadth or so of it had escaped wetting; so -they patiently wrought until, with shreds and bark gathered from the -under sides of sheltered logs, they coaxed the fire to burn again. Then -they piled on great dead boughs till they had a roaring furnace, and -were glad-hearted once more. They dried their boiled ham and had a -feast, and after that they sat by the fire and expanded and glorified -their midnight adventure until morning, for there was not a dry spot to -sleep on, anywhere around. - -As the sun began to steal in upon the boys, drowsiness came over them, -and they went out on the sandbar and lay down to sleep. They got -scorched out by and by, and drearily set about getting breakfast. After -the meal they felt rusty, and stiff-jointed, and a little homesick once -more. Tom saw the signs, and fell to cheering up the pirates as well as -he could. But they cared nothing for marbles, or circus, or swimming, -or anything. He reminded them of the imposing secret, and raised a ray -of cheer. While it lasted, he got them interested in a new device. This -was to knock off being pirates, for a while, and be Indians for a -change. They were attracted by this idea; so it was not long before -they were stripped, and striped from head to heel with black mud, like -so many zebras--all of them chiefs, of course--and then they went -tearing through the woods to attack an English settlement. - -By and by they separated into three hostile tribes, and darted upon -each other from ambush with dreadful war-whoops, and killed and scalped -each other by thousands. It was a gory day. Consequently it was an -extremely satisfactory one. - -They assembled in camp toward supper-time, hungry and happy; but now a -difficulty arose--hostile Indians could not break the bread of -hospitality together without first making peace, and this was a simple -impossibility without smoking a pipe of peace. There was no other -process that ever they had heard of. Two of the savages almost wished -they had remained pirates. However, there was no other way; so with -such show of cheerfulness as they could muster they called for the pipe -and took their whiff as it passed, in due form. - -And behold, they were glad they had gone into savagery, for they had -gained something; they found that they could now smoke a little without -having to go and hunt for a lost knife; they did not get sick enough to -be seriously uncomfortable. They were not likely to fool away this high -promise for lack of effort. No, they practised cautiously, after -supper, with right fair success, and so they spent a jubilant evening. -They were prouder and happier in their new acquirement than they would -have been in the scalping and skinning of the Six Nations. We will -leave them to smoke and chatter and brag, since we have no further use -for them at present. - - - -CHAPTER XVII - -BUT there was no hilarity in the little town that same tranquil -Saturday afternoon. The Harpers, and Aunt Polly's family, were being -put into mourning, with great grief and many tears. An unusual quiet -possessed the village, although it was ordinarily quiet enough, in all -conscience. The villagers conducted their concerns with an absent air, -and talked little; but they sighed often. The Saturday holiday seemed a -burden to the children. They had no heart in their sports, and -gradually gave them up. - -In the afternoon Becky Thatcher found herself moping about the -deserted schoolhouse yard, and feeling very melancholy. But she found -nothing there to comfort her. She soliloquized: - -"Oh, if I only had a brass andiron-knob again! But I haven't got -anything now to remember him by." And she choked back a little sob. - -Presently she stopped, and said to herself: - -"It was right here. Oh, if it was to do over again, I wouldn't say -that--I wouldn't say it for the whole world. But he's gone now; I'll -never, never, never see him any more." - -This thought broke her down, and she wandered away, with tears rolling -down her cheeks. Then quite a group of boys and girls--playmates of -Tom's and Joe's--came by, and stood looking over the paling fence and -talking in reverent tones of how Tom did so-and-so the last time they -saw him, and how Joe said this and that small trifle (pregnant with -awful prophecy, as they could easily see now!)--and each speaker -pointed out the exact spot where the lost lads stood at the time, and -then added something like "and I was a-standing just so--just as I am -now, and as if you was him--I was as close as that--and he smiled, just -this way--and then something seemed to go all over me, like--awful, you -know--and I never thought what it meant, of course, but I can see now!" - -Then there was a dispute about who saw the dead boys last in life, and -many claimed that dismal distinction, and offered evidences, more or -less tampered with by the witness; and when it was ultimately decided -who DID see the departed last, and exchanged the last words with them, -the lucky parties took upon themselves a sort of sacred importance, and -were gaped at and envied by all the rest. One poor chap, who had no -other grandeur to offer, said with tolerably manifest pride in the -remembrance: - -"Well, Tom Sawyer he licked me once." - -But that bid for glory was a failure. Most of the boys could say that, -and so that cheapened the distinction too much. The group loitered -away, still recalling memories of the lost heroes, in awed voices. - -When the Sunday-school hour was finished, the next morning, the bell -began to toll, instead of ringing in the usual way. It was a very still -Sabbath, and the mournful sound seemed in keeping with the musing hush -that lay upon nature. The villagers began to gather, loitering a moment -in the vestibule to converse in whispers about the sad event. But there -was no whispering in the house; only the funereal rustling of dresses -as the women gathered to their seats disturbed the silence there. None -could remember when the little church had been so full before. There -was finally a waiting pause, an expectant dumbness, and then Aunt Polly -entered, followed by Sid and Mary, and they by the Harper family, all -in deep black, and the whole congregation, the old minister as well, -rose reverently and stood until the mourners were seated in the front -pew. There was another communing silence, broken at intervals by -muffled sobs, and then the minister spread his hands abroad and prayed. -A moving hymn was sung, and the text followed: "I am the Resurrection -and the Life." - -As the service proceeded, the clergyman drew such pictures of the -graces, the winning ways, and the rare promise of the lost lads that -every soul there, thinking he recognized these pictures, felt a pang in -remembering that he had persistently blinded himself to them always -before, and had as persistently seen only faults and flaws in the poor -boys. The minister related many a touching incident in the lives of the -departed, too, which illustrated their sweet, generous natures, and the -people could easily see, now, how noble and beautiful those episodes -were, and remembered with grief that at the time they occurred they had -seemed rank rascalities, well deserving of the cowhide. The -congregation became more and more moved, as the pathetic tale went on, -till at last the whole company broke down and joined the weeping -mourners in a chorus of anguished sobs, the preacher himself giving way -to his feelings, and crying in the pulpit. - -There was a rustle in the gallery, which nobody noticed; a moment -later the church door creaked; the minister raised his streaming eyes -above his handkerchief, and stood transfixed! First one and then -another pair of eyes followed the minister's, and then almost with one -impulse the congregation rose and stared while the three dead boys came -marching up the aisle, Tom in the lead, Joe next, and Huck, a ruin of -drooping rags, sneaking sheepishly in the rear! They had been hid in -the unused gallery listening to their own funeral sermon! - -Aunt Polly, Mary, and the Harpers threw themselves upon their restored -ones, smothered them with kisses and poured out thanksgivings, while -poor Huck stood abashed and uncomfortable, not knowing exactly what to -do or where to hide from so many unwelcoming eyes. He wavered, and -started to slink away, but Tom seized him and said: - -"Aunt Polly, it ain't fair. Somebody's got to be glad to see Huck." - -"And so they shall. I'm glad to see him, poor motherless thing!" And -the loving attentions Aunt Polly lavished upon him were the one thing -capable of making him more uncomfortable than he was before. - -Suddenly the minister shouted at the top of his voice: "Praise God -from whom all blessings flow--SING!--and put your hearts in it!" - -And they did. Old Hundred swelled up with a triumphant burst, and -while it shook the rafters Tom Sawyer the Pirate looked around upon the -envying juveniles about him and confessed in his heart that this was -the proudest moment of his life. - -As the "sold" congregation trooped out they said they would almost be -willing to be made ridiculous again to hear Old Hundred sung like that -once more. - -Tom got more cuffs and kisses that day--according to Aunt Polly's -varying moods--than he had earned before in a year; and he hardly knew -which expressed the most gratefulness to God and affection for himself. - - - -CHAPTER XVIII - -THAT was Tom's great secret--the scheme to return home with his -brother pirates and attend their own funerals. They had paddled over to -the Missouri shore on a log, at dusk on Saturday, landing five or six -miles below the village; they had slept in the woods at the edge of the -town till nearly daylight, and had then crept through back lanes and -alleys and finished their sleep in the gallery of the church among a -chaos of invalided benches. - -At breakfast, Monday morning, Aunt Polly and Mary were very loving to -Tom, and very attentive to his wants. There was an unusual amount of -talk. In the course of it Aunt Polly said: - -"Well, I don't say it wasn't a fine joke, Tom, to keep everybody -suffering 'most a week so you boys had a good time, but it is a pity -you could be so hard-hearted as to let me suffer so. If you could come -over on a log to go to your funeral, you could have come over and give -me a hint some way that you warn't dead, but only run off." - -"Yes, you could have done that, Tom," said Mary; "and I believe you -would if you had thought of it." - -"Would you, Tom?" said Aunt Polly, her face lighting wistfully. "Say, -now, would you, if you'd thought of it?" - -"I--well, I don't know. 'Twould 'a' spoiled everything." - -"Tom, I hoped you loved me that much," said Aunt Polly, with a grieved -tone that discomforted the boy. "It would have been something if you'd -cared enough to THINK of it, even if you didn't DO it." - -"Now, auntie, that ain't any harm," pleaded Mary; "it's only Tom's -giddy way--he is always in such a rush that he never thinks of -anything." - -"More's the pity. Sid would have thought. And Sid would have come and -DONE it, too. Tom, you'll look back, some day, when it's too late, and -wish you'd cared a little more for me when it would have cost you so -little." - -"Now, auntie, you know I do care for you," said Tom. - -"I'd know it better if you acted more like it." - -"I wish now I'd thought," said Tom, with a repentant tone; "but I -dreamt about you, anyway. That's something, ain't it?" - -"It ain't much--a cat does that much--but it's better than nothing. -What did you dream?" - -"Why, Wednesday night I dreamt that you was sitting over there by the -bed, and Sid was sitting by the woodbox, and Mary next to him." - -"Well, so we did. So we always do. I'm glad your dreams could take -even that much trouble about us." - -"And I dreamt that Joe Harper's mother was here." - -"Why, she was here! Did you dream any more?" - -"Oh, lots. But it's so dim, now." - -"Well, try to recollect--can't you?" - -"Somehow it seems to me that the wind--the wind blowed the--the--" - -"Try harder, Tom! The wind did blow something. Come!" - -Tom pressed his fingers on his forehead an anxious minute, and then -said: - -"I've got it now! I've got it now! It blowed the candle!" - -"Mercy on us! Go on, Tom--go on!" - -"And it seems to me that you said, 'Why, I believe that that door--'" - -"Go ON, Tom!" - -"Just let me study a moment--just a moment. Oh, yes--you said you -believed the door was open." - -"As I'm sitting here, I did! Didn't I, Mary! Go on!" - -"And then--and then--well I won't be certain, but it seems like as if -you made Sid go and--and--" - -"Well? Well? What did I make him do, Tom? What did I make him do?" - -"You made him--you--Oh, you made him shut it." - -"Well, for the land's sake! I never heard the beat of that in all my -days! Don't tell ME there ain't anything in dreams, any more. Sereny -Harper shall know of this before I'm an hour older. I'd like to see her -get around THIS with her rubbage 'bout superstition. Go on, Tom!" - -"Oh, it's all getting just as bright as day, now. Next you said I -warn't BAD, only mischeevous and harum-scarum, and not any more -responsible than--than--I think it was a colt, or something." - -"And so it was! Well, goodness gracious! Go on, Tom!" - -"And then you began to cry." - -"So I did. So I did. Not the first time, neither. And then--" - -"Then Mrs. Harper she began to cry, and said Joe was just the same, -and she wished she hadn't whipped him for taking cream when she'd -throwed it out her own self--" - -"Tom! The sperrit was upon you! You was a prophesying--that's what you -was doing! Land alive, go on, Tom!" - -"Then Sid he said--he said--" - -"I don't think I said anything," said Sid. - -"Yes you did, Sid," said Mary. - -"Shut your heads and let Tom go on! What did he say, Tom?" - -"He said--I THINK he said he hoped I was better off where I was gone -to, but if I'd been better sometimes--" - -"THERE, d'you hear that! It was his very words!" - -"And you shut him up sharp." - -"I lay I did! There must 'a' been an angel there. There WAS an angel -there, somewheres!" - -"And Mrs. Harper told about Joe scaring her with a firecracker, and -you told about Peter and the Painkiller--" - -"Just as true as I live!" - -"And then there was a whole lot of talk 'bout dragging the river for -us, and 'bout having the funeral Sunday, and then you and old Miss -Harper hugged and cried, and she went." - -"It happened just so! It happened just so, as sure as I'm a-sitting in -these very tracks. Tom, you couldn't told it more like if you'd 'a' -seen it! And then what? Go on, Tom!" - -"Then I thought you prayed for me--and I could see you and hear every -word you said. And you went to bed, and I was so sorry that I took and -wrote on a piece of sycamore bark, 'We ain't dead--we are only off -being pirates,' and put it on the table by the candle; and then you -looked so good, laying there asleep, that I thought I went and leaned -over and kissed you on the lips." - -"Did you, Tom, DID you! I just forgive you everything for that!" And -she seized the boy in a crushing embrace that made him feel like the -guiltiest of villains. - -"It was very kind, even though it was only a--dream," Sid soliloquized -just audibly. - -"Shut up, Sid! A body does just the same in a dream as he'd do if he -was awake. Here's a big Milum apple I've been saving for you, Tom, if -you was ever found again--now go 'long to school. I'm thankful to the -good God and Father of us all I've got you back, that's long-suffering -and merciful to them that believe on Him and keep His word, though -goodness knows I'm unworthy of it, but if only the worthy ones got His -blessings and had His hand to help them over the rough places, there's -few enough would smile here or ever enter into His rest when the long -night comes. Go 'long Sid, Mary, Tom--take yourselves off--you've -hendered me long enough." - -The children left for school, and the old lady to call on Mrs. Harper -and vanquish her realism with Tom's marvellous dream. Sid had better -judgment than to utter the thought that was in his mind as he left the -house. It was this: "Pretty thin--as long a dream as that, without any -mistakes in it!" - -What a hero Tom was become, now! He did not go skipping and prancing, -but moved with a dignified swagger as became a pirate who felt that the -public eye was on him. And indeed it was; he tried not to seem to see -the looks or hear the remarks as he passed along, but they were food -and drink to him. Smaller boys than himself flocked at his heels, as -proud to be seen with him, and tolerated by him, as if he had been the -drummer at the head of a procession or the elephant leading a menagerie -into town. Boys of his own size pretended not to know he had been away -at all; but they were consuming with envy, nevertheless. They would -have given anything to have that swarthy suntanned skin of his, and his -glittering notoriety; and Tom would not have parted with either for a -circus. - -At school the children made so much of him and of Joe, and delivered -such eloquent admiration from their eyes, that the two heroes were not -long in becoming insufferably "stuck-up." They began to tell their -adventures to hungry listeners--but they only began; it was not a thing -likely to have an end, with imaginations like theirs to furnish -material. And finally, when they got out their pipes and went serenely -puffing around, the very summit of glory was reached. - -Tom decided that he could be independent of Becky Thatcher now. Glory -was sufficient. He would live for glory. Now that he was distinguished, -maybe she would be wanting to "make up." Well, let her--she should see -that he could be as indifferent as some other people. Presently she -arrived. Tom pretended not to see her. He moved away and joined a group -of boys and girls and began to talk. Soon he observed that she was -tripping gayly back and forth with flushed face and dancing eyes, -pretending to be busy chasing schoolmates, and screaming with laughter -when she made a capture; but he noticed that she always made her -captures in his vicinity, and that she seemed to cast a conscious eye -in his direction at such times, too. It gratified all the vicious -vanity that was in him; and so, instead of winning him, it only "set -him up" the more and made him the more diligent to avoid betraying that -he knew she was about. Presently she gave over skylarking, and moved -irresolutely about, sighing once or twice and glancing furtively and -wistfully toward Tom. Then she observed that now Tom was talking more -particularly to Amy Lawrence than to any one else. She felt a sharp -pang and grew disturbed and uneasy at once. She tried to go away, but -her feet were treacherous, and carried her to the group instead. She -said to a girl almost at Tom's elbow--with sham vivacity: - -"Why, Mary Austin! you bad girl, why didn't you come to Sunday-school?" - -"I did come--didn't you see me?" - -"Why, no! Did you? Where did you sit?" - -"I was in Miss Peters' class, where I always go. I saw YOU." - -"Did you? Why, it's funny I didn't see you. I wanted to tell you about -the picnic." - -"Oh, that's jolly. Who's going to give it?" - -"My ma's going to let me have one." - -"Oh, goody; I hope she'll let ME come." - -"Well, she will. The picnic's for me. She'll let anybody come that I -want, and I want you." - -"That's ever so nice. When is it going to be?" - -"By and by. Maybe about vacation." - -"Oh, won't it be fun! You going to have all the girls and boys?" - -"Yes, every one that's friends to me--or wants to be"; and she glanced -ever so furtively at Tom, but he talked right along to Amy Lawrence -about the terrible storm on the island, and how the lightning tore the -great sycamore tree "all to flinders" while he was "standing within -three feet of it." - -"Oh, may I come?" said Grace Miller. - -"Yes." - -"And me?" said Sally Rogers. - -"Yes." - -"And me, too?" said Susy Harper. "And Joe?" - -"Yes." - -And so on, with clapping of joyful hands till all the group had begged -for invitations but Tom and Amy. Then Tom turned coolly away, still -talking, and took Amy with him. Becky's lips trembled and the tears -came to her eyes; she hid these signs with a forced gayety and went on -chattering, but the life had gone out of the picnic, now, and out of -everything else; she got away as soon as she could and hid herself and -had what her sex call "a good cry." Then she sat moody, with wounded -pride, till the bell rang. She roused up, now, with a vindictive cast -in her eye, and gave her plaited tails a shake and said she knew what -SHE'D do. - -At recess Tom continued his flirtation with Amy with jubilant -self-satisfaction. And he kept drifting about to find Becky and lacerate -her with the performance. At last he spied her, but there was a sudden -falling of his mercury. She was sitting cosily on a little bench behind -the schoolhouse looking at a picture-book with Alfred Temple--and so -absorbed were they, and their heads so close together over the book, -that they did not seem to be conscious of anything in the world besides. -Jealousy ran red-hot through Tom's veins. He began to hate himself for -throwing away the chance Becky had offered for a reconciliation. He -called himself a fool, and all the hard names he could think of. He -wanted to cry with vexation. Amy chatted happily along, as they walked, -for her heart was singing, but Tom's tongue had lost its function. He -did not hear what Amy was saying, and whenever she paused expectantly he -could only stammer an awkward assent, which was as often misplaced as -otherwise. He kept drifting to the rear of the schoolhouse, again and -again, to sear his eyeballs with the hateful spectacle there. He could -not help it. And it maddened him to see, as he thought he saw, that -Becky Thatcher never once suspected that he was even in the land of the -living. But she did see, nevertheless; and she knew she was winning her -fight, too, and was glad to see him suffer as she had suffered. - -Amy's happy prattle became intolerable. Tom hinted at things he had to -attend to; things that must be done; and time was fleeting. But in -vain--the girl chirped on. Tom thought, "Oh, hang her, ain't I ever -going to get rid of her?" At last he must be attending to those -things--and she said artlessly that she would be "around" when school -let out. And he hastened away, hating her for it. - -"Any other boy!" Tom thought, grating his teeth. "Any boy in the whole -town but that Saint Louis smarty that thinks he dresses so fine and is -aristocracy! Oh, all right, I licked you the first day you ever saw -this town, mister, and I'll lick you again! You just wait till I catch -you out! I'll just take and--" - -And he went through the motions of thrashing an imaginary boy ---pummelling the air, and kicking and gouging. "Oh, you do, do you? You -holler 'nough, do you? Now, then, let that learn you!" And so the -imaginary flogging was finished to his satisfaction. - -Tom fled home at noon. His conscience could not endure any more of -Amy's grateful happiness, and his jealousy could bear no more of the -other distress. Becky resumed her picture inspections with Alfred, but -as the minutes dragged along and no Tom came to suffer, her triumph -began to cloud and she lost interest; gravity and absent-mindedness -followed, and then melancholy; two or three times she pricked up her -ear at a footstep, but it was a false hope; no Tom came. At last she -grew entirely miserable and wished she hadn't carried it so far. When -poor Alfred, seeing that he was losing her, he did not know how, kept -exclaiming: "Oh, here's a jolly one! look at this!" she lost patience -at last, and said, "Oh, don't bother me! I don't care for them!" and -burst into tears, and got up and walked away. - -Alfred dropped alongside and was going to try to comfort her, but she -said: - -"Go away and leave me alone, can't you! I hate you!" - -So the boy halted, wondering what he could have done--for she had said -she would look at pictures all through the nooning--and she walked on, -crying. Then Alfred went musing into the deserted schoolhouse. He was -humiliated and angry. He easily guessed his way to the truth--the girl -had simply made a convenience of him to vent her spite upon Tom Sawyer. -He was far from hating Tom the less when this thought occurred to him. -He wished there was some way to get that boy into trouble without much -risk to himself. Tom's spelling-book fell under his eye. Here was his -opportunity. He gratefully opened to the lesson for the afternoon and -poured ink upon the page. - -Becky, glancing in at a window behind him at the moment, saw the act, -and moved on, without discovering herself. She started homeward, now, -intending to find Tom and tell him; Tom would be thankful and their -troubles would be healed. Before she was half way home, however, she -had changed her mind. The thought of Tom's treatment of her when she -was talking about her picnic came scorching back and filled her with -shame. She resolved to let him get whipped on the damaged -spelling-book's account, and to hate him forever, into the bargain. - - - -CHAPTER XIX - -TOM arrived at home in a dreary mood, and the first thing his aunt -said to him showed him that he had brought his sorrows to an -unpromising market: - -"Tom, I've a notion to skin you alive!" - -"Auntie, what have I done?" - -"Well, you've done enough. Here I go over to Sereny Harper, like an -old softy, expecting I'm going to make her believe all that rubbage -about that dream, when lo and behold you she'd found out from Joe that -you was over here and heard all the talk we had that night. Tom, I -don't know what is to become of a boy that will act like that. It makes -me feel so bad to think you could let me go to Sereny Harper and make -such a fool of myself and never say a word." - -This was a new aspect of the thing. His smartness of the morning had -seemed to Tom a good joke before, and very ingenious. It merely looked -mean and shabby now. He hung his head and could not think of anything -to say for a moment. Then he said: - -"Auntie, I wish I hadn't done it--but I didn't think." - -"Oh, child, you never think. You never think of anything but your own -selfishness. You could think to come all the way over here from -Jackson's Island in the night to laugh at our troubles, and you could -think to fool me with a lie about a dream; but you couldn't ever think -to pity us and save us from sorrow." - -"Auntie, I know now it was mean, but I didn't mean to be mean. I -didn't, honest. And besides, I didn't come over here to laugh at you -that night." - -"What did you come for, then?" - -"It was to tell you not to be uneasy about us, because we hadn't got -drownded." - -"Tom, Tom, I would be the thankfullest soul in this world if I could -believe you ever had as good a thought as that, but you know you never -did--and I know it, Tom." - -"Indeed and 'deed I did, auntie--I wish I may never stir if I didn't." - -"Oh, Tom, don't lie--don't do it. It only makes things a hundred times -worse." - -"It ain't a lie, auntie; it's the truth. I wanted to keep you from -grieving--that was all that made me come." - -"I'd give the whole world to believe that--it would cover up a power -of sins, Tom. I'd 'most be glad you'd run off and acted so bad. But it -ain't reasonable; because, why didn't you tell me, child?" - -"Why, you see, when you got to talking about the funeral, I just got -all full of the idea of our coming and hiding in the church, and I -couldn't somehow bear to spoil it. So I just put the bark back in my -pocket and kept mum." - -"What bark?" - -"The bark I had wrote on to tell you we'd gone pirating. I wish, now, -you'd waked up when I kissed you--I do, honest." - -The hard lines in his aunt's face relaxed and a sudden tenderness -dawned in her eyes. - -"DID you kiss me, Tom?" - -"Why, yes, I did." - -"Are you sure you did, Tom?" - -"Why, yes, I did, auntie--certain sure." - -"What did you kiss me for, Tom?" - -"Because I loved you so, and you laid there moaning and I was so sorry." - -The words sounded like truth. The old lady could not hide a tremor in -her voice when she said: - -"Kiss me again, Tom!--and be off with you to school, now, and don't -bother me any more." - -The moment he was gone, she ran to a closet and got out the ruin of a -jacket which Tom had gone pirating in. Then she stopped, with it in her -hand, and said to herself: - -"No, I don't dare. Poor boy, I reckon he's lied about it--but it's a -blessed, blessed lie, there's such a comfort come from it. I hope the -Lord--I KNOW the Lord will forgive him, because it was such -goodheartedness in him to tell it. But I don't want to find out it's a -lie. I won't look." - -She put the jacket away, and stood by musing a minute. Twice she put -out her hand to take the garment again, and twice she refrained. Once -more she ventured, and this time she fortified herself with the -thought: "It's a good lie--it's a good lie--I won't let it grieve me." -So she sought the jacket pocket. A moment later she was reading Tom's -piece of bark through flowing tears and saying: "I could forgive the -boy, now, if he'd committed a million sins!" - - - -CHAPTER XX - -THERE was something about Aunt Polly's manner, when she kissed Tom, -that swept away his low spirits and made him lighthearted and happy -again. He started to school and had the luck of coming upon Becky -Thatcher at the head of Meadow Lane. His mood always determined his -manner. Without a moment's hesitation he ran to her and said: - -"I acted mighty mean to-day, Becky, and I'm so sorry. I won't ever, -ever do that way again, as long as ever I live--please make up, won't -you?" - -The girl stopped and looked him scornfully in the face: - -"I'll thank you to keep yourself TO yourself, Mr. Thomas Sawyer. I'll -never speak to you again." - -She tossed her head and passed on. Tom was so stunned that he had not -even presence of mind enough to say "Who cares, Miss Smarty?" until the -right time to say it had gone by. So he said nothing. But he was in a -fine rage, nevertheless. He moped into the schoolyard wishing she were -a boy, and imagining how he would trounce her if she were. He presently -encountered her and delivered a stinging remark as he passed. She -hurled one in return, and the angry breach was complete. It seemed to -Becky, in her hot resentment, that she could hardly wait for school to -"take in," she was so impatient to see Tom flogged for the injured -spelling-book. If she had had any lingering notion of exposing Alfred -Temple, Tom's offensive fling had driven it entirely away. - -Poor girl, she did not know how fast she was nearing trouble herself. -The master, Mr. Dobbins, had reached middle age with an unsatisfied -ambition. The darling of his desires was, to be a doctor, but poverty -had decreed that he should be nothing higher than a village -schoolmaster. Every day he took a mysterious book out of his desk and -absorbed himself in it at times when no classes were reciting. He kept -that book under lock and key. There was not an urchin in school but was -perishing to have a glimpse of it, but the chance never came. Every boy -and girl had a theory about the nature of that book; but no two -theories were alike, and there was no way of getting at the facts in -the case. Now, as Becky was passing by the desk, which stood near the -door, she noticed that the key was in the lock! It was a precious -moment. She glanced around; found herself alone, and the next instant -she had the book in her hands. The title-page--Professor Somebody's -ANATOMY--carried no information to her mind; so she began to turn the -leaves. She came at once upon a handsomely engraved and colored -frontispiece--a human figure, stark naked. At that moment a shadow fell -on the page and Tom Sawyer stepped in at the door and caught a glimpse -of the picture. Becky snatched at the book to close it, and had the -hard luck to tear the pictured page half down the middle. She thrust -the volume into the desk, turned the key, and burst out crying with -shame and vexation. - -"Tom Sawyer, you are just as mean as you can be, to sneak up on a -person and look at what they're looking at." - -"How could I know you was looking at anything?" - -"You ought to be ashamed of yourself, Tom Sawyer; you know you're -going to tell on me, and oh, what shall I do, what shall I do! I'll be -whipped, and I never was whipped in school." - -Then she stamped her little foot and said: - -"BE so mean if you want to! I know something that's going to happen. -You just wait and you'll see! Hateful, hateful, hateful!"--and she -flung out of the house with a new explosion of crying. - -Tom stood still, rather flustered by this onslaught. Presently he said -to himself: - -"What a curious kind of a fool a girl is! Never been licked in school! -Shucks! What's a licking! That's just like a girl--they're so -thin-skinned and chicken-hearted. Well, of course I ain't going to tell -old Dobbins on this little fool, because there's other ways of getting -even on her, that ain't so mean; but what of it? Old Dobbins will ask -who it was tore his book. Nobody'll answer. Then he'll do just the way -he always does--ask first one and then t'other, and when he comes to the -right girl he'll know it, without any telling. Girls' faces always tell -on them. They ain't got any backbone. She'll get licked. Well, it's a -kind of a tight place for Becky Thatcher, because there ain't any way -out of it." Tom conned the thing a moment longer, and then added: "All -right, though; she'd like to see me in just such a fix--let her sweat it -out!" - -Tom joined the mob of skylarking scholars outside. In a few moments -the master arrived and school "took in." Tom did not feel a strong -interest in his studies. Every time he stole a glance at the girls' -side of the room Becky's face troubled him. Considering all things, he -did not want to pity her, and yet it was all he could do to help it. He -could get up no exultation that was really worthy the name. Presently -the spelling-book discovery was made, and Tom's mind was entirely full -of his own matters for a while after that. Becky roused up from her -lethargy of distress and showed good interest in the proceedings. She -did not expect that Tom could get out of his trouble by denying that he -spilt the ink on the book himself; and she was right. The denial only -seemed to make the thing worse for Tom. Becky supposed she would be -glad of that, and she tried to believe she was glad of it, but she -found she was not certain. When the worst came to the worst, she had an -impulse to get up and tell on Alfred Temple, but she made an effort and -forced herself to keep still--because, said she to herself, "he'll tell -about me tearing the picture sure. I wouldn't say a word, not to save -his life!" - -Tom took his whipping and went back to his seat not at all -broken-hearted, for he thought it was possible that he had unknowingly -upset the ink on the spelling-book himself, in some skylarking bout--he -had denied it for form's sake and because it was custom, and had stuck -to the denial from principle. - -A whole hour drifted by, the master sat nodding in his throne, the air -was drowsy with the hum of study. By and by, Mr. Dobbins straightened -himself up, yawned, then unlocked his desk, and reached for his book, -but seemed undecided whether to take it out or leave it. Most of the -pupils glanced up languidly, but there were two among them that watched -his movements with intent eyes. Mr. Dobbins fingered his book absently -for a while, then took it out and settled himself in his chair to read! -Tom shot a glance at Becky. He had seen a hunted and helpless rabbit -look as she did, with a gun levelled at its head. Instantly he forgot -his quarrel with her. Quick--something must be done! done in a flash, -too! But the very imminence of the emergency paralyzed his invention. -Good!--he had an inspiration! He would run and snatch the book, spring -through the door and fly. But his resolution shook for one little -instant, and the chance was lost--the master opened the volume. If Tom -only had the wasted opportunity back again! Too late. There was no help -for Becky now, he said. The next moment the master faced the school. -Every eye sank under his gaze. There was that in it which smote even -the innocent with fear. There was silence while one might count ten ---the master was gathering his wrath. Then he spoke: "Who tore this book?" - -There was not a sound. One could have heard a pin drop. The stillness -continued; the master searched face after face for signs of guilt. - -"Benjamin Rogers, did you tear this book?" - -A denial. Another pause. - -"Joseph Harper, did you?" - -Another denial. Tom's uneasiness grew more and more intense under the -slow torture of these proceedings. The master scanned the ranks of -boys--considered a while, then turned to the girls: - -"Amy Lawrence?" - -A shake of the head. - -"Gracie Miller?" - -The same sign. - -"Susan Harper, did you do this?" - -Another negative. The next girl was Becky Thatcher. Tom was trembling -from head to foot with excitement and a sense of the hopelessness of -the situation. - -"Rebecca Thatcher" [Tom glanced at her face--it was white with terror] ---"did you tear--no, look me in the face" [her hands rose in appeal] ---"did you tear this book?" - -A thought shot like lightning through Tom's brain. He sprang to his -feet and shouted--"I done it!" - -The school stared in perplexity at this incredible folly. Tom stood a -moment, to gather his dismembered faculties; and when he stepped -forward to go to his punishment the surprise, the gratitude, the -adoration that shone upon him out of poor Becky's eyes seemed pay -enough for a hundred floggings. Inspired by the splendor of his own -act, he took without an outcry the most merciless flaying that even Mr. -Dobbins had ever administered; and also received with indifference the -added cruelty of a command to remain two hours after school should be -dismissed--for he knew who would wait for him outside till his -captivity was done, and not count the tedious time as loss, either. - -Tom went to bed that night planning vengeance against Alfred Temple; -for with shame and repentance Becky had told him all, not forgetting -her own treachery; but even the longing for vengeance had to give way, -soon, to pleasanter musings, and he fell asleep at last with Becky's -latest words lingering dreamily in his ear-- - -"Tom, how COULD you be so noble!" - - - -CHAPTER XXI - -VACATION was approaching. The schoolmaster, always severe, grew -severer and more exacting than ever, for he wanted the school to make a -good showing on "Examination" day. His rod and his ferule were seldom -idle now--at least among the smaller pupils. Only the biggest boys, and -young ladies of eighteen and twenty, escaped lashing. Mr. Dobbins' -lashings were very vigorous ones, too; for although he carried, under -his wig, a perfectly bald and shiny head, he had only reached middle -age, and there was no sign of feebleness in his muscle. As the great -day approached, all the tyranny that was in him came to the surface; he -seemed to take a vindictive pleasure in punishing the least -shortcomings. The consequence was, that the smaller boys spent their -days in terror and suffering and their nights in plotting revenge. They -threw away no opportunity to do the master a mischief. But he kept -ahead all the time. The retribution that followed every vengeful -success was so sweeping and majestic that the boys always retired from -the field badly worsted. At last they conspired together and hit upon a -plan that promised a dazzling victory. They swore in the sign-painter's -boy, told him the scheme, and asked his help. He had his own reasons -for being delighted, for the master boarded in his father's family and -had given the boy ample cause to hate him. The master's wife would go -on a visit to the country in a few days, and there would be nothing to -interfere with the plan; the master always prepared himself for great -occasions by getting pretty well fuddled, and the sign-painter's boy -said that when the dominie had reached the proper condition on -Examination Evening he would "manage the thing" while he napped in his -chair; then he would have him awakened at the right time and hurried -away to school. - -In the fulness of time the interesting occasion arrived. At eight in -the evening the schoolhouse was brilliantly lighted, and adorned with -wreaths and festoons of foliage and flowers. The master sat throned in -his great chair upon a raised platform, with his blackboard behind him. -He was looking tolerably mellow. Three rows of benches on each side and -six rows in front of him were occupied by the dignitaries of the town -and by the parents of the pupils. To his left, back of the rows of -citizens, was a spacious temporary platform upon which were seated the -scholars who were to take part in the exercises of the evening; rows of -small boys, washed and dressed to an intolerable state of discomfort; -rows of gawky big boys; snowbanks of girls and young ladies clad in -lawn and muslin and conspicuously conscious of their bare arms, their -grandmothers' ancient trinkets, their bits of pink and blue ribbon and -the flowers in their hair. All the rest of the house was filled with -non-participating scholars. - -The exercises began. A very little boy stood up and sheepishly -recited, "You'd scarce expect one of my age to speak in public on the -stage," etc.--accompanying himself with the painfully exact and -spasmodic gestures which a machine might have used--supposing the -machine to be a trifle out of order. But he got through safely, though -cruelly scared, and got a fine round of applause when he made his -manufactured bow and retired. - -A little shamefaced girl lisped, "Mary had a little lamb," etc., -performed a compassion-inspiring curtsy, got her meed of applause, and -sat down flushed and happy. - -Tom Sawyer stepped forward with conceited confidence and soared into -the unquenchable and indestructible "Give me liberty or give me death" -speech, with fine fury and frantic gesticulation, and broke down in the -middle of it. A ghastly stage-fright seized him, his legs quaked under -him and he was like to choke. True, he had the manifest sympathy of the -house but he had the house's silence, too, which was even worse than -its sympathy. The master frowned, and this completed the disaster. Tom -struggled awhile and then retired, utterly defeated. There was a weak -attempt at applause, but it died early. - -"The Boy Stood on the Burning Deck" followed; also "The Assyrian Came -Down," and other declamatory gems. Then there were reading exercises, -and a spelling fight. The meagre Latin class recited with honor. The -prime feature of the evening was in order, now--original "compositions" -by the young ladies. Each in her turn stepped forward to the edge of -the platform, cleared her throat, held up her manuscript (tied with -dainty ribbon), and proceeded to read, with labored attention to -"expression" and punctuation. The themes were the same that had been -illuminated upon similar occasions by their mothers before them, their -grandmothers, and doubtless all their ancestors in the female line -clear back to the Crusades. "Friendship" was one; "Memories of Other -Days"; "Religion in History"; "Dream Land"; "The Advantages of -Culture"; "Forms of Political Government Compared and Contrasted"; -"Melancholy"; "Filial Love"; "Heart Longings," etc., etc. - -A prevalent feature in these compositions was a nursed and petted -melancholy; another was a wasteful and opulent gush of "fine language"; -another was a tendency to lug in by the ears particularly prized words -and phrases until they were worn entirely out; and a peculiarity that -conspicuously marked and marred them was the inveterate and intolerable -sermon that wagged its crippled tail at the end of each and every one -of them. No matter what the subject might be, a brain-racking effort -was made to squirm it into some aspect or other that the moral and -religious mind could contemplate with edification. The glaring -insincerity of these sermons was not sufficient to compass the -banishment of the fashion from the schools, and it is not sufficient -to-day; it never will be sufficient while the world stands, perhaps. -There is no school in all our land where the young ladies do not feel -obliged to close their compositions with a sermon; and you will find -that the sermon of the most frivolous and the least religious girl in -the school is always the longest and the most relentlessly pious. But -enough of this. Homely truth is unpalatable. - -Let us return to the "Examination." The first composition that was -read was one entitled "Is this, then, Life?" Perhaps the reader can -endure an extract from it: - - "In the common walks of life, with what delightful - emotions does the youthful mind look forward to some - anticipated scene of festivity! Imagination is busy - sketching rose-tinted pictures of joy. In fancy, the - voluptuous votary of fashion sees herself amid the - festive throng, 'the observed of all observers.' Her - graceful form, arrayed in snowy robes, is whirling - through the mazes of the joyous dance; her eye is - brightest, her step is lightest in the gay assembly. - - "In such delicious fancies time quickly glides by, - and the welcome hour arrives for her entrance into - the Elysian world, of which she has had such bright - dreams. How fairy-like does everything appear to - her enchanted vision! Each new scene is more charming - than the last. But after a while she finds that - beneath this goodly exterior, all is vanity, the - flattery which once charmed her soul, now grates - harshly upon her ear; the ball-room has lost its - charms; and with wasted health and imbittered heart, - she turns away with the conviction that earthly - pleasures cannot satisfy the longings of the soul!" - -And so forth and so on. There was a buzz of gratification from time to -time during the reading, accompanied by whispered ejaculations of "How -sweet!" "How eloquent!" "So true!" etc., and after the thing had closed -with a peculiarly afflicting sermon the applause was enthusiastic. - -Then arose a slim, melancholy girl, whose face had the "interesting" -paleness that comes of pills and indigestion, and read a "poem." Two -stanzas of it will do: - - "A MISSOURI MAIDEN'S FAREWELL TO ALABAMA - - "Alabama, good-bye! I love thee well! - But yet for a while do I leave thee now! - Sad, yes, sad thoughts of thee my heart doth swell, - And burning recollections throng my brow! - For I have wandered through thy flowery woods; - Have roamed and read near Tallapoosa's stream; - Have listened to Tallassee's warring floods, - And wooed on Coosa's side Aurora's beam. - - "Yet shame I not to bear an o'er-full heart, - Nor blush to turn behind my tearful eyes; - 'Tis from no stranger land I now must part, - 'Tis to no strangers left I yield these sighs. - Welcome and home were mine within this State, - Whose vales I leave--whose spires fade fast from me - And cold must be mine eyes, and heart, and tete, - When, dear Alabama! they turn cold on thee!" - -There were very few there who knew what "tete" meant, but the poem was -very satisfactory, nevertheless. - -Next appeared a dark-complexioned, black-eyed, black-haired young -lady, who paused an impressive moment, assumed a tragic expression, and -began to read in a measured, solemn tone: - - "A VISION - - "Dark and tempestuous was night. Around the - throne on high not a single star quivered; but - the deep intonations of the heavy thunder - constantly vibrated upon the ear; whilst the - terrific lightning revelled in angry mood - through the cloudy chambers of heaven, seeming - to scorn the power exerted over its terror by - the illustrious Franklin! Even the boisterous - winds unanimously came forth from their mystic - homes, and blustered about as if to enhance by - their aid the wildness of the scene. - - "At such a time, so dark, so dreary, for human - sympathy my very spirit sighed; but instead thereof, - - "'My dearest friend, my counsellor, my comforter - and guide--My joy in grief, my second bliss - in joy,' came to my side. She moved like one of - those bright beings pictured in the sunny walks - of fancy's Eden by the romantic and young, a - queen of beauty unadorned save by her own - transcendent loveliness. So soft was her step, it - failed to make even a sound, and but for the - magical thrill imparted by her genial touch, as - other unobtrusive beauties, she would have glided - away un-perceived--unsought. A strange sadness - rested upon her features, like icy tears upon - the robe of December, as she pointed to the - contending elements without, and bade me contemplate - the two beings presented." - -This nightmare occupied some ten pages of manuscript and wound up with -a sermon so destructive of all hope to non-Presbyterians that it took -the first prize. This composition was considered to be the very finest -effort of the evening. The mayor of the village, in delivering the -prize to the author of it, made a warm speech in which he said that it -was by far the most "eloquent" thing he had ever listened to, and that -Daniel Webster himself might well be proud of it. - -It may be remarked, in passing, that the number of compositions in -which the word "beauteous" was over-fondled, and human experience -referred to as "life's page," was up to the usual average. - -Now the master, mellow almost to the verge of geniality, put his chair -aside, turned his back to the audience, and began to draw a map of -America on the blackboard, to exercise the geography class upon. But he -made a sad business of it with his unsteady hand, and a smothered -titter rippled over the house. He knew what the matter was, and set -himself to right it. He sponged out lines and remade them; but he only -distorted them more than ever, and the tittering was more pronounced. -He threw his entire attention upon his work, now, as if determined not -to be put down by the mirth. He felt that all eyes were fastened upon -him; he imagined he was succeeding, and yet the tittering continued; it -even manifestly increased. And well it might. There was a garret above, -pierced with a scuttle over his head; and down through this scuttle -came a cat, suspended around the haunches by a string; she had a rag -tied about her head and jaws to keep her from mewing; as she slowly -descended she curved upward and clawed at the string, she swung -downward and clawed at the intangible air. The tittering rose higher -and higher--the cat was within six inches of the absorbed teacher's -head--down, down, a little lower, and she grabbed his wig with her -desperate claws, clung to it, and was snatched up into the garret in an -instant with her trophy still in her possession! And how the light did -blaze abroad from the master's bald pate--for the sign-painter's boy -had GILDED it! - -That broke up the meeting. The boys were avenged. Vacation had come. - - NOTE:--The pretended "compositions" quoted in - this chapter are taken without alteration from a - volume entitled "Prose and Poetry, by a Western - Lady"--but they are exactly and precisely after - the schoolgirl pattern, and hence are much - happier than any mere imitations could be. - - - -CHAPTER XXII - -TOM joined the new order of Cadets of Temperance, being attracted by -the showy character of their "regalia." He promised to abstain from -smoking, chewing, and profanity as long as he remained a member. Now he -found out a new thing--namely, that to promise not to do a thing is the -surest way in the world to make a body want to go and do that very -thing. Tom soon found himself tormented with a desire to drink and -swear; the desire grew to be so intense that nothing but the hope of a -chance to display himself in his red sash kept him from withdrawing -from the order. Fourth of July was coming; but he soon gave that up ---gave it up before he had worn his shackles over forty-eight hours--and -fixed his hopes upon old Judge Frazer, justice of the peace, who was -apparently on his deathbed and would have a big public funeral, since -he was so high an official. During three days Tom was deeply concerned -about the Judge's condition and hungry for news of it. Sometimes his -hopes ran high--so high that he would venture to get out his regalia -and practise before the looking-glass. But the Judge had a most -discouraging way of fluctuating. At last he was pronounced upon the -mend--and then convalescent. Tom was disgusted; and felt a sense of -injury, too. He handed in his resignation at once--and that night the -Judge suffered a relapse and died. Tom resolved that he would never -trust a man like that again. - -The funeral was a fine thing. The Cadets paraded in a style calculated -to kill the late member with envy. Tom was a free boy again, however ---there was something in that. He could drink and swear, now--but found -to his surprise that he did not want to. The simple fact that he could, -took the desire away, and the charm of it. - -Tom presently wondered to find that his coveted vacation was beginning -to hang a little heavily on his hands. - -He attempted a diary--but nothing happened during three days, and so -he abandoned it. - -The first of all the negro minstrel shows came to town, and made a -sensation. Tom and Joe Harper got up a band of performers and were -happy for two days. - -Even the Glorious Fourth was in some sense a failure, for it rained -hard, there was no procession in consequence, and the greatest man in -the world (as Tom supposed), Mr. Benton, an actual United States -Senator, proved an overwhelming disappointment--for he was not -twenty-five feet high, nor even anywhere in the neighborhood of it. - -A circus came. The boys played circus for three days afterward in -tents made of rag carpeting--admission, three pins for boys, two for -girls--and then circusing was abandoned. - -A phrenologist and a mesmerizer came--and went again and left the -village duller and drearier than ever. - -There were some boys-and-girls' parties, but they were so few and so -delightful that they only made the aching voids between ache the harder. - -Becky Thatcher was gone to her Constantinople home to stay with her -parents during vacation--so there was no bright side to life anywhere. - -The dreadful secret of the murder was a chronic misery. It was a very -cancer for permanency and pain. - -Then came the measles. - -During two long weeks Tom lay a prisoner, dead to the world and its -happenings. He was very ill, he was interested in nothing. When he got -upon his feet at last and moved feebly down-town, a melancholy change -had come over everything and every creature. There had been a -"revival," and everybody had "got religion," not only the adults, but -even the boys and girls. Tom went about, hoping against hope for the -sight of one blessed sinful face, but disappointment crossed him -everywhere. He found Joe Harper studying a Testament, and turned sadly -away from the depressing spectacle. He sought Ben Rogers, and found him -visiting the poor with a basket of tracts. He hunted up Jim Hollis, who -called his attention to the precious blessing of his late measles as a -warning. Every boy he encountered added another ton to his depression; -and when, in desperation, he flew for refuge at last to the bosom of -Huckleberry Finn and was received with a Scriptural quotation, his -heart broke and he crept home and to bed realizing that he alone of all -the town was lost, forever and forever. - -And that night there came on a terrific storm, with driving rain, -awful claps of thunder and blinding sheets of lightning. He covered his -head with the bedclothes and waited in a horror of suspense for his -doom; for he had not the shadow of a doubt that all this hubbub was -about him. He believed he had taxed the forbearance of the powers above -to the extremity of endurance and that this was the result. It might -have seemed to him a waste of pomp and ammunition to kill a bug with a -battery of artillery, but there seemed nothing incongruous about the -getting up such an expensive thunderstorm as this to knock the turf -from under an insect like himself. - -By and by the tempest spent itself and died without accomplishing its -object. The boy's first impulse was to be grateful, and reform. His -second was to wait--for there might not be any more storms. - -The next day the doctors were back; Tom had relapsed. The three weeks -he spent on his back this time seemed an entire age. When he got abroad -at last he was hardly grateful that he had been spared, remembering how -lonely was his estate, how companionless and forlorn he was. He drifted -listlessly down the street and found Jim Hollis acting as judge in a -juvenile court that was trying a cat for murder, in the presence of her -victim, a bird. He found Joe Harper and Huck Finn up an alley eating a -stolen melon. Poor lads! they--like Tom--had suffered a relapse. - - - -CHAPTER XXIII - -AT last the sleepy atmosphere was stirred--and vigorously: the murder -trial came on in the court. It became the absorbing topic of village -talk immediately. Tom could not get away from it. Every reference to -the murder sent a shudder to his heart, for his troubled conscience and -fears almost persuaded him that these remarks were put forth in his -hearing as "feelers"; he did not see how he could be suspected of -knowing anything about the murder, but still he could not be -comfortable in the midst of this gossip. It kept him in a cold shiver -all the time. He took Huck to a lonely place to have a talk with him. -It would be some relief to unseal his tongue for a little while; to -divide his burden of distress with another sufferer. Moreover, he -wanted to assure himself that Huck had remained discreet. - -"Huck, have you ever told anybody about--that?" - -"'Bout what?" - -"You know what." - -"Oh--'course I haven't." - -"Never a word?" - -"Never a solitary word, so help me. What makes you ask?" - -"Well, I was afeard." - -"Why, Tom Sawyer, we wouldn't be alive two days if that got found out. -YOU know that." - -Tom felt more comfortable. After a pause: - -"Huck, they couldn't anybody get you to tell, could they?" - -"Get me to tell? Why, if I wanted that half-breed devil to drownd me -they could get me to tell. They ain't no different way." - -"Well, that's all right, then. I reckon we're safe as long as we keep -mum. But let's swear again, anyway. It's more surer." - -"I'm agreed." - -So they swore again with dread solemnities. - -"What is the talk around, Huck? I've heard a power of it." - -"Talk? Well, it's just Muff Potter, Muff Potter, Muff Potter all the -time. It keeps me in a sweat, constant, so's I want to hide som'ers." - -"That's just the same way they go on round me. I reckon he's a goner. -Don't you feel sorry for him, sometimes?" - -"Most always--most always. He ain't no account; but then he hain't -ever done anything to hurt anybody. Just fishes a little, to get money -to get drunk on--and loafs around considerable; but lord, we all do -that--leastways most of us--preachers and such like. But he's kind of -good--he give me half a fish, once, when there warn't enough for two; -and lots of times he's kind of stood by me when I was out of luck." - -"Well, he's mended kites for me, Huck, and knitted hooks on to my -line. I wish we could get him out of there." - -"My! we couldn't get him out, Tom. And besides, 'twouldn't do any -good; they'd ketch him again." - -"Yes--so they would. But I hate to hear 'em abuse him so like the -dickens when he never done--that." - -"I do too, Tom. Lord, I hear 'em say he's the bloodiest looking -villain in this country, and they wonder he wasn't ever hung before." - -"Yes, they talk like that, all the time. I've heard 'em say that if he -was to get free they'd lynch him." - -"And they'd do it, too." - -The boys had a long talk, but it brought them little comfort. As the -twilight drew on, they found themselves hanging about the neighborhood -of the little isolated jail, perhaps with an undefined hope that -something would happen that might clear away their difficulties. But -nothing happened; there seemed to be no angels or fairies interested in -this luckless captive. - -The boys did as they had often done before--went to the cell grating -and gave Potter some tobacco and matches. He was on the ground floor -and there were no guards. - -His gratitude for their gifts had always smote their consciences -before--it cut deeper than ever, this time. They felt cowardly and -treacherous to the last degree when Potter said: - -"You've been mighty good to me, boys--better'n anybody else in this -town. And I don't forget it, I don't. Often I says to myself, says I, -'I used to mend all the boys' kites and things, and show 'em where the -good fishin' places was, and befriend 'em what I could, and now they've -all forgot old Muff when he's in trouble; but Tom don't, and Huck -don't--THEY don't forget him, says I, 'and I don't forget them.' Well, -boys, I done an awful thing--drunk and crazy at the time--that's the -only way I account for it--and now I got to swing for it, and it's -right. Right, and BEST, too, I reckon--hope so, anyway. Well, we won't -talk about that. I don't want to make YOU feel bad; you've befriended -me. But what I want to say, is, don't YOU ever get drunk--then you won't -ever get here. Stand a litter furder west--so--that's it; it's a prime -comfort to see faces that's friendly when a body's in such a muck of -trouble, and there don't none come here but yourn. Good friendly -faces--good friendly faces. Git up on one another's backs and let me -touch 'em. That's it. Shake hands--yourn'll come through the bars, but -mine's too big. Little hands, and weak--but they've helped Muff Potter -a power, and they'd help him more if they could." - -Tom went home miserable, and his dreams that night were full of -horrors. The next day and the day after, he hung about the court-room, -drawn by an almost irresistible impulse to go in, but forcing himself -to stay out. Huck was having the same experience. They studiously -avoided each other. Each wandered away, from time to time, but the same -dismal fascination always brought them back presently. Tom kept his -ears open when idlers sauntered out of the court-room, but invariably -heard distressing news--the toils were closing more and more -relentlessly around poor Potter. At the end of the second day the -village talk was to the effect that Injun Joe's evidence stood firm and -unshaken, and that there was not the slightest question as to what the -jury's verdict would be. - -Tom was out late, that night, and came to bed through the window. He -was in a tremendous state of excitement. It was hours before he got to -sleep. All the village flocked to the court-house the next morning, for -this was to be the great day. Both sexes were about equally represented -in the packed audience. After a long wait the jury filed in and took -their places; shortly afterward, Potter, pale and haggard, timid and -hopeless, was brought in, with chains upon him, and seated where all -the curious eyes could stare at him; no less conspicuous was Injun Joe, -stolid as ever. There was another pause, and then the judge arrived and -the sheriff proclaimed the opening of the court. The usual whisperings -among the lawyers and gathering together of papers followed. These -details and accompanying delays worked up an atmosphere of preparation -that was as impressive as it was fascinating. - -Now a witness was called who testified that he found Muff Potter -washing in the brook, at an early hour of the morning that the murder -was discovered, and that he immediately sneaked away. After some -further questioning, counsel for the prosecution said: - -"Take the witness." - -The prisoner raised his eyes for a moment, but dropped them again when -his own counsel said: - -"I have no questions to ask him." - -The next witness proved the finding of the knife near the corpse. -Counsel for the prosecution said: - -"Take the witness." - -"I have no questions to ask him," Potter's lawyer replied. - -A third witness swore he had often seen the knife in Potter's -possession. - -"Take the witness." - -Counsel for Potter declined to question him. The faces of the audience -began to betray annoyance. Did this attorney mean to throw away his -client's life without an effort? - -Several witnesses deposed concerning Potter's guilty behavior when -brought to the scene of the murder. They were allowed to leave the -stand without being cross-questioned. - -Every detail of the damaging circumstances that occurred in the -graveyard upon that morning which all present remembered so well was -brought out by credible witnesses, but none of them were cross-examined -by Potter's lawyer. The perplexity and dissatisfaction of the house -expressed itself in murmurs and provoked a reproof from the bench. -Counsel for the prosecution now said: - -"By the oaths of citizens whose simple word is above suspicion, we -have fastened this awful crime, beyond all possibility of question, -upon the unhappy prisoner at the bar. We rest our case here." - -A groan escaped from poor Potter, and he put his face in his hands and -rocked his body softly to and fro, while a painful silence reigned in -the court-room. Many men were moved, and many women's compassion -testified itself in tears. Counsel for the defence rose and said: - -"Your honor, in our remarks at the opening of this trial, we -foreshadowed our purpose to prove that our client did this fearful deed -while under the influence of a blind and irresponsible delirium -produced by drink. We have changed our mind. We shall not offer that -plea." [Then to the clerk:] "Call Thomas Sawyer!" - -A puzzled amazement awoke in every face in the house, not even -excepting Potter's. Every eye fastened itself with wondering interest -upon Tom as he rose and took his place upon the stand. The boy looked -wild enough, for he was badly scared. The oath was administered. - -"Thomas Sawyer, where were you on the seventeenth of June, about the -hour of midnight?" - -Tom glanced at Injun Joe's iron face and his tongue failed him. The -audience listened breathless, but the words refused to come. After a -few moments, however, the boy got a little of his strength back, and -managed to put enough of it into his voice to make part of the house -hear: - -"In the graveyard!" - -"A little bit louder, please. Don't be afraid. You were--" - -"In the graveyard." - -A contemptuous smile flitted across Injun Joe's face. - -"Were you anywhere near Horse Williams' grave?" - -"Yes, sir." - -"Speak up--just a trifle louder. How near were you?" - -"Near as I am to you." - -"Were you hidden, or not?" - -"I was hid." - -"Where?" - -"Behind the elms that's on the edge of the grave." - -Injun Joe gave a barely perceptible start. - -"Any one with you?" - -"Yes, sir. I went there with--" - -"Wait--wait a moment. Never mind mentioning your companion's name. We -will produce him at the proper time. Did you carry anything there with -you." - -Tom hesitated and looked confused. - -"Speak out, my boy--don't be diffident. The truth is always -respectable. What did you take there?" - -"Only a--a--dead cat." - -There was a ripple of mirth, which the court checked. - -"We will produce the skeleton of that cat. Now, my boy, tell us -everything that occurred--tell it in your own way--don't skip anything, -and don't be afraid." - -Tom began--hesitatingly at first, but as he warmed to his subject his -words flowed more and more easily; in a little while every sound ceased -but his own voice; every eye fixed itself upon him; with parted lips -and bated breath the audience hung upon his words, taking no note of -time, rapt in the ghastly fascinations of the tale. The strain upon -pent emotion reached its climax when the boy said: - -"--and as the doctor fetched the board around and Muff Potter fell, -Injun Joe jumped with the knife and--" - -Crash! Quick as lightning the half-breed sprang for a window, tore his -way through all opposers, and was gone! - - - -CHAPTER XXIV - -TOM was a glittering hero once more--the pet of the old, the envy of -the young. His name even went into immortal print, for the village -paper magnified him. There were some that believed he would be -President, yet, if he escaped hanging. - -As usual, the fickle, unreasoning world took Muff Potter to its bosom -and fondled him as lavishly as it had abused him before. But that sort -of conduct is to the world's credit; therefore it is not well to find -fault with it. - -Tom's days were days of splendor and exultation to him, but his nights -were seasons of horror. Injun Joe infested all his dreams, and always -with doom in his eye. Hardly any temptation could persuade the boy to -stir abroad after nightfall. Poor Huck was in the same state of -wretchedness and terror, for Tom had told the whole story to the lawyer -the night before the great day of the trial, and Huck was sore afraid -that his share in the business might leak out, yet, notwithstanding -Injun Joe's flight had saved him the suffering of testifying in court. -The poor fellow had got the attorney to promise secrecy, but what of -that? Since Tom's harassed conscience had managed to drive him to the -lawyer's house by night and wring a dread tale from lips that had been -sealed with the dismalest and most formidable of oaths, Huck's -confidence in the human race was well-nigh obliterated. - -Daily Muff Potter's gratitude made Tom glad he had spoken; but nightly -he wished he had sealed up his tongue. - -Half the time Tom was afraid Injun Joe would never be captured; the -other half he was afraid he would be. He felt sure he never could draw -a safe breath again until that man was dead and he had seen the corpse. - -Rewards had been offered, the country had been scoured, but no Injun -Joe was found. One of those omniscient and awe-inspiring marvels, a -detective, came up from St. Louis, moused around, shook his head, -looked wise, and made that sort of astounding success which members of -that craft usually achieve. That is to say, he "found a clew." But you -can't hang a "clew" for murder, and so after that detective had got -through and gone home, Tom felt just as insecure as he was before. - -The slow days drifted on, and each left behind it a slightly lightened -weight of apprehension. - - - -CHAPTER XXV - -THERE comes a time in every rightly-constructed boy's life when he has -a raging desire to go somewhere and dig for hidden treasure. This -desire suddenly came upon Tom one day. He sallied out to find Joe -Harper, but failed of success. Next he sought Ben Rogers; he had gone -fishing. Presently he stumbled upon Huck Finn the Red-Handed. Huck -would answer. Tom took him to a private place and opened the matter to -him confidentially. Huck was willing. Huck was always willing to take a -hand in any enterprise that offered entertainment and required no -capital, for he had a troublesome superabundance of that sort of time -which is not money. "Where'll we dig?" said Huck. - -"Oh, most anywhere." - -"Why, is it hid all around?" - -"No, indeed it ain't. It's hid in mighty particular places, Huck ---sometimes on islands, sometimes in rotten chests under the end of a -limb of an old dead tree, just where the shadow falls at midnight; but -mostly under the floor in ha'nted houses." - -"Who hides it?" - -"Why, robbers, of course--who'd you reckon? Sunday-school -sup'rintendents?" - -"I don't know. If 'twas mine I wouldn't hide it; I'd spend it and have -a good time." - -"So would I. But robbers don't do that way. They always hide it and -leave it there." - -"Don't they come after it any more?" - -"No, they think they will, but they generally forget the marks, or -else they die. Anyway, it lays there a long time and gets rusty; and by -and by somebody finds an old yellow paper that tells how to find the -marks--a paper that's got to be ciphered over about a week because it's -mostly signs and hy'roglyphics." - -"Hyro--which?" - -"Hy'roglyphics--pictures and things, you know, that don't seem to mean -anything." - -"Have you got one of them papers, Tom?" - -"No." - -"Well then, how you going to find the marks?" - -"I don't want any marks. They always bury it under a ha'nted house or -on an island, or under a dead tree that's got one limb sticking out. -Well, we've tried Jackson's Island a little, and we can try it again -some time; and there's the old ha'nted house up the Still-House branch, -and there's lots of dead-limb trees--dead loads of 'em." - -"Is it under all of them?" - -"How you talk! No!" - -"Then how you going to know which one to go for?" - -"Go for all of 'em!" - -"Why, Tom, it'll take all summer." - -"Well, what of that? Suppose you find a brass pot with a hundred -dollars in it, all rusty and gray, or rotten chest full of di'monds. -How's that?" - -Huck's eyes glowed. - -"That's bully. Plenty bully enough for me. Just you gimme the hundred -dollars and I don't want no di'monds." - -"All right. But I bet you I ain't going to throw off on di'monds. Some -of 'em's worth twenty dollars apiece--there ain't any, hardly, but's -worth six bits or a dollar." - -"No! Is that so?" - -"Cert'nly--anybody'll tell you so. Hain't you ever seen one, Huck?" - -"Not as I remember." - -"Oh, kings have slathers of them." - -"Well, I don' know no kings, Tom." - -"I reckon you don't. But if you was to go to Europe you'd see a raft -of 'em hopping around." - -"Do they hop?" - -"Hop?--your granny! No!" - -"Well, what did you say they did, for?" - -"Shucks, I only meant you'd SEE 'em--not hopping, of course--what do -they want to hop for?--but I mean you'd just see 'em--scattered around, -you know, in a kind of a general way. Like that old humpbacked Richard." - -"Richard? What's his other name?" - -"He didn't have any other name. Kings don't have any but a given name." - -"No?" - -"But they don't." - -"Well, if they like it, Tom, all right; but I don't want to be a king -and have only just a given name, like a nigger. But say--where you -going to dig first?" - -"Well, I don't know. S'pose we tackle that old dead-limb tree on the -hill t'other side of Still-House branch?" - -"I'm agreed." - -So they got a crippled pick and a shovel, and set out on their -three-mile tramp. They arrived hot and panting, and threw themselves -down in the shade of a neighboring elm to rest and have a smoke. - -"I like this," said Tom. - -"So do I." - -"Say, Huck, if we find a treasure here, what you going to do with your -share?" - -"Well, I'll have pie and a glass of soda every day, and I'll go to -every circus that comes along. I bet I'll have a gay time." - -"Well, ain't you going to save any of it?" - -"Save it? What for?" - -"Why, so as to have something to live on, by and by." - -"Oh, that ain't any use. Pap would come back to thish-yer town some -day and get his claws on it if I didn't hurry up, and I tell you he'd -clean it out pretty quick. What you going to do with yourn, Tom?" - -"I'm going to buy a new drum, and a sure-'nough sword, and a red -necktie and a bull pup, and get married." - -"Married!" - -"That's it." - -"Tom, you--why, you ain't in your right mind." - -"Wait--you'll see." - -"Well, that's the foolishest thing you could do. Look at pap and my -mother. Fight! Why, they used to fight all the time. I remember, mighty -well." - -"That ain't anything. The girl I'm going to marry won't fight." - -"Tom, I reckon they're all alike. They'll all comb a body. Now you -better think 'bout this awhile. I tell you you better. What's the name -of the gal?" - -"It ain't a gal at all--it's a girl." - -"It's all the same, I reckon; some says gal, some says girl--both's -right, like enough. Anyway, what's her name, Tom?" - -"I'll tell you some time--not now." - -"All right--that'll do. Only if you get married I'll be more lonesomer -than ever." - -"No you won't. You'll come and live with me. Now stir out of this and -we'll go to digging." - -They worked and sweated for half an hour. No result. They toiled -another half-hour. Still no result. Huck said: - -"Do they always bury it as deep as this?" - -"Sometimes--not always. Not generally. I reckon we haven't got the -right place." - -So they chose a new spot and began again. The labor dragged a little, -but still they made progress. They pegged away in silence for some -time. Finally Huck leaned on his shovel, swabbed the beaded drops from -his brow with his sleeve, and said: - -"Where you going to dig next, after we get this one?" - -"I reckon maybe we'll tackle the old tree that's over yonder on -Cardiff Hill back of the widow's." - -"I reckon that'll be a good one. But won't the widow take it away from -us, Tom? It's on her land." - -"SHE take it away! Maybe she'd like to try it once. Whoever finds one -of these hid treasures, it belongs to him. It don't make any difference -whose land it's on." - -That was satisfactory. The work went on. By and by Huck said: - -"Blame it, we must be in the wrong place again. What do you think?" - -"It is mighty curious, Huck. I don't understand it. Sometimes witches -interfere. I reckon maybe that's what's the trouble now." - -"Shucks! Witches ain't got no power in the daytime." - -"Well, that's so. I didn't think of that. Oh, I know what the matter -is! What a blamed lot of fools we are! You got to find out where the -shadow of the limb falls at midnight, and that's where you dig!" - -"Then consound it, we've fooled away all this work for nothing. Now -hang it all, we got to come back in the night. It's an awful long way. -Can you get out?" - -"I bet I will. We've got to do it to-night, too, because if somebody -sees these holes they'll know in a minute what's here and they'll go -for it." - -"Well, I'll come around and maow to-night." - -"All right. Let's hide the tools in the bushes." - -The boys were there that night, about the appointed time. They sat in -the shadow waiting. It was a lonely place, and an hour made solemn by -old traditions. Spirits whispered in the rustling leaves, ghosts lurked -in the murky nooks, the deep baying of a hound floated up out of the -distance, an owl answered with his sepulchral note. The boys were -subdued by these solemnities, and talked little. By and by they judged -that twelve had come; they marked where the shadow fell, and began to -dig. Their hopes commenced to rise. Their interest grew stronger, and -their industry kept pace with it. The hole deepened and still deepened, -but every time their hearts jumped to hear the pick strike upon -something, they only suffered a new disappointment. It was only a stone -or a chunk. At last Tom said: - -"It ain't any use, Huck, we're wrong again." - -"Well, but we CAN'T be wrong. We spotted the shadder to a dot." - -"I know it, but then there's another thing." - -"What's that?". - -"Why, we only guessed at the time. Like enough it was too late or too -early." - -Huck dropped his shovel. - -"That's it," said he. "That's the very trouble. We got to give this -one up. We can't ever tell the right time, and besides this kind of -thing's too awful, here this time of night with witches and ghosts -a-fluttering around so. I feel as if something's behind me all the time; -and I'm afeard to turn around, becuz maybe there's others in front -a-waiting for a chance. I been creeping all over, ever since I got here." - -"Well, I've been pretty much so, too, Huck. They most always put in a -dead man when they bury a treasure under a tree, to look out for it." - -"Lordy!" - -"Yes, they do. I've always heard that." - -"Tom, I don't like to fool around much where there's dead people. A -body's bound to get into trouble with 'em, sure." - -"I don't like to stir 'em up, either. S'pose this one here was to -stick his skull out and say something!" - -"Don't Tom! It's awful." - -"Well, it just is. Huck, I don't feel comfortable a bit." - -"Say, Tom, let's give this place up, and try somewheres else." - -"All right, I reckon we better." - -"What'll it be?" - -Tom considered awhile; and then said: - -"The ha'nted house. That's it!" - -"Blame it, I don't like ha'nted houses, Tom. Why, they're a dern sight -worse'n dead people. Dead people might talk, maybe, but they don't come -sliding around in a shroud, when you ain't noticing, and peep over your -shoulder all of a sudden and grit their teeth, the way a ghost does. I -couldn't stand such a thing as that, Tom--nobody could." - -"Yes, but, Huck, ghosts don't travel around only at night. They won't -hender us from digging there in the daytime." - -"Well, that's so. But you know mighty well people don't go about that -ha'nted house in the day nor the night." - -"Well, that's mostly because they don't like to go where a man's been -murdered, anyway--but nothing's ever been seen around that house except -in the night--just some blue lights slipping by the windows--no regular -ghosts." - -"Well, where you see one of them blue lights flickering around, Tom, -you can bet there's a ghost mighty close behind it. It stands to -reason. Becuz you know that they don't anybody but ghosts use 'em." - -"Yes, that's so. But anyway they don't come around in the daytime, so -what's the use of our being afeard?" - -"Well, all right. We'll tackle the ha'nted house if you say so--but I -reckon it's taking chances." - -They had started down the hill by this time. There in the middle of -the moonlit valley below them stood the "ha'nted" house, utterly -isolated, its fences gone long ago, rank weeds smothering the very -doorsteps, the chimney crumbled to ruin, the window-sashes vacant, a -corner of the roof caved in. The boys gazed awhile, half expecting to -see a blue light flit past a window; then talking in a low tone, as -befitted the time and the circumstances, they struck far off to the -right, to give the haunted house a wide berth, and took their way -homeward through the woods that adorned the rearward side of Cardiff -Hill. - - - -CHAPTER XXVI - -ABOUT noon the next day the boys arrived at the dead tree; they had -come for their tools. Tom was impatient to go to the haunted house; -Huck was measurably so, also--but suddenly said: - -"Lookyhere, Tom, do you know what day it is?" - -Tom mentally ran over the days of the week, and then quickly lifted -his eyes with a startled look in them-- - -"My! I never once thought of it, Huck!" - -"Well, I didn't neither, but all at once it popped onto me that it was -Friday." - -"Blame it, a body can't be too careful, Huck. We might 'a' got into an -awful scrape, tackling such a thing on a Friday." - -"MIGHT! Better say we WOULD! There's some lucky days, maybe, but -Friday ain't." - -"Any fool knows that. I don't reckon YOU was the first that found it -out, Huck." - -"Well, I never said I was, did I? And Friday ain't all, neither. I had -a rotten bad dream last night--dreampt about rats." - -"No! Sure sign of trouble. Did they fight?" - -"No." - -"Well, that's good, Huck. When they don't fight it's only a sign that -there's trouble around, you know. All we got to do is to look mighty -sharp and keep out of it. We'll drop this thing for to-day, and play. -Do you know Robin Hood, Huck?" - -"No. Who's Robin Hood?" - -"Why, he was one of the greatest men that was ever in England--and the -best. He was a robber." - -"Cracky, I wisht I was. Who did he rob?" - -"Only sheriffs and bishops and rich people and kings, and such like. -But he never bothered the poor. He loved 'em. He always divided up with -'em perfectly square." - -"Well, he must 'a' been a brick." - -"I bet you he was, Huck. Oh, he was the noblest man that ever was. -They ain't any such men now, I can tell you. He could lick any man in -England, with one hand tied behind him; and he could take his yew bow -and plug a ten-cent piece every time, a mile and a half." - -"What's a YEW bow?" - -"I don't know. It's some kind of a bow, of course. And if he hit that -dime only on the edge he would set down and cry--and curse. But we'll -play Robin Hood--it's nobby fun. I'll learn you." - -"I'm agreed." - -So they played Robin Hood all the afternoon, now and then casting a -yearning eye down upon the haunted house and passing a remark about the -morrow's prospects and possibilities there. As the sun began to sink -into the west they took their way homeward athwart the long shadows of -the trees and soon were buried from sight in the forests of Cardiff -Hill. - -On Saturday, shortly after noon, the boys were at the dead tree again. -They had a smoke and a chat in the shade, and then dug a little in -their last hole, not with great hope, but merely because Tom said there -were so many cases where people had given up a treasure after getting -down within six inches of it, and then somebody else had come along and -turned it up with a single thrust of a shovel. The thing failed this -time, however, so the boys shouldered their tools and went away feeling -that they had not trifled with fortune, but had fulfilled all the -requirements that belong to the business of treasure-hunting. - -When they reached the haunted house there was something so weird and -grisly about the dead silence that reigned there under the baking sun, -and something so depressing about the loneliness and desolation of the -place, that they were afraid, for a moment, to venture in. Then they -crept to the door and took a trembling peep. They saw a weed-grown, -floorless room, unplastered, an ancient fireplace, vacant windows, a -ruinous staircase; and here, there, and everywhere hung ragged and -abandoned cobwebs. They presently entered, softly, with quickened -pulses, talking in whispers, ears alert to catch the slightest sound, -and muscles tense and ready for instant retreat. - -In a little while familiarity modified their fears and they gave the -place a critical and interested examination, rather admiring their own -boldness, and wondering at it, too. Next they wanted to look up-stairs. -This was something like cutting off retreat, but they got to daring -each other, and of course there could be but one result--they threw -their tools into a corner and made the ascent. Up there were the same -signs of decay. In one corner they found a closet that promised -mystery, but the promise was a fraud--there was nothing in it. Their -courage was up now and well in hand. They were about to go down and -begin work when-- - -"Sh!" said Tom. - -"What is it?" whispered Huck, blanching with fright. - -"Sh!... There!... Hear it?" - -"Yes!... Oh, my! Let's run!" - -"Keep still! Don't you budge! They're coming right toward the door." - -The boys stretched themselves upon the floor with their eyes to -knot-holes in the planking, and lay waiting, in a misery of fear. - -"They've stopped.... No--coming.... Here they are. Don't whisper -another word, Huck. My goodness, I wish I was out of this!" - -Two men entered. Each boy said to himself: "There's the old deaf and -dumb Spaniard that's been about town once or twice lately--never saw -t'other man before." - -"T'other" was a ragged, unkempt creature, with nothing very pleasant -in his face. The Spaniard was wrapped in a serape; he had bushy white -whiskers; long white hair flowed from under his sombrero, and he wore -green goggles. When they came in, "t'other" was talking in a low voice; -they sat down on the ground, facing the door, with their backs to the -wall, and the speaker continued his remarks. His manner became less -guarded and his words more distinct as he proceeded: - -"No," said he, "I've thought it all over, and I don't like it. It's -dangerous." - -"Dangerous!" grunted the "deaf and dumb" Spaniard--to the vast -surprise of the boys. "Milksop!" - -This voice made the boys gasp and quake. It was Injun Joe's! There was -silence for some time. Then Joe said: - -"What's any more dangerous than that job up yonder--but nothing's come -of it." - -"That's different. Away up the river so, and not another house about. -'Twon't ever be known that we tried, anyway, long as we didn't succeed." - -"Well, what's more dangerous than coming here in the daytime!--anybody -would suspicion us that saw us." - -"I know that. But there warn't any other place as handy after that -fool of a job. I want to quit this shanty. I wanted to yesterday, only -it warn't any use trying to stir out of here, with those infernal boys -playing over there on the hill right in full view." - -"Those infernal boys" quaked again under the inspiration of this -remark, and thought how lucky it was that they had remembered it was -Friday and concluded to wait a day. They wished in their hearts they -had waited a year. - -The two men got out some food and made a luncheon. After a long and -thoughtful silence, Injun Joe said: - -"Look here, lad--you go back up the river where you belong. Wait there -till you hear from me. I'll take the chances on dropping into this town -just once more, for a look. We'll do that 'dangerous' job after I've -spied around a little and think things look well for it. Then for -Texas! We'll leg it together!" - -This was satisfactory. Both men presently fell to yawning, and Injun -Joe said: - -"I'm dead for sleep! It's your turn to watch." - -He curled down in the weeds and soon began to snore. His comrade -stirred him once or twice and he became quiet. Presently the watcher -began to nod; his head drooped lower and lower, both men began to snore -now. - -The boys drew a long, grateful breath. Tom whispered: - -"Now's our chance--come!" - -Huck said: - -"I can't--I'd die if they was to wake." - -Tom urged--Huck held back. At last Tom rose slowly and softly, and -started alone. But the first step he made wrung such a hideous creak -from the crazy floor that he sank down almost dead with fright. He -never made a second attempt. The boys lay there counting the dragging -moments till it seemed to them that time must be done and eternity -growing gray; and then they were grateful to note that at last the sun -was setting. - -Now one snore ceased. Injun Joe sat up, stared around--smiled grimly -upon his comrade, whose head was drooping upon his knees--stirred him -up with his foot and said: - -"Here! YOU'RE a watchman, ain't you! All right, though--nothing's -happened." - -"My! have I been asleep?" - -"Oh, partly, partly. Nearly time for us to be moving, pard. What'll we -do with what little swag we've got left?" - -"I don't know--leave it here as we've always done, I reckon. No use to -take it away till we start south. Six hundred and fifty in silver's -something to carry." - -"Well--all right--it won't matter to come here once more." - -"No--but I'd say come in the night as we used to do--it's better." - -"Yes: but look here; it may be a good while before I get the right -chance at that job; accidents might happen; 'tain't in such a very good -place; we'll just regularly bury it--and bury it deep." - -"Good idea," said the comrade, who walked across the room, knelt down, -raised one of the rearward hearth-stones and took out a bag that -jingled pleasantly. He subtracted from it twenty or thirty dollars for -himself and as much for Injun Joe, and passed the bag to the latter, -who was on his knees in the corner, now, digging with his bowie-knife. - -The boys forgot all their fears, all their miseries in an instant. -With gloating eyes they watched every movement. Luck!--the splendor of -it was beyond all imagination! Six hundred dollars was money enough to -make half a dozen boys rich! Here was treasure-hunting under the -happiest auspices--there would not be any bothersome uncertainty as to -where to dig. They nudged each other every moment--eloquent nudges and -easily understood, for they simply meant--"Oh, but ain't you glad NOW -we're here!" - -Joe's knife struck upon something. - -"Hello!" said he. - -"What is it?" said his comrade. - -"Half-rotten plank--no, it's a box, I believe. Here--bear a hand and -we'll see what it's here for. Never mind, I've broke a hole." - -He reached his hand in and drew it out-- - -"Man, it's money!" - -The two men examined the handful of coins. They were gold. The boys -above were as excited as themselves, and as delighted. - -Joe's comrade said: - -"We'll make quick work of this. There's an old rusty pick over amongst -the weeds in the corner the other side of the fireplace--I saw it a -minute ago." - -He ran and brought the boys' pick and shovel. Injun Joe took the pick, -looked it over critically, shook his head, muttered something to -himself, and then began to use it. The box was soon unearthed. It was -not very large; it was iron bound and had been very strong before the -slow years had injured it. The men contemplated the treasure awhile in -blissful silence. - -"Pard, there's thousands of dollars here," said Injun Joe. - -"'Twas always said that Murrel's gang used to be around here one -summer," the stranger observed. - -"I know it," said Injun Joe; "and this looks like it, I should say." - -"Now you won't need to do that job." - -The half-breed frowned. Said he: - -"You don't know me. Least you don't know all about that thing. 'Tain't -robbery altogether--it's REVENGE!" and a wicked light flamed in his -eyes. "I'll need your help in it. When it's finished--then Texas. Go -home to your Nance and your kids, and stand by till you hear from me." - -"Well--if you say so; what'll we do with this--bury it again?" - -"Yes. [Ravishing delight overhead.] NO! by the great Sachem, no! -[Profound distress overhead.] I'd nearly forgot. That pick had fresh -earth on it! [The boys were sick with terror in a moment.] What -business has a pick and a shovel here? What business with fresh earth -on them? Who brought them here--and where are they gone? Have you heard -anybody?--seen anybody? What! bury it again and leave them to come and -see the ground disturbed? Not exactly--not exactly. We'll take it to my -den." - -"Why, of course! Might have thought of that before. You mean Number -One?" - -"No--Number Two--under the cross. The other place is bad--too common." - -"All right. It's nearly dark enough to start." - -Injun Joe got up and went about from window to window cautiously -peeping out. Presently he said: - -"Who could have brought those tools here? Do you reckon they can be -up-stairs?" - -The boys' breath forsook them. Injun Joe put his hand on his knife, -halted a moment, undecided, and then turned toward the stairway. The -boys thought of the closet, but their strength was gone. The steps came -creaking up the stairs--the intolerable distress of the situation woke -the stricken resolution of the lads--they were about to spring for the -closet, when there was a crash of rotten timbers and Injun Joe landed -on the ground amid the debris of the ruined stairway. He gathered -himself up cursing, and his comrade said: - -"Now what's the use of all that? If it's anybody, and they're up -there, let them STAY there--who cares? If they want to jump down, now, -and get into trouble, who objects? It will be dark in fifteen minutes ---and then let them follow us if they want to. I'm willing. In my -opinion, whoever hove those things in here caught a sight of us and -took us for ghosts or devils or something. I'll bet they're running -yet." - -Joe grumbled awhile; then he agreed with his friend that what daylight -was left ought to be economized in getting things ready for leaving. -Shortly afterward they slipped out of the house in the deepening -twilight, and moved toward the river with their precious box. - -Tom and Huck rose up, weak but vastly relieved, and stared after them -through the chinks between the logs of the house. Follow? Not they. -They were content to reach ground again without broken necks, and take -the townward track over the hill. They did not talk much. They were too -much absorbed in hating themselves--hating the ill luck that made them -take the spade and the pick there. But for that, Injun Joe never would -have suspected. He would have hidden the silver with the gold to wait -there till his "revenge" was satisfied, and then he would have had the -misfortune to find that money turn up missing. Bitter, bitter luck that -the tools were ever brought there! - -They resolved to keep a lookout for that Spaniard when he should come -to town spying out for chances to do his revengeful job, and follow him -to "Number Two," wherever that might be. Then a ghastly thought -occurred to Tom. - -"Revenge? What if he means US, Huck!" - -"Oh, don't!" said Huck, nearly fainting. - -They talked it all over, and as they entered town they agreed to -believe that he might possibly mean somebody else--at least that he -might at least mean nobody but Tom, since only Tom had testified. - -Very, very small comfort it was to Tom to be alone in danger! Company -would be a palpable improvement, he thought. - - - -CHAPTER XXVII - -THE adventure of the day mightily tormented Tom's dreams that night. -Four times he had his hands on that rich treasure and four times it -wasted to nothingness in his fingers as sleep forsook him and -wakefulness brought back the hard reality of his misfortune. As he lay -in the early morning recalling the incidents of his great adventure, he -noticed that they seemed curiously subdued and far away--somewhat as if -they had happened in another world, or in a time long gone by. Then it -occurred to him that the great adventure itself must be a dream! There -was one very strong argument in favor of this idea--namely, that the -quantity of coin he had seen was too vast to be real. He had never seen -as much as fifty dollars in one mass before, and he was like all boys -of his age and station in life, in that he imagined that all references -to "hundreds" and "thousands" were mere fanciful forms of speech, and -that no such sums really existed in the world. He never had supposed -for a moment that so large a sum as a hundred dollars was to be found -in actual money in any one's possession. If his notions of hidden -treasure had been analyzed, they would have been found to consist of a -handful of real dimes and a bushel of vague, splendid, ungraspable -dollars. - -But the incidents of his adventure grew sensibly sharper and clearer -under the attrition of thinking them over, and so he presently found -himself leaning to the impression that the thing might not have been a -dream, after all. This uncertainty must be swept away. He would snatch -a hurried breakfast and go and find Huck. Huck was sitting on the -gunwale of a flatboat, listlessly dangling his feet in the water and -looking very melancholy. Tom concluded to let Huck lead up to the -subject. If he did not do it, then the adventure would be proved to -have been only a dream. - -"Hello, Huck!" - -"Hello, yourself." - -Silence, for a minute. - -"Tom, if we'd 'a' left the blame tools at the dead tree, we'd 'a' got -the money. Oh, ain't it awful!" - -"'Tain't a dream, then, 'tain't a dream! Somehow I most wish it was. -Dog'd if I don't, Huck." - -"What ain't a dream?" - -"Oh, that thing yesterday. I been half thinking it was." - -"Dream! If them stairs hadn't broke down you'd 'a' seen how much dream -it was! I've had dreams enough all night--with that patch-eyed Spanish -devil going for me all through 'em--rot him!" - -"No, not rot him. FIND him! Track the money!" - -"Tom, we'll never find him. A feller don't have only one chance for -such a pile--and that one's lost. I'd feel mighty shaky if I was to see -him, anyway." - -"Well, so'd I; but I'd like to see him, anyway--and track him out--to -his Number Two." - -"Number Two--yes, that's it. I been thinking 'bout that. But I can't -make nothing out of it. What do you reckon it is?" - -"I dono. It's too deep. Say, Huck--maybe it's the number of a house!" - -"Goody!... No, Tom, that ain't it. If it is, it ain't in this -one-horse town. They ain't no numbers here." - -"Well, that's so. Lemme think a minute. Here--it's the number of a -room--in a tavern, you know!" - -"Oh, that's the trick! They ain't only two taverns. We can find out -quick." - -"You stay here, Huck, till I come." - -Tom was off at once. He did not care to have Huck's company in public -places. He was gone half an hour. He found that in the best tavern, No. -2 had long been occupied by a young lawyer, and was still so occupied. -In the less ostentatious house, No. 2 was a mystery. The -tavern-keeper's young son said it was kept locked all the time, and he -never saw anybody go into it or come out of it except at night; he did -not know any particular reason for this state of things; had had some -little curiosity, but it was rather feeble; had made the most of the -mystery by entertaining himself with the idea that that room was -"ha'nted"; had noticed that there was a light in there the night before. - -"That's what I've found out, Huck. I reckon that's the very No. 2 -we're after." - -"I reckon it is, Tom. Now what you going to do?" - -"Lemme think." - -Tom thought a long time. Then he said: - -"I'll tell you. The back door of that No. 2 is the door that comes out -into that little close alley between the tavern and the old rattle trap -of a brick store. Now you get hold of all the door-keys you can find, -and I'll nip all of auntie's, and the first dark night we'll go there -and try 'em. And mind you, keep a lookout for Injun Joe, because he -said he was going to drop into town and spy around once more for a -chance to get his revenge. If you see him, you just follow him; and if -he don't go to that No. 2, that ain't the place." - -"Lordy, I don't want to foller him by myself!" - -"Why, it'll be night, sure. He mightn't ever see you--and if he did, -maybe he'd never think anything." - -"Well, if it's pretty dark I reckon I'll track him. I dono--I dono. -I'll try." - -"You bet I'll follow him, if it's dark, Huck. Why, he might 'a' found -out he couldn't get his revenge, and be going right after that money." - -"It's so, Tom, it's so. I'll foller him; I will, by jingoes!" - -"Now you're TALKING! Don't you ever weaken, Huck, and I won't." - - - -CHAPTER XXVIII - -THAT night Tom and Huck were ready for their adventure. They hung -about the neighborhood of the tavern until after nine, one watching the -alley at a distance and the other the tavern door. Nobody entered the -alley or left it; nobody resembling the Spaniard entered or left the -tavern door. The night promised to be a fair one; so Tom went home with -the understanding that if a considerable degree of darkness came on, -Huck was to come and "maow," whereupon he would slip out and try the -keys. But the night remained clear, and Huck closed his watch and -retired to bed in an empty sugar hogshead about twelve. - -Tuesday the boys had the same ill luck. Also Wednesday. But Thursday -night promised better. Tom slipped out in good season with his aunt's -old tin lantern, and a large towel to blindfold it with. He hid the -lantern in Huck's sugar hogshead and the watch began. An hour before -midnight the tavern closed up and its lights (the only ones -thereabouts) were put out. No Spaniard had been seen. Nobody had -entered or left the alley. Everything was auspicious. The blackness of -darkness reigned, the perfect stillness was interrupted only by -occasional mutterings of distant thunder. - -Tom got his lantern, lit it in the hogshead, wrapped it closely in the -towel, and the two adventurers crept in the gloom toward the tavern. -Huck stood sentry and Tom felt his way into the alley. Then there was a -season of waiting anxiety that weighed upon Huck's spirits like a -mountain. He began to wish he could see a flash from the lantern--it -would frighten him, but it would at least tell him that Tom was alive -yet. It seemed hours since Tom had disappeared. Surely he must have -fainted; maybe he was dead; maybe his heart had burst under terror and -excitement. In his uneasiness Huck found himself drawing closer and -closer to the alley; fearing all sorts of dreadful things, and -momentarily expecting some catastrophe to happen that would take away -his breath. There was not much to take away, for he seemed only able to -inhale it by thimblefuls, and his heart would soon wear itself out, the -way it was beating. Suddenly there was a flash of light and Tom came -tearing by him: "Run!" said he; "run, for your life!" - -He needn't have repeated it; once was enough; Huck was making thirty -or forty miles an hour before the repetition was uttered. The boys -never stopped till they reached the shed of a deserted slaughter-house -at the lower end of the village. Just as they got within its shelter -the storm burst and the rain poured down. As soon as Tom got his breath -he said: - -"Huck, it was awful! I tried two of the keys, just as soft as I could; -but they seemed to make such a power of racket that I couldn't hardly -get my breath I was so scared. They wouldn't turn in the lock, either. -Well, without noticing what I was doing, I took hold of the knob, and -open comes the door! It warn't locked! I hopped in, and shook off the -towel, and, GREAT CAESAR'S GHOST!" - -"What!--what'd you see, Tom?" - -"Huck, I most stepped onto Injun Joe's hand!" - -"No!" - -"Yes! He was lying there, sound asleep on the floor, with his old -patch on his eye and his arms spread out." - -"Lordy, what did you do? Did he wake up?" - -"No, never budged. Drunk, I reckon. I just grabbed that towel and -started!" - -"I'd never 'a' thought of the towel, I bet!" - -"Well, I would. My aunt would make me mighty sick if I lost it." - -"Say, Tom, did you see that box?" - -"Huck, I didn't wait to look around. I didn't see the box, I didn't -see the cross. I didn't see anything but a bottle and a tin cup on the -floor by Injun Joe; yes, I saw two barrels and lots more bottles in the -room. Don't you see, now, what's the matter with that ha'nted room?" - -"How?" - -"Why, it's ha'nted with whiskey! Maybe ALL the Temperance Taverns have -got a ha'nted room, hey, Huck?" - -"Well, I reckon maybe that's so. Who'd 'a' thought such a thing? But -say, Tom, now's a mighty good time to get that box, if Injun Joe's -drunk." - -"It is, that! You try it!" - -Huck shuddered. - -"Well, no--I reckon not." - -"And I reckon not, Huck. Only one bottle alongside of Injun Joe ain't -enough. If there'd been three, he'd be drunk enough and I'd do it." - -There was a long pause for reflection, and then Tom said: - -"Lookyhere, Huck, less not try that thing any more till we know Injun -Joe's not in there. It's too scary. Now, if we watch every night, we'll -be dead sure to see him go out, some time or other, and then we'll -snatch that box quicker'n lightning." - -"Well, I'm agreed. I'll watch the whole night long, and I'll do it -every night, too, if you'll do the other part of the job." - -"All right, I will. All you got to do is to trot up Hooper Street a -block and maow--and if I'm asleep, you throw some gravel at the window -and that'll fetch me." - -"Agreed, and good as wheat!" - -"Now, Huck, the storm's over, and I'll go home. It'll begin to be -daylight in a couple of hours. You go back and watch that long, will -you?" - -"I said I would, Tom, and I will. I'll ha'nt that tavern every night -for a year! I'll sleep all day and I'll stand watch all night." - -"That's all right. Now, where you going to sleep?" - -"In Ben Rogers' hayloft. He lets me, and so does his pap's nigger man, -Uncle Jake. I tote water for Uncle Jake whenever he wants me to, and -any time I ask him he gives me a little something to eat if he can -spare it. That's a mighty good nigger, Tom. He likes me, becuz I don't -ever act as if I was above him. Sometime I've set right down and eat -WITH him. But you needn't tell that. A body's got to do things when -he's awful hungry he wouldn't want to do as a steady thing." - -"Well, if I don't want you in the daytime, I'll let you sleep. I won't -come bothering around. Any time you see something's up, in the night, -just skip right around and maow." - - - -CHAPTER XXIX - -THE first thing Tom heard on Friday morning was a glad piece of news ---Judge Thatcher's family had come back to town the night before. Both -Injun Joe and the treasure sunk into secondary importance for a moment, -and Becky took the chief place in the boy's interest. He saw her and -they had an exhausting good time playing "hi-spy" and "gully-keeper" -with a crowd of their school-mates. The day was completed and crowned -in a peculiarly satisfactory way: Becky teased her mother to appoint -the next day for the long-promised and long-delayed picnic, and she -consented. The child's delight was boundless; and Tom's not more -moderate. The invitations were sent out before sunset, and straightway -the young folks of the village were thrown into a fever of preparation -and pleasurable anticipation. Tom's excitement enabled him to keep -awake until a pretty late hour, and he had good hopes of hearing Huck's -"maow," and of having his treasure to astonish Becky and the picnickers -with, next day; but he was disappointed. No signal came that night. - -Morning came, eventually, and by ten or eleven o'clock a giddy and -rollicking company were gathered at Judge Thatcher's, and everything -was ready for a start. It was not the custom for elderly people to mar -the picnics with their presence. The children were considered safe -enough under the wings of a few young ladies of eighteen and a few -young gentlemen of twenty-three or thereabouts. The old steam ferryboat -was chartered for the occasion; presently the gay throng filed up the -main street laden with provision-baskets. Sid was sick and had to miss -the fun; Mary remained at home to entertain him. The last thing Mrs. -Thatcher said to Becky, was: - -"You'll not get back till late. Perhaps you'd better stay all night -with some of the girls that live near the ferry-landing, child." - -"Then I'll stay with Susy Harper, mamma." - -"Very well. And mind and behave yourself and don't be any trouble." - -Presently, as they tripped along, Tom said to Becky: - -"Say--I'll tell you what we'll do. 'Stead of going to Joe Harper's -we'll climb right up the hill and stop at the Widow Douglas'. She'll -have ice-cream! She has it most every day--dead loads of it. And she'll -be awful glad to have us." - -"Oh, that will be fun!" - -Then Becky reflected a moment and said: - -"But what will mamma say?" - -"How'll she ever know?" - -The girl turned the idea over in her mind, and said reluctantly: - -"I reckon it's wrong--but--" - -"But shucks! Your mother won't know, and so what's the harm? All she -wants is that you'll be safe; and I bet you she'd 'a' said go there if -she'd 'a' thought of it. I know she would!" - -The Widow Douglas' splendid hospitality was a tempting bait. It and -Tom's persuasions presently carried the day. So it was decided to say -nothing anybody about the night's programme. Presently it occurred to -Tom that maybe Huck might come this very night and give the signal. The -thought took a deal of the spirit out of his anticipations. Still he -could not bear to give up the fun at Widow Douglas'. And why should he -give it up, he reasoned--the signal did not come the night before, so -why should it be any more likely to come to-night? The sure fun of the -evening outweighed the uncertain treasure; and, boy-like, he determined -to yield to the stronger inclination and not allow himself to think of -the box of money another time that day. - -Three miles below town the ferryboat stopped at the mouth of a woody -hollow and tied up. The crowd swarmed ashore and soon the forest -distances and craggy heights echoed far and near with shoutings and -laughter. All the different ways of getting hot and tired were gone -through with, and by-and-by the rovers straggled back to camp fortified -with responsible appetites, and then the destruction of the good things -began. After the feast there was a refreshing season of rest and chat -in the shade of spreading oaks. By-and-by somebody shouted: - -"Who's ready for the cave?" - -Everybody was. Bundles of candles were procured, and straightway there -was a general scamper up the hill. The mouth of the cave was up the -hillside--an opening shaped like a letter A. Its massive oaken door -stood unbarred. Within was a small chamber, chilly as an ice-house, and -walled by Nature with solid limestone that was dewy with a cold sweat. -It was romantic and mysterious to stand here in the deep gloom and look -out upon the green valley shining in the sun. But the impressiveness of -the situation quickly wore off, and the romping began again. The moment -a candle was lighted there was a general rush upon the owner of it; a -struggle and a gallant defence followed, but the candle was soon -knocked down or blown out, and then there was a glad clamor of laughter -and a new chase. But all things have an end. By-and-by the procession -went filing down the steep descent of the main avenue, the flickering -rank of lights dimly revealing the lofty walls of rock almost to their -point of junction sixty feet overhead. This main avenue was not more -than eight or ten feet wide. Every few steps other lofty and still -narrower crevices branched from it on either hand--for McDougal's cave -was but a vast labyrinth of crooked aisles that ran into each other and -out again and led nowhere. It was said that one might wander days and -nights together through its intricate tangle of rifts and chasms, and -never find the end of the cave; and that he might go down, and down, -and still down, into the earth, and it was just the same--labyrinth -under labyrinth, and no end to any of them. No man "knew" the cave. -That was an impossible thing. Most of the young men knew a portion of -it, and it was not customary to venture much beyond this known portion. -Tom Sawyer knew as much of the cave as any one. - -The procession moved along the main avenue some three-quarters of a -mile, and then groups and couples began to slip aside into branch -avenues, fly along the dismal corridors, and take each other by -surprise at points where the corridors joined again. Parties were able -to elude each other for the space of half an hour without going beyond -the "known" ground. - -By-and-by, one group after another came straggling back to the mouth -of the cave, panting, hilarious, smeared from head to foot with tallow -drippings, daubed with clay, and entirely delighted with the success of -the day. Then they were astonished to find that they had been taking no -note of time and that night was about at hand. The clanging bell had -been calling for half an hour. However, this sort of close to the day's -adventures was romantic and therefore satisfactory. When the ferryboat -with her wild freight pushed into the stream, nobody cared sixpence for -the wasted time but the captain of the craft. - -Huck was already upon his watch when the ferryboat's lights went -glinting past the wharf. He heard no noise on board, for the young -people were as subdued and still as people usually are who are nearly -tired to death. He wondered what boat it was, and why she did not stop -at the wharf--and then he dropped her out of his mind and put his -attention upon his business. The night was growing cloudy and dark. Ten -o'clock came, and the noise of vehicles ceased, scattered lights began -to wink out, all straggling foot-passengers disappeared, the village -betook itself to its slumbers and left the small watcher alone with the -silence and the ghosts. Eleven o'clock came, and the tavern lights were -put out; darkness everywhere, now. Huck waited what seemed a weary long -time, but nothing happened. His faith was weakening. Was there any use? -Was there really any use? Why not give it up and turn in? - -A noise fell upon his ear. He was all attention in an instant. The -alley door closed softly. He sprang to the corner of the brick store. -The next moment two men brushed by him, and one seemed to have -something under his arm. It must be that box! So they were going to -remove the treasure. Why call Tom now? It would be absurd--the men -would get away with the box and never be found again. No, he would -stick to their wake and follow them; he would trust to the darkness for -security from discovery. So communing with himself, Huck stepped out -and glided along behind the men, cat-like, with bare feet, allowing -them to keep just far enough ahead not to be invisible. - -They moved up the river street three blocks, then turned to the left -up a cross-street. They went straight ahead, then, until they came to -the path that led up Cardiff Hill; this they took. They passed by the -old Welshman's house, half-way up the hill, without hesitating, and -still climbed upward. Good, thought Huck, they will bury it in the old -quarry. But they never stopped at the quarry. They passed on, up the -summit. They plunged into the narrow path between the tall sumach -bushes, and were at once hidden in the gloom. Huck closed up and -shortened his distance, now, for they would never be able to see him. -He trotted along awhile; then slackened his pace, fearing he was -gaining too fast; moved on a piece, then stopped altogether; listened; -no sound; none, save that he seemed to hear the beating of his own -heart. The hooting of an owl came over the hill--ominous sound! But no -footsteps. Heavens, was everything lost! He was about to spring with -winged feet, when a man cleared his throat not four feet from him! -Huck's heart shot into his throat, but he swallowed it again; and then -he stood there shaking as if a dozen agues had taken charge of him at -once, and so weak that he thought he must surely fall to the ground. He -knew where he was. He knew he was within five steps of the stile -leading into Widow Douglas' grounds. Very well, he thought, let them -bury it there; it won't be hard to find. - -Now there was a voice--a very low voice--Injun Joe's: - -"Damn her, maybe she's got company--there's lights, late as it is." - -"I can't see any." - -This was that stranger's voice--the stranger of the haunted house. A -deadly chill went to Huck's heart--this, then, was the "revenge" job! -His thought was, to fly. Then he remembered that the Widow Douglas had -been kind to him more than once, and maybe these men were going to -murder her. He wished he dared venture to warn her; but he knew he -didn't dare--they might come and catch him. He thought all this and -more in the moment that elapsed between the stranger's remark and Injun -Joe's next--which was-- - -"Because the bush is in your way. Now--this way--now you see, don't -you?" - -"Yes. Well, there IS company there, I reckon. Better give it up." - -"Give it up, and I just leaving this country forever! Give it up and -maybe never have another chance. I tell you again, as I've told you -before, I don't care for her swag--you may have it. But her husband was -rough on me--many times he was rough on me--and mainly he was the -justice of the peace that jugged me for a vagrant. And that ain't all. -It ain't a millionth part of it! He had me HORSEWHIPPED!--horsewhipped -in front of the jail, like a nigger!--with all the town looking on! -HORSEWHIPPED!--do you understand? He took advantage of me and died. But -I'll take it out of HER." - -"Oh, don't kill her! Don't do that!" - -"Kill? Who said anything about killing? I would kill HIM if he was -here; but not her. When you want to get revenge on a woman you don't -kill her--bosh! you go for her looks. You slit her nostrils--you notch -her ears like a sow!" - -"By God, that's--" - -"Keep your opinion to yourself! It will be safest for you. I'll tie -her to the bed. If she bleeds to death, is that my fault? I'll not cry, -if she does. My friend, you'll help me in this thing--for MY sake ---that's why you're here--I mightn't be able alone. If you flinch, I'll -kill you. Do you understand that? And if I have to kill you, I'll kill -her--and then I reckon nobody'll ever know much about who done this -business." - -"Well, if it's got to be done, let's get at it. The quicker the -better--I'm all in a shiver." - -"Do it NOW? And company there? Look here--I'll get suspicious of you, -first thing you know. No--we'll wait till the lights are out--there's -no hurry." - -Huck felt that a silence was going to ensue--a thing still more awful -than any amount of murderous talk; so he held his breath and stepped -gingerly back; planted his foot carefully and firmly, after balancing, -one-legged, in a precarious way and almost toppling over, first on one -side and then on the other. He took another step back, with the same -elaboration and the same risks; then another and another, and--a twig -snapped under his foot! His breath stopped and he listened. There was -no sound--the stillness was perfect. His gratitude was measureless. Now -he turned in his tracks, between the walls of sumach bushes--turned -himself as carefully as if he were a ship--and then stepped quickly but -cautiously along. When he emerged at the quarry he felt secure, and so -he picked up his nimble heels and flew. Down, down he sped, till he -reached the Welshman's. He banged at the door, and presently the heads -of the old man and his two stalwart sons were thrust from windows. - -"What's the row there? Who's banging? What do you want?" - -"Let me in--quick! I'll tell everything." - -"Why, who are you?" - -"Huckleberry Finn--quick, let me in!" - -"Huckleberry Finn, indeed! It ain't a name to open many doors, I -judge! But let him in, lads, and let's see what's the trouble." - -"Please don't ever tell I told you," were Huck's first words when he -got in. "Please don't--I'd be killed, sure--but the widow's been good -friends to me sometimes, and I want to tell--I WILL tell if you'll -promise you won't ever say it was me." - -"By George, he HAS got something to tell, or he wouldn't act so!" -exclaimed the old man; "out with it and nobody here'll ever tell, lad." - -Three minutes later the old man and his sons, well armed, were up the -hill, and just entering the sumach path on tiptoe, their weapons in -their hands. Huck accompanied them no further. He hid behind a great -bowlder and fell to listening. There was a lagging, anxious silence, -and then all of a sudden there was an explosion of firearms and a cry. - -Huck waited for no particulars. He sprang away and sped down the hill -as fast as his legs could carry him. - - - -CHAPTER XXX - -AS the earliest suspicion of dawn appeared on Sunday morning, Huck -came groping up the hill and rapped gently at the old Welshman's door. -The inmates were asleep, but it was a sleep that was set on a -hair-trigger, on account of the exciting episode of the night. A call -came from a window: - -"Who's there!" - -Huck's scared voice answered in a low tone: - -"Please let me in! It's only Huck Finn!" - -"It's a name that can open this door night or day, lad!--and welcome!" - -These were strange words to the vagabond boy's ears, and the -pleasantest he had ever heard. He could not recollect that the closing -word had ever been applied in his case before. The door was quickly -unlocked, and he entered. Huck was given a seat and the old man and his -brace of tall sons speedily dressed themselves. - -"Now, my boy, I hope you're good and hungry, because breakfast will be -ready as soon as the sun's up, and we'll have a piping hot one, too ---make yourself easy about that! I and the boys hoped you'd turn up and -stop here last night." - -"I was awful scared," said Huck, "and I run. I took out when the -pistols went off, and I didn't stop for three mile. I've come now becuz -I wanted to know about it, you know; and I come before daylight becuz I -didn't want to run across them devils, even if they was dead." - -"Well, poor chap, you do look as if you'd had a hard night of it--but -there's a bed here for you when you've had your breakfast. No, they -ain't dead, lad--we are sorry enough for that. You see we knew right -where to put our hands on them, by your description; so we crept along -on tiptoe till we got within fifteen feet of them--dark as a cellar -that sumach path was--and just then I found I was going to sneeze. It -was the meanest kind of luck! I tried to keep it back, but no use ---'twas bound to come, and it did come! I was in the lead with my pistol -raised, and when the sneeze started those scoundrels a-rustling to get -out of the path, I sung out, 'Fire boys!' and blazed away at the place -where the rustling was. So did the boys. But they were off in a jiffy, -those villains, and we after them, down through the woods. I judge we -never touched them. They fired a shot apiece as they started, but their -bullets whizzed by and didn't do us any harm. As soon as we lost the -sound of their feet we quit chasing, and went down and stirred up the -constables. They got a posse together, and went off to guard the river -bank, and as soon as it is light the sheriff and a gang are going to -beat up the woods. My boys will be with them presently. I wish we had -some sort of description of those rascals--'twould help a good deal. -But you couldn't see what they were like, in the dark, lad, I suppose?" - -"Oh yes; I saw them down-town and follered them." - -"Splendid! Describe them--describe them, my boy!" - -"One's the old deaf and dumb Spaniard that's ben around here once or -twice, and t'other's a mean-looking, ragged--" - -"That's enough, lad, we know the men! Happened on them in the woods -back of the widow's one day, and they slunk away. Off with you, boys, -and tell the sheriff--get your breakfast to-morrow morning!" - -The Welshman's sons departed at once. As they were leaving the room -Huck sprang up and exclaimed: - -"Oh, please don't tell ANYbody it was me that blowed on them! Oh, -please!" - -"All right if you say it, Huck, but you ought to have the credit of -what you did." - -"Oh no, no! Please don't tell!" - -When the young men were gone, the old Welshman said: - -"They won't tell--and I won't. But why don't you want it known?" - -Huck would not explain, further than to say that he already knew too -much about one of those men and would not have the man know that he -knew anything against him for the whole world--he would be killed for -knowing it, sure. - -The old man promised secrecy once more, and said: - -"How did you come to follow these fellows, lad? Were they looking -suspicious?" - -Huck was silent while he framed a duly cautious reply. Then he said: - -"Well, you see, I'm a kind of a hard lot,--least everybody says so, -and I don't see nothing agin it--and sometimes I can't sleep much, on -account of thinking about it and sort of trying to strike out a new way -of doing. That was the way of it last night. I couldn't sleep, and so I -come along up-street 'bout midnight, a-turning it all over, and when I -got to that old shackly brick store by the Temperance Tavern, I backed -up agin the wall to have another think. Well, just then along comes -these two chaps slipping along close by me, with something under their -arm, and I reckoned they'd stole it. One was a-smoking, and t'other one -wanted a light; so they stopped right before me and the cigars lit up -their faces and I see that the big one was the deaf and dumb Spaniard, -by his white whiskers and the patch on his eye, and t'other one was a -rusty, ragged-looking devil." - -"Could you see the rags by the light of the cigars?" - -This staggered Huck for a moment. Then he said: - -"Well, I don't know--but somehow it seems as if I did." - -"Then they went on, and you--" - -"Follered 'em--yes. That was it. I wanted to see what was up--they -sneaked along so. I dogged 'em to the widder's stile, and stood in the -dark and heard the ragged one beg for the widder, and the Spaniard -swear he'd spile her looks just as I told you and your two--" - -"What! The DEAF AND DUMB man said all that!" - -Huck had made another terrible mistake! He was trying his best to keep -the old man from getting the faintest hint of who the Spaniard might -be, and yet his tongue seemed determined to get him into trouble in -spite of all he could do. He made several efforts to creep out of his -scrape, but the old man's eye was upon him and he made blunder after -blunder. Presently the Welshman said: - -"My boy, don't be afraid of me. I wouldn't hurt a hair of your head -for all the world. No--I'd protect you--I'd protect you. This Spaniard -is not deaf and dumb; you've let that slip without intending it; you -can't cover that up now. You know something about that Spaniard that -you want to keep dark. Now trust me--tell me what it is, and trust me ---I won't betray you." - -Huck looked into the old man's honest eyes a moment, then bent over -and whispered in his ear: - -"'Tain't a Spaniard--it's Injun Joe!" - -The Welshman almost jumped out of his chair. In a moment he said: - -"It's all plain enough, now. When you talked about notching ears and -slitting noses I judged that that was your own embellishment, because -white men don't take that sort of revenge. But an Injun! That's a -different matter altogether." - -During breakfast the talk went on, and in the course of it the old man -said that the last thing which he and his sons had done, before going -to bed, was to get a lantern and examine the stile and its vicinity for -marks of blood. They found none, but captured a bulky bundle of-- - -"Of WHAT?" - -If the words had been lightning they could not have leaped with a more -stunning suddenness from Huck's blanched lips. His eyes were staring -wide, now, and his breath suspended--waiting for the answer. The -Welshman started--stared in return--three seconds--five seconds--ten ---then replied: - -"Of burglar's tools. Why, what's the MATTER with you?" - -Huck sank back, panting gently, but deeply, unutterably grateful. The -Welshman eyed him gravely, curiously--and presently said: - -"Yes, burglar's tools. That appears to relieve you a good deal. But -what did give you that turn? What were YOU expecting we'd found?" - -Huck was in a close place--the inquiring eye was upon him--he would -have given anything for material for a plausible answer--nothing -suggested itself--the inquiring eye was boring deeper and deeper--a -senseless reply offered--there was no time to weigh it, so at a venture -he uttered it--feebly: - -"Sunday-school books, maybe." - -Poor Huck was too distressed to smile, but the old man laughed loud -and joyously, shook up the details of his anatomy from head to foot, -and ended by saying that such a laugh was money in a-man's pocket, -because it cut down the doctor's bill like everything. Then he added: - -"Poor old chap, you're white and jaded--you ain't well a bit--no -wonder you're a little flighty and off your balance. But you'll come -out of it. Rest and sleep will fetch you out all right, I hope." - -Huck was irritated to think he had been such a goose and betrayed such -a suspicious excitement, for he had dropped the idea that the parcel -brought from the tavern was the treasure, as soon as he had heard the -talk at the widow's stile. He had only thought it was not the treasure, -however--he had not known that it wasn't--and so the suggestion of a -captured bundle was too much for his self-possession. But on the whole -he felt glad the little episode had happened, for now he knew beyond -all question that that bundle was not THE bundle, and so his mind was -at rest and exceedingly comfortable. In fact, everything seemed to be -drifting just in the right direction, now; the treasure must be still -in No. 2, the men would be captured and jailed that day, and he and Tom -could seize the gold that night without any trouble or any fear of -interruption. - -Just as breakfast was completed there was a knock at the door. Huck -jumped for a hiding-place, for he had no mind to be connected even -remotely with the late event. The Welshman admitted several ladies and -gentlemen, among them the Widow Douglas, and noticed that groups of -citizens were climbing up the hill--to stare at the stile. So the news -had spread. The Welshman had to tell the story of the night to the -visitors. The widow's gratitude for her preservation was outspoken. - -"Don't say a word about it, madam. There's another that you're more -beholden to than you are to me and my boys, maybe, but he don't allow -me to tell his name. We wouldn't have been there but for him." - -Of course this excited a curiosity so vast that it almost belittled -the main matter--but the Welshman allowed it to eat into the vitals of -his visitors, and through them be transmitted to the whole town, for he -refused to part with his secret. When all else had been learned, the -widow said: - -"I went to sleep reading in bed and slept straight through all that -noise. Why didn't you come and wake me?" - -"We judged it warn't worth while. Those fellows warn't likely to come -again--they hadn't any tools left to work with, and what was the use of -waking you up and scaring you to death? My three negro men stood guard -at your house all the rest of the night. They've just come back." - -More visitors came, and the story had to be told and retold for a -couple of hours more. - -There was no Sabbath-school during day-school vacation, but everybody -was early at church. The stirring event was well canvassed. News came -that not a sign of the two villains had been yet discovered. When the -sermon was finished, Judge Thatcher's wife dropped alongside of Mrs. -Harper as she moved down the aisle with the crowd and said: - -"Is my Becky going to sleep all day? I just expected she would be -tired to death." - -"Your Becky?" - -"Yes," with a startled look--"didn't she stay with you last night?" - -"Why, no." - -Mrs. Thatcher turned pale, and sank into a pew, just as Aunt Polly, -talking briskly with a friend, passed by. Aunt Polly said: - -"Good-morning, Mrs. Thatcher. Good-morning, Mrs. Harper. I've got a -boy that's turned up missing. I reckon my Tom stayed at your house last -night--one of you. And now he's afraid to come to church. I've got to -settle with him." - -Mrs. Thatcher shook her head feebly and turned paler than ever. - -"He didn't stay with us," said Mrs. Harper, beginning to look uneasy. -A marked anxiety came into Aunt Polly's face. - -"Joe Harper, have you seen my Tom this morning?" - -"No'm." - -"When did you see him last?" - -Joe tried to remember, but was not sure he could say. The people had -stopped moving out of church. Whispers passed along, and a boding -uneasiness took possession of every countenance. Children were -anxiously questioned, and young teachers. They all said they had not -noticed whether Tom and Becky were on board the ferryboat on the -homeward trip; it was dark; no one thought of inquiring if any one was -missing. One young man finally blurted out his fear that they were -still in the cave! Mrs. Thatcher swooned away. Aunt Polly fell to -crying and wringing her hands. - -The alarm swept from lip to lip, from group to group, from street to -street, and within five minutes the bells were wildly clanging and the -whole town was up! The Cardiff Hill episode sank into instant -insignificance, the burglars were forgotten, horses were saddled, -skiffs were manned, the ferryboat ordered out, and before the horror -was half an hour old, two hundred men were pouring down highroad and -river toward the cave. - -All the long afternoon the village seemed empty and dead. Many women -visited Aunt Polly and Mrs. Thatcher and tried to comfort them. They -cried with them, too, and that was still better than words. All the -tedious night the town waited for news; but when the morning dawned at -last, all the word that came was, "Send more candles--and send food." -Mrs. Thatcher was almost crazed; and Aunt Polly, also. Judge Thatcher -sent messages of hope and encouragement from the cave, but they -conveyed no real cheer. - -The old Welshman came home toward daylight, spattered with -candle-grease, smeared with clay, and almost worn out. He found Huck -still in the bed that had been provided for him, and delirious with -fever. The physicians were all at the cave, so the Widow Douglas came -and took charge of the patient. She said she would do her best by him, -because, whether he was good, bad, or indifferent, he was the Lord's, -and nothing that was the Lord's was a thing to be neglected. The -Welshman said Huck had good spots in him, and the widow said: - -"You can depend on it. That's the Lord's mark. He don't leave it off. -He never does. Puts it somewhere on every creature that comes from his -hands." - -Early in the forenoon parties of jaded men began to straggle into the -village, but the strongest of the citizens continued searching. All the -news that could be gained was that remotenesses of the cavern were -being ransacked that had never been visited before; that every corner -and crevice was going to be thoroughly searched; that wherever one -wandered through the maze of passages, lights were to be seen flitting -hither and thither in the distance, and shoutings and pistol-shots sent -their hollow reverberations to the ear down the sombre aisles. In one -place, far from the section usually traversed by tourists, the names -"BECKY & TOM" had been found traced upon the rocky wall with -candle-smoke, and near at hand a grease-soiled bit of ribbon. Mrs. -Thatcher recognized the ribbon and cried over it. She said it was the -last relic she should ever have of her child; and that no other memorial -of her could ever be so precious, because this one parted latest from -the living body before the awful death came. Some said that now and -then, in the cave, a far-away speck of light would glimmer, and then a -glorious shout would burst forth and a score of men go trooping down the -echoing aisle--and then a sickening disappointment always followed; the -children were not there; it was only a searcher's light. - -Three dreadful days and nights dragged their tedious hours along, and -the village sank into a hopeless stupor. No one had heart for anything. -The accidental discovery, just made, that the proprietor of the -Temperance Tavern kept liquor on his premises, scarcely fluttered the -public pulse, tremendous as the fact was. In a lucid interval, Huck -feebly led up to the subject of taverns, and finally asked--dimly -dreading the worst--if anything had been discovered at the Temperance -Tavern since he had been ill. - -"Yes," said the widow. - -Huck started up in bed, wild-eyed: - -"What? What was it?" - -"Liquor!--and the place has been shut up. Lie down, child--what a turn -you did give me!" - -"Only tell me just one thing--only just one--please! Was it Tom Sawyer -that found it?" - -The widow burst into tears. "Hush, hush, child, hush! I've told you -before, you must NOT talk. You are very, very sick!" - -Then nothing but liquor had been found; there would have been a great -powwow if it had been the gold. So the treasure was gone forever--gone -forever! But what could she be crying about? Curious that she should -cry. - -These thoughts worked their dim way through Huck's mind, and under the -weariness they gave him he fell asleep. The widow said to herself: - -"There--he's asleep, poor wreck. Tom Sawyer find it! Pity but somebody -could find Tom Sawyer! Ah, there ain't many left, now, that's got hope -enough, or strength enough, either, to go on searching." - - - -CHAPTER XXXI - -NOW to return to Tom and Becky's share in the picnic. They tripped -along the murky aisles with the rest of the company, visiting the -familiar wonders of the cave--wonders dubbed with rather -over-descriptive names, such as "The Drawing-Room," "The Cathedral," -"Aladdin's Palace," and so on. Presently the hide-and-seek frolicking -began, and Tom and Becky engaged in it with zeal until the exertion -began to grow a trifle wearisome; then they wandered down a sinuous -avenue holding their candles aloft and reading the tangled web-work of -names, dates, post-office addresses, and mottoes with which the rocky -walls had been frescoed (in candle-smoke). Still drifting along and -talking, they scarcely noticed that they were now in a part of the cave -whose walls were not frescoed. They smoked their own names under an -overhanging shelf and moved on. Presently they came to a place where a -little stream of water, trickling over a ledge and carrying a limestone -sediment with it, had, in the slow-dragging ages, formed a laced and -ruffled Niagara in gleaming and imperishable stone. Tom squeezed his -small body behind it in order to illuminate it for Becky's -gratification. He found that it curtained a sort of steep natural -stairway which was enclosed between narrow walls, and at once the -ambition to be a discoverer seized him. Becky responded to his call, -and they made a smoke-mark for future guidance, and started upon their -quest. They wound this way and that, far down into the secret depths of -the cave, made another mark, and branched off in search of novelties to -tell the upper world about. In one place they found a spacious cavern, -from whose ceiling depended a multitude of shining stalactites of the -length and circumference of a man's leg; they walked all about it, -wondering and admiring, and presently left it by one of the numerous -passages that opened into it. This shortly brought them to a bewitching -spring, whose basin was incrusted with a frostwork of glittering -crystals; it was in the midst of a cavern whose walls were supported by -many fantastic pillars which had been formed by the joining of great -stalactites and stalagmites together, the result of the ceaseless -water-drip of centuries. Under the roof vast knots of bats had packed -themselves together, thousands in a bunch; the lights disturbed the -creatures and they came flocking down by hundreds, squeaking and -darting furiously at the candles. Tom knew their ways and the danger of -this sort of conduct. He seized Becky's hand and hurried her into the -first corridor that offered; and none too soon, for a bat struck -Becky's light out with its wing while she was passing out of the -cavern. The bats chased the children a good distance; but the fugitives -plunged into every new passage that offered, and at last got rid of the -perilous things. Tom found a subterranean lake, shortly, which -stretched its dim length away until its shape was lost in the shadows. -He wanted to explore its borders, but concluded that it would be best -to sit down and rest awhile, first. Now, for the first time, the deep -stillness of the place laid a clammy hand upon the spirits of the -children. Becky said: - -"Why, I didn't notice, but it seems ever so long since I heard any of -the others." - -"Come to think, Becky, we are away down below them--and I don't know -how far away north, or south, or east, or whichever it is. We couldn't -hear them here." - -Becky grew apprehensive. - -"I wonder how long we've been down here, Tom? We better start back." - -"Yes, I reckon we better. P'raps we better." - -"Can you find the way, Tom? It's all a mixed-up crookedness to me." - -"I reckon I could find it--but then the bats. If they put our candles -out it will be an awful fix. Let's try some other way, so as not to go -through there." - -"Well. But I hope we won't get lost. It would be so awful!" and the -girl shuddered at the thought of the dreadful possibilities. - -They started through a corridor, and traversed it in silence a long -way, glancing at each new opening, to see if there was anything -familiar about the look of it; but they were all strange. Every time -Tom made an examination, Becky would watch his face for an encouraging -sign, and he would say cheerily: - -"Oh, it's all right. This ain't the one, but we'll come to it right -away!" - -But he felt less and less hopeful with each failure, and presently -began to turn off into diverging avenues at sheer random, in desperate -hope of finding the one that was wanted. He still said it was "all -right," but there was such a leaden dread at his heart that the words -had lost their ring and sounded just as if he had said, "All is lost!" -Becky clung to his side in an anguish of fear, and tried hard to keep -back the tears, but they would come. At last she said: - -"Oh, Tom, never mind the bats, let's go back that way! We seem to get -worse and worse off all the time." - -"Listen!" said he. - -Profound silence; silence so deep that even their breathings were -conspicuous in the hush. Tom shouted. The call went echoing down the -empty aisles and died out in the distance in a faint sound that -resembled a ripple of mocking laughter. - -"Oh, don't do it again, Tom, it is too horrid," said Becky. - -"It is horrid, but I better, Becky; they might hear us, you know," and -he shouted again. - -The "might" was even a chillier horror than the ghostly laughter, it -so confessed a perishing hope. The children stood still and listened; -but there was no result. Tom turned upon the back track at once, and -hurried his steps. It was but a little while before a certain -indecision in his manner revealed another fearful fact to Becky--he -could not find his way back! - -"Oh, Tom, you didn't make any marks!" - -"Becky, I was such a fool! Such a fool! I never thought we might want -to come back! No--I can't find the way. It's all mixed up." - -"Tom, Tom, we're lost! we're lost! We never can get out of this awful -place! Oh, why DID we ever leave the others!" - -She sank to the ground and burst into such a frenzy of crying that Tom -was appalled with the idea that she might die, or lose her reason. He -sat down by her and put his arms around her; she buried her face in his -bosom, she clung to him, she poured out her terrors, her unavailing -regrets, and the far echoes turned them all to jeering laughter. Tom -begged her to pluck up hope again, and she said she could not. He fell -to blaming and abusing himself for getting her into this miserable -situation; this had a better effect. She said she would try to hope -again, she would get up and follow wherever he might lead if only he -would not talk like that any more. For he was no more to blame than -she, she said. - -So they moved on again--aimlessly--simply at random--all they could do -was to move, keep moving. For a little while, hope made a show of -reviving--not with any reason to back it, but only because it is its -nature to revive when the spring has not been taken out of it by age -and familiarity with failure. - -By-and-by Tom took Becky's candle and blew it out. This economy meant -so much! Words were not needed. Becky understood, and her hope died -again. She knew that Tom had a whole candle and three or four pieces in -his pockets--yet he must economize. - -By-and-by, fatigue began to assert its claims; the children tried to -pay attention, for it was dreadful to think of sitting down when time -was grown to be so precious, moving, in some direction, in any -direction, was at least progress and might bear fruit; but to sit down -was to invite death and shorten its pursuit. - -At last Becky's frail limbs refused to carry her farther. She sat -down. Tom rested with her, and they talked of home, and the friends -there, and the comfortable beds and, above all, the light! Becky cried, -and Tom tried to think of some way of comforting her, but all his -encouragements were grown threadbare with use, and sounded like -sarcasms. Fatigue bore so heavily upon Becky that she drowsed off to -sleep. Tom was grateful. He sat looking into her drawn face and saw it -grow smooth and natural under the influence of pleasant dreams; and -by-and-by a smile dawned and rested there. The peaceful face reflected -somewhat of peace and healing into his own spirit, and his thoughts -wandered away to bygone times and dreamy memories. While he was deep in -his musings, Becky woke up with a breezy little laugh--but it was -stricken dead upon her lips, and a groan followed it. - -"Oh, how COULD I sleep! I wish I never, never had waked! No! No, I -don't, Tom! Don't look so! I won't say it again." - -"I'm glad you've slept, Becky; you'll feel rested, now, and we'll find -the way out." - -"We can try, Tom; but I've seen such a beautiful country in my dream. -I reckon we are going there." - -"Maybe not, maybe not. Cheer up, Becky, and let's go on trying." - -They rose up and wandered along, hand in hand and hopeless. They tried -to estimate how long they had been in the cave, but all they knew was -that it seemed days and weeks, and yet it was plain that this could not -be, for their candles were not gone yet. A long time after this--they -could not tell how long--Tom said they must go softly and listen for -dripping water--they must find a spring. They found one presently, and -Tom said it was time to rest again. Both were cruelly tired, yet Becky -said she thought she could go a little farther. She was surprised to -hear Tom dissent. She could not understand it. They sat down, and Tom -fastened his candle to the wall in front of them with some clay. -Thought was soon busy; nothing was said for some time. Then Becky broke -the silence: - -"Tom, I am so hungry!" - -Tom took something out of his pocket. - -"Do you remember this?" said he. - -Becky almost smiled. - -"It's our wedding-cake, Tom." - -"Yes--I wish it was as big as a barrel, for it's all we've got." - -"I saved it from the picnic for us to dream on, Tom, the way grown-up -people do with wedding-cake--but it'll be our--" - -She dropped the sentence where it was. Tom divided the cake and Becky -ate with good appetite, while Tom nibbled at his moiety. There was -abundance of cold water to finish the feast with. By-and-by Becky -suggested that they move on again. Tom was silent a moment. Then he -said: - -"Becky, can you bear it if I tell you something?" - -Becky's face paled, but she thought she could. - -"Well, then, Becky, we must stay here, where there's water to drink. -That little piece is our last candle!" - -Becky gave loose to tears and wailings. Tom did what he could to -comfort her, but with little effect. At length Becky said: - -"Tom!" - -"Well, Becky?" - -"They'll miss us and hunt for us!" - -"Yes, they will! Certainly they will!" - -"Maybe they're hunting for us now, Tom." - -"Why, I reckon maybe they are. I hope they are." - -"When would they miss us, Tom?" - -"When they get back to the boat, I reckon." - -"Tom, it might be dark then--would they notice we hadn't come?" - -"I don't know. But anyway, your mother would miss you as soon as they -got home." - -A frightened look in Becky's face brought Tom to his senses and he saw -that he had made a blunder. Becky was not to have gone home that night! -The children became silent and thoughtful. In a moment a new burst of -grief from Becky showed Tom that the thing in his mind had struck hers -also--that the Sabbath morning might be half spent before Mrs. Thatcher -discovered that Becky was not at Mrs. Harper's. - -The children fastened their eyes upon their bit of candle and watched -it melt slowly and pitilessly away; saw the half inch of wick stand -alone at last; saw the feeble flame rise and fall, climb the thin -column of smoke, linger at its top a moment, and then--the horror of -utter darkness reigned! - -How long afterward it was that Becky came to a slow consciousness that -she was crying in Tom's arms, neither could tell. All that they knew -was, that after what seemed a mighty stretch of time, both awoke out of -a dead stupor of sleep and resumed their miseries once more. Tom said -it might be Sunday, now--maybe Monday. He tried to get Becky to talk, -but her sorrows were too oppressive, all her hopes were gone. Tom said -that they must have been missed long ago, and no doubt the search was -going on. He would shout and maybe some one would come. He tried it; -but in the darkness the distant echoes sounded so hideously that he -tried it no more. - -The hours wasted away, and hunger came to torment the captives again. -A portion of Tom's half of the cake was left; they divided and ate it. -But they seemed hungrier than before. The poor morsel of food only -whetted desire. - -By-and-by Tom said: - -"SH! Did you hear that?" - -Both held their breath and listened. There was a sound like the -faintest, far-off shout. Instantly Tom answered it, and leading Becky -by the hand, started groping down the corridor in its direction. -Presently he listened again; again the sound was heard, and apparently -a little nearer. - -"It's them!" said Tom; "they're coming! Come along, Becky--we're all -right now!" - -The joy of the prisoners was almost overwhelming. Their speed was -slow, however, because pitfalls were somewhat common, and had to be -guarded against. They shortly came to one and had to stop. It might be -three feet deep, it might be a hundred--there was no passing it at any -rate. Tom got down on his breast and reached as far down as he could. -No bottom. They must stay there and wait until the searchers came. They -listened; evidently the distant shoutings were growing more distant! a -moment or two more and they had gone altogether. The heart-sinking -misery of it! Tom whooped until he was hoarse, but it was of no use. He -talked hopefully to Becky; but an age of anxious waiting passed and no -sounds came again. - -The children groped their way back to the spring. The weary time -dragged on; they slept again, and awoke famished and woe-stricken. Tom -believed it must be Tuesday by this time. - -Now an idea struck him. There were some side passages near at hand. It -would be better to explore some of these than bear the weight of the -heavy time in idleness. He took a kite-line from his pocket, tied it to -a projection, and he and Becky started, Tom in the lead, unwinding the -line as he groped along. At the end of twenty steps the corridor ended -in a "jumping-off place." Tom got down on his knees and felt below, and -then as far around the corner as he could reach with his hands -conveniently; he made an effort to stretch yet a little farther to the -right, and at that moment, not twenty yards away, a human hand, holding -a candle, appeared from behind a rock! Tom lifted up a glorious shout, -and instantly that hand was followed by the body it belonged to--Injun -Joe's! Tom was paralyzed; he could not move. He was vastly gratified -the next moment, to see the "Spaniard" take to his heels and get -himself out of sight. Tom wondered that Joe had not recognized his -voice and come over and killed him for testifying in court. But the -echoes must have disguised the voice. Without doubt, that was it, he -reasoned. Tom's fright weakened every muscle in his body. He said to -himself that if he had strength enough to get back to the spring he -would stay there, and nothing should tempt him to run the risk of -meeting Injun Joe again. He was careful to keep from Becky what it was -he had seen. He told her he had only shouted "for luck." - -But hunger and wretchedness rise superior to fears in the long run. -Another tedious wait at the spring and another long sleep brought -changes. The children awoke tortured with a raging hunger. Tom believed -that it must be Wednesday or Thursday or even Friday or Saturday, now, -and that the search had been given over. He proposed to explore another -passage. He felt willing to risk Injun Joe and all other terrors. But -Becky was very weak. She had sunk into a dreary apathy and would not be -roused. She said she would wait, now, where she was, and die--it would -not be long. She told Tom to go with the kite-line and explore if he -chose; but she implored him to come back every little while and speak -to her; and she made him promise that when the awful time came, he -would stay by her and hold her hand until all was over. - -Tom kissed her, with a choking sensation in his throat, and made a -show of being confident of finding the searchers or an escape from the -cave; then he took the kite-line in his hand and went groping down one -of the passages on his hands and knees, distressed with hunger and sick -with bodings of coming doom. - - - -CHAPTER XXXII - -TUESDAY afternoon came, and waned to the twilight. The village of St. -Petersburg still mourned. The lost children had not been found. Public -prayers had been offered up for them, and many and many a private -prayer that had the petitioner's whole heart in it; but still no good -news came from the cave. The majority of the searchers had given up the -quest and gone back to their daily avocations, saying that it was plain -the children could never be found. Mrs. Thatcher was very ill, and a -great part of the time delirious. People said it was heartbreaking to -hear her call her child, and raise her head and listen a whole minute -at a time, then lay it wearily down again with a moan. Aunt Polly had -drooped into a settled melancholy, and her gray hair had grown almost -white. The village went to its rest on Tuesday night, sad and forlorn. - -Away in the middle of the night a wild peal burst from the village -bells, and in a moment the streets were swarming with frantic half-clad -people, who shouted, "Turn out! turn out! they're found! they're -found!" Tin pans and horns were added to the din, the population massed -itself and moved toward the river, met the children coming in an open -carriage drawn by shouting citizens, thronged around it, joined its -homeward march, and swept magnificently up the main street roaring -huzzah after huzzah! - -The village was illuminated; nobody went to bed again; it was the -greatest night the little town had ever seen. During the first half-hour -a procession of villagers filed through Judge Thatcher's house, seized -the saved ones and kissed them, squeezed Mrs. Thatcher's hand, tried to -speak but couldn't--and drifted out raining tears all over the place. - -Aunt Polly's happiness was complete, and Mrs. Thatcher's nearly so. It -would be complete, however, as soon as the messenger dispatched with -the great news to the cave should get the word to her husband. Tom lay -upon a sofa with an eager auditory about him and told the history of -the wonderful adventure, putting in many striking additions to adorn it -withal; and closed with a description of how he left Becky and went on -an exploring expedition; how he followed two avenues as far as his -kite-line would reach; how he followed a third to the fullest stretch of -the kite-line, and was about to turn back when he glimpsed a far-off -speck that looked like daylight; dropped the line and groped toward it, -pushed his head and shoulders through a small hole, and saw the broad -Mississippi rolling by! And if it had only happened to be night he would -not have seen that speck of daylight and would not have explored that -passage any more! He told how he went back for Becky and broke the good -news and she told him not to fret her with such stuff, for she was -tired, and knew she was going to die, and wanted to. He described how he -labored with her and convinced her; and how she almost died for joy when -she had groped to where she actually saw the blue speck of daylight; how -he pushed his way out at the hole and then helped her out; how they sat -there and cried for gladness; how some men came along in a skiff and Tom -hailed them and told them their situation and their famished condition; -how the men didn't believe the wild tale at first, "because," said they, -"you are five miles down the river below the valley the cave is in" ---then took them aboard, rowed to a house, gave them supper, made them -rest till two or three hours after dark and then brought them home. - -Before day-dawn, Judge Thatcher and the handful of searchers with him -were tracked out, in the cave, by the twine clews they had strung -behind them, and informed of the great news. - -Three days and nights of toil and hunger in the cave were not to be -shaken off at once, as Tom and Becky soon discovered. They were -bedridden all of Wednesday and Thursday, and seemed to grow more and -more tired and worn, all the time. Tom got about, a little, on -Thursday, was down-town Friday, and nearly as whole as ever Saturday; -but Becky did not leave her room until Sunday, and then she looked as -if she had passed through a wasting illness. - -Tom learned of Huck's sickness and went to see him on Friday, but -could not be admitted to the bedroom; neither could he on Saturday or -Sunday. He was admitted daily after that, but was warned to keep still -about his adventure and introduce no exciting topic. The Widow Douglas -stayed by to see that he obeyed. At home Tom learned of the Cardiff -Hill event; also that the "ragged man's" body had eventually been found -in the river near the ferry-landing; he had been drowned while trying -to escape, perhaps. - -About a fortnight after Tom's rescue from the cave, he started off to -visit Huck, who had grown plenty strong enough, now, to hear exciting -talk, and Tom had some that would interest him, he thought. Judge -Thatcher's house was on Tom's way, and he stopped to see Becky. The -Judge and some friends set Tom to talking, and some one asked him -ironically if he wouldn't like to go to the cave again. Tom said he -thought he wouldn't mind it. The Judge said: - -"Well, there are others just like you, Tom, I've not the least doubt. -But we have taken care of that. Nobody will get lost in that cave any -more." - -"Why?" - -"Because I had its big door sheathed with boiler iron two weeks ago, -and triple-locked--and I've got the keys." - -Tom turned as white as a sheet. - -"What's the matter, boy! Here, run, somebody! Fetch a glass of water!" - -The water was brought and thrown into Tom's face. - -"Ah, now you're all right. What was the matter with you, Tom?" - -"Oh, Judge, Injun Joe's in the cave!" - - - -CHAPTER XXXIII - -WITHIN a few minutes the news had spread, and a dozen skiff-loads of -men were on their way to McDougal's cave, and the ferryboat, well -filled with passengers, soon followed. Tom Sawyer was in the skiff that -bore Judge Thatcher. - -When the cave door was unlocked, a sorrowful sight presented itself in -the dim twilight of the place. Injun Joe lay stretched upon the ground, -dead, with his face close to the crack of the door, as if his longing -eyes had been fixed, to the latest moment, upon the light and the cheer -of the free world outside. Tom was touched, for he knew by his own -experience how this wretch had suffered. His pity was moved, but -nevertheless he felt an abounding sense of relief and security, now, -which revealed to him in a degree which he had not fully appreciated -before how vast a weight of dread had been lying upon him since the day -he lifted his voice against this bloody-minded outcast. - -Injun Joe's bowie-knife lay close by, its blade broken in two. The -great foundation-beam of the door had been chipped and hacked through, -with tedious labor; useless labor, too, it was, for the native rock -formed a sill outside it, and upon that stubborn material the knife had -wrought no effect; the only damage done was to the knife itself. But if -there had been no stony obstruction there the labor would have been -useless still, for if the beam had been wholly cut away Injun Joe could -not have squeezed his body under the door, and he knew it. So he had -only hacked that place in order to be doing something--in order to pass -the weary time--in order to employ his tortured faculties. Ordinarily -one could find half a dozen bits of candle stuck around in the crevices -of this vestibule, left there by tourists; but there were none now. The -prisoner had searched them out and eaten them. He had also contrived to -catch a few bats, and these, also, he had eaten, leaving only their -claws. The poor unfortunate had starved to death. In one place, near at -hand, a stalagmite had been slowly growing up from the ground for ages, -builded by the water-drip from a stalactite overhead. The captive had -broken off the stalagmite, and upon the stump had placed a stone, -wherein he had scooped a shallow hollow to catch the precious drop -that fell once in every three minutes with the dreary regularity of a -clock-tick--a dessertspoonful once in four and twenty hours. That drop -was falling when the Pyramids were new; when Troy fell; when the -foundations of Rome were laid; when Christ was crucified; when the -Conqueror created the British empire; when Columbus sailed; when the -massacre at Lexington was "news." It is falling now; it will still be -falling when all these things shall have sunk down the afternoon of -history, and the twilight of tradition, and been swallowed up in the -thick night of oblivion. Has everything a purpose and a mission? Did -this drop fall patiently during five thousand years to be ready for -this flitting human insect's need? and has it another important object -to accomplish ten thousand years to come? No matter. It is many and -many a year since the hapless half-breed scooped out the stone to catch -the priceless drops, but to this day the tourist stares longest at that -pathetic stone and that slow-dropping water when he comes to see the -wonders of McDougal's cave. Injun Joe's cup stands first in the list of -the cavern's marvels; even "Aladdin's Palace" cannot rival it. - -Injun Joe was buried near the mouth of the cave; and people flocked -there in boats and wagons from the towns and from all the farms and -hamlets for seven miles around; they brought their children, and all -sorts of provisions, and confessed that they had had almost as -satisfactory a time at the funeral as they could have had at the -hanging. - -This funeral stopped the further growth of one thing--the petition to -the governor for Injun Joe's pardon. The petition had been largely -signed; many tearful and eloquent meetings had been held, and a -committee of sappy women been appointed to go in deep mourning and wail -around the governor, and implore him to be a merciful ass and trample -his duty under foot. Injun Joe was believed to have killed five -citizens of the village, but what of that? If he had been Satan himself -there would have been plenty of weaklings ready to scribble their names -to a pardon-petition, and drip a tear on it from their permanently -impaired and leaky water-works. - -The morning after the funeral Tom took Huck to a private place to have -an important talk. Huck had learned all about Tom's adventure from the -Welshman and the Widow Douglas, by this time, but Tom said he reckoned -there was one thing they had not told him; that thing was what he -wanted to talk about now. Huck's face saddened. He said: - -"I know what it is. You got into No. 2 and never found anything but -whiskey. Nobody told me it was you; but I just knowed it must 'a' ben -you, soon as I heard 'bout that whiskey business; and I knowed you -hadn't got the money becuz you'd 'a' got at me some way or other and -told me even if you was mum to everybody else. Tom, something's always -told me we'd never get holt of that swag." - -"Why, Huck, I never told on that tavern-keeper. YOU know his tavern -was all right the Saturday I went to the picnic. Don't you remember you -was to watch there that night?" - -"Oh yes! Why, it seems 'bout a year ago. It was that very night that I -follered Injun Joe to the widder's." - -"YOU followed him?" - -"Yes--but you keep mum. I reckon Injun Joe's left friends behind him, -and I don't want 'em souring on me and doing me mean tricks. If it -hadn't ben for me he'd be down in Texas now, all right." - -Then Huck told his entire adventure in confidence to Tom, who had only -heard of the Welshman's part of it before. - -"Well," said Huck, presently, coming back to the main question, -"whoever nipped the whiskey in No. 2, nipped the money, too, I reckon ---anyways it's a goner for us, Tom." - -"Huck, that money wasn't ever in No. 2!" - -"What!" Huck searched his comrade's face keenly. "Tom, have you got on -the track of that money again?" - -"Huck, it's in the cave!" - -Huck's eyes blazed. - -"Say it again, Tom." - -"The money's in the cave!" - -"Tom--honest injun, now--is it fun, or earnest?" - -"Earnest, Huck--just as earnest as ever I was in my life. Will you go -in there with me and help get it out?" - -"I bet I will! I will if it's where we can blaze our way to it and not -get lost." - -"Huck, we can do that without the least little bit of trouble in the -world." - -"Good as wheat! What makes you think the money's--" - -"Huck, you just wait till we get in there. If we don't find it I'll -agree to give you my drum and every thing I've got in the world. I -will, by jings." - -"All right--it's a whiz. When do you say?" - -"Right now, if you say it. Are you strong enough?" - -"Is it far in the cave? I ben on my pins a little, three or four days, -now, but I can't walk more'n a mile, Tom--least I don't think I could." - -"It's about five mile into there the way anybody but me would go, -Huck, but there's a mighty short cut that they don't anybody but me -know about. Huck, I'll take you right to it in a skiff. I'll float the -skiff down there, and I'll pull it back again all by myself. You -needn't ever turn your hand over." - -"Less start right off, Tom." - -"All right. We want some bread and meat, and our pipes, and a little -bag or two, and two or three kite-strings, and some of these -new-fangled things they call lucifer matches. I tell you, many's -the time I wished I had some when I was in there before." - -A trifle after noon the boys borrowed a small skiff from a citizen who -was absent, and got under way at once. When they were several miles -below "Cave Hollow," Tom said: - -"Now you see this bluff here looks all alike all the way down from the -cave hollow--no houses, no wood-yards, bushes all alike. But do you see -that white place up yonder where there's been a landslide? Well, that's -one of my marks. We'll get ashore, now." - -They landed. - -"Now, Huck, where we're a-standing you could touch that hole I got out -of with a fishing-pole. See if you can find it." - -Huck searched all the place about, and found nothing. Tom proudly -marched into a thick clump of sumach bushes and said: - -"Here you are! Look at it, Huck; it's the snuggest hole in this -country. You just keep mum about it. All along I've been wanting to be -a robber, but I knew I'd got to have a thing like this, and where to -run across it was the bother. We've got it now, and we'll keep it -quiet, only we'll let Joe Harper and Ben Rogers in--because of course -there's got to be a Gang, or else there wouldn't be any style about it. -Tom Sawyer's Gang--it sounds splendid, don't it, Huck?" - -"Well, it just does, Tom. And who'll we rob?" - -"Oh, most anybody. Waylay people--that's mostly the way." - -"And kill them?" - -"No, not always. Hive them in the cave till they raise a ransom." - -"What's a ransom?" - -"Money. You make them raise all they can, off'n their friends; and -after you've kept them a year, if it ain't raised then you kill them. -That's the general way. Only you don't kill the women. You shut up the -women, but you don't kill them. They're always beautiful and rich, and -awfully scared. You take their watches and things, but you always take -your hat off and talk polite. They ain't anybody as polite as robbers ---you'll see that in any book. Well, the women get to loving you, and -after they've been in the cave a week or two weeks they stop crying and -after that you couldn't get them to leave. If you drove them out they'd -turn right around and come back. It's so in all the books." - -"Why, it's real bully, Tom. I believe it's better'n to be a pirate." - -"Yes, it's better in some ways, because it's close to home and -circuses and all that." - -By this time everything was ready and the boys entered the hole, Tom -in the lead. They toiled their way to the farther end of the tunnel, -then made their spliced kite-strings fast and moved on. A few steps -brought them to the spring, and Tom felt a shudder quiver all through -him. He showed Huck the fragment of candle-wick perched on a lump of -clay against the wall, and described how he and Becky had watched the -flame struggle and expire. - -The boys began to quiet down to whispers, now, for the stillness and -gloom of the place oppressed their spirits. They went on, and presently -entered and followed Tom's other corridor until they reached the -"jumping-off place." The candles revealed the fact that it was not -really a precipice, but only a steep clay hill twenty or thirty feet -high. Tom whispered: - -"Now I'll show you something, Huck." - -He held his candle aloft and said: - -"Look as far around the corner as you can. Do you see that? There--on -the big rock over yonder--done with candle-smoke." - -"Tom, it's a CROSS!" - -"NOW where's your Number Two? 'UNDER THE CROSS,' hey? Right yonder's -where I saw Injun Joe poke up his candle, Huck!" - -Huck stared at the mystic sign awhile, and then said with a shaky voice: - -"Tom, less git out of here!" - -"What! and leave the treasure?" - -"Yes--leave it. Injun Joe's ghost is round about there, certain." - -"No it ain't, Huck, no it ain't. It would ha'nt the place where he -died--away out at the mouth of the cave--five mile from here." - -"No, Tom, it wouldn't. It would hang round the money. I know the ways -of ghosts, and so do you." - -Tom began to fear that Huck was right. Misgivings gathered in his -mind. But presently an idea occurred to him-- - -"Lookyhere, Huck, what fools we're making of ourselves! Injun Joe's -ghost ain't a going to come around where there's a cross!" - -The point was well taken. It had its effect. - -"Tom, I didn't think of that. But that's so. It's luck for us, that -cross is. I reckon we'll climb down there and have a hunt for that box." - -Tom went first, cutting rude steps in the clay hill as he descended. -Huck followed. Four avenues opened out of the small cavern which the -great rock stood in. The boys examined three of them with no result. -They found a small recess in the one nearest the base of the rock, with -a pallet of blankets spread down in it; also an old suspender, some -bacon rind, and the well-gnawed bones of two or three fowls. But there -was no money-box. The lads searched and researched this place, but in -vain. Tom said: - -"He said UNDER the cross. Well, this comes nearest to being under the -cross. It can't be under the rock itself, because that sets solid on -the ground." - -They searched everywhere once more, and then sat down discouraged. -Huck could suggest nothing. By-and-by Tom said: - -"Lookyhere, Huck, there's footprints and some candle-grease on the -clay about one side of this rock, but not on the other sides. Now, -what's that for? I bet you the money IS under the rock. I'm going to -dig in the clay." - -"That ain't no bad notion, Tom!" said Huck with animation. - -Tom's "real Barlow" was out at once, and he had not dug four inches -before he struck wood. - -"Hey, Huck!--you hear that?" - -Huck began to dig and scratch now. Some boards were soon uncovered and -removed. They had concealed a natural chasm which led under the rock. -Tom got into this and held his candle as far under the rock as he -could, but said he could not see to the end of the rift. He proposed to -explore. He stooped and passed under; the narrow way descended -gradually. He followed its winding course, first to the right, then to -the left, Huck at his heels. Tom turned a short curve, by-and-by, and -exclaimed: - -"My goodness, Huck, lookyhere!" - -It was the treasure-box, sure enough, occupying a snug little cavern, -along with an empty powder-keg, a couple of guns in leather cases, two -or three pairs of old moccasins, a leather belt, and some other rubbish -well soaked with the water-drip. - -"Got it at last!" said Huck, ploughing among the tarnished coins with -his hand. "My, but we're rich, Tom!" - -"Huck, I always reckoned we'd get it. It's just too good to believe, -but we HAVE got it, sure! Say--let's not fool around here. Let's snake -it out. Lemme see if I can lift the box." - -It weighed about fifty pounds. Tom could lift it, after an awkward -fashion, but could not carry it conveniently. - -"I thought so," he said; "THEY carried it like it was heavy, that day -at the ha'nted house. I noticed that. I reckon I was right to think of -fetching the little bags along." - -The money was soon in the bags and the boys took it up to the cross -rock. - -"Now less fetch the guns and things," said Huck. - -"No, Huck--leave them there. They're just the tricks to have when we -go to robbing. We'll keep them there all the time, and we'll hold our -orgies there, too. It's an awful snug place for orgies." - -"What orgies?" - -"I dono. But robbers always have orgies, and of course we've got to -have them, too. Come along, Huck, we've been in here a long time. It's -getting late, I reckon. I'm hungry, too. We'll eat and smoke when we -get to the skiff." - -They presently emerged into the clump of sumach bushes, looked warily -out, found the coast clear, and were soon lunching and smoking in the -skiff. As the sun dipped toward the horizon they pushed out and got -under way. Tom skimmed up the shore through the long twilight, chatting -cheerily with Huck, and landed shortly after dark. - -"Now, Huck," said Tom, "we'll hide the money in the loft of the -widow's woodshed, and I'll come up in the morning and we'll count it -and divide, and then we'll hunt up a place out in the woods for it -where it will be safe. Just you lay quiet here and watch the stuff till -I run and hook Benny Taylor's little wagon; I won't be gone a minute." - -He disappeared, and presently returned with the wagon, put the two -small sacks into it, threw some old rags on top of them, and started -off, dragging his cargo behind him. When the boys reached the -Welshman's house, they stopped to rest. Just as they were about to move -on, the Welshman stepped out and said: - -"Hallo, who's that?" - -"Huck and Tom Sawyer." - -"Good! Come along with me, boys, you are keeping everybody waiting. -Here--hurry up, trot ahead--I'll haul the wagon for you. Why, it's not -as light as it might be. Got bricks in it?--or old metal?" - -"Old metal," said Tom. - -"I judged so; the boys in this town will take more trouble and fool -away more time hunting up six bits' worth of old iron to sell to the -foundry than they would to make twice the money at regular work. But -that's human nature--hurry along, hurry along!" - -The boys wanted to know what the hurry was about. - -"Never mind; you'll see, when we get to the Widow Douglas'." - -Huck said with some apprehension--for he was long used to being -falsely accused: - -"Mr. Jones, we haven't been doing nothing." - -The Welshman laughed. - -"Well, I don't know, Huck, my boy. I don't know about that. Ain't you -and the widow good friends?" - -"Yes. Well, she's ben good friends to me, anyway." - -"All right, then. What do you want to be afraid for?" - -This question was not entirely answered in Huck's slow mind before he -found himself pushed, along with Tom, into Mrs. Douglas' drawing-room. -Mr. Jones left the wagon near the door and followed. - -The place was grandly lighted, and everybody that was of any -consequence in the village was there. The Thatchers were there, the -Harpers, the Rogerses, Aunt Polly, Sid, Mary, the minister, the editor, -and a great many more, and all dressed in their best. The widow -received the boys as heartily as any one could well receive two such -looking beings. They were covered with clay and candle-grease. Aunt -Polly blushed crimson with humiliation, and frowned and shook her head -at Tom. Nobody suffered half as much as the two boys did, however. Mr. -Jones said: - -"Tom wasn't at home, yet, so I gave him up; but I stumbled on him and -Huck right at my door, and so I just brought them along in a hurry." - -"And you did just right," said the widow. "Come with me, boys." - -She took them to a bedchamber and said: - -"Now wash and dress yourselves. Here are two new suits of clothes ---shirts, socks, everything complete. They're Huck's--no, no thanks, -Huck--Mr. Jones bought one and I the other. But they'll fit both of you. -Get into them. We'll wait--come down when you are slicked up enough." - -Then she left. - - - -CHAPTER XXXIV - -HUCK said: "Tom, we can slope, if we can find a rope. The window ain't -high from the ground." - -"Shucks! what do you want to slope for?" - -"Well, I ain't used to that kind of a crowd. I can't stand it. I ain't -going down there, Tom." - -"Oh, bother! It ain't anything. I don't mind it a bit. I'll take care -of you." - -Sid appeared. - -"Tom," said he, "auntie has been waiting for you all the afternoon. -Mary got your Sunday clothes ready, and everybody's been fretting about -you. Say--ain't this grease and clay, on your clothes?" - -"Now, Mr. Siddy, you jist 'tend to your own business. What's all this -blow-out about, anyway?" - -"It's one of the widow's parties that she's always having. This time -it's for the Welshman and his sons, on account of that scrape they -helped her out of the other night. And say--I can tell you something, -if you want to know." - -"Well, what?" - -"Why, old Mr. Jones is going to try to spring something on the people -here to-night, but I overheard him tell auntie to-day about it, as a -secret, but I reckon it's not much of a secret now. Everybody knows ---the widow, too, for all she tries to let on she don't. Mr. Jones was -bound Huck should be here--couldn't get along with his grand secret -without Huck, you know!" - -"Secret about what, Sid?" - -"About Huck tracking the robbers to the widow's. I reckon Mr. Jones -was going to make a grand time over his surprise, but I bet you it will -drop pretty flat." - -Sid chuckled in a very contented and satisfied way. - -"Sid, was it you that told?" - -"Oh, never mind who it was. SOMEBODY told--that's enough." - -"Sid, there's only one person in this town mean enough to do that, and -that's you. If you had been in Huck's place you'd 'a' sneaked down the -hill and never told anybody on the robbers. You can't do any but mean -things, and you can't bear to see anybody praised for doing good ones. -There--no thanks, as the widow says"--and Tom cuffed Sid's ears and -helped him to the door with several kicks. "Now go and tell auntie if -you dare--and to-morrow you'll catch it!" - -Some minutes later the widow's guests were at the supper-table, and a -dozen children were propped up at little side-tables in the same room, -after the fashion of that country and that day. At the proper time Mr. -Jones made his little speech, in which he thanked the widow for the -honor she was doing himself and his sons, but said that there was -another person whose modesty-- - -And so forth and so on. He sprung his secret about Huck's share in the -adventure in the finest dramatic manner he was master of, but the -surprise it occasioned was largely counterfeit and not as clamorous and -effusive as it might have been under happier circumstances. However, -the widow made a pretty fair show of astonishment, and heaped so many -compliments and so much gratitude upon Huck that he almost forgot the -nearly intolerable discomfort of his new clothes in the entirely -intolerable discomfort of being set up as a target for everybody's gaze -and everybody's laudations. - -The widow said she meant to give Huck a home under her roof and have -him educated; and that when she could spare the money she would start -him in business in a modest way. Tom's chance was come. He said: - -"Huck don't need it. Huck's rich." - -Nothing but a heavy strain upon the good manners of the company kept -back the due and proper complimentary laugh at this pleasant joke. But -the silence was a little awkward. Tom broke it: - -"Huck's got money. Maybe you don't believe it, but he's got lots of -it. Oh, you needn't smile--I reckon I can show you. You just wait a -minute." - -Tom ran out of doors. The company looked at each other with a -perplexed interest--and inquiringly at Huck, who was tongue-tied. - -"Sid, what ails Tom?" said Aunt Polly. "He--well, there ain't ever any -making of that boy out. I never--" - -Tom entered, struggling with the weight of his sacks, and Aunt Polly -did not finish her sentence. Tom poured the mass of yellow coin upon -the table and said: - -"There--what did I tell you? Half of it's Huck's and half of it's mine!" - -The spectacle took the general breath away. All gazed, nobody spoke -for a moment. Then there was a unanimous call for an explanation. Tom -said he could furnish it, and he did. The tale was long, but brimful of -interest. There was scarcely an interruption from any one to break the -charm of its flow. When he had finished, Mr. Jones said: - -"I thought I had fixed up a little surprise for this occasion, but it -don't amount to anything now. This one makes it sing mighty small, I'm -willing to allow." - -The money was counted. The sum amounted to a little over twelve -thousand dollars. It was more than any one present had ever seen at one -time before, though several persons were there who were worth -considerably more than that in property. - - - -CHAPTER XXXV - -THE reader may rest satisfied that Tom's and Huck's windfall made a -mighty stir in the poor little village of St. Petersburg. So vast a -sum, all in actual cash, seemed next to incredible. It was talked -about, gloated over, glorified, until the reason of many of the -citizens tottered under the strain of the unhealthy excitement. Every -"haunted" house in St. Petersburg and the neighboring villages was -dissected, plank by plank, and its foundations dug up and ransacked for -hidden treasure--and not by boys, but men--pretty grave, unromantic -men, too, some of them. Wherever Tom and Huck appeared they were -courted, admired, stared at. The boys were not able to remember that -their remarks had possessed weight before; but now their sayings were -treasured and repeated; everything they did seemed somehow to be -regarded as remarkable; they had evidently lost the power of doing and -saying commonplace things; moreover, their past history was raked up -and discovered to bear marks of conspicuous originality. The village -paper published biographical sketches of the boys. - -The Widow Douglas put Huck's money out at six per cent., and Judge -Thatcher did the same with Tom's at Aunt Polly's request. Each lad had -an income, now, that was simply prodigious--a dollar for every week-day -in the year and half of the Sundays. It was just what the minister got ---no, it was what he was promised--he generally couldn't collect it. A -dollar and a quarter a week would board, lodge, and school a boy in -those old simple days--and clothe him and wash him, too, for that -matter. - -Judge Thatcher had conceived a great opinion of Tom. He said that no -commonplace boy would ever have got his daughter out of the cave. When -Becky told her father, in strict confidence, how Tom had taken her -whipping at school, the Judge was visibly moved; and when she pleaded -grace for the mighty lie which Tom had told in order to shift that -whipping from her shoulders to his own, the Judge said with a fine -outburst that it was a noble, a generous, a magnanimous lie--a lie that -was worthy to hold up its head and march down through history breast to -breast with George Washington's lauded Truth about the hatchet! Becky -thought her father had never looked so tall and so superb as when he -walked the floor and stamped his foot and said that. She went straight -off and told Tom about it. - -Judge Thatcher hoped to see Tom a great lawyer or a great soldier some -day. He said he meant to look to it that Tom should be admitted to the -National Military Academy and afterward trained in the best law school -in the country, in order that he might be ready for either career or -both. - -Huck Finn's wealth and the fact that he was now under the Widow -Douglas' protection introduced him into society--no, dragged him into -it, hurled him into it--and his sufferings were almost more than he -could bear. The widow's servants kept him clean and neat, combed and -brushed, and they bedded him nightly in unsympathetic sheets that had -not one little spot or stain which he could press to his heart and know -for a friend. He had to eat with a knife and fork; he had to use -napkin, cup, and plate; he had to learn his book, he had to go to -church; he had to talk so properly that speech was become insipid in -his mouth; whithersoever he turned, the bars and shackles of -civilization shut him in and bound him hand and foot. - -He bravely bore his miseries three weeks, and then one day turned up -missing. For forty-eight hours the widow hunted for him everywhere in -great distress. The public were profoundly concerned; they searched -high and low, they dragged the river for his body. Early the third -morning Tom Sawyer wisely went poking among some old empty hogsheads -down behind the abandoned slaughter-house, and in one of them he found -the refugee. Huck had slept there; he had just breakfasted upon some -stolen odds and ends of food, and was lying off, now, in comfort, with -his pipe. He was unkempt, uncombed, and clad in the same old ruin of -rags that had made him picturesque in the days when he was free and -happy. Tom routed him out, told him the trouble he had been causing, -and urged him to go home. Huck's face lost its tranquil content, and -took a melancholy cast. He said: - -"Don't talk about it, Tom. I've tried it, and it don't work; it don't -work, Tom. It ain't for me; I ain't used to it. The widder's good to -me, and friendly; but I can't stand them ways. She makes me get up just -at the same time every morning; she makes me wash, they comb me all to -thunder; she won't let me sleep in the woodshed; I got to wear them -blamed clothes that just smothers me, Tom; they don't seem to any air -git through 'em, somehow; and they're so rotten nice that I can't set -down, nor lay down, nor roll around anywher's; I hain't slid on a -cellar-door for--well, it 'pears to be years; I got to go to church and -sweat and sweat--I hate them ornery sermons! I can't ketch a fly in -there, I can't chaw. I got to wear shoes all Sunday. The widder eats by -a bell; she goes to bed by a bell; she gits up by a bell--everything's -so awful reg'lar a body can't stand it." - -"Well, everybody does that way, Huck." - -"Tom, it don't make no difference. I ain't everybody, and I can't -STAND it. It's awful to be tied up so. And grub comes too easy--I don't -take no interest in vittles, that way. I got to ask to go a-fishing; I -got to ask to go in a-swimming--dern'd if I hain't got to ask to do -everything. Well, I'd got to talk so nice it wasn't no comfort--I'd got -to go up in the attic and rip out awhile, every day, to git a taste in -my mouth, or I'd a died, Tom. The widder wouldn't let me smoke; she -wouldn't let me yell, she wouldn't let me gape, nor stretch, nor -scratch, before folks--" [Then with a spasm of special irritation and -injury]--"And dad fetch it, she prayed all the time! I never see such a -woman! I HAD to shove, Tom--I just had to. And besides, that school's -going to open, and I'd a had to go to it--well, I wouldn't stand THAT, -Tom. Looky here, Tom, being rich ain't what it's cracked up to be. It's -just worry and worry, and sweat and sweat, and a-wishing you was dead -all the time. Now these clothes suits me, and this bar'l suits me, and -I ain't ever going to shake 'em any more. Tom, I wouldn't ever got into -all this trouble if it hadn't 'a' ben for that money; now you just take -my sheer of it along with your'n, and gimme a ten-center sometimes--not -many times, becuz I don't give a dern for a thing 'thout it's tollable -hard to git--and you go and beg off for me with the widder." - -"Oh, Huck, you know I can't do that. 'Tain't fair; and besides if -you'll try this thing just a while longer you'll come to like it." - -"Like it! Yes--the way I'd like a hot stove if I was to set on it long -enough. No, Tom, I won't be rich, and I won't live in them cussed -smothery houses. I like the woods, and the river, and hogsheads, and -I'll stick to 'em, too. Blame it all! just as we'd got guns, and a -cave, and all just fixed to rob, here this dern foolishness has got to -come up and spile it all!" - -Tom saw his opportunity-- - -"Lookyhere, Huck, being rich ain't going to keep me back from turning -robber." - -"No! Oh, good-licks; are you in real dead-wood earnest, Tom?" - -"Just as dead earnest as I'm sitting here. But Huck, we can't let you -into the gang if you ain't respectable, you know." - -Huck's joy was quenched. - -"Can't let me in, Tom? Didn't you let me go for a pirate?" - -"Yes, but that's different. A robber is more high-toned than what a -pirate is--as a general thing. In most countries they're awful high up -in the nobility--dukes and such." - -"Now, Tom, hain't you always ben friendly to me? You wouldn't shet me -out, would you, Tom? You wouldn't do that, now, WOULD you, Tom?" - -"Huck, I wouldn't want to, and I DON'T want to--but what would people -say? Why, they'd say, 'Mph! Tom Sawyer's Gang! pretty low characters in -it!' They'd mean you, Huck. You wouldn't like that, and I wouldn't." - -Huck was silent for some time, engaged in a mental struggle. Finally -he said: - -"Well, I'll go back to the widder for a month and tackle it and see if -I can come to stand it, if you'll let me b'long to the gang, Tom." - -"All right, Huck, it's a whiz! Come along, old chap, and I'll ask the -widow to let up on you a little, Huck." - -"Will you, Tom--now will you? That's good. If she'll let up on some of -the roughest things, I'll smoke private and cuss private, and crowd -through or bust. When you going to start the gang and turn robbers?" - -"Oh, right off. We'll get the boys together and have the initiation -to-night, maybe." - -"Have the which?" - -"Have the initiation." - -"What's that?" - -"It's to swear to stand by one another, and never tell the gang's -secrets, even if you're chopped all to flinders, and kill anybody and -all his family that hurts one of the gang." - -"That's gay--that's mighty gay, Tom, I tell you." - -"Well, I bet it is. And all that swearing's got to be done at -midnight, in the lonesomest, awfulest place you can find--a ha'nted -house is the best, but they're all ripped up now." - -"Well, midnight's good, anyway, Tom." - -"Yes, so it is. And you've got to swear on a coffin, and sign it with -blood." - -"Now, that's something LIKE! Why, it's a million times bullier than -pirating. I'll stick to the widder till I rot, Tom; and if I git to be -a reg'lar ripper of a robber, and everybody talking 'bout it, I reckon -she'll be proud she snaked me in out of the wet." - - - -CONCLUSION - -SO endeth this chronicle. It being strictly a history of a BOY, it -must stop here; the story could not go much further without becoming -the history of a MAN. When one writes a novel about grown people, he -knows exactly where to stop--that is, with a marriage; but when he -writes of juveniles, he must stop where he best can. - -Most of the characters that perform in this book still live, and are -prosperous and happy. Some day it may seem worth while to take up the -story of the younger ones again and see what sort of men and women they -turned out to be; therefore it will be wisest not to reveal any of that -part of their lives at present. - - - - - -End of the Project Gutenberg EBook of The Adventures of Tom Sawyer, Complete -by Mark Twain (Samuel Clemens) - -*** END OF THIS PROJECT GUTENBERG EBOOK TOM SAWYER *** - -***** This file should be named 74.txt or 74.zip ***** -This and all associated files of various formats will be found in: - http://www.gutenberg.net/7/74/ - -Produced by David Widger. The previous edition was update by Jose -Menendez. - - -Updated editions will replace the previous one--the old editions -will be renamed. - -Creating the works from public domain print editions means that no -one owns a United States copyright in these works, so the Foundation -(and you!) can copy and distribute it in the United States without -permission and without paying copyright royalties. Special rules, -set forth in the General Terms of Use part of this license, apply to -copying and distributing Project Gutenberg-tm electronic works to -protect the PROJECT GUTENBERG-tm concept and trademark. Project -Gutenberg is a registered trademark, and may not be used if you -charge for the eBooks, unless you receive specific permission. If you -do not charge anything for copies of this eBook, complying with the -rules is very easy. You may use this eBook for nearly any purpose -such as creation of derivative works, reports, performances and -research. They may be modified and printed and given away--you may do -practically ANYTHING with public domain eBooks. Redistribution is -subject to the trademark license, especially commercial -redistribution. - - - -*** START: FULL LICENSE *** - -THE FULL PROJECT GUTENBERG LICENSE -PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK - -To protect the Project Gutenberg-tm mission of promoting the free -distribution of electronic works, by using or distributing this work -(or any other work associated in any way with the phrase "Project -Gutenberg"), you agree to comply with all the terms of the Full Project -Gutenberg-tm License (available with this file or online at -http://gutenberg.net/license). - - -Section 1. General Terms of Use and Redistributing Project Gutenberg-tm -electronic works - -1.A. By reading or using any part of this Project Gutenberg-tm -electronic work, you indicate that you have read, understand, agree to -and accept all the terms of this license and intellectual property -(trademark/copyright) agreement. If you do not agree to abide by all -the terms of this agreement, you must cease using and return or destroy -all copies of Project Gutenberg-tm electronic works in your possession. -If you paid a fee for obtaining a copy of or access to a Project -Gutenberg-tm electronic work and you do not agree to be bound by the -terms of this agreement, you may obtain a refund from the person or -entity to whom you paid the fee as set forth in paragraph 1.E.8. - -1.B. "Project Gutenberg" is a registered trademark. It may only be -used on or associated in any way with an electronic work by people who -agree to be bound by the terms of this agreement. There are a few -things that you can do with most Project Gutenberg-tm electronic works -even without complying with the full terms of this agreement. See -paragraph 1.C below. There are a lot of things you can do with Project -Gutenberg-tm electronic works if you follow the terms of this agreement -and help preserve free future access to Project Gutenberg-tm electronic -works. See paragraph 1.E below. - -1.C. The Project Gutenberg Literary Archive Foundation ("the Foundation" -or PGLAF), owns a compilation copyright in the collection of Project -Gutenberg-tm electronic works. Nearly all the individual works in the -collection are in the public domain in the United States. If an -individual work is in the public domain in the United States and you are -located in the United States, we do not claim a right to prevent you from -copying, distributing, performing, displaying or creating derivative -works based on the work as long as all references to Project Gutenberg -are removed. Of course, we hope that you will support the Project -Gutenberg-tm mission of promoting free access to electronic works by -freely sharing Project Gutenberg-tm works in compliance with the terms of -this agreement for keeping the Project Gutenberg-tm name associated with -the work. You can easily comply with the terms of this agreement by -keeping this work in the same format with its attached full Project -Gutenberg-tm License when you share it without charge with others. - -1.D. The copyright laws of the place where you are located also govern -what you can do with this work. Copyright laws in most countries are in -a constant state of change. If you are outside the United States, check -the laws of your country in addition to the terms of this agreement -before downloading, copying, displaying, performing, distributing or -creating derivative works based on this work or any other Project -Gutenberg-tm work. The Foundation makes no representations concerning -the copyright status of any work in any country outside the United -States. - -1.E. Unless you have removed all references to Project Gutenberg: - -1.E.1. The following sentence, with active links to, or other immediate -access to, the full Project Gutenberg-tm License must appear prominently -whenever any copy of a Project Gutenberg-tm work (any work on which the -phrase "Project Gutenberg" appears, or with which the phrase "Project -Gutenberg" is associated) is accessed, displayed, performed, viewed, -copied or distributed: - -This eBook is for the use of anyone anywhere at no cost and with -almost no restrictions whatsoever. You may copy it, give it away or -re-use it under the terms of the Project Gutenberg License included -with this eBook or online at www.gutenberg.net - -1.E.2. If an individual Project Gutenberg-tm electronic work is derived -from the public domain (does not contain a notice indicating that it is -posted with permission of the copyright holder), the work can be copied -and distributed to anyone in the United States without paying any fees -or charges. If you are redistributing or providing access to a work -with the phrase "Project Gutenberg" associated with or appearing on the -work, you must comply either with the requirements of paragraphs 1.E.1 -through 1.E.7 or obtain permission for the use of the work and the -Project Gutenberg-tm trademark as set forth in paragraphs 1.E.8 or -1.E.9. - -1.E.3. If an individual Project Gutenberg-tm electronic work is posted -with the permission of the copyright holder, your use and distribution -must comply with both paragraphs 1.E.1 through 1.E.7 and any additional -terms imposed by the copyright holder. Additional terms will be linked -to the Project Gutenberg-tm License for all works posted with the -permission of the copyright holder found at the beginning of this work. - -1.E.4. Do not unlink or detach or remove the full Project Gutenberg-tm -License terms from this work, or any files containing a part of this -work or any other work associated with Project Gutenberg-tm. - -1.E.5. Do not copy, display, perform, distribute or redistribute this -electronic work, or any part of this electronic work, without -prominently displaying the sentence set forth in paragraph 1.E.1 with -active links or immediate access to the full terms of the Project -Gutenberg-tm License. - -1.E.6. You may convert to and distribute this work in any binary, -compressed, marked up, nonproprietary or proprietary form, including any -word processing or hypertext form. However, if you provide access to or -distribute copies of a Project Gutenberg-tm work in a format other than -"Plain Vanilla ASCII" or other format used in the official version -posted on the official Project Gutenberg-tm web site (www.gutenberg.net), -you must, at no additional cost, fee or expense to the user, provide a -copy, a means of exporting a copy, or a means of obtaining a copy upon -request, of the work in its original "Plain Vanilla ASCII" or other -form. Any alternate format must include the full Project Gutenberg-tm -License as specified in paragraph 1.E.1. - -1.E.7. Do not charge a fee for access to, viewing, displaying, -performing, copying or distributing any Project Gutenberg-tm works -unless you comply with paragraph 1.E.8 or 1.E.9. - -1.E.8. You may charge a reasonable fee for copies of or providing -access to or distributing Project Gutenberg-tm electronic works provided -that - -- You pay a royalty fee of 20% of the gross profits you derive from - the use of Project Gutenberg-tm works calculated using the method - you already use to calculate your applicable taxes. The fee is - owed to the owner of the Project Gutenberg-tm trademark, but he - has agreed to donate royalties under this paragraph to the - Project Gutenberg Literary Archive Foundation. Royalty payments - must be paid within 60 days following each date on which you - prepare (or are legally required to prepare) your periodic tax - returns. Royalty payments should be clearly marked as such and - sent to the Project Gutenberg Literary Archive Foundation at the - address specified in Section 4, "Information about donations to - the Project Gutenberg Literary Archive Foundation." - -- You provide a full refund of any money paid by a user who notifies - you in writing (or by e-mail) within 30 days of receipt that s/he - does not agree to the terms of the full Project Gutenberg-tm - License. You must require such a user to return or - destroy all copies of the works possessed in a physical medium - and discontinue all use of and all access to other copies of - Project Gutenberg-tm works. - -- You provide, in accordance with paragraph 1.F.3, a full refund of any - money paid for a work or a replacement copy, if a defect in the - electronic work is discovered and reported to you within 90 days - of receipt of the work. - -- You comply with all other terms of this agreement for free - distribution of Project Gutenberg-tm works. - -1.E.9. If you wish to charge a fee or distribute a Project Gutenberg-tm -electronic work or group of works on different terms than are set -forth in this agreement, you must obtain permission in writing from -both the Project Gutenberg Literary Archive Foundation and Michael -Hart, the owner of the Project Gutenberg-tm trademark. Contact the -Foundation as set forth in Section 3 below. - -1.F. - -1.F.1. Project Gutenberg volunteers and employees expend considerable -effort to identify, do copyright research on, transcribe and proofread -public domain works in creating the Project Gutenberg-tm -collection. Despite these efforts, Project Gutenberg-tm electronic -works, and the medium on which they may be stored, may contain -"Defects," such as, but not limited to, incomplete, inaccurate or -corrupt data, transcription errors, a copyright or other intellectual -property infringement, a defective or damaged disk or other medium, a -computer virus, or computer codes that damage or cannot be read by -your equipment. - -1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for the "Right -of Replacement or Refund" described in paragraph 1.F.3, the Project -Gutenberg Literary Archive Foundation, the owner of the Project -Gutenberg-tm trademark, and any other party distributing a Project -Gutenberg-tm electronic work under this agreement, disclaim all -liability to you for damages, costs and expenses, including legal -fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR NEGLIGENCE, STRICT -LIABILITY, BREACH OF WARRANTY OR BREACH OF CONTRACT EXCEPT THOSE -PROVIDED IN PARAGRAPH F3. YOU AGREE THAT THE FOUNDATION, THE -TRADEMARK OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL NOT BE -LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT, CONSEQUENTIAL, PUNITIVE OR -INCIDENTAL DAMAGES EVEN IF YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH -DAMAGE. - -1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you discover a -defect in this electronic work within 90 days of receiving it, you can -receive a refund of the money (if any) you paid for it by sending a -written explanation to the person you received the work from. If you -received the work on a physical medium, you must return the medium with -your written explanation. The person or entity that provided you with -the defective work may elect to provide a replacement copy in lieu of a -refund. If you received the work electronically, the person or entity -providing it to you may choose to give you a second opportunity to -receive the work electronically in lieu of a refund. If the second copy -is also defective, you may demand a refund in writing without further -opportunities to fix the problem. - -1.F.4. Except for the limited right of replacement or refund set forth -in paragraph 1.F.3, this work is provided to you 'AS-IS' WITH NO OTHER -WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO -WARRANTIES OF MERCHANTIBILITY OR FITNESS FOR ANY PURPOSE. - -1.F.5. Some states do not allow disclaimers of certain implied -warranties or the exclusion or limitation of certain types of damages. -If any disclaimer or limitation set forth in this agreement violates the -law of the state applicable to this agreement, the agreement shall be -interpreted to make the maximum disclaimer or limitation permitted by -the applicable state law. The invalidity or unenforceability of any -provision of this agreement shall not void the remaining provisions. - -1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation, the -trademark owner, any agent or employee of the Foundation, anyone -providing copies of Project Gutenberg-tm electronic works in accordance -with this agreement, and any volunteers associated with the production, -promotion and distribution of Project Gutenberg-tm electronic works, -harmless from all liability, costs and expenses, including legal fees, -that arise directly or indirectly from any of the following which you do -or cause to occur: (a) distribution of this or any Project Gutenberg-tm -work, (b) alteration, modification, or additions or deletions to any -Project Gutenberg-tm work, and (c) any Defect you cause. - - -Section 2. Information about the Mission of Project Gutenberg-tm - -Project Gutenberg-tm is synonymous with the free distribution of -electronic works in formats readable by the widest variety of computers -including obsolete, old, middle-aged and new computers. It exists -because of the efforts of hundreds of volunteers and donations from -people in all walks of life. - -Volunteers and financial support to provide volunteers with the -assistance they need, is critical to reaching Project Gutenberg-tm's -goals and ensuring that the Project Gutenberg-tm collection will -remain freely available for generations to come. In 2001, the Project -Gutenberg Literary Archive Foundation was created to provide a secure -and permanent future for Project Gutenberg-tm and future generations. -To learn more about the Project Gutenberg Literary Archive Foundation -and how your efforts and donations can help, see Sections 3 and 4 -and the Foundation web page at http://www.pglaf.org. - - -Section 3. Information about the Project Gutenberg Literary Archive -Foundation - -The Project Gutenberg Literary Archive Foundation is a non profit -501(c)(3) educational corporation organized under the laws of the -state of Mississippi and granted tax exempt status by the Internal -Revenue Service. The Foundation's EIN or federal tax identification -number is 64-6221541. Its 501(c)(3) letter is posted at -http://pglaf.org/fundraising. Contributions to the Project Gutenberg -Literary Archive Foundation are tax deductible to the full extent -permitted by U.S. federal laws and your state's laws. - -The Foundation's principal office is located at 4557 Melan Dr. S. -Fairbanks, AK, 99712., but its volunteers and employees are scattered -throughout numerous locations. Its business office is located at -809 North 1500 West, Salt Lake City, UT 84116, (801) 596-1887, email -business@pglaf.org. Email contact links and up to date contact -information can be found at the Foundation's web site and official -page at http://pglaf.org - -For additional contact information: - Dr. Gregory B. Newby - Chief Executive and Director - gbnewby@pglaf.org - - -Section 4. Information about Donations to the Project Gutenberg -Literary Archive Foundation - -Project Gutenberg-tm depends upon and cannot survive without wide -spread public support and donations to carry out its mission of -increasing the number of public domain and licensed works that can be -freely distributed in machine readable form accessible by the widest -array of equipment including outdated equipment. Many small donations -($1 to $5,000) are particularly important to maintaining tax exempt -status with the IRS. - -The Foundation is committed to complying with the laws regulating -charities and charitable donations in all 50 states of the United -States. Compliance requirements are not uniform and it takes a -considerable effort, much paperwork and many fees to meet and keep up -with these requirements. We do not solicit donations in locations -where we have not received written confirmation of compliance. To -SEND DONATIONS or determine the status of compliance for any -particular state visit http://pglaf.org - -While we cannot and do not solicit contributions from states where we -have not met the solicitation requirements, we know of no prohibition -against accepting unsolicited donations from donors in such states who -approach us with offers to donate. - -International donations are gratefully accepted, but we cannot make -any statements concerning tax treatment of donations received from -outside the United States. U.S. laws alone swamp our small staff. - -Please check the Project Gutenberg Web pages for current donation -methods and addresses. Donations are accepted in a number of other -ways including including checks, online payments and credit card -donations. To donate, please visit: http://pglaf.org/donate - - -Section 5. General Information About Project Gutenberg-tm electronic -works. - -Professor Michael S. Hart is the originator of the Project Gutenberg-tm -concept of a library of electronic works that could be freely shared -with anyone. For thirty years, he produced and distributed Project -Gutenberg-tm eBooks with only a loose network of volunteer support. - - -Project Gutenberg-tm eBooks are often created from several printed -editions, all of which are confirmed as Public Domain in the U.S. -unless a copyright notice is included. Thus, we do not necessarily -keep eBooks in compliance with any particular paper edition. - - -Most people start at our Web site which has the main PG search facility: - - http://www.gutenberg.net - -This Web site includes information about Project Gutenberg-tm, -including how to make donations to the Project Gutenberg Literary -Archive Foundation, how to help produce our new eBooks, and how to -subscribe to our email newsletter to hear about new eBooks. diff --git a/src/pkg/compress/testdata/e.txt b/src/pkg/compress/testdata/e.txt deleted file mode 100644 index 5ca186f14..000000000 --- a/src/pkg/compress/testdata/e.txt +++ /dev/null @@ -1 +0,0 @@ -2.7182818284590452353602874713526624977572470936999595749669676277240766303535475945713821785251664274274663919320030599218174135966290435729003342952605956307381323286279434907632338298807531952510190115738341879307021540891499348841675092447614606680822648001684774118537423454424371075390777449920695517027618386062613313845830007520449338265602976067371132007093287091274437470472306969772093101416928368190255151086574637721112523897844250569536967707854499699679468644549059879316368892300987931277361782154249992295763514822082698951936680331825288693984964651058209392398294887933203625094431173012381970684161403970198376793206832823764648042953118023287825098194558153017567173613320698112509961818815930416903515988885193458072738667385894228792284998920868058257492796104841984443634632449684875602336248270419786232090021609902353043699418491463140934317381436405462531520961836908887070167683964243781405927145635490613031072085103837505101157477041718986106873969655212671546889570350354021234078498193343210681701210056278802351930332247450158539047304199577770935036604169973297250886876966403555707162268447162560798826517871341951246652010305921236677194325278675398558944896970964097545918569563802363701621120477427228364896134225164450781824423529486363721417402388934412479635743702637552944483379980161254922785092577825620926226483262779333865664816277251640191059004916449982893150566047258027786318641551956532442586982946959308019152987211725563475463964479101459040905862984967912874068705048958586717479854667757573205681288459205413340539220001137863009455606881667400169842055804033637953764520304024322566135278369511778838638744396625322498506549958862342818997077332761717839280349465014345588970719425863987727547109629537415211151368350627526023264847287039207643100595841166120545297030236472549296669381151373227536450988890313602057248176585118063036442812314965507047510254465011727211555194866850800368532281831521960037356252794495158284188294787610852639813955990067376482922443752871846245780361929819713991475644882626039033814418232625150974827987779964373089970388867782271383605772978824125611907176639465070633045279546618550966661856647097113444740160704626215680717481877844371436988218559670959102596862002353718588748569652200050311734392073211390803293634479727355955277349071783793421637012050054513263835440001863239914907054797780566978533580489669062951194324730995876552368128590413832411607226029983305353708761389396391779574540161372236187893652605381558415871869255386061647798340254351284396129460352913325942794904337299085731580290958631382683291477116396337092400316894586360606458459251269946557248391865642097526850823075442545993769170419777800853627309417101634349076964237222943523661255725088147792231519747780605696725380171807763603462459278778465850656050780844211529697521890874019660906651803516501792504619501366585436632712549639908549144200014574760819302212066024330096412704894390397177195180699086998606636583232278709376502260149291011517177635944602023249300280401867723910288097866605651183260043688508817157238669842242201024950551881694803221002515426494639812873677658927688163598312477886520141174110913601164995076629077943646005851941998560162647907615321038727557126992518275687989302761761146162549356495903798045838182323368612016243736569846703785853305275833337939907521660692380533698879565137285593883499894707416181550125397064648171946708348197214488898790676503795903669672494992545279033729636162658976039498576741397359441023744329709355477982629614591442936451428617158587339746791897571211956187385783644758448423555581050025611492391518893099463428413936080383091662818811503715284967059741625628236092168075150177725387402564253470879089137291722828611515915683725241630772254406337875931059826760944203261924285317018781772960235413060672136046000389661093647095141417185777014180606443636815464440053316087783143174440811949422975599314011888683314832802706553833004693290115744147563139997221703804617092894579096271662260740718749975359212756084414737823303270330168237193648002173285734935947564334129943024850235732214597843282641421684878721673367010615094243456984401873312810107945127223737886126058165668053714396127888732527373890392890506865324138062796025930387727697783792868409325365880733988457218746021005311483351323850047827169376218004904795597959290591655470505777514308175112698985188408718564026035305583737832422924185625644255022672155980274012617971928047139600689163828665277009752767069777036439260224372841840883251848770472638440379530166905465937461619323840363893131364327137688841026811219891275223056256756254701725086349765367288605966752740868627407912856576996313789753034660616669804218267724560530660773899624218340859882071864682623215080288286359746839654358856685503773131296587975810501214916207656769950659715344763470320853215603674828608378656803073062657633469774295634643716709397193060876963495328846833613038829431040800296873869117066666146800015121143442256023874474325250769387077775193299942137277211258843608715834835626961661980572526612206797540621062080649882918454395301529982092503005498257043390553570168653120526495614857249257386206917403695213533732531666345466588597286659451136441370331393672118569553952108458407244323835586063106806964924851232632699514603596037297253198368423363904632136710116192821711150282801604488058802382031981493096369596735832742024988245684941273860566491352526706046234450549227581151709314921879592718001940968866986837037302200475314338181092708030017205935530520700706072233999463990571311587099635777359027196285061146514837526209565346713290025994397663114545902685898979115837093419370441155121920117164880566945938131183843765620627846310490346293950029458341164824114969758326011800731699437393506966295712410273239138741754923071862454543222039552735295240245903805744502892246886285336542213815722131163288112052146489805180092024719391710555390113943316681515828843687606961102505171007392762385553386272553538830960671644662370922646809671254061869502143176211668140097595281493907222601112681153108387317617323235263605838173151034595736538223534992935822836851007810884634349983518404451704270189381994243410090575376257767571118090088164183319201962623416288166521374717325477727783488774366518828752156685719506371936565390389449366421764003121527870222366463635755503565576948886549500270853923617105502131147413744106134445544192101336172996285694899193369184729478580729156088510396781959429833186480756083679551496636448965592948187851784038773326247051945050419847742014183947731202815886845707290544057510601285258056594703046836344592652552137008068752009593453607316226118728173928074623094685367823106097921599360019946237993434210687813497346959246469752506246958616909178573976595199392993995567542714654910456860702099012606818704984178079173924071945996323060254707901774527513186809982284730860766536866855516467702911336827563107223346726113705490795365834538637196235856312618387156774118738527722922594743373785695538456246801013905727871016512966636764451872465653730402443684140814488732957847348490003019477888020460324660842875351848364959195082888323206522128104190448047247949291342284951970022601310430062410717971502793433263407995960531446053230488528972917659876016667811937932372453857209607582277178483361613582612896226118129455927462767137794487586753657544861407611931125958512655759734573015333642630767985443385761715333462325270572005303988289499034259566232975782488735029259166825894456894655992658454762694528780516501720674785417887982276806536650641910973434528878338621726156269582654478205672987756426325321594294418039943217000090542650763095588465895171709147607437136893319469090981904501290307099566226620303182649365733698419555776963787624918852865686607600566025605445711337286840205574416030837052312242587223438854123179481388550075689381124935386318635287083799845692619981794523364087429591180747453419551420351726184200845509170845682368200897739455842679214273477560879644279202708312150156406341341617166448069815483764491573900121217041547872591998943825364950514771379399147205219529079396137621107238494290616357604596231253506068537651423115349665683715116604220796394466621163255157729070978473156278277598788136491951257483328793771571459091064841642678309949723674420175862269402159407924480541255360431317992696739157542419296607312393763542139230617876753958711436104089409966089471418340698362993675362621545247298464213752891079884381306095552622720837518629837066787224430195793793786072107254277289071732854874374355781966511716618330881129120245204048682200072344035025448202834254187884653602591506445271657700044521097735585897622655484941621714989532383421600114062950718490427789258552743035221396835679018076406042138307308774460170842688272261177180842664333651780002171903449234264266292261456004337383868335555343453004264818473989215627086095650629340405264943244261445665921291225648893569655009154306426134252668472594914314239398845432486327461842846655985332312210466259890141712103446084271616619001257195870793217569698544013397622096749454185407118446433946990162698351607848924514058940946395267807354579700307051163682519487701189764002827648414160587206184185297189154019688253289309149665345753571427318482016384644832499037886069008072709327673127581966563941148961716832980455139729506687604740915420428429993541025829113502241690769431668574242522509026939034814856451303069925199590436384028429267412573422447765584177886171737265462085498294498946787350929581652632072258992368768457017823038096567883112289305809140572610865884845873101658151167533327674887014829167419701512559782572707406431808601428149024146780472327597684269633935773542930186739439716388611764209004068663398856841681003872389214483176070116684503887212364367043314091155733280182977988736590916659612402021778558854876176161989370794380056663364884365089144805571039765214696027662583599051987042300179465536788567430285974600143785483237068701190078499404930918919181649327259774030074879681484882342932023012128032327460392219687528340516906974194257614673978110715464186273369091584973185011183960482533518748438923177292613543024932562896371361977285456622924461644497284597867711574125670307871885109336344480149675240618536569532074170533486782754827815415561966911055101472799040386897220465550833170782394808785990501947563108984124144672821865459971596639015641941751820935932616316888380132758752601460507676098392625726411120135288591317848299475682472564885533357279772205543568126302535748216585414000805314820697137262149755576051890481622376790414926742600071045922695314835188137463887104273544767623577933993970632396604969145303273887874557905934937772320142954803345000695256980935282887783710670585567749481373858630385762823040694005665340584887527005308832459182183494318049834199639981458773435863115940570443683515285383609442955964360676090221741896883548131643997437764158365242234642619597390455450680695232850751868719449064767791886720306418630751053512149851051207313846648717547518382979990189317751550639981016466414592102406838294603208535554058147159273220677567669213664081505900806952540610628536408293276621931939933861623836069111767785448236129326858199965239275488427435414402884536455595124735546139403154952097397051896240157976832639450633230452192645049651735466775699295718989690470902730288544945416699791992948038254980285946029052763145580316514066229171223429375806143993484914362107993576737317948964252488813720435579287511385856973381976083524423240466778020948399639946684833774706725483618848273000648319163826022110555221246733323184463005504481849916996622087746140216157021029603318588727333298779352570182393861244026868339555870607758169954398469568540671174444932479519572159419645863736126915526457574786985964242176592896862383506370433939811671397544736228625506803682664135541448048997721373174119199970017293907303350869020922519124447393278376156321810842898207706974138707053266117683698647741787180202729412982310888796831880854367327806879771659111654224453806625861711729498038248879986504061563975629936962809358189761491017145343556659542757064194408833816841111166200759787244137082333917886114708228657531078536674695018462140736493917366254937783014074302668422150335117736471853872324040421037907750266020114814935482228916663640782450166815341213505278578539332606110249802273093636740213515386431693015267460536064351732154701091440650878823636764236831187390937464232609021646365627553976834019482932795750624399645272578624400375983422050808935129023122475970644105678361870877172333555465482598906861201410107222465904008553798235253885171623518256518482203125214950700378300411216212126052726059944320443056274522916128891766814160639131235975350390320077529587392412476451850809163911459296071156344204347133544720981178461451077872399140606290228276664309264900592249810291068759434533858330391178747575977065953570979640012224092199031158229259667913153991561438070129260780197022589662923368154312499412259460023399472228171056603931877226800493833148980338548909468685130789292064242819174795866199944411196208730498064385006852620258432842085582338566936649849720817046135376163584015342840674118587581546514598270228676671855309311923340191286170613364873183197560812569460089402953094429119590295968563923037689976327462283900735457144596414108229285922239332836210192822937243590283003884445701383771632056518351970100115722010956997890484964453434612129224964732356126321951155701565824427661599326463155806672053127596948538057364208384918887095176052287817339462747644656858900936266123311152910816041524100214195937349786431661556732702792109593543055579732660554677963552005378304619540636971842916168582734122217145885870814274090248185446421774876925093328785670674677381226752831653559245204578070541352576903253522738963847495646255940378924925007624386893776475310102323746733771474581625530698032499033676455430305274561512961214585944432150749051491453950981001388737926379964873728396416897555132275962011838248650746985492038097691932606437608743209385602815642849756549307909733854185583515789409814007691892389063090542534883896831762904120212949167195811935791203162514344096503132835216728021372415947344095498316138322505486708172221475138425166790445416617303200820330902895488808516797258495813407132180533988828139346049850532340472595097214331492586604248511405819579711564191458842833000525684776874305916390494306871343118796189637475503362820939949343690321031976898112055595369465424704173323895394046035325396758354395350516720261647961347790912327995264929045151148307923369382166010702872651938143844844532639517394110131152502750465749343063766541866128915264446926222884366299462732467958736383501937142786471398054038215513463223702071533134887083174146591492406359493020921122052610312390682941345696785958518393491382340884274312419099152870804332809132993078936867127413922890033069995875921815297612482409116951587789964090352577345938248232053055567238095022266790439614231852991989181065554412477204508510210071522352342792531266930108270633942321762570076323139159349709946933241013908779161651226804414809765618979735043151396066913258379033748620836695475083280318786707751177525663963479259219733577949555498655214193398170268639987388347010255262052312317215254062571636771270010760912281528326508984359568975961038372157726831170734552250194121701541318793651818502020877326906133592182000762327269503283827391243828198170871168108951187896746707073377869592565542713340052326706040004348843432902760360498027862160749469654989210474443927871934536701798673920803845633723311983855862638008516345597194441994344624761123844617615736242015935078520825600604101556889899501732554337298073561699861101908472096600708320280569917042590103876928658336557728758684250492690370934262028022399861803400211320742198642917383679176232826444645756330336556777374808644109969141827774253417010988435853189339175934511574023847292909015468559163792696196841000676598399744972047287881831200233383298030567865480871476464512824264478216644266616732096012564794514827125671326697067367144617795643752391742928503987022583734069852309190464967260243411270345611114149835783901793499713790913696706497637127248466613279908254305449295528594932793818341607827091326680865655921102733746700132583428715240835661522165574998431236278287106649401564670141943713823863454729606978693335973109537126499416282656463708490580151538205338326511289504938566468752921135932220265681856418260827538790002407915892646028490894922299966167437731347776134150965262448332709343898412056926145108857812249139616912534202918139898683901335795857624435194008943955180554746554000051766240202825944828833811886381749594284892013520090951007864941868256009273977667585642598378587497776669563350170748579027248701370264203283965756348010818356182372177082236423186591595883669487322411726504487268392328453010991677518376831599821263237123854357312681202445175401852132663740538802901249728180895021553100673598184430429105288459323064725590442355960551978839325930339572934663055160430923785677229293537208416693134575284011873746854691620648991164726909428982971065606801805807843600461866223562874591385185904416250663222249561448724413813849763797102676020845531824111963927941069619465426480006761727618115630063644321116224837379105623611358836334550102286170517890440570419577859833348463317921904494652923021469259756566389965893747728751393377105569802455757436190501772466214587592374418657530064998056688376964229825501195065837843125232135309371235243969149662310110328243570065781487677299160941153954063362752423712935549926713485031578238899567545287915578420483105749330060197958207739558522807307048950936235550769837881926357141779338750216344391014187576711938914416277109602859415809719913429313295145924373636456473035037374538503489286113141638094752301745088784885645741275003353303416138096560043105860548355773946625033230034341587814634602169235079216111013148948281895391028916816328709309713184139815427678818067628650978085718262117003140003377301581536334149093237034703637513354537634521050370995452942055232078817449370937677056009306353645510913481627378204985657055608784211964039972344556458607689515569686899384896439195225232309703301037277227710870564912966121061494072782442033414057441446459968236966118878411656290355117839944070961772567164919790168195234523807446299877664824873753313018142763910519234685081979001796519907050490865237442841652776611425351538665162781316090964802801234493372427866930894827913465443931965254154829494577875758599482099181824522449312077768250830768282335001597040419199560509705364696473142448453825888112602753909548852639708652339052941829691802357120545328231809270356491743371932080628731303589640570873779967845174740515317401384878082881006046388936711640477755985481263907504747295012609419990373721246201677030517790352952793168766305099837441859803498821239340919805055103821539827677291373138006715339240126954586376422065097810852907639079727841301764553247527073788764069366420012194745702358295481365781809867944020220280822637957006755393575808086318932075864444206644691649334467698180811716568665213389686173592450920801465312529777966137198695916451869432324246404401672381978020728394418264502183131483366019384891972317817154372192103946638473715630226701801343515930442853848941825678870721238520597263859224934763623122188113706307506918260109689069251417142514218153491532129077723748506635489170892850760234351768218355008829647410655814882049239533702270536705630750317499788187009989251020178015601042277836283644323729779929935160925884515772055232896978333126427671291093993103773425910592303277652667641874842441076564447767097790392324958416348527735171981064673837142742974468992320406932506062834468937543016787815320616009057693404906146176607094380110915443261929000745209895959201159412324102274845482605404361871836330268992858623582145643879695210235266673372434423091577183277565800211928270391042391966426911155333594569685782817020325495552528875464466074620294766116004435551604735044292127916358748473501590215522120388281168021413865865168464569964810015633741255098479730138656275460161279246359783661480163871602794405482710196290774543628092612567507181773641749763254436773503632580004042919906963117397787875081560227368824967077635559869284901628768699628053790181848148810833946900016380791075960745504688912686792812391148880036720729730801354431325347713094186717178607522981373539126772812593958220524289991371690685650421575056729991274177149279608831502358697816190894908487717722503860872618384947939757440664912760518878124233683125467278331513186758915668300679210215947336858591201395360301678110413444411030903388761520488296909104689167671555373346622545575975202624771242796225983278405833585897671474205724047439720232895903726148688388003174146490203843590358527993123871042845981608996101945691646983837718267264685264869172948414153004604004299585035164101899027529366867431834955447458124140190754681607770977920579383895378192128847409929537040546962226547278807248685508046571043123854873351653070570784584243335550958221912862797205455466267099131902370311779690892786623112661337671178512943059323281605826535623848164192144732543731002062738466812351691016359252588256806438946389880872735284406462208149513862275239938938734905082625472417781702582044129853760499827899020083498387362992498125742354568439023012261733665820546785671147973065077035475620567428300187473019197310881157516777005071432012726354601912460800451608108641835539669946936947322271670748972850464195392966434725254724357659192969949061670189061433616907056148280980363243454128229968275980226694045642181328624517549652147221620839824594576613342710564957193564431561774500828376935700995419541839029151033187933907614207467028867968594985439789457300768939890070073924697461812855764662265412913204052279071212820653775058280040897163467163709024906774736309136904002615646432159560910851092445162454420141442641660181385990017417408244245378610158433361777292580611159192008414091888191208858207627011483671760749046980914443057262211104583300789331698191603917150622792986282709446275915009683226345073725451366858172483498470080840163868209726371345205439802277866337293290829914010645589761697455978409211409167684020269370229231743334499986901841510888993165125090001163719114994852024821586396216294981753094623047604832399379391002142532996476235163569009445086058091202459904612118623318278614464727795523218635916551883057930657703331498510068357135624341881884405780028844018129031378653794869614630467726914552953690154167025838032477842272417994513653582260971652588356712133519546838335349801503269359798167463231847628306340588324731228951257944267639877946713121042763380872695738609314631539148548792514028885025189788076023838995615684850391995855029256054176767663145354058496296796781349420116003325874431438746248313850214980401681940795687219268462617287403480967931949965604299190281810597603263251746405016454606266765529010639868703668263299050577706266397868453584384057673298268163448646707439990917504018892319267557518354054956017732907127219134577524905771512773358423314008356080926962298894163047287780054743798498545562870729968407382937218623831766524716090967192007237658894226186550487552614557855898773008703234726418384831040394818743616224455286163287628541175946460497027724490799275146445792982549802258601001772437840167723166802004162547244179415547810554178036773553354467030326469619447560812831933095679685582771932031205941616693902049665352189672822671972640029493307384717544753761937017882976382487233361813499414541694736549254840633793674361541081593464960431603544354737728802361047743115330785159902977771499610274627769759612488879448609863349422852847651310277926279743981957617505591300993377368240510902583759345170015340522266144077237050890044496613295859536020556034009492820943862994618834790932894161098856594954213114335608810239423706087108026465913203560121875933791639666437282836752328391688865373751335794859860107569374889645657187292540448508624449947816273842517229343960137212406286783636675845331904743954740664015260871940915743955282773904303868772728262065663129387459875317749973799293043294371763801856280061141619563942414312254397099163565102848315765427037906837175764870230052388197498746636856292655058222887713221781440489538099681072143012394693530931524054081215705402274414521876541901428386744260011889041724570537470755550581632831687247110220353727166112304857340460879272501694701067831178927095527253222125224361673343366384756590949728221809418684074238351567868893421148203905824224324264643630201441787982022116248471657468291146315407563770222740135841109076078464780070182766336227978104546331131294044833570134869585165267459515187680033395522410548181767867772152798270250117195816577603549732923724732067853690257536233971216884390878879262188202305529937132397194333083536231248870386416194361506529551267334207198502259771408638122015980894363561808597010080081622557455039101321981979045520049618583777721048046635533806616517023595097133203631578945644487800945620369784973459902004606886572701865867757842758530645706617127194967371083950603267501532435909029491516973738110897934782297684100117657987098185725131372267749706609250481876835516003714638685918913011736805218743265426063700710595364425062760458252336880552521181566417553430681181548267844169315284408461087588214317641649835663127518728182948655658524206852221830755306118393326934164459415342651778653397980580828158806300749952897558204686612590853678738603318442905510689778698417735603118111677563872589911516803236547002987989628986181014596471307916144369564690909518788574398821730583884980809523077569358851616027719521488998358632323127308909861560777386006984035267826785387215920936255817889813416247486456433211043194821421299793188104636399541496539441501383868748384870224681829391860319598667962363489309283087840712400431022706137591368056518861313458307990705003607588327248867879324093380071864152853317943535073401891193638546730000660453783784472469288830546979000131248952100446949032058838294923613919284305249167833012980192255157050378521810552961623637523647962685751660066539364142273063001648652613891842243501797455993616794063303522111829071597538821839777552812981538570168702202620274678647916644030729018445497956399844836807851997088201407769199261674991148329821854382718946282165387064858588646221611410343570342878862979083418871606214430014533275029715104673156021000043869510583773779766003460887624861640938645252177935289947578496255243925598620521409052346250847830487046492688313289470553891357290706967599556298586669559721686506052072801342104355762779184021797626656484580261591407173477009039475168017709900129391137881248534255949312866653465033728846390649968460644741907524313323903404908195233044389559060547854954620263256676813262435925020249516275607080900436460421497025691488555265022810327762115842282433269528629137662675481993546118143913367579700141255870143319434764035725376914388899683088262844616425575034001428982557620386364384137906519612917777354183694676232982904981261717676191554292570438432239918482261744350470199171258214687683172646078959690569981353264435973965173473319484798758064137926885413552523275720457329477215706850016950046959758389373527538622664943456437071610511521617176237598050900553232154896062817794302268640579555845730600598376482703339859420098582351400179507104569019191359062304102336798080907240196312675268916362136351032648077232914950859151265812143823371072949148088472355286394195993455684156344577951727033374238129903260198160571971183950662758220321837136059718025940870615534713104482272716848395524105913605919812444978458110854511231668173534838253724825347636777581712867205865148285317273569069839935110763432091319780314031658897379628301178409806410175016511072932907832177487566289310650383806093372841399226733384778203302020700517188941706465146238366720632742644336612174011766914919235570905644803016342294301837655263108450172510307540942604409687066288066265900569082451407632599158164499361455172452057020443093722305550217222299706209749268609762787409626448772056043078634808885709143464793241536214303199965695610753570417207285334250171325558818113295504095217830139465216436594262960768570585698507157151317262928960072587601564840556088613165411835958628710665496282599535127193244635791046554389165150954187306071015034430609582302257455974944275067630926322529966338219395202927917973247094559691016402983683080426309910481567503623509654924302589575273521412445149542462972258510120707802110188106722347972579330653187713438466713807546383471635428854957610942841898601794658721444495198801550804042506452191484989920400007310672369944655246020908767882300064337725657385010969899058191290957079866699453765080407917852438222041070599278889267745752084287526377986730360561230710723922581504781379172731261234878334034473833573601973235946604273704635201327182592410906040097638585857716958419563109577748529579836844756803121874818202833941887076311731615289811756429711334181497218078040465077657204457082859417475114926179367379999220181789399433337731146911970737861041963986422166045588965683206701337505745038872111332436739840284188639147633491695114032583475841514170325690161784931455706904169858050217798497637014758914810543205854914100662201721719726878930012101267481270235940855162601689425111458499658315589660460091525797881670384625905383256920520425791378948827579603278877535466861441826827797651258953563761485994485049706638406266121957141911063246061774180577212381659872472432252969098533628440799030007594546281549235506086481557928961969617060715201589825299772803520002610888814176506636216905928021516429198484077446143617891415191517976537848282687018750030264867608433204658525470555882410254654806040437372771834769014720664234434374255514129178503032471263418076525187802925534774001104853996960549926508093910691337614841834884596365621526610332239417467064368340504749943339802285610313083038484571294767389856293937641914407036507544622061186499127249643799875806537850203753189972618014404667793050140301580709266213229273649718653952866567538572115133606114457222800851183757899219543063413692302293139751143702404830227357629039911794499248480915071002444078482866598579406525539141041497342780203520135419925977628178182825372022920108186449448349255421793982723279357095828748597126780783134286180750497175747373730296280477376908932558914598141724852658299510882230055223242218586191394795184220131553319634363922684259164168669438122537135960710031743651959027712571604588486044820674410935215327906816032054215967959066411120187618531256710150212239401285668608469435937408158536481912528004920724042172170913983123118054043277015835629513656274610248827706488865037765175678806872498861657094846665770674577000207144332525555736557083150320019082992096545498737419756608619533492312940263904930982014700371161829485939931199955070455381196711289367735249958182011774799788636393286405807810818657337668157893827656450642917396685579555053188715314552353070355994740186225988149854660737787698781542360397080977412361518245964026869979609564523828584235953564615185448165799966460648261396618720304839119560250381111550938420209894591555760083897989949964566262540514195610780090298667014635238532066032574466820259430618801773091109212741138269148784355679352572808875543164693077235363768226036080174040660997151176880434927489197133087822951123746632635635328517394189466510943745768270782209928468034684157443127739811044186762032954475468077511126663685479944460934809992951875666499902261686019672053749149951226823637895865245462813439289338365156536992413109638102559114643923805213907862893561660998836479175633176725856523591069520326895990054884753424160586689820067483163174286329119633399132709086065074595260357157323069712106423424081597068328707624437165532750228797802598690981111226558888151520837482450034463046505984569690276166958278982913613535306291331427881888249342136442417833519319786543940201465328083410341785272489879050919932369270996567133507711905899945951923990615156165480300145359212550696405345263823452155999210578191371030188979206408883974767667144727314254467923500524618849237455307575734902707342496298879996942094595961008702501329453325358045689285707241207965919809225550560061971283541270202072583994171175520920820151096509526685113897577150810849443508285458749912943857563115668324566827992991861539009255871716840495663991959154034218364537212023678608655364745175654879318925644085274489190918193411667583563439758886046349413111875241038425467937999203546910411935443113219136068129657568583611774564654674861061988591414805799318725367531243470335482637527081353105570818049642498584646147973467599315946514787025065271083508782350656532331797738656666181652390017664988485456054961300215776115255813396184027067814900350252876823607822107397102339146870159735868589015297010347780503292154014359595298683404657471756232196640515401477953167461726208727304820634652469109953327375561090578378455945469160223687689641425960164689647106348074109928546482353083540132332924864037318003195202317476206537726163717445360549726690601711176761047774971666890152163838974311714180622222345718567941507299526201086205084783127474791909996889937275229053674785020500038630036526218800670926674104806027341997756660029427941090400064654281074454007616429525362460261476180471744322889953285828397762184600967669267581270302806519535452053173536808954589902180783145775891280203970053633193821100095443241244197949192916205234421346395653840781209416214835001155883618421164283992454027590719621537570187067083731012246141362048926555668109467076386536083015847614512581588569610030337081197058344452874666198891534664244887911940711423940115986970795745946337170243268484864632018986352827092313047089215684758207753034387689978702323438584381125011714013265769320554911860153519551654627941175593967947958810333935413289702528893533748106257875620364294270257512121137330213811951395756419122685155962476203282038726342066227347868223036522019655729325905068134849292299647248229359787842720945578267329975853818536442370617353517653060396801087899490506654491544577952166038552398013798104340564182403396162494910454712104839439200945914647542424785991096900046541371091630096785951563947332190934511838669964622788855817353221326876634958059123761251203010983867841195725887799206041260049865895027247133146763722204388398558347770112599424691208308595666787531942465131444389971195968105937957532155524204659410081418351120174196853432672343271868099625045432475688702055341969199545300952644398446384346598830418262932239295612610045884644244285011551557765935780379565026806130721758672048541797157896401554276881090475899564605488362989140226580026134158039480357971019004151547655018391755772677897148793477372747525743898158705040701968215101218826088040084551332795162841280679678965570163917067779841529149397403158167896865448841319046368332179115059107813898261026271979696826411179918656038993895418928488851750122504754778999508544083983800725431468842988412616042682248823097788556495765424017114510393927980290997604904428832198976751320535115230545666467143795931915272680278210241540629795828828466355623580986725638200565215519951793551069127710538552661926903526081367717666435071213453983711357500975854405939558661737828297120544693182260401670308530911657973113259516101749193468250063285777004686987177255226525708428745733039859744230639751837209975339055095883623642814493247460522424051972825153787541962759327436278819283740253185668545040893929401040561666867664402868211607294830305236465560955351079987185041352121321534713770667681396211443891632403235741573773787908838267618458756361026435182951815392455211729022985278518025598478407179607904114472041476091765804302984501746867981277584971731733287305281134969591668387877072315968334322509070204019030503595891994666652037530271923764252552910347950343816357721698115464329245608951158732012675424975710520894362639501382962152214033621065422821876739580121286442788547491928976959315766891987305176388698461503354594898541849550251690616888419122873385522699976822609645007504500096116866129171093180282355042553653997166054753907348915189650027442328981181709248273610863801576007240601649547082331349361582435128299050405405333992577071321011503713898695076713447940748097845416328110406350804863393555238405735580863718763530261867971725608155328716436111474875107033512913923595452951407437943144900950809932872153235195999616750297532475931909938012968640379783553559071355708369947311923538531051736669154087312467233440702525006918026747725078958903448856673081487299464807786497709361969389290891718228134002845552513917355978456150353144603409441211512001738697261466786933733154341007587514908295822756919350542184106448264951943804240543255345965248373785310657979037977505031436474651422484768831323479762673689855474944277949916560108528257618964374464656819789319422077536824661110427671936481836360534108748971066866318805026555929568123959680449295166615409802610781691689418764353363449482900125929366840591370059526914934421861891742142561071896846626335874414976973921566392767687720145153302241853125308442727245771161505550519076276250016522166274796257424425420546785767478190959486500575711016264847833741198041625940813327229905891486422127968042984725356237202887830051788539737909455265135144073130049869453403245984236934627060242579432563660640597549471239092372458126154582526667304702319359866523378856244229188278436440434628094888288712101968642736370461639297485616780079779959696843367730352483047478240669928277140069031660709951473154191919911453182543906294573298686613524886500574780251977607442660798300291573030523199052185718628543687577860915726925232573171665625274275808460620177046433101212443409281314659760221360416223031167750085960128475289259463348312408766740128170543067985261868949895004918275008304998926472034986965363326210919830621495095877228260815566702155693484634079776879525038204442326697479264829899016938511552124688935873289878336267819361764023681714606495185508780596635354698788205094762016350757090024201498400967867845405354130050482404996646978558002628931826518708714613909521454987992300431779500489569529280112698632533646737179519363094399609176354568799002814515169743717518330632232942199132137614506411391269837128970829395360832883050256072727563548374205497856659895469089938558918441085605111510354367477810778500572718180809661542709143010161515013086522842238721618109043183163796046431523184434669799904865336375319295967726080853457652274714047941973192220960296582500937408249714373040087376988068797038047223488825819819025644086847749767508999164153502160223967816357097637814023962825054332801828798160046910336602415904504637333597488119998663995617171089911809851197616486499233594328274275983382931099806461605360243604040848379619072542165869409486682092396143083817303621520642297839982533698027039931804024928814430649614747600087654305571672697259114631990688823893005380061568007730984416061355843701277573463708822073792921409548717956947854414951731561828176343929570234710460088230637509877521391223419548471196982303169544468045517922669260631327498272520906329003279972932906827204647650366969765227673645419031639887433042226322021325368176044169612053532174352764937901877252263626883107879345194133825996368795020985033021472307603375442346871647223795507794130304865403488955400210765171630884759704098331306109510294140865574071074640401937347718815339902047036749084359309086354777210564861918603858715882024476138160390378532660185842568914109194464566162667753712365992832481865739251429498555141512136758288423285957759412684479036912662015308418041737698963759002546999454131659341985624780714434977201991702665380714107259910648709897259362243300706760476097690456341576573395549588448948093604077155688747288451838106069038026528318275560395905381507241627615047252487759578650784894547389096573312763852962664517004459626327934637721151028545472312880039058405918498833810711366073657536918428084655898982349219315205257478363855266205400703561310260405145079325925798227406012199249391735122145336707913500607486561657301854049217477162051678486507913573336334257685988361252720250944019430674728667983441293018131344299088234006652915385763779110955708000600143579956351811596764725075668367726052352939773016348235753572874236648294604770429166438403558846422370760111774821079625901180265548868995181239470625954254584491340203400196442965370643088660925268811549596291166168612036195319253262662271108142149856132646467211954801142455133946382385908540917878668826947602781853283155445565265933912487885639504644196022475186011405239187543742526581685003052301877096152411653980646785444273124462179491306502631062903402737260479940181929954454297256377507172705659271779285537195547433852182309492703218343678206382655341157162788603990157495208065443409462446634653253581574814022471260618973060860559065082163068709634119751925774318683671722139063093061019303182326666420628155129647685313861018672921889347039342072245556791239578260248978371473556820782675452142687314252252601795889759116238720807580527221031327444754083319215135934526961397220564699247718289310588394769170851420631557192703636345039529604362885088555160008371973526383838996789184600327073682083234847108471706160879195227388252347506380811606090840124222431476103563328940609282430125462013806032608121942876847907192546246309055749298781661271916548229644317263587524548607563020667656942355342774617635549231817456159185668061686428714964129290560130053913469569829490891003991259088290348791943368696942620662946948514931472688923571615032405542263391673583102728579723061998175868700492227418629077079508809336215346303842967525604369606110193842723883107587771653594778681499030978765900869583480043137176832954871752604714113064847270887246697164585218774442100900090916189819413456305028950484575822161887397443918833085509908566008543102796375247476265353031558684515120283396640547496946343986288291957510384781539068343717740714095628337554413567955424664601335663617305811711646062717854078898495334329100315985673932305693426085376230981047171826940937686754301837015557540822371538037838383342702379535934403549452173960327095407712107332936507766465603712364707109272580867897181182493799540477008369348889220963814281561595610931815183701135104790176383595168144627670903450457460997444500166918675661035889313483800512736411157304599205955471122443903196476642761038164285918037488354360663299436899730090925177601162043761411616688128178292382311221745850238080733727204908880095181889576314103157447684338100457385008523652069340710078955916549813037292944462306371284357984809871964143085146878525033128989319500645722582281175483887671061073178169281242483613796475692482076321356427357261609825142445262515952514875273805633150964052552659776922077806644338105562443538136258941809788015677378951310313157361136026047890761945591820289365770116416881703644242694283057457471567494391573593353763114830246668754727566653059819746822346578699972291792416156043557665183382167059157867799311835820189855730344883681934418305987021880502259192818047775223884407167894780414701414651073580452021499197980812095692195622632313741870979731320870864552236740416185590793816745658234353037283309503729022429802768451559528656923189798000383061378732434546500582722712325031420712488100290697226311129067629080951145758060270806092801504406139446350643069742785469477459876821004441453438033759717384777232052065301037861326418823586036569054773343070911759152582503029410738914441818378779490613137536794654893375260322906277631983337976816641721083140551864133302224787118511817036598365960493964571491686005656771360533192423185262166760222073368844844409234470948568027905894191829969467724456269443308241243846160408284006424867072583661011433404214473683453638496544701067827313169538435919120440283949541956874453676459875488726170687163109591315801609722382049772577307454562979127906177531663252857205858766376754282917933549923678212008601904369428956102301731743150352204665675088491593025926618816581008701658499456495586855628208747248318351516339189292646558880593601275151838235485893426165223086697314511412035659916934103076974774451947043836739600076578628245472064617380804602903639144493859012422380173377038154675297645596518492676039300171943042511794045679862114630138402371099347243455794730048929825402680821621522346560274258486595687074510352794291633405915025075992398611224340312056999780516223878772230396359709132856830486160362127579561601328561866388146004722200580017580282279272167842720649966956840905752590774886105493806116954293569077377792821084159737469613143291808510446953973485067590503662391722108732333169909603363771705474725026941732982890400239372879549386540463828596742216318201530139629734398479588628632934746650690284066719018081265539973675916799759010867483920062877888531102781695087545740384607594616919584610655963327283485609570305572502494416337066573150237126843581984154103154401008430380631442183776750349813408169325201240813452285974626715177152223063741359255747513535160669108359443999692315898156732033027129284241219651936303734407981204656795322986357374589031654007016472204989445629050395873788912680565516464274460174738175296313458739390484560414203426465560422112239134631023161290836446988901247285192778589195228773637440432659264672239982186452797664826673070168802722052338600372842903155828454593854349099449420750911108532138744823216151007808922516285123275724355101999038195993350032641446053470357293073912578481757987468353429629749652545426864234949270336399427519354240001973125098882419600095766257217621860474573769577649582201796258392376391717855799468922496750179251915218219624653575570564228220399546682648329822996167217080156801080799777126517156274295763666959661983507435667132218383358509536665806605597148376773866922551603463644386269977295750658468929599809168949981898588529537874489519527097766262684177088590284321676352132630838812766335363319004134332844347630067982023716933653652880580156390360562722752187272454764258840995216482554453662083811789117725225682611478014242896970967121967502094421226279437073328703410646312100557376727450271638975234111426287828736758358819056742163061523416789476056879277154789714326222041069587947186435439940738639948986836168919377836648327137363654676901173760246643082285362494712605173293777247276797635865806019396287718060679122426813922872134061694882029506831654589707623668302556167559477498715183426989208952182644710514911419441192277010977616645850068963849426165593473112961064282379048216056210094265076173838082479030510998790719611852832556787472942907151041468948104916751035295897242381802288151276582257190705537652455285511598636421244284176256230139538669970308943645907600684938040875210854159851278070333207779865635907968462191534944587677170063778573171211036517486371634098385626541555573292664616402279791195975248525300376741774056125700303625811704838385391207273191845064713669122576415213769896260940351804147432053600369234179035440735703058314741623452840188940808983125191307741823338981880316339159565954543405777784331681162551898060409183018907512170192983622897099598983405484962284289398469847938668614293324543983592637036699355184231661615244505980576745765335552338715678211466689996845227042954589710922163652573965950289645637766038988037941517917867910675199009966139206238732318786758420544279396366759104126821843375015743069045967947046685602358283919759975285865384338189120042853787549302768972168199113340697282255535300044743958830079799736518459131437946494086272149669719100359399974735262764126125995350902609540048669398955899487421379590802893196914845826873123710180229775301190684280440780938156598081694611679374425663244656799606363751546304833112722231812338371779800439731087402647536582575657351059978314264831879619843765495877803685261751835391844920488198629786329743136948511780579298636452193232481339393090754566368038513630619718033957979522539508697432546502659123585049283028832934489284591373621624852528877442891851104093746333590660233239711922814450735588373324057814862662207486215513375036775585494138678352928273109003823116855374520901095101174796663003330352534143230024288248051396631446632656081582045216883922312025671065388459503224002320453633895521539919011035217362720909565500846486605368975498478995875596103167696587161281951919668893326641203784750417081752273735270989343717167642329956935697166213782736138899530515711822960896394055380431939398453970864418654291655853168697537052760701061488025700785387150835779480952313152747735711713643356413242974208137266896149109564214803567792270566625834289773407718710649866150447478726164249976671481383053947984958938064202886667951943482750168192023591633247099185942520392818083953020434979919361853380201407072481627304313418985942503858404365993281651941497377286729589582881907490040331593436076189609669494800067194371424058105327517721952474344983414191979918179909864631583246021516575531754156198940698289315745851842783390581029411600498699307751428513021286202539508732388779357409781288187000829944831476678183644656510024467827445695591845768068704978044824105799710771577579093525803824227377612436908709875189149049904225568041463131309240101049368241449253427992201346380538342369643767428862595140146178201810734100565466708236854312816339049676558789901487477972479202502227218169405159042170892104287552188658308608452708423928652597536146290037780167001654671681605343292907573031466562485809639550080023347676187068086526878722783177420214068980703410506200235273632267291964034093571225623659496432076928058165514428643204955256838543079254299909353199329432966018220787933122323225928276556048763399988478426451731890365879756498207607478270258861409976050788036706732268192473513646356758611212953074644777149423343867876705824452296605797007134458987594126654609414211447540007211790607458330686866231309155780005966522736183536340439991445294960728379007338249976020630448806064574892740547730693971337007962746135534442514745423654662752252624869916077111131569725392943756732215758704952417232428206555322808868670153681482911738542735797154157943689491063759749151524510096986573825654899585216747260540468342338610760823605782941948009334370046866568258579827323875158302566720152604684361412652956519894291184887986819088277339147282063794512260294515707367105637720023427811802621502691790400488001808901847311751199425460594416773315777951735444490965752131026306836047140331442314298077895617051256930051804287472368435536402764392777908638966566390166776625678575354239947427919442544664643315554138265543388487778859972063679660692327601733858843763144148113561693030468420017434061395220072403658812798249143261731617813894970955038369479594617979829257740992171922783223006387384996138434398468502234780438733784470928703890536420557474836284616809363650973790900204118525835525201575239280826462555785658190226958376345342663420946214426672453987171047721482128157607275305173330963455909323664528978019175132987747952929099598069790148515839540444283988381797511245355548426126784217797728268989735007954505834273726937288386902125284843370917479603207479554080911491866208687184899550445210616155437083299502854903659617362726552868081324793106686855857401668022408227992433394360936223390321499357262507480617409173636062365464458476384647869520547719533384203403990244761056010612777546471464177412625548519830144627405538601855708359981544891286863480720710061787059669365218674805943569985859699554089329219507269337550235821561424994538234781138316591662683103065194730233419384164076823699357668723462219641322516076261161976034708844046473083172682611277723613381938490606534404043904909864126903479263503943531836741051762565704797064478004684323069430241749029731181951132935746854550484711078742905499870600373983113761544808189067620753424526993443755719446665453524088287267537759197074526286322840219629557247932987132852479994638938924943286917770190128914220188747760484939855471168524810559991574441551507431214406120333762869533792439547155394213121021954430556748370425907553004950664994802614794524739012802842646689229455664958621308118913500279654910344806150170407268010067948926855360944990373928383520627992820181576427054962997401900837493444950600754365525758905546552402103412862124809003162941975876195941956592556732874237856112669741771367104424821916671499611728903944393665340294226514575682907490402153401026923964977275904729573320027982816062130523130658731513076913832317193626664465502290735017347656293033318520949298475227462534564256702254695786484819977513326393221579478212493307051107367474918016345667888810782101151826314878755138027101379868751299375133303843885631415175908928986956197561123025310875057188962535763225834275763348421016668109884514141469311719314272028007223449941999003964948245457520704922091620614222912795322688239046498239081592961111003756999529251250673688233852648213896986384052437049402152187547825163347082430303521036927849762517317825860862215614519165573478940019558704784741658847364803865995119651409542615026615147651220820245816010801218275982577477652393859159165067449846149161165153821266726927461290533753163055654440793427876550267301214578324885948736899073512166118397877342715872870912311383472485146035661382188014840560716074652441118841800734067898587159273982452147328317214621907330492060817440914125388918087968538960627860118193099489240811702350413554126823863744341209267781729790694714759018264824761112414556423937732224538665992861551475342773370683344173073150805440138894084087253197595538897613986400165639906934600670780501058567196636796167140097031535132386972899001749862948883362389858632127176571330142071330179992326381982094042993377790345261665892577931395405145369730429462079488033141099249907113241694504241391265397274078984953073730364134893688060340009640631540701820289244667315059736321311926231179142794944897281477264038321021720718017561601025111179022163703476297572233435788863537030535008357679180120653016668316780269873860755423748298548246360981608957670421903145684942967286646362305101773132268579232832164818921732941553151386988781837232271364011755881332524294135348699384658137175857614330952147617551708342432434174779579226338663454959438736807839569911987059388085500837507984051126658973018149321061950769007587519836861526164087252594820126991923916722273718430385263107266000047367872474915828601694439920041571102706081507270147619679971490141639274282889578424398001497985658130305740620028554097382687819891158955487586486645709231721825870342960508203415938806006561845735081804032347750084214100574577342802985404049555529215986404933246481040773076611691605586804857302606467764258503301836174306413323887707999698641372275526317649662882467901094531117120243890323410259937511584651917675138077575448307953064925086002835629697045016137935696266759775923436166369375035368699454550392874449940328328128905560530091416446608691247256021455381248285307613556149618444364923014290938289373215312818797541139219415606631622784836152140668972661027123715779503062132916001988806369127647416567067485490795342762338253943990022498972883660263920518704790601584084302914787302246651371144395418253441269003331181914268070735159284180415100555199146564934872796969351992963117195821262627236458009708099166752820365818699111948365866102758375863322993225541477479210421324166848264953111826527351008031659958888814809945737293785681411438021523876706455063233067233939551964260397443829874822322662036352861302543796600943104500158604854027036789711934695579989189112302233381602302236277726084846296189550730850698061500281436425336666311433321645213882557346329366870956708432252564333895997812402164189946978348320376011613913855499933990786652305860332060641949298931012423081105800169745975038516887112037747631577311831360002742502722451570906304496369230938382329175076469684003556425503797106891999812319602533733677437970687713814747552190142928586781724044248049323750330957002929126630316970587409214456472022710796484778657310660832173093768033821742156446602190335203981531618935787083561603302255162155107179460621892674335641960083663483835896703409115513087820138723494714321400450513941428998350576038799343355677628023346565854351219361896876831439866735726040869511136649881229957801618882834124004126142251475184552502502640896823664946401177803776799157180146386554733265278569418005501363433953502870836220605121839418516239153709790768084909674194289061134979961034672077354959593868862427986411437928435620575955500144308051267664432183688321434583708549082240014585748228606859593502657405750939203135881722442164955416889785558265198046245527898343289578416968890756237467281044803018524217706136533236073856228166664597654076844715963930782091017090763377917711485205493367936868430832404126789220929930411890501756484917499452393770674524578019171841679541825554377930299249277892416277257788147974770446005423669346157135208417428211847353652367573702352791459837645712257646122605628127852169580892808988394594406165340521932514843306105322700231133680378433377389724881307874325614952744243584753011150345103737688223837573804282007358586938044331529253129961025096113761670187568525921208929131354473196308440066835155160913925692912175784379179004808848023029304392630921342768601226558630456913133560978156776098711809238440656353136182676923761613389237802972720736243967239854144480757286813436768000573823963610796223140429490728058551444771338682314499547929338131259971996894072233847404542592316639781608209399269744676323921370773991899853301483814622364299493902073285072098040905300059160091641710175605409814301906444379905831277826625762288108104414704097708248077905168225857235732665234414956169007985520848841886027352780861218049418060017941147110410688703738674378147161236141950474056521041002268987858525470689031657094677131822113205505046579701869337769278257145248837213394613987859786320048011792814546859096532616616068403160077901584946840224344163938313618742275417712170336151163782359059685168880561304838542087505126933144171705880517278127917564053282929427357971823360842784676292324980318169828654166132873909074116734612367109059236155113860447246378721244612580406931724769152219217409096880209008801535633471775664392125733993165330324425899852598966724744126503608416484160724482125980550754851232313331300621490042708542735985913041306918279258584509440150719217604794274047740253314305451367710311947544521321732225875550489799267468541529538871443696399406391099267018219539890685186755868574434469213792094590683677929528246795437302263472495359466300235998990248299853826140395410812427393530207575128774273992824866921285637240069184859771126480352376025469714309316636539718514623865421671429236191647402172547787238964043145364190541101514371773797752463632741619269990461595895793940622986041489302535678633503526382069821487003578061101552210224486633247184367035502326672749787730470216165019711937442505629639916559369593557640005236360445141148916155147776301876302136068825296274460238077523189646894043033182148655637014692476427395401909403584437251915352134557610698046469739424511797999048754951422010043090235713636892619493763602673645872492900162675597083797995647487354531686531900176427222751039446099641439322672532108666047912598938351926694497553568096931962642014042788365702610390456105151611792018698900673027082384103280213487456720062839744828713298223957579105420819286308176631987048287388639069922461848323992902685392499812367091421613488781501234093387999776097433615750910992585468475923085725368613605356762146929424264323906626708602846163376051573599050869800314239735368928435294958099434465414316189806451480849292695749412903363373410480943579407321266012450796613789442208485840536446021616517885568969302685188950832476793300404851688934411125834396590422211152736276278672366665845757559585409486248261694480201791748223085835007862255216359325125768382924978090431102048708975715033330963651576804501966025215527080352103848176167004443740572131294252820989545456276344353575741673638980108310579931697917916718271145837435222026387771805250290791645414791173616253155840768495583288190293564201219633684854080865928095131505012602919562576032932512847250469881908146475324342363863860247943921015193235101390117789997483527186469346024554247028375300033725403910085997650987642832802908445662021678362267272292737780213652404028817217012490974899454430826861772239385250883760749742195942655217301733355851389407457348144161511380845358039740277795072051893487170722955427683655826706766313911972211811528466502223383490906676554168336907959409404576472940901354356409277969379842065738891481990225399022315913388145851487225126560927576795873759207013915029216513720851137197522734365458411622066281660256333632074449918511469174455062297146086578736313585389023662557285424516018080487167823688885575325066254262367702604215835160174851981885460860036597606743233346410471991027562358645341748631726556391320606407754779439671383653877377610828300019937359760370467245737880967939894493795829602910746901609451288456550071458091887879542641820145369659962842686882363495879277007025298960996798975941955735253914237782443302746708282008722602053415292735847582937522487377937899136764642153727843553986244015856488692101644781661602962113570056638347990334049623875941092886778920270077504951511405782565295015024484968204744379710872943108541684540513016310902267112951959140520827546866418137305837933236150599142045255880213558474751516267815309465541240524091663857551298894834797423322854504140527354235070335984964593699534959698554244978249586929179182415068053002553370412778703476446244329205906832901886692400222391918714603175399666877477960121790688623311002908668305431787009355066944389131913333586368037447530664502418437136030852288582121720231274167009740351431532131803978033680228154223490183737494117973254478594157962104378787072154814091725163615415163381388912588517924237727229603497305533840942889918919161186249580560073570527227874940321250645426206304469470804277945973817146810395192821550688079136701210109944220737024613687196031491162370967939354636396448139025711768057799751751298979667073292674886430097398814873780767363792886767781170520534367705731566895899181530825761606591843760505051704242093231358724816618683821026679970982966436224723644898648976857100173643547336955619347638598187756855912376232580849341570570863450733443976604780386678461711520325115528237161469200634713570383377229877321365028868868859434051205798386937002783312365427450532283462669786446920780944052138528653384627970748017872477988461146015077617116261800781557915472305214759943058006652042710117125674185860274188801377931279938153727692612114066810156521441903567333926116697140453812010040811760123270513163743154487571768761575554916236601762880220601068655524141619314312671535587154866747899398685510873576261006923021359580838145290642217792987748784161516349497309700794368305080955621264592795333690631936594413261117944256602433064619312002953123619348034504503004315096798588111896950537335671086336886944665564112662287921812114121425167348136472449021275252555647623248505638391391630760976364990288930588053406631352470996993362568102360392264043588787550723319888417590521211390376609272658409023873553418516426444865247805763826160023858280693148922231457758783791564902227590699346481624734399733206013058796068136378152964615963260698744961105368384203105364183675373594176373955988088591188920114871545460924735613515979992999722298041707112256996310945945097765566409972722824015293663094891067963296735505830412258608050740410916678539569261234499102819759563955711753011823480304181029089719655278245770283085321733741593938595853203645590564229716679900322284081259569032886928291260139267587858284765599075828016611120063145411315144108875767081854894287737618991537664505164279985451077400771946398046265077776614053524831090497899859510873112620613018757108643735744708366215377470972660188656210681516328000908086198554303597948479869789466434027029290899143432223920333487108261968698934611177160561910681226015874410833093070377506876977485840324132474643763087889666151972556180371472590029550718424245405129246729039791532535999005557334600111693557020225722442772950263840538309433999383388018839553821540371447394465152512354603526742382254148328248990134023054550811390236768038649723899924257800315803725555410178461863478690646045865826036072306952576113184134225274786464852363324759102670562466350802553058142201552282050989197818420425028259521880098846231828512448393059455162005455907776121981297954040150653985341579053629101777939776957892084510979265382905626736402636703151957650493344879513766262192237185642999150828898080904189181015450813145034385734032579549707819385285699926238835221520814478940626889936085239827537174490903769904145555260249190126341431327373827075950390882531223536876389814182564965563294518709637484074360669912550026080424160562533591856230955376566866124027875883101021495284600804805028045254063691285010599912421270508133194975917146762267305044225075915290251742774636494555052325186322411388406191257012917881384181566918237215400893603475101448554254698937834239606460813666829750019379115061709452680984785152862123171377897417492087541064556959508967969794980679770961683057941674310519254486327358885118436597143583348756027405400165571178309126113117314169066606067613797690123141099672013123730329707678988740099317309687380126740538923612230370779727025191340850390101739924877352408881040807749924412635346413181858792480760553268122881584307471326768283097203149049868884456187976015468233715478415429742230166504759393312132256510189175368566338139736836336126010908419590215582111816677413843969205870515074254852744810154541079359513596653630049188769523677579147319184225806802539818418929888943038224766186405856591859943091324575886587044653095332668532261321209825839180538360814144791320319699276037194760191286674308615217243049852806380129834255379486287824758850820609389214668693729881191560115633701248675404205911464930888219050248857645752083363921499441937170268576222251074166230901665867067714568862793343153513505688216165112807318529333124070912343832502302341169501745502360505475824093175657701604884577017762183184615567978427541088499501610912720817913532406784267161792013428902861583277304794830971705537485109380418091491750245433432217445924133037928381694330975012918544596923388733288616144238100112755828623259628572648121538348900698511503485369544461542161283241700533583180520082915722904696365553178152398468725451306350506984981006205514844020769539324155096762680887603572463913955278222246439122592651921288446961107463586148252820017348957533954255019475442643148903233373926763409115527189768429887783617346613535388507656327107814312435018965109238453660236940276060642119384227665755210663671879603217527184404651560427289869560206997012906367847161654793068868305846508082886614111979138822898112498261434559408961813509226857611474609406147937240008842153535862052780125014270055274468359151840373309373580494342483940467505708347927948338133276237937844629209323999417593374917899786484958148818865149169302451512835579818112344900827168644548306546633975256079615935830821400021951611342337058359111545217293721664061708131602078213341260356852013161345136871600980378712556766143923146458085652084039744217352744813741215277475202259244561520365608268890193913957991844109971588312780020898275935898106482117936157951837937026741451400902833064466209280549839169261068975151083963132117128513257434964510681479694782619701483204392206140109523453209269311762298139422044308117317394338867965739135764377642819353621467837436136161591167926578700137748127848510041447845416464568496606699139509524527949914769441031612575776863713634644477006787131066832417871556281779122339077841275184193161188155887229676749605752053192594847679397486414128879475647133049543555044790277128690095643357913405127375570391806822344718167939329121448449553897728696601037841520390662890781218240141299368590465146519209198605347788576842696538459445700169758422531241268031418456268722581132040056433413524302102739213788415250475704533878002467378571470021087314693254557923134757243640544448132093266582986850659125571745568328831440322798049274104403921761438405750750288608423536966715191668510428001748971774811216784160854454400190449242294333666338347684438072624307319019363571067447363413698467328522605570126450123348367412135721830146848071241856625742852208909104583727386227300781566668914250733456373259567253354316171586533339843321723688126003809020585719930855573100508771533737446465211874481748868710652311198691114058503492239156755462142467550498676710264926176510110766876596258810039163948397811986615585196216487695936398904500383258041054420595482859955239065758108017936807080830518996468540836412752905182813744878769639548306385089756146421874889271294890398025623046812175145502330254086076115859321603465240763923593699949180470780496764486889980902123735780457040380820770357387588525976042434608851075199334470112741787878845674656640471901619633546770714090590826954225196409446319547658653032104723804625249971910690110456227579220926904132753699634145768795242244563973018311291451151322757841320376225862458224784696669785947914981610522628786944136373683125108310682898766123782697506343047263278453719024447970975017396831214493357290791648779915089163278018852504558488782722376705263811803792477835540018117452957747339714012352011459901984753358434861297092928529424139865507522507808919352104173963493428604871342370429572757862549365917805401652536330410692033704691093097588782938291296447890613200063096560747882082122140978472301680600835812336957051454650181292694364578357815608503303392466039553797630836137289498678842851139853615593352782103740733076818433040893624460576706096188294529171362940967592507631348636606011346115980434147450705511490716640635688739020690279453438236930531133440901381392849163507484449076828386687476663619303412376248380175840467851210698290605196112357188811150723607303158506622574566366740720668999061320627793994112805759798332878792144188725498543014546662945079670707688135022230580562225942983096887732856788971494623888272184647618153045844390967248232348259587963698908456664795754200195991919240707615823002328977439748112690476546256873684352229063217889227643289360535947903046811114130586348244566489159211382258867880972564351646404364328416076247766114349880319792230537889671148058968061594279189647401954989466232962162567264739015818692956765601444248501821713300527995551312539849919933907083138030214072556753022600033565715934283182650908979350869698950542635843046765145668997627989606295925119763672907762567862769469947280606094290314917493590511523235698715397127866718077578671910380368991445381484562682604003456798248689847811138328054940490519768008320299631757043011485087384048591850157264392187414592464617404735275250506783992273121600117160338604710710015235631159734711153198198710616109850375758965576728904060387168114313084172893710817412764581206119054145955378853200366615264923610030157044627231777788649806700723598889528747481372190175074700005571108178930354895017924552067329003818814068686247959272205591627902292600592107710510448103392878991286820705448979977319695574374529708195463942431669050083984398993036790655541596099324867822475424361758944371791403787168166189093900243862038610001362193667280872414291108080291896093127526202667881902085595708111853836166128848729527875143202956393295910508349687029060692838441522579419764824996318479414814660898281725690484184326061946254276693688953540732363428302189694947766126078346328490315128061501009539164530614554234923393806214007779256337619373052025699319099789404390847443596972052065999017828537676265683558625452697455260991024576619614037537859594506363227095122489241931813728141668427013096050734578659047904243852086508154491350136491698639048125666610843702294730266721499164849610746803261583352580352858275799038584091667618877199539888680431991650866887781701439663176815592262016991396613153738021294160006906947533431677802632207226265881842757216055461439677336258462997385077307751473833315101468395296411397329672457933540390136107395245686243008096720460995545708974893048753897955544443791303790422346037768729236001386569593952300768091377768847789746299699489949016141866131552200856673695770822720338936659590666350594330040363762591189195691561626122704788696510356062748423100605472091437069471661080277379848576543481249822444235828329813543645124092220896643987201997945619030397327254617823136363375927622656301565813545578319730419339269008282952718252138855126583037630477490625995514925943105307478901043009876580816508144862607975129633326675259272351611791836777128931053144471668835182920514343609292493191180249366051791485330421043899773019267686085347768149502299280938065840007311767895491286098112311307002535600347898600653805084532572431553654422067661352337408211307834360326940015926958459588297845649462271300855594293344520727007718206398887404742186697709349647758173683580193168322111365547392288184271373843690526638607662451284299368435082612881367358536293873792369928837047900484722240370919885912556341130849457067599032002751632513926694249485692320904596897775676762684224768120033279577059394613185252356456291805905295974791266162882381429824622654141067246487216174351317397697122228010100668178786776119825961537643641828573481088089988571570279722274734750248439022607880448075724807701621064670166965100202654371260046641935546165838945950143502160890185703558173661823437491622669077311800121188299737319891006060966841193266075165452741829459541189277264192546108246351931647783837078295218389645376236304858042774417907169146356546201215125418664885396161542055152375000426794253417764590821513675258479774465114750438460596325820468809667795709044645884673847481638045635188183210386594798204376334738389017759714236223057776395541011294523488098341476645559342209402059733452337956309441446698222457026367119493286653989491344225517746402732596722993581333110831711807234044326813737231209669052411856734897392234152750707954137453460386506786693396236535556479102508529284294227710593056660625152290924148057080971159783458351173168204129645967070633303569271821496292272073250126955216172649821895790908865085382490848904421755530946832055636316431893917626269931034289485184392539670922412565933079102365485294162132200251193795272480340133135247014182195618419055761030190199521647459734401211601239235679307823190770288415814605647291481745105388060109787505925537152356112290181284710137917215124667428500061818271276125025241876177485994084521492727902567005925854431027704636911098800554312457229683836980470864041706010966962231877065395275783874454229129966623016408054769705821417128636329650130416501278156397799631957412627634011130135082721772287129164002237230234809031485343677016544959380750634285293053131127965945266651960426350406454862543383772209428482543536823186182982713182489884498260285705690699045790998144649193654563259496570044689011049923939218088155626191834404362264965506449848521612498442375928443642612004256628602157801140467879662339228190804577624109076487087406157070486658398144845855803277997327929143195789110373530019873110486895656281917362036703039179710646309906285483702836118486672219457621775034511770110458001291255925462680537427727378863726783016568351092332280649908459179620305691566806180826586923920561895421631986004793961133953226395999749526798801074576466538377400437463695133685671362553184054638475191646737948743270916620098057717103475575333102702706317395612448413745782734376330101853438497450236265733191742446567787499665000938706441886733491099877926005340862442833450486907338279348425305698737469497333364267191968992849534561045719338665222471536681145666596959735075972188416698767321649331898967182978657974612216573922404856900225324160367805329990925438960169901664189038843548375648056012628830409421321300206164540821986138099462721214327234457806819925823202851398237118926541234460723597174777907172041523181575194793527456442984630888846385381068621715274531612303165705848974316209831401326306699896632888532682145204083110738032052784669279984003137878996525635126885368435559620598057278951754498694219326972133205286374577983487319388899574634252048213337552584571056619586932031563299451502519194559691231437579991138301656117185508816658756751184338145761060365142858427872190232598107834593970738225147111878311540875777560020664124562293239116606733386480367086953749244898068000217666674827426925968686433731916548717750106343608307376281613984107392410037196754833838054369880310983922140260514297591221159148505938770679068701351029862207502287721123345624421024715163941251258954337788492834236361124473822814504596821452253550035968325337489186278678359443979041598043992124889848660795045011701169092519383155609441705397900600291315024253848282782826223304151370929502192196508374714697845805550615914539506437316401173317807741497557116733034632008408954066541694665746735785483133770133628948904397670025863002540635264006601631712883920305576358989492412827022489373848906764385339931878608019223108328847459816417701264089078551777830131616162049792779670521847212730327970738223860581986744668610994383049960437407323195784473254857416239738852016202384784256163512597161783106850156299135559874758848151014815490937380933394074455700842090155903853444962128368313687375166780513082594599771257467939781491953642874321122421579851584491669362551569370916855252644720786527971466476760328471332985501945689772758983450586004316822658631176606237201721007922216410188299330808409384014213759697185976897042759041500946595252763487628135867117352364964121058854934496645898651826545634382851159137631569519895230262881794959971545221250667461174394884433312659432286710965281109501693028351496524082850120190831078678067061851145740970787563117610746428835593915985421673115153096948758378955979586132649569817205284291038172721213138681565524428109871168862743968021885581515367531218374119972919471325465199144188500672036481975944167950887487934416759598361960010994838744709079104099785974656112459851972157558134628546189728615020774374529539536929655449012953097288963767713353842429715394179547179095580120134210175150931491664699052366350233024087218654727629639065723341455005903913890253699317155917179823065162679744711857951506573868504088229934804445549850597823297898617029498418376255258757455303112991914341109413088238114443068843062655305601658801408561023324210300218460588586954418502977463085858496130037238190325162225570729975710727306066072916922978033647048840958711228045188511908718588299514331534128549297173849768523136276076868494780364948299904475715771141080958058141208956059471668626290036145602625334863284986816039463372436667112964460292915746181117789169695839947080954788863503281129626899231110099889317815313946681882028368363373822281414974006917942192888817139116283910295684918233358930813360131488748366464224381776081007739183393749346933644748150564933649323157235306109385796839902153381449126925350768211098738352197507736653475499431740580563099143218212547336281359488317681489194306530426029773885492974570569448783077945878865062970895499843760181694031056909587141386804846359853684034105948341788438963179956468815791937174656705047441528027712541569401365862097760735632832966564135817028088013546326104892768731829917950379944446328158595181380144716817284996793061814177131912099236282922612543236071226270324572637946863533391758737446552006008819975294017572421299723542069630427857950608911113416534893431149175314953530067419744979017235181671568754163484949491289001739377451431928382431183263265079530371177806185851153508809998200482761808307209649636476943066172549186143700971387567940218696710148540307471561091358933165600167252126542502898612259306484105898847129649230941215144563947889999327145875969555737090855150648002321476443037232466147111552578583071024936898814562568786834745518893385181791667579054210421036349316257870476543126790661216644142285017446278477132740595579600648343288827864837043456066966456899746910373987712891593313271266247505582258634928427718355831641593667712218537642376222104779338956378722902509543014182257180331300148113377736941508488867501893156994849838936052666818012783912005801431596441910546663236810148207799356523056490420711364192200177189107935243234322761787712568251126481332974354926568682748715986654943041648468220593921673359485057849622807932422649812705271398407720995707236227009245067665680069149966555737866411877079767754867028786431817941521796178310655030287157272282250812017060713380339641841211253856248920130010782462165136989511064611133562443838185366273563783436921279354709230119655914915800561707258518503167289370411936374780625824298250726464801821523430268081486978164824349353456855843696378384153838051184406043696871666416514036129729992912630842812149152469877429332305214999981829046119471676727503742221367186614654042534463141660649871499001000660041544868437352208483059495953182872280520828676300361091734508632133033647289584176588755345227938480297724485711815574893561311524926772006362198369980664159549388683836411891430443767715498026544959061738265591178545999378510861446014967645550103653971251138583505085112442517772923814396233043724036032603181442991365750246012787514117944901305803452199992701148071712847770301254994886841867572975189214295652512486943983729047410363121899124217339550688778643130750024823361832738729697376598820053895902935486054979802320400472236873557411858132734337978931582039412878989728973298812553514507641535360519462112217000676321611195841029252568536561813138784086477147099724553013170761712163186600291464501378587854802096244703771373587720086738054108140042311418525803293267396324596914044834665722042880679280616029884043400536534009706581694636096660911110968789751801325224478246957913251892122653056085866541115373584912790254654369020869419871125588453729063224423222287139122012248769976837147645598526739225904997885514250047585260297929306159913444898341973583316070107516452301310796620382579278533125161760789984630103493496981494261055367836366022561213767081421091373531780682420175737470287189310207606953355721704357535177461573524838432101571399813798596607129664438314791296359275429627129436142685922138993054980645399144588692472767598544271527788443836760149912897358259961869729756588978741082189422337344547375227693199222635973520722998387368484349176841191020246627479579564349615012657433845758638834735832242535328142047826934473129971189346354502994681747128179298167439644524956655532311649920677163664580318205849626132234652606175413532444702007661807418914040158148560001030119994109595492321434406067634769713089513389171050503856336503545166431774489640061738861761193622676890576955693918707703942304940038440622614449572516631017080642923345170422426679607075404028551182398361531383751432493056398381877995594942545196756559181968690885283434886050828529642437578712929439366177362830136595872723080969468398938676366226456791132977469812675226595621009318322081754694778878755356188335083870248295346078597023609865656376722755704495258739871812593441903785275571333409842450127258596692434317689018966145404453679047136294238156127656824247864736176671770647002431119711090007474065945650315375044177982192306323700872039212085499569681061379189029961178936752146022386905665481382858280449537530160921422195940638787074787991194920898374091788534417523064715030278397979864517336625329511775105559014160459873338186887977858817291976604516353353556047648420520888811722831990044504284486852338334530105533929637308039738230604714104525470094899407601215247602819963846343554852932377161410869591950786873276075400085220065031871239272857835807010762542769655355964789450166013816295177908531139811092831583216931563867459747449584385282701658246192092219529134323496779345585613140207765996142546463288677356891785576835169608392864188830094883324700447958316931533832382377876344426323456301679513671047510469669001217777128065522453689371871451567394733440447280450959433090683667110655953338602938000999949010642769859623260401863733572846679531229683156358145420890540651226419162015504500430562136991850941034609601030543816694795964585804425194905110733387679946734471718615647723811737035654917628707589456035519195603962301157866323750234725054461073979402475184415558178087962822231972692984516683306919505079993357259165675557294585962182052650473353712351623662770479333289322136141858785972771685682725303734836891911847197133753088446777943274857148827821608844765700041403499921376794209627560883081509438030705666022764678117533361028187800710219794428777313146387857817205661409023041499923248268982477222109852189758140879763486146763606368674611966620347304608917277240045953051376938375381543486981101990651706961774052218247422657652138152740612699012706880875386408669901461740890540981877671880076124151967064152117653084325544261017536348281196837493395825742541244634247233586360777980960199745187758845459645895956779558869098404768259253477849930457883128541747079059795909431627722327844578918694214929451540174214623240300841907975296782445969183509474202123617940309048634960534054931299919496087957952586977170236680033862505764938088740994009589948109397983231108838769236490221499111120870639202892490698435333152727991330986335454324971441378059132240814960156485679843966464780280409057580889190254236606774500413415794312112501275232250148067232979652230488493751166084976116412777395311302041566848265531411348993243747890268935173904043294851610659785832253168204202834993641595980197343889883020994152152288611175126686173051956249367180053845637855129171848417841594797435580617856680758491080185805695567990185198397660693358224779136504562705766735170961550493338390452612404395517449136885115987454340932040102218982707539212403241042424451570052968378815749468441508011138612561164102477190903050040240662278945607061512108266146098662040425010583978098192019726759010749924884966139441184159734610382401178556739080566483321039073867083298691078093495828888707110651559651222542929154212923108071159723275797510859911398076844732639426419452063138217862260999160086752446265457028969067192282283045169111363652774517975842147102219099906257373383472726498678244401048998507631630668050267115944636293525120269424810854530602810627264236538250773340575475701704367039596467715959261029438313074897245505729085688496091346323165819468660587092144653716755655531962091865952628448253731353698162517351930115341581171353292035873164168839107994000677266031617527582917398395852606454113318985505747847121053505795649095931672167565624818782002769963734155880000867852567422461511406015760115910256449002264980039498403358091309140197877843650167960167465370287466062584346329708303725980494653589318912163976013193079476972058034710553111117215859219066231028099212084069283091906017370764654655683413207556315315006453462321007133584907633048328153458698497332599801187479664273140279381289961720524540674695271948079930396730194274036466594154400092799908634806622334906695224044652158992864203435098858422692019340575496840904812955522654754650713532842543496616084954788090727649930252702815067862810825243222979985391759845188868387004477101866772159439708514664612871148749531862180941719676843144666435175837688436786081446319641912566574047718699160915550910878919431253671945651261878486910876729910565595155159739659034383628124629118117760949411880105946336671039049777312004243578115790429823045072038322781246413671297959415082918378213212876890545963586369344879749784841123274921331663162812456388238288715648447883142417650147980187858215768793063001153788998014623690135803753306246148576074932567807682651045738059018831237617271889933790487113395588485234240255002352200613574914318259142479829367775490496399350755839668967578364316618369307625603528602940662803255416535431518013714821941772672244005268401996533334184004345525296592918502940131600651124395297874364222806977720437363717873457948420238745151249157913139411148608416429347958793681868609689684640858334131017858142710955416293375915178392341303110543328703526599993904966822112768158316511246866451167351378214345336650598328347443536290312393672084593164394941881138607974670134709640378534907149089842317891739783650654751982883367395714360000003439863363212091718954899055748693397700245632475954504411422582410783866837655467400137324322809113692670682805397549111166171102397437749479335174036135005397581475520834285772800986189401984375446435081498218360112577632447389452051636938585136484259964518361856989088721789764694721246807900330925083496645841656554261294195108847197209106605105540933731954888406444080280579549008076040034154662137669606444293774985897353625591959618552448187940317374508256072895120945456562159540405425814886929842786582357673195799285293120866275922366115137445767916063621675267440451221051052090834707443986137829082352772895849625656881972792768694795806100573787084121444815034797422312103295359297822377134077549545477791813823542607184617108389097825964406170543546968567030745411634244134486308676327949177682923093183221341455482591367202823284396549001805653203960795517074496039006696990334199278212696767771835209083959545341866777944872740383733381985235884202840150981579594685874537989503257362809837592216229258598599123843993575573285028613155970362934249814178056461615863415338635077223269996508860870999964899373049307170967888740149746147542880387421250689212155876692242387434701120990859082164073576380817386959755176083877600277517253037133445654852635661720197563001580049790223419586738061442401502436288957503206533690825756785507020555105572381878574650371086308158185862815883054564662297694803970618265491385181326737485227188267917919091354407852685476254126683398240534022469989966652573155637645862251862823092085424412805997628505488913098331761884983352975136073772030571342739638126588567405013841074788943393996603591853934198416322617654857376671943132840050626295140357877264680649549355746326408186979718630218760025813995719923601345374229758918285167511358171472625828596940798518571870075823122317068134867930884899275181661399609753105295773584618525865211893339375771859916335112163441037910451845019023066893064178977808158101360449495409665363660370075881004450265734935127707426742578608784898185628869980851665713320835842613381142623855420315774246613108873106318111989880289722849790551075148403702290580483052731884959994156606537314021296702220821915862905952604040620011815269664910068587592655660567562963361434230232810747488395040380984981860056164646099819257616235478710913832967563761506732550860683433720438748186791668975746563456020002562889601191100980453350423842063824039434163502977688802779835087481178298349417211674919425601608685332435385951152061809031241698182079314615062073826097180458265687043623935757495737332781578904386011378078508110273049446611821957450170106059384336519458628360682108585130499820420578458577175933849015564447305834515291412561679970569657426139901681932056241927977282026714297258700193234337873153939403115411184101414292741703537542003698760608765500109345299007034032401334806388514095769557147190364152027721127070187421548123931953220997506553022646844227700020589045922742423904937051507367764629844971682121994198274794049092601715727439368569721862936007387077810797440975556627807371228030350048829843919546433753355787895064018998685060281902452191177018634505171087023903398550540704454189088472042376499749035038518949505897971286631644699407490959473411581934618336692169573605081585080837952036335619947691937965065016808710250735070825260046821242820434367245824478859256555487861614478717581068572356895150707602217433511627331709472765932413249132702425519391509083601346239612335001086614623850633127072987745618984384288764099836164964775714638573247333226653894523588365972955159905187411779288608760239306160016168434070611663449248395156319152882728822831375458678269830696691220130954815935450754923554167766876455212545681242936427474153815692219503331560151614492247512488957534835926226263545406704767033866410025277276800886383266629488582740369655329362236090572479794734434077704284318507901973469071141230364111729224929307731939309795452877412451183953480382210373644697046967493042810911797232448615413264031578430955396671061468083815548947146733652483679138566431084747848676243012018489329109615281108087617422779131629345494425395422727309645057976122885347393189600810965202090151104579377602529543130188938184010247010134929317443562883578609861545691161669857388024973756940558138630581099823372565164920155443216861690537054630176154809626620800633059320775897175589925862195462096455464624399535391743228225433267174308492508396461328929584567927365409119947616225155964704061297047759818551878441419948614013153859322060745185909608884280218943358691959604936409651570327527570641500776261323783648149005245481413195989296398441371781402764122087644989688629798910870164270169014007825748311598976330612951195680427485317886333041169767175063822135213839779138443325644288490872919067009802496281560626258636942322658490628628035057282983101266919109637258378149363774960594515216932644945188292639525772348420077356021656909077097264985642831778694777804964343991762549216500608626285329471055602670413384500507827390640287529864161287496473708235188892189612641279553536442286955430551308700009878557534223100547153412810957024870812654319123261956462149376527526356402127388765103883255007364899937167183280028398832319373301564123277185395654932422977953016534830128490677845037490891749347389015649588574802194996722621185874361039774946338633057887487405540005440439344888192044102134790034598411927024921557026873700970995205391930979319495883265922171508324621942300185974396706491149559411733728199869021311629886680267446443489233020607003821262841723679627307191405008084085703978151998148822390059948911946474438682533745889962375133378280532928272016815977970066488394482446332210928320504045983008943565954267256879714918703447338237767914829203283196838105907715727191903042365315650957464549643425328069510396558733549803850995143463506175361480050195045201350200180281506933241918267855737764414097080945745624854867704904368368717590918057269794010465019484853146726642978667687697789291431128505043098192949736165944259471754765135205245072597538577958372797702972231435199958499522344049394502115428867244188717409524554771867484911475031801773304689909317974472957035192387686405544278134169807249382219749124257510162187439772902147704638010731470653154201300583810458905006764557332998149945854655105526374914354195867992595981412218735238407957416123372264063860431988936249867649693592569592128495906254446474331759999685163660305216426770428154681777589339252115538590526823311608302751194384823861552852465010329467297198112105314125898165100120742688143577590825227466863206188376830450921784582526239594189673003640808624233657620979111641766331328852352062487922978959456450333733139422384778582717195412347860434376165241568717943562570215636666680088531006728947033079540804583324192188488870712275670333173939262509073556164513677064199539111948881240659821685787131385056850623094155206877987539740658484250135205615103489821873770245063583314243624807432542464195984647411575625441010389671576677263196442524931941806472423789334668561083789808830313571333157729435664956078125304917594015895146954965223118559669048559467607968190167266634650186182955669893965019614544401768162810604465068448139561667220729261210164692339016793399632833013163850830967942792934551268435760356901970523138364640961311774904600772840862214747547653221505518116489887879087780918009050706040061220010051271575991225725282523378026809030528461581739558198122397010092017202251606352922464781615533532275453264543087093320924631855976580561717446840450048285353396546862678852330044967795580761661801833668792312510460809773895565488962815089519622093675058841609752282328250433712970186608193748968699961301486924694482420723632912367052542145464162968910442981633373266871675946715392611950649224725627254543274193495995569590243279097174392258098103601486364409101491734183079646345064833303404765711827040276868271418084574998493392039317445402616663674646668754385093967129918067471909885312710726724428584870694307099756567949198418996425748884764622030325637751112534060087936904565779272035205921345924272965206683338510673615276261016026647772485083344719891986802656197236420847504962661607797092906844757798251795569758235084371746103310387911789239441630112634077535773520558040066982523191225570519133631407211349723226549151062961739050617857127509403623146700931176133132018631158730886798239298009805089491510788371194099750375473674305745187265414016446924576792185753680363289139664155342066705623272936001177781498886100830877849571709880858667023104043242526785955562077310543072298032125941107957349146684680220501816192150766649106862033378713826058987655210423668198670177861672671972374156917880001690656659046965316154923604061891820982414006103779407166342002735828911994182647812782659666207030384795881442790246669264032799404016800137293477301530941805070587421153284642203006550763966756168318897005152026656649929417382840327305940740147117478464839241225676523593418554066440983706083636457657081801664285044258224551650808864421212113914352453935225522162483791737330329812349528984098613273709957407786789349311975204237925022851375880436791854547836416773151821457226504640800104202100410766027807729152555503218182387221708112766208665317651926458452495269685376314437998340336947124447247796973890514941120010934140073794061859447165516612674930799374705772930521750426383798367668159183589049652163726492960837147204067428996276720315410211504333742057182854090136325721437592054640471894328548696883599785122262130812989581571391597464534806099601555877223193450760315411663112963843719400333736013305526352571490454327925190794007111504785378036370897340146753465517470747096935814912797188187854376797751675927822300312945518595042883902735494672667647506072643698761394806879080593531793001711000214417701504495496412454361656210150919997862972495905809191825255486358703529320142005857057855419217730505342687533799076038746689684283402648733290888881745453047194740939258407362058242849349024756883352446212456101562729065130618520732925434179252299417447855189995098959999877410951464170076989305620163502192692653166599093238118295411937545448509428621839424186218067457128099385258842631930670182098008050900019819621758458932516877698594110522845465835679362969619219080897536813210484518784516230623911878024604050824909336069998094776253792973597037759066145994638578378211017122446355845171941670344732162722443265914858595797823752976323442911242311368603724514438765801271594060878788638511089680883165505046309006148832545452819908256238805872042843941834687865142541377686054291079721004271658 diff --git a/src/pkg/compress/testdata/pi.txt b/src/pkg/compress/testdata/pi.txt deleted file mode 100644 index ca99bbc2a..000000000 --- a/src/pkg/compress/testdata/pi.txt +++ /dev/null @@ -1 +0,0 @@ -3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632788659361533818279682303019520353018529689957736225994138912497217752834791315155748572424541506959508295331168617278558890750983817546374649393192550604009277016711390098488240128583616035637076601047101819429555961989467678374494482553797747268471040475346462080466842590694912933136770289891521047521620569660240580381501935112533824300355876402474964732639141992726042699227967823547816360093417216412199245863150302861829745557067498385054945885869269956909272107975093029553211653449872027559602364806654991198818347977535663698074265425278625518184175746728909777727938000816470600161452491921732172147723501414419735685481613611573525521334757418494684385233239073941433345477624168625189835694855620992192221842725502542568876717904946016534668049886272327917860857843838279679766814541009538837863609506800642251252051173929848960841284886269456042419652850222106611863067442786220391949450471237137869609563643719172874677646575739624138908658326459958133904780275900994657640789512694683983525957098258226205224894077267194782684826014769909026401363944374553050682034962524517493996514314298091906592509372216964615157098583874105978859597729754989301617539284681382686838689427741559918559252459539594310499725246808459872736446958486538367362226260991246080512438843904512441365497627807977156914359977001296160894416948685558484063534220722258284886481584560285060168427394522674676788952521385225499546667278239864565961163548862305774564980355936345681743241125150760694794510965960940252288797108931456691368672287489405601015033086179286809208747609178249385890097149096759852613655497818931297848216829989487226588048575640142704775551323796414515237462343645428584447952658678210511413547357395231134271661021359695362314429524849371871101457654035902799344037420073105785390621983874478084784896833214457138687519435064302184531910484810053706146806749192781911979399520614196634287544406437451237181921799983910159195618146751426912397489409071864942319615679452080951465502252316038819301420937621378559566389377870830390697920773467221825625996615014215030680384477345492026054146659252014974428507325186660021324340881907104863317346496514539057962685610055081066587969981635747363840525714591028970641401109712062804390397595156771577004203378699360072305587631763594218731251471205329281918261861258673215791984148488291644706095752706957220917567116722910981690915280173506712748583222871835209353965725121083579151369882091444210067510334671103141267111369908658516398315019701651511685171437657618351556508849099898599823873455283316355076479185358932261854896321329330898570642046752590709154814165498594616371802709819943099244889575712828905923233260972997120844335732654893823911932597463667305836041428138830320382490375898524374417029132765618093773444030707469211201913020330380197621101100449293215160842444859637669838952286847831235526582131449576857262433441893039686426243410773226978028073189154411010446823252716201052652272111660396665573092547110557853763466820653109896526918620564769312570586356620185581007293606598764861179104533488503461136576867532494416680396265797877185560845529654126654085306143444318586769751456614068007002378776591344017127494704205622305389945613140711270004078547332699390814546646458807972708266830634328587856983052358089330657574067954571637752542021149557615814002501262285941302164715509792592309907965473761255176567513575178296664547791745011299614890304639947132962107340437518957359614589019389713111790429782856475032031986915140287080859904801094121472213179476477726224142548545403321571853061422881375850430633217518297986622371721591607716692547487389866549494501146540628433663937900397692656721463853067360965712091807638327166416274888800786925602902284721040317211860820419000422966171196377921337575114959501566049631862947265473642523081770367515906735023507283540567040386743513622224771589150495309844489333096340878076932599397805419341447377441842631298608099888687413260472156951623965864573021631598193195167353812974167729478672422924654366800980676928238280689964004824354037014163149658979409243237896907069779422362508221688957383798623001593776471651228935786015881617557829735233446042815126272037343146531977774160319906655418763979293344195215413418994854447345673831624993419131814809277771038638773431772075456545322077709212019051660962804909263601975988281613323166636528619326686336062735676303544776280350450777235547105859548702790814356240145171806246436267945612753181340783303362542327839449753824372058353114771199260638133467768796959703098339130771098704085913374641442822772634659470474587847787201927715280731767907707157213444730605700733492436931138350493163128404251219256517980694113528013147013047816437885185290928545201165839341965621349143415956258658655705526904965209858033850722426482939728584783163057777560688876446248246857926039535277348030480290058760758251047470916439613626760449256274204208320856611906254543372131535958450687724602901618766795240616342522577195429162991930645537799140373404328752628889639958794757291746426357455254079091451357111369410911939325191076020825202618798531887705842972591677813149699009019211697173727847684726860849003377024242916513005005168323364350389517029893922334517220138128069650117844087451960121228599371623130171144484640903890644954440061986907548516026327505298349187407866808818338510228334508504860825039302133219715518430635455007668282949304137765527939751754613953984683393638304746119966538581538420568533862186725233402830871123282789212507712629463229563989898935821167456270102183564622013496715188190973038119800497340723961036854066431939509790190699639552453005450580685501956730229219139339185680344903982059551002263535361920419947455385938102343955449597783779023742161727111723643435439478221818528624085140066604433258885698670543154706965747458550332323342107301545940516553790686627333799585115625784322988273723198987571415957811196358330059408730681216028764962867446047746491599505497374256269010490377819868359381465741268049256487985561453723478673303904688383436346553794986419270563872931748723320837601123029911367938627089438799362016295154133714248928307220126901475466847653576164773794675200490757155527819653621323926406160136358155907422020203187277605277219005561484255518792530343513984425322341576233610642506390497500865627109535919465897514131034822769306247435363256916078154781811528436679570611086153315044521274739245449454236828860613408414863776700961207151249140430272538607648236341433462351897576645216413767969031495019108575984423919862916421939949072362346468441173940326591840443780513338945257423995082965912285085558215725031071257012668302402929525220118726767562204154205161841634847565169998116141010029960783869092916030288400269104140792886215078424516709087000699282120660418371806535567252532567532861291042487761825829765157959847035622262934860034158722980534989650226291748788202734209222245339856264766914905562842503912757710284027998066365825488926488025456610172967026640765590429099456815065265305371829412703369313785178609040708667114965583434347693385781711386455873678123014587687126603489139095620099393610310291616152881384379099042317473363948045759314931405297634757481193567091101377517210080315590248530906692037671922033229094334676851422144773793937517034436619910403375111735471918550464490263655128162288244625759163330391072253837421821408835086573917715096828874782656995995744906617583441375223970968340800535598491754173818839994469748676265516582765848358845314277568790029095170283529716344562129640435231176006651012412006597558512761785838292041974844236080071930457618932349229279650198751872127267507981255470958904556357921221033346697499235630254947802490114195212382815309114079073860251522742995818072471625916685451333123948049470791191532673430282441860414263639548000448002670496248201792896476697583183271314251702969234889627668440323260927524960357996469256504936818360900323809293459588970695365349406034021665443755890045632882250545255640564482465151875471196218443965825337543885690941130315095261793780029741207665147939425902989695946995565761218656196733786236256125216320862869222103274889218654364802296780705765615144632046927906821207388377814233562823608963208068222468012248261177185896381409183903673672220888321513755600372798394004152970028783076670944474560134556417254370906979396122571429894671543578468788614445812314593571984922528471605049221242470141214780573455105008019086996033027634787081081754501193071412233908663938339529425786905076431006383519834389341596131854347546495569781038293097164651438407007073604112373599843452251610507027056235266012764848308407611830130527932054274628654036036745328651057065874882256981579367897669742205750596834408697350201410206723585020072452256326513410559240190274216248439140359989535394590944070469120914093870012645600162374288021092764579310657922955249887275846101264836999892256959688159205600101655256375678566722796619885782794848855834397518744545512965634434803966420557982936804352202770984294232533022576341807039476994159791594530069752148293366555661567873640053666564165473217043903521329543529169414599041608753201868379370234888689479151071637852902345292440773659495630510074210871426134974595615138498713757047101787957310422969066670214498637464595280824369445789772330048764765241339075920434019634039114732023380715095222010682563427471646024335440051521266932493419673977041595683753555166730273900749729736354964533288869844061196496162773449518273695588220757355176651589855190986665393549481068873206859907540792342402300925900701731960362254756478940647548346647760411463233905651343306844953979070903023460461470961696886885014083470405460742958699138296682468185710318879065287036650832431974404771855678934823089431068287027228097362480939962706074726455399253994428081137369433887294063079261595995462624629707062594845569034711972996409089418059534393251236235508134949004364278527138315912568989295196427287573946914272534366941532361004537304881985517065941217352462589548730167600298865925786628561249665523533829428785425340483083307016537228563559152534784459818313411290019992059813522051173365856407826484942764411376393866924803118364453698589175442647399882284621844900877769776312795722672655562596282542765318300134070922334365779160128093179401718598599933849235495640057099558561134980252499066984233017350358044081168552653117099570899427328709258487894436460050410892266917835258707859512983441729535195378855345737426085902908176515578039059464087350612322611200937310804854852635722825768203416050484662775045003126200800799804925485346941469775164932709504934639382432227188515974054702148289711177792376122578873477188196825462981268685817050740272550263329044976277894423621674119186269439650671515779586756482399391760426017633870454990176143641204692182370764887834196896861181558158736062938603810171215855272668300823834046564758804051380801633638874216371406435495561868964112282140753302655100424104896783528588290243670904887118190909494533144218287661810310073547705498159680772009474696134360928614849417850171807793068108546900094458995279424398139213505586422196483491512639012803832001097738680662877923971801461343244572640097374257007359210031541508936793008169980536520276007277496745840028362405346037263416554259027601834840306811381855105979705664007509426087885735796037324514146786703688098806097164258497595138069309449401515422221943291302173912538355915031003330325111749156969174502714943315155885403922164097229101129035521815762823283182342548326111912800928252561902052630163911477247331485739107775874425387611746578671169414776421441111263583553871361011023267987756410246824032264834641766369806637857681349204530224081972785647198396308781543221166912246415911776732253264335686146186545222681268872684459684424161078540167681420808850280054143613146230821025941737562389942075713627516745731891894562835257044133543758575342698699472547031656613991999682628247270641336222178923903176085428943733935618891651250424404008952719837873864805847268954624388234375178852014395600571048119498842390606136957342315590796703461491434478863604103182350736502778590897578272731305048893989009923913503373250855982655867089242612429473670193907727130706869170926462548423240748550366080136046689511840093668609546325002145852930950000907151058236267293264537382104938724996699339424685516483261134146110680267446637334375340764294026682973865220935701626384648528514903629320199199688285171839536691345222444708045923966028171565515656661113598231122506289058549145097157553900243931535190902107119457300243880176615035270862602537881797519478061013715004489917210022201335013106016391541589578037117792775225978742891917915522417189585361680594741234193398420218745649256443462392531953135103311476394911995072858430658361935369329699289837914941939406085724863968836903265564364216644257607914710869984315733749648835292769328220762947282381537409961545598798259891093717126218283025848112389011968221429457667580718653806506487026133892822994972574530332838963818439447707794022843598834100358385423897354243956475556840952248445541392394100016207693636846776413017819659379971557468541946334893748439129742391433659360410035234377706588867781139498616478747140793263858738624732889645643598774667638479466504074111825658378878454858148962961273998413442726086061872455452360643153710112746809778704464094758280348769758948328241239292960582948619196670918958089833201210318430340128495116203534280144127617285830243559830032042024512072872535581195840149180969253395075778400067465526031446167050827682772223534191102634163157147406123850425845988419907611287258059113935689601431668283176323567325417073420817332230462987992804908514094790368878687894930546955703072619009502076433493359106024545086453628935456862958531315337183868265617862273637169757741830239860065914816164049449650117321313895747062088474802365371031150898427992754426853277974311395143574172219759799359685252285745263796289612691572357986620573408375766873884266405990993505000813375432454635967504844235284874701443545419576258473564216198134073468541117668831186544893776979566517279662326714810338643913751865946730024434500544995399742372328712494834706044063471606325830649829795510109541836235030309453097335834462839476304775645015008507578949548931393944899216125525597701436858943585877526379625597081677643800125436502371412783467926101995585224717220177723700417808419423948725406801556035998390548985723546745642390585850216719031395262944554391316631345308939062046784387785054239390524731362012947691874975191011472315289326772533918146607300089027768963114810902209724520759167297007850580717186381054967973100167870850694207092232908070383263453452038027860990556900134137182368370991949516489600755049341267876436746384902063964019766685592335654639138363185745698147196210841080961884605456039038455343729141446513474940784884423772175154334260306698831768331001133108690421939031080143784334151370924353013677631084913516156422698475074303297167469640666531527035325467112667522460551199581831963763707617991919203579582007595605302346267757943936307463056901080114942714100939136913810725813781357894005599500183542511841721360557275221035268037357265279224173736057511278872181908449006178013889710770822931002797665935838758909395688148560263224393726562472776037890814458837855019702843779362407825052704875816470324581290878395232453237896029841669225489649715606981192186584926770403956481278102179913217416305810554598801300484562997651121241536374515005635070127815926714241342103301566165356024733807843028655257222753049998837015348793008062601809623815161366903341111386538510919367393835229345888322550887064507539473952043968079067086806445096986548801682874343786126453815834280753061845485903798217994599681154419742536344399602902510015888272164745006820704193761584547123183460072629339550548239557137256840232268213012476794522644820910235647752723082081063518899152692889108455571126603965034397896278250016110153235160519655904211844949907789992007329476905868577878720982901352956613978884860509786085957017731298155314951681467176959760994210036183559138777817698458758104466283998806006162298486169353373865787735983361613384133853684211978938900185295691967804554482858483701170967212535338758621582310133103877668272115726949518179589754693992642197915523385766231676275475703546994148929041301863861194391962838870543677743224276809132365449485366768000001065262485473055861598999140170769838548318875014293890899506854530765116803337322265175662207526951791442252808165171667766727930354851542040238174608923283917032754257508676551178593950027933895920576682789677644531840404185540104351348389531201326378369283580827193783126549617459970567450718332065034556644034490453627560011250184335607361222765949278393706478426456763388188075656121689605041611390390639601620221536849410926053876887148379895599991120991646464411918568277004574243434021672276445589330127781586869525069499364610175685060167145354315814801054588605645501332037586454858403240298717093480910556211671546848477803944756979804263180991756422809873998766973237695737015808068229045992123661689025962730430679316531149401764737693873514093361833216142802149763399189835484875625298752423873077559555955465196394401821840998412489826236737714672260616336432964063357281070788758164043814850188411431885988276944901193212968271588841338694346828590066640806314077757725705630729400492940302420498416565479736705485580445865720227637840466823379852827105784319753541795011347273625774080213476826045022851579795797647467022840999561601569108903845824502679265942055503958792298185264800706837650418365620945554346135134152570065974881916341359556719649654032187271602648593049039787489589066127250794828276938953521753621850796297785146188432719223223810158744450528665238022532843891375273845892384422535472653098171578447834215822327020690287232330053862163479885094695472004795231120150432932266282727632177908840087861480221475376578105819702226309717495072127248479478169572961423658595782090830733233560348465318730293026659645013718375428897557971449924654038681799213893469244741985097334626793321072686870768062639919361965044099542167627840914669856925715074315740793805323925239477557441591845821562518192155233709607483329234921034514626437449805596103307994145347784574699992128599999399612281615219314888769388022281083001986016549416542616968586788372609587745676182507275992950893180521872924610867639958916145855058397274209809097817293239301067663868240401113040247007350857828724627134946368531815469690466968693925472519413992914652423857762550047485295476814795467007050347999588867695016124972282040303995463278830695976249361510102436555352230690612949388599015734661023712235478911292547696176005047974928060721268039226911027772261025441492215765045081206771735712027180242968106203776578837166909109418074487814049075517820385653909910477594141321543284406250301802757169650820964273484146957263978842560084531214065935809041271135920041975985136254796160632288736181367373244506079244117639975974619383584574915988097667447093006546342423460634237474666080431701260052055928493695941434081468529815053947178900451835755154125223590590687264878635752541911288877371766374860276606349603536794702692322971868327717393236192007774522126247518698334951510198642698878471719396649769070825217423365662725928440620430214113719922785269984698847702323823840055655517889087661360130477098438611687052310553149162517283732728676007248172987637569816335415074608838663640693470437206688651275688266149730788657015685016918647488541679154596507234287730699853713904300266530783987763850323818215535597323530686043010675760838908627049841888595138091030423595782495143988590113185835840667472370297149785084145853085781339156270760356390763947311455495832266945702494139831634332378975955680856836297253867913275055542524491943589128405045226953812179131914513500993846311774017971512283785460116035955402864405902496466930707769055481028850208085800878115773817191741776017330738554758006056014337743299012728677253043182519757916792969965041460706645712588834697979642931622965520168797300035646304579308840327480771811555330909887025505207680463034608658165394876951960044084820659673794731680864156456505300498816164905788311543454850526600698230931577765003780704661264706021457505793270962047825615247145918965223608396645624105195510522357239739512881816405978591427914816542632892004281609136937773722299983327082082969955737727375667615527113922588055201898876201141680054687365580633471603734291703907986396522961312801782679717289822936070288069087768660593252746378405397691848082041021944719713869256084162451123980620113184541244782050110798760717155683154078865439041210873032402010685341947230476666721749869868547076781205124736792479193150856444775379853799732234456122785843296846647513336573692387201464723679427870042503255589926884349592876124007558756946413705625140011797133166207153715436006876477318675587148783989081074295309410605969443158477539700943988394914432353668539209946879645066533985738887866147629443414010498889931600512076781035886116602029611936396821349607501116498327856353161451684576956871090029997698412632665023477167286573785790857466460772283415403114415294188047825438761770790430001566986776795760909966936075594965152736349811896413043311662774712338817406037317439705406703109676765748695358789670031925866259410510533584384656023391796749267844763708474978333655579007384191473198862713525954625181604342253729962863267496824058060296421146386436864224724887283434170441573482481833301640566959668866769563491416328426414974533349999480002669987588815935073578151958899005395120853510357261373640343675347141048360175464883004078464167452167371904831096767113443494819262681110739948250607394950735031690197318521195526356325843390998224986240670310768318446607291248747540316179699411397387765899868554170318847788675929026070043212666179192235209382278788809886335991160819235355570464634911320859189796132791319756490976000139962344455350143464268604644958624769094347048293294140411146540923988344435159133201077394411184074107684981066347241048239358274019449356651610884631256785297769734684303061462418035852933159734583038455410337010916767763742762102137013548544509263071901147318485749233181672072137279355679528443925481560913728128406333039373562420016045664557414588166052166608738748047243391212955877763906969037078828527753894052460758496231574369171131761347838827194168606625721036851321566478001476752310393578606896111259960281839309548709059073861351914591819510297327875571049729011487171897180046961697770017913919613791417162707018958469214343696762927459109940060084983568425201915593703701011049747339493877885989417433031785348707603221982970579751191440510994235883034546353492349826883624043327267415540301619505680654180939409982020609994140216890900708213307230896621197755306659188141191577836272927461561857103721724710095214236964830864102592887457999322374955191221951903424452307535133806856807354464995127203174487195403976107308060269906258076020292731455252078079914184290638844373499681458273372072663917670201183004648190002413083508846584152148991276106513741539435657211390328574918769094413702090517031487773461652879848235338297260136110984514841823808120540996125274580881099486972216128524897425555516076371675054896173016809613803811914361143992106380050832140987604599309324851025168294467260666138151745712559754953580239983146982203613380828499356705575524712902745397762140493182014658008021566536067765508783804304134310591804606800834591136640834887408005741272586704792258319127415739080914383138456424150940849133918096840251163991936853225557338966953749026620923261318855891580832455571948453875628786128859004106006073746501402627824027346962528217174941582331749239683530136178653673760642166778137739951006589528877427662636841830680190804609849809469763667335662282915132352788806157768278159588669180238940333076441912403412022316368577860357276941541778826435238131905028087018575047046312933353757285386605888904583111450773942935201994321971171642235005644042979892081594307167019857469273848653833436145794634175922573898588001698014757420542995801242958105456510831046297282937584161162532562516572498078492099897990620035936509934721582965174135798491047111660791587436986541222348341887722929446335178653856731962559852026072947674072616767145573649812105677716893484917660771705277187601199908144113058645577910525684304811440261938402322470939249802933550731845890355397133088446174107959162511714864874468611247605428673436709046678468670274091881014249711149657817724279347070216688295610877794405048437528443375108828264771978540006509704033021862556147332117771174413350281608840351781452541964320309576018694649088681545285621346988355444560249556668436602922195124830910605377201980218310103270417838665447181260397190688462370857518080035327047185659499476124248110999288679158969049563947624608424065930948621507690314987020673533848349550836366017848771060809804269247132410009464014373603265645184566792456669551001502298330798496079949882497061723674493612262229617908143114146609412341593593095854079139087208322733549572080757165171876599449856937956238755516175754380917805280294642004472153962807463602113294255916002570735628126387331060058910652457080244749375431841494014821199962764531068006631183823761639663180931444671298615527598201451410275600689297502463040173514891945763607893528555053173314164570504996443890936308438744847839616840518452732884032345202470568516465716477139323775517294795126132398229602394548579754586517458787713318138752959809412174227300352296508089177705068259248822322154938048371454781647213976820963320508305647920482085920475499857320388876391601995240918938945576768749730856955958010659526503036266159750662225084067428898265907510637563569968211510949669744580547288693631020367823250182323708459790111548472087618212477813266330412076216587312970811230758159821248639807212407868878114501655825136178903070860870198975889807456643955157415363193191981070575336633738038272152798849350397480015890519420879711308051233933221903466249917169150948541401871060354603794643379005890957721180804465743962806186717861017156740967662080295766577051291209907944304632892947306159510430902221439371849560634056189342513057268291465783293340524635028929175470872564842600349629611654138230077313327298305001602567240141851520418907011542885799208121984493156999059182011819733500126187728036812481995877070207532406361259313438595542547781961142935163561223496661522614735399674051584998603552953329245752388810136202347624669055816438967863097627365504724348643071218494373485300606387644566272186661701238127715621379746149861328744117714552444708997144522885662942440230184791205478498574521634696448973892062401943518310088283480249249085403077863875165911302873958787098100772718271874529013972836614842142871705531796543076504534324600536361472618180969976933486264077435199928686323835088756683595097265574815431940195576850437248001020413749831872259677387154958399718444907279141965845930083942637020875635398216962055324803212267498911402678528599673405242031091797899905718821949391320753431707980023736590985375520238911643467185582906853711897952626234492483392496342449714656846591248918556629589329909035239233333647435203707701010843880032907598342170185542283861617210417603011645918780539367447472059985023582891833692922337323999480437108419659473162654825748099482509991833006976569367159689364493348864744213500840700660883597235039532340179582557036016936990988671132109798897070517280755855191269930673099250704070245568507786790694766126298082251633136399521170984528092630375922426742575599892892783704744452189363203489415521044597261883800300677617931381399162058062701651024458869247649246891924612125310275731390840470007143561362316992371694848132554200914530410371354532966206392105479824392125172540132314902740585892063217589494345489068463993137570910346332714153162232805522972979538018801628590735729554162788676498274186164218789885741071649069191851162815285486794173638906653885764229158342500673612453849160674137340173572779956341043326883569507814931378007362354180070619180267328551191942676091221035987469241172837493126163395001239599240508454375698507957046222664619000103500490183034153545842833764378111988556318777792537201166718539541835984438305203762819440761594106820716970302285152250573126093046898423433152732131361216582808075212631547730604423774753505952287174402666389148817173086436111389069420279088143119448799417154042103412190847094080254023932942945493878640230512927119097513536000921971105412096683111516328705423028470073120658032626417116165957613272351566662536672718998534199895236884830999302757419916463841427077988708874229277053891227172486322028898425125287217826030500994510824783572905691988555467886079462805371227042466543192145281760741482403827835829719301017888345674167811398954750448339314689630763396657226727043393216745421824557062524797219978668542798977992339579057581890622525473582205236424850783407110144980478726691990186438822932305382318559732869780922253529591017341407334884761005564018242392192695062083183814546983923664613639891012102177095976704908305081854704194664371312299692358895384930136356576186106062228705599423371631021278457446463989738188566746260879482018647487672727222062676465338099801966883680994159075776852639865146253336312450536402610569605513183813174261184420189088853196356986962795036738424313011331753305329802016688817481342988681585577810343231753064784983210629718425184385534427620128234570716988530518326179641178579608888150329602290705614476220915094739035946646916235396809201394578175891088931992112260073928149169481615273842736264298098234063200244024495894456129167049508235812487391799648641133480324757775219708932772262349486015046652681439877051615317026696929704928316285504212898146706195331970269507214378230476875280287354126166391708245925170010714180854800636923259462019002278087409859771921805158532147392653251559035410209284665925299914353791825314545290598415817637058927906909896911164381187809435371521332261443625314490127454772695739393481546916311624928873574718824071503995009446731954316193855485207665738825139639163576723151005556037263394867208207808653734942440115799667507360711159351331959197120948964717553024531364770942094635696982226673775209945168450643623824211853534887989395673187806606107885440005508276570305587448541805778891719207881423351138662929667179643468760077047999537883387870348718021842437342112273940255717690819603092018240188427057046092622564178375265263358324240661253311529423457965569502506810018310900411245379015332966156970522379210325706937051090830789479999004999395322153622748476603613677697978567386584670936679588583788795625946464891376652199588286933801836011932368578558558195556042156250883650203322024513762158204618106705195330653060606501054887167245377942831338871631395596905832083416898476065607118347136218123246227258841990286142087284956879639325464285343075301105285713829643709990356948885285190402956047346131138263878897551788560424998748316382804046848618938189590542039889872650697620201995548412650005394428203930127481638158530396439925470201672759328574366661644110962566337305409219519675148328734808957477775278344221091073111351828046036347198185655572957144747682552857863349342858423118749440003229690697758315903858039353521358860079600342097547392296733310649395601812237812854584317605561733861126734780745850676063048229409653041118306671081893031108871728167519579675347188537229309616143204006381322465841111157758358581135018569047815368938137718472814751998350504781297718599084707621974605887423256995828892535041937958260616211842368768511418316068315867994601652057740529423053601780313357263267054790338401257305912339601880137825421927094767337191987287385248057421248921183470876629667207272325650565129333126059505777727542471241648312832982072361750574673870128209575544305968395555686861188397135522084452852640081252027665557677495969626612604565245684086139238265768583384698499778726706555191854468698469478495734622606294219624557085371272776523098955450193037732166649182578154677292005212667143463209637891852323215018976126034373684067194193037746880999296877582441047878123266253181845960453853543839114496775312864260925211537673258866722604042523491087026958099647595805794663973419064010036361904042033113579336542426303561457009011244800890020801478056603710154122328891465722393145076071670643556827437743965789067972687438473076346451677562103098604092717090951280863090297385044527182892749689212106670081648583395537735919136950153162018908887484210798706899114804669270650940762046502772528650728905328548561433160812693005693785417861096969202538865034577183176686885923681488475276498468821949739729707737187188400414323127636504814531122850990020742409255859252926103021067368154347015252348786351643976235860419194129697690405264832347009911154242601273438022089331096686367898694977994001260164227609260823493041180643829138347354679725399262338791582998486459271734059225620749105308531537182911681637219395188700957788181586850464507699343940987433514431626330317247747486897918209239480833143970840673084079589358108966564775859905563769525232653614424780230826811831037735887089240613031336477371011628214614661679404090518615260360092521947218890918107335871964142144478654899528582343947050079830388538860831035719306002771194558021911942899922722353458707566246926177663178855144350218287026685610665003531050216318206017609217984684936863161293727951873078972637353717150256378733579771808184878458866504335824377004147710414934927438457587107159731559439426412570270965125108115548247939403597681188117282472158250109496096625393395380922195591918188552678062149923172763163218339896938075616855911752998450132067129392404144593862398809381240452191484831646210147389182510109096773869066404158973610476436500068077105656718486281496371118832192445663945814491486165500495676982690308911185687986929470513524816091743243015383684707292898982846022237301452655679898627767968091469798378268764311598832109043715611299766521539635464420869197567370005738764978437686287681792497469438427465256316323005551304174227341646455127812784577772457520386543754282825671412885834544435132562054464241011037955464190581168623059644769587054072141985212106734332410756767575818456990693046047522770167005684543969234041711089888993416350585157887353430815520811772071880379104046983069578685473937656433631979786803671873079693924236321448450354776315670255390065423117920153464977929066241508328858395290542637687668968805033317227800185885069736232403894700471897619347344308437443759925034178807972235859134245813144049847701732361694719765715353197754997162785663119046912609182591249890367654176979903623755286526375733763526969344354400473067198868901968147428767790866979688522501636949856730217523132529265375896415171479559538784278499866456302878831962099830494519874396369070682762657485810439112232618794059941554063270131989895703761105323606298674803779153767511583043208498720920280929752649812569163425000522908872646925284666104665392171482080130502298052637836426959733707053922789153510568883938113249757071331029504430346715989448786847116438328050692507766274500122003526203709466023414648998390252588830148678162196775194583167718762757200505439794412459900771152051546199305098386982542846407255540927403132571632640792934183342147090412542533523248021932277075355546795871638358750181593387174236061551171013123525633485820365146141870049205704372018261733194715700867578539336078622739558185797587258744102542077105475361294047460100094095444959662881486915903899071865980563617137692227290764197755177720104276496949611056220592502420217704269622154958726453989227697660310524980855759471631075870133208861463266412591148633881220284440694169488261529577625325019870359870674380469821942056381255833436421949232275937221289056420943082352544084110864545369404969271494003319782861318186188811118408257865928757426384450059944229568586460481033015388911499486935436030221810943466764000022362550573631294626296096198760564259963946138692330837196265954739234624134597795748524647837980795693198650815977675350553918991151335252298736112779182748542008689539658359421963331502869561192012298889887006079992795411188269023078913107603617634779489432032102773359416908650071932804017163840644987871753756781185321328408216571107549528294974936214608215583205687232185574065161096274874375098092230211609982633033915469494644491004515280925089745074896760324090768983652940657920198315265410658136823791984090645712468948470209357761193139980246813405200394781949866202624008902150166163813538381515037735022966074627952910384068685569070157516624192987244482719429331004854824454580718897633003232525821581280327467962002814762431828622171054352898348208273451680186131719593324711074662228508710666117703465352839577625997744672185715816126411143271794347885990892808486694914139097716736900277758502686646540565950394867841110790116104008572744562938425494167594605487117235946429105850909950214958793112196135908315882620682332156153086833730838173279328196983875087083483880463884784418840031847126974543709373298362402875197920802321878744882872843727378017827008058782410749357514889978911739746129320351081432703251409030487462262942344327571260086642508333187688650756429271605525289544921537651751492196367181049435317858383453865255656640657251363575064353236508936790431702597878177190314867963840828810209461490079715137717099061954969640070867667102330048672631475510537231757114322317411411680622864206388906210192355223546711662137499693269321737043105987225039456574924616978260970253359475020913836673772894438696400028110344026084712899000746807764844088711341352503367877316797709372778682166117865344231732264637847697875144332095340001650692130546476890985050203015044880834261845208730530973189492916425322933612431514306578264070283898409841602950309241897120971601649265613413433422298827909921786042679812457285345801338260995877178113102167340256562744007296834066198480676615805021691833723680399027931606420436812079900316264449146190219458229690992122788553948783538305646864881655562294315673128274390826450611628942803501661336697824051770155219626522725455850738640585299830379180350432876703809252167907571204061237596327685674845079151147313440001832570344920909712435809447900462494313455028900680648704293534037436032625820535790118395649089354345101342969617545249573960621490288728932792520696535386396443225388327522499605986974759882329916263545973324445163755334377492928990581175786355555626937426910947117002165411718219750519831787137106051063795558588905568852887989084750915764639074693619881507814685262133252473837651192990156109189777922008705793396463827490680698769168197492365624226087154176100430608904377976678519661891404144925270480881971498801542057787006521594009289777601330756847966992955433656139847738060394368895887646054983871478968482805384701730871117761159663505039979343869339119789887109156541709133082607647406305711411098839388095481437828474528838368079418884342666222070438722887413947801017721392281911992365405516395893474263953824829609036900288359327745855060801317988407162446563997948275783650195514221551339281978226984278638391679715091262410548725700924070045488485692950448110738087996547481568913935380943474556972128919827177020766613602489581468119133614121258783895577357194986317210844398901423948496659251731388171602663261931065366535041473070804414939169363262373767777095850313255990095762731957308648042467701212327020533742667053142448208168130306397378736642483672539837487690980602182785786216512738563513290148903509883270617258932575363993979055729175160097615459044771692265806315111028038436017374742152476085152099016158582312571590733421736576267142390478279587281505095633092802668458937649649770232973641319060982740633531089792464242134583740901169391964250459128813403498810635400887596820054408364386516617880557608956896727531538081942077332597917278437625661184319891025007491829086475149794003160703845549465385946027452447466812314687943441610993338908992638411847425257044572517459325738989565185716575961481266020310797628254165590506042479114016957900338356574869252800743025623419498286467914476322774005529460903940177536335655471931000175430047504719144899841040015867946179241610016454716551337074073950260442769538553834397550548871099785205401175169747581344926079433689543783221172450687344231989878844128542064742809735625807066983106979935260693392135685881391214807354728463227784908087002467776303605551232386656295178853719673034634701222939581606792509153217489030840886516061119011498443412350124646928028805996134283511884715449771278473361766285062169778717743824362565711779450064477718370221999106695021656757644044997940765037999954845002710665987813603802314126836905783190460792765297277694043613023051787080546511542469395265127101052927070306673024447125973939950514628404767431363739978259184541176413327906460636584152927019030276017339474866960348694976541752429306040727005059039503148522921392575594845078867977925253931765156416197168443524369794447355964260633391055126826061595726217036698506473281266724521989060549880280782881429796336696744124805982192146339565745722102298677599746738126069367069134081559412016115960190237753525556300606247983261249881288192937343476862689219239777833910733106588256813777172328315329082525092733047850724977139448333892552081175608452966590553940965568541706001179857293813998258319293679100391844099286575605993598910002969864460974714718470101531283762631146774209145574041815908800064943237855839308530828305476076799524357391631221886057549673832243195650655460852881201902363644712703748634421727257879503428486312944916318475347531435041392096108796057730987201352484075057637199253650470908582513936863463863368042891767107602111159828875539940120076013947033661793715396306139863655492213741597905119083588290097656647300733879314678913181465109316761575821351424860442292445304113160652700974330088499034675405518640677342603583409608605533747362760935658853109760994238347382222087292464497684560579562516765574088410321731345627735856052358236389532038534024842273371639123973215995440828421666636023296545694703577184873442034227706653837387506169212768015766181095420097708363604361110592409117889540338021426523948929686439808926114635414571535194342850721353453018315875628275733898268898523557799295727645229391567477566676051087887648453493636068278050564622813598885879259940946446041705204470046315137975431737187756039815962647501410906658866162180038266989961965580587208639721176995219466789857011798332440601811575658074284182910615193917630059194314434605154047710570054339000182453117733718955857603607182860506356479979004139761808955363669603162193113250223851791672055180659263518036251214575926238369348222665895576994660491938112486609099798128571823494006615552196112207203092277646200999315244273589488710576623894693889446495093960330454340842102462401048723328750081749179875543879387381439894238011762700837196053094383940063756116458560943129517597713935396074322792489221267045808183313764165818269562105872892447740035947009268662659651422050630078592002488291860839743732353849083964326147000532423540647042089499210250404726781059083644007466380020870126664209457181702946752278540074508552377720890581683918446592829417018288233014971554235235911774818628592967605048203864343108779562892925405638946621948268711042828163893975711757786915430165058602965217459581988878680408110328432739867198621306205559855266036405046282152306154594474489908839081999738747452969810776201487134000122535522246695409315213115337915798026979555710508507473874750758068765376445782524432638046143042889235934852961058269382103498000405248407084403561167817170512813378805705643450616119330424440798260377951198548694559152051960093041271007277849301555038895360338261929343797081874320949914159593396368110627557295278004254863060054523839151068998913578820019411786535682149118528207852130125518518493711503422159542244511900207393539627400208110465530207932867254740543652717595893500716336076321614725815407642053020045340183572338292661915308354095120226329165054426123619197051613839357326693760156914429944943744856809775696303129588719161129294681884936338647392747601226964158848900965717086160598147204467428664208765334799858222090619802173211614230419477754990738738567941189824660913091691772274207233367635032678340586301930193242996397204445179288122854478211953530898910125342975524727635730226281382091807439748671453590778633530160821559911314144205091447293535022230817193663509346865858656314855575862447818620108711889760652969899269328178705576435143382060141077329261063431525337182243385263520217735440715281898137698755157574546939727150488469793619500477720970561793913828989845327426227288647108883270173723258818244658436249580592560338105215606206155713299156084892064340303395262263451454283678698288074251422567451806184149564686111635404971897682154227722479474033571527436819409892050113653400123846714296551867344153741615042563256713430247655125219218035780169240326699541746087592409207004669340396510178134857835694440760470232540755557764728450751826890418293966113310160131119077398632462778219023650660374041606724962490137433217246454097412995570529142438208076098364823465973886691349919784013108015581343979194852830436739012482082444814128095443773898320059864909159505322857914576884962578665885999179867520554558099004556461178755249370124553217170194282884617402736649978475508294228020232901221630102309772151569446427909802190826689868834263071609207914085197695235553488657743425277531197247430873043619511396119080030255878387644206085044730631299277888942729189727169890575925244679660189707482960949190648764693702750773866432391919042254290235318923377293166736086996228032557185308919284403805071030064776847863243191000223929785255372375566213644740096760539439838235764606992465260089090624105904215453927904411529580345334500256244101006359530039598864466169595626351878060688513723462707997327233134693971456285542615467650632465676620279245208581347717608521691340946520307673391841147504140168924121319826881568664561485380287539331160232292555618941042995335640095786495340935115266454024418775949316930560448686420862757201172319526405023099774567647838488973464317215980626787671838005247696884084989185086149003432403476742686245952395890358582135006450998178244636087317754378859677672919526111213859194725451400301180503437875277664402762618941017576872680428176623860680477885242887430259145247073950546525135339459598789619778911041890292943818567205070964606263541732944649576612651953495701860015412623962286413897796733329070567376962156498184506842263690367849555970026079867996261019039331263768556968767029295371162528005543100786408728939225714512481135778627664902425161990277471090335933309304948380597856628844787441469841499067123764789582263294904679812089984857163571087831191848630254501620929805829208334813638405421720056121989353669371336733392464416125223196943471206417375491216357008573694397305979709719726666642267431117762176403068681310351899112271339724036887000996862922546465006385288620393800504778276912835603372548255793912985251506829969107754257647488325341412132800626717094009098223529657957997803018282428490221470748111124018607613415150387569830918652780658896682362523937845272634530420418802508442363190383318384550522367992357752929106925043261446950109861088899914658551881873582528164302520939285258077969737620845637482114433988162710031703151334402309526351929588680690821355853680161000213740851154484912685841268695899174149133820578492800698255195740201818105641297250836070356851055331787840829000041552511865779453963317538532092149720526607831260281961164858098684587525129997404092797683176639914655386108937587952214971731728131517932904431121815871023518740757222100123768721944747209349312324107065080618562372526732540733324875754482967573450019321902199119960797989373383673242576103938985349278777473980508080015544764061053522202325409443567718794565430406735896491017610775948364540823486130254718476485189575836674399791508512858020607820554462991723202028222914886959399729974297471155371858924238493855858595407438104882624648788053304271463011941589896328792678327322456103852197011130466587100500083285177311776489735230926661234588873102883515626446023671996644554727608310118788389151149340939344750073025855814756190881398752357812331342279866503522725367171230756861045004548970360079569827626392344107146584895780241408158405229536937499710665594894459246286619963556350652623405339439142111271810691052290024657423604130093691889255865784668461215679554256605416005071276641766056874274200329577160643448606201239821698271723197826816628249938714995449137302051843669076723577400053932662622760323659751718925901801104290384274185507894887438832703063283279963007200698012244365116394086922220745320244624121155804354542064215121585056896157356414313068883443185280853975927734433655384188340303517822946253702015782157373265523185763554098954033236382319219892171177449469403678296185920803403867575834111518824177439145077366384071880489358256868542011645031357633355509440319236720348651010561049872726472131986543435450409131859513145181276437310438972507004981987052176272494065214619959232142314439776546708351714749367986186552791715824080651063799500184295938799158350171580759883784962257398512129810326379376218322456594236685376799113140108043139732335449090824910499143325843298821033984698141715756010829706583065211347076803680695322971990599904451209087275776225351040902392888779424630483280319132710495478599180196967835321464441189260631526618167443193550817081875477050802654025294109218264858213857526688155584113198560022135158887210365696087515063187533002942118682221893775546027227291290504292259787710667873840000616772154638441292371193521828499824350920891801685572798156421858191197490985730570332667646460728757430565372602768982373259745084479649545648030771598153955827779139373601717422996027353102768719449444917939785144631597314435351850491413941557329382048542123508173912549749819308714396615132942045919380106231421774199184060180347949887691051557905554806953878540066453375981862846419905220452803306263695626490910827627115903856995051246529996062855443838330327638599800792922846659503551211245284087516229060262011857775313747949362055496401073001348853150735487353905602908933526400713274732621960311773433943673385759124508149335736911664541281788171454023054750667136518258284898099512139193995633241336556777098003081910272040997148687418134667006094051021462690280449159646545330107754695413088714165312544813061192407821188690056027781824235022696189344352547633573536485619363254417756613981703930632872166905722259745209192917262199844409646158269456380239502837121686446561785235565164127712826918688615572716201474934052276946595712198314943381622114006936307430444173284786101777743837977037231795255434107223445512555589998646183876764903972461167959018100035098928641204195163551108763204267612979826529425882951141275841262732790798807559751851576841264742209479721843309352972665210015662514552994745127631550917636730259462132930190402837954246323258550301096706922720227074863419005438302650681214142135057154175057508639907673946335146209082888934938376439399256900604067311422093312195936202982972351163259386772241477911629572780752395056251581603133359382311500518626890530658368129988108663263271980611271548858798093487912913707498230575929091862939195014721197586067270092547718025750337730799397134539532646195269996596385654917590458333585799102012713204583903200853878881633637685182083727885131175227769609787962142372162545214591281831798216044111311671406914827170981015457781939202311563871950805024679725792497605772625913328559726371211201905720771409148645074094926718035815157571514050397610963846755569298970383547314100223802583468767350129775413279532060971154506484212185936490997917766874774481882870632315515865032898164228288232746866106592732197907162384642153489852476216789050260998045266483929542357287343977680495774091449538391575565485459058976495198513801007958010783759945775299196700547602252552034453988712538780171960718164078124847847257912407824544361682345239570689514272269750431873633263011103053423335821609333191218806608268341428910415173247216053355849993224548730778822905252324234861531520976938461042582849714963475341837562003014915703279685301868631572488401526639835689563634657435321783493199825542117308467745297085839507616458229630324424328237737450517028560698067889521768198156710781633405266759539424926280756968326107495323390536223090807081455919837355377748742029039018142937311529334644468151212945097596534306284215319445727118614900017650558177095302468875263250119705209476159416768727784472000192789137251841622857783792284439084301181121496366424659033634194540657183544771912446621259392656620306888520055599121235363718226922531781458792593750441448933981608657900876165024635197045828895481793756681046474614105142498870252139936870509372305447734112641354892806841059107716677821238332810262185587751312721179344448201440425745083063944738363793906283008973306241380614589414227694747931665717623182472168350678076487573420491557628217583972975134478990696589532548940335615613167403276472469212505759116251529654568544633498114317670257295661844775487469378464233737238981920662048511894378868224807279352022501796545343757274163910791972952950812942922205347717304184477915673991738418311710362524395716152714669005814700002633010452643547865903290733205468338872078735444762647925297690170912007874183736735087713376977683496344252419949951388315074877537433849458259765560996555954318040920178497184685497370696212088524377013853757681416632722412634423982152941645378000492507262765150789085071265997036708726692764308377229685985169122305037462744310852934305273078865283977335246017463527703205938179125396915621063637625882937571373840754406468964783100704580613446731271591194608435935825987782835266531151065041623295329047772174083559349723758552138048305090009646676088301540612824308740645594431853413755220166305812111033453120745086824339432159043594430312431227471385842030390106070940315235556172767994160020393975099897629335325855575624808996691829864222677502360193257974726742578211119734709402357457222271212526852384295874273501563660093188045493338989741571490544182559738080871565281430102670460284316819230392535297795765862414392701549740879273131051636119137577008929564823323648298263024607975875767745377160102490804624301856524161756655600160859121534556267602192689982855377872583145144082654583484409478463178777374794653580169960779405568701192328608041130904629350871827125934668712766694873899824598527786499569165464029458935064964335809824765965165142090986755203808309203230487342703468288751604071546653834619611223013759451579252696743642531927390036038608236450762698827497618723575476762889950752114804852527950845033958570838130476937881321123674281319487950228066320170022460331989671970649163741175854851878484012054844672588851401562725019821719066960812627785485964818369621410721714214986361918774754509650308957099470934337856981674465828267911940611956037845397855839240761276344105766751024307559814552786167815949657062559755074306521085301597908073343736079432866757890533483669555486803913433720156498834220893399971641479746938696905480089193067138057171505857307148815649920714086758259602876056459782423770242469805328056632787041926768467116266879463486950464507420219373945259262668613552940624781361206202636498199999498405143868285258956342264328707663299304891723400725471764188685351372332667877921738347541480022803392997357936152412755829569276837231234798989446274330454566790062032420516396282588443085438307201495672106460533238537203143242112607424485845094580494081820927639140008540422023556260218564348994145439950410980591817948882628052066441086319001688568155169229486203010738897181007709290590480749092427141018933542818429995988169660993836961644381528877214085268088757488293258735809905670755817017949161906114001908553744882726200936685604475596557476485674008177381703307380305476973609786543859382187220583902344443508867499866506040645874346005331827436296177862518081893144363251205107094690813586440519229512932450078833398788429339342435126343365204385812912834345297308652909783300671261798130316794385535726296998740359570458452230856390098913179475948752126397078375944861139451960286751210561638976008880092746115860800207803341591451797073036835196977766076373785333012024120112046988609209339085365773222392412449051532780950955866459477634482269986074813297302630975028812103517723124465095349653693090018637764094094349837313251321862080214809922685502948454661814715557444709669530177690434272031892770604717784527939160472281534379803539679861424370956683221491465438014593829277393396032754048009552231816667380357183932757077142046723838624617803976292377131209580789363841447929802588065522129262093623930637313496640186619510811583471173312025805866727639992763579078063818813069156366274125431259589936119647626101405563503399523140323113819656236327198961837254845333702062563464223952766943568376761368711962921818754576081617053031590728828700712313666308722754918661395773730546065997437810987649802414011242142773668082751390959313404155826266789510846776118665957660165998178089414985754976284387856100263796543178313634025135814161151902096499133548733131115022700681930135929595971640197196053625033558479980963488718039111612813595968565478868325856437896173159762002419621552896297904819822199462269487137462444729093456470028537694958859591606789282491054412515996300781368367490209374915732896270028656829344431342347351239298259166739503425995868970697267332582735903121288746660451461487850346142827765991608090398652575717263081833494441820193533385071292345774375579344062178711330063106003324053991693682603746176638565758877580201229366353270267100681261825172914608202541892885935244491070138206211553827793565296914576502048643282865557934707209634807372692141186895467322767751335690190153723669036865389161291688887876407525493494249733427181178892759931596719354758988097924525262363659036320070854440784544797348291802082044926670634420437555325050527522833778887040804033531923407685630109347772125639088640413101073817853338316038135280828119040832564401842053746792992622037698718018061122624490909242641985820861751177113789051609140381575003366424156095216328197122335023167422600567941281406217219641842705784328959802882335059828208196666249035857789940333152274817776952843681630088531769694783690580671064828083598046698841098135158654906933319522394363287923990534810987830274500172065433699066117784554364687723631844464768069142828004551074686645392805399409108754939166095731619715033166968309929466349142798780842257220697148875580637480308862995118473187124777291910070227588893486939456289515802965372150409603107761289831263589964893410247036036645058687287589051406841238124247386385427908282733827973326885504935874303160274749063129572349742611221517417153133618622410913869500688835898962349276317316478340077460886655598733382113829928776911495492184192087771606068472874673681886167507221017261103830671787856694812948785048943063086169948798703160515884108282351274153538513365895332948629494495061868514779105804696039069372662670386512905201137810858616188886947957607413585534585151768051973334433495230120395770739623771316030242887200537320998253008977618973129817881944671731160647231476248457551928732782825127182446807824215216469567819294098238926284943760248852279003620219386696482215628093605373178040863727268426696421929946819214908701707533361094791381804063287387593848269535583077395761447997270003472880182785281389503217986345216111066608839314053226944905455527867894417579202440021450780192099804461382547805858048442416404775031536054906591430078158372430123137511562284015838644270890718284816757527123846782459534334449622010096071051370608461801187543120725491334994247617115633321408934609156561550600317384218701570226103101916603887064661438897736318780940711527528174689576401581047016965247557740891644568677717158500583269943401677202156767724068128366565264122982439465133197359199709403275938502669557470231813203243716420586141033606524536939160050644953060161267822648942437397166717661231048975031885732165554988342121802846912529086101485527815277625623750456375769497734336846015607727035509629049392487088406281067943622418704747008368842671022558302403599841645951122485272633632645114017395248086194635840783753556885622317115520947223065437092606797351000565549381224575483728545711797393615756167641692895805257297522338558611388322171107362265816218842443178857488798109026653793426664216990914056536432249301334867988154886628665052346997235574738424830590423677143278792316422403877764330192600192284778313837632536121025336935812624086866699738275977365682227907215832478888642369346396164363308730139814211430306008730666164803678984091335926293402304324974926887831643602681011309570716141912830686577323532639653677390317661361315965553584999398600565155921936759977717933019744688148371103206503693192894521402650915465184309936553493337183425298433679915939417466223900389527673813330617747629574943868716978453767219493506590875711917720875477107189937960894774512654757501871194870738736785890200617373321075693302216320628432065671192096950585761173961632326217708945426214609858410237813215817727602222738133495410481003073275107799948991977963883530734443457532975914263768405442264784216063122769646967156473999043715903323906560726644116438605404838847161912109008701019130726071044114143241976796828547885524779476481802959736049439700479596040292746299203572099761950140348315380947714601056333446998820822120587281510729182971211917876424880354672316916541852256729234429187128163232596965413548589577133208339911288775917226115273379010341362085614577992398778325083550730199818459025958355989260553299673770491722454935329683300002230181517226575787524058832249085821280089747909326100762578770428656006996176212176845478996440705066241710213327486796237430229155358200780141165348065647488230615003392068983794766255036549822805329662862117930628430170492402301985719978948836897183043805182174419147660429752437251683435411217038631379411422095295885798060152938752753799030938871683572095760715221900279379292786303637268765822681241993384808166021603722154710143007377537792699069587121289288019052031601285861825494413353820784883465311632650407642428390870121015194231961652268422003711230464300673442064747718021353070124098860353399152667923871101706221865883573781210935179775604425634694999787251125440854522274810914874307259869602040275941178942581281882159952359658979181144077653354321757595255536158128001163846720319346507296807990793963714961774312119402021297573125165253768017359101557338153772001952444543620071848475663415407442328621060997613243487548847434539665981338717466093020535070271952983943271425371155766600025784423031073429551533945060486222764966687624079324353192992639253731076892135352572321080889819339168668278948281170472624501948409700975760920983724090074717973340788141825195842598096241747610138252643955135259311885045636264188300338539652435997416931322894719878308427600401368074703904097238473945834896186539790594118599310356168436869219485382055780395773881360679549900085123259442529724486666766834641402189915944565309423440650667851948417766779470472041958822043295380326310537494883122180391279678446100139726753892195119117836587662528083690053249004597410947068772912328214304635337283519953648274325833119144459017809607782883583730111857543659958982724531925310588115026307542571493943024453931870179923608166611305426253995833897942971602070338767815033010280120095997252222280801423571094760351925544434929986767817891045559063015953809761875920358937341978962358931125983902598310267193304189215109689156225069659119828323455503059081730735195503721665870288053992138576037035377105178021280129566841984140362872725623214428754302210909472721073474134975514190737043318276626177275996888826027225247133683353452816692779591328861381766349857728936900965749562287103024362590772412219094300871755692625758065709912016659622436080242870024547362036394841255954881727272473653467783647201918303998717627037515724649922289467932322693619177641614618795613956699567783068290316589699430767333508234990790624100202506134057344300695745474682175690441651540636584680463692621274211075399042188716127617787014258864825775223889184599523376292377915585744549477361295525952226578636462118377598473700347971408206994145580719080213590732269233100831759510659019121294795408603640757358750205890208704579670007055262505811420663907459215273309406823649441590891009220296680523325266198911311842016291631076894084723564366808182168657219688268358402785500782804043453710183651096951782335743030504852653738073531074185917705610397395062640355442275156101107261779370634723804990666922161971194259120445084641746383589938239946517395509000859479990136026674261494290066467115067175422177038774507673563742154782905911012619157555870238957001405117822646989944917908301795475876760168094100135837613578591356924455647764464178667115391951357696104864922490083446715486383054477914330097680486878348184672733758436892724310447406807685278625585165092088263813233623148733336714764520450876627614950389949504809560460989604329123358348859990294526400284994280878624039811814884767301216754161106629995553668193123287425702063738352020086863691311733469731741219153633246745325630871347302792174956227014687325867891734558379964351358800959350877556356248810493852999007675135513527792412429277488565888566513247302514710210575352516511814850902750476845518252096331899068527614435138213662152368890578786699432288816028377482035506016029894009119713850179871683633744139275973644017007014763706655703504338121113576415018451821413619823495159601064752712575935185304332875537783057509567425442684712219618709178560783936144511383335649103256405733898667178123972237519316430617013859539474367843392670986712452211189690840236327411496601243483098929941738030588417166613073040067588380432111555379440605497721705942821514886165672771240903387727745629097110134885184374118695655449745736845218066982911045058004299887953899027804383596282409421860556287788428802127553884803728640019441614257499904272009595204654170598104989967504511936471172772220436102614079750809686975176600237187748348016120310234680567112644766123747627852190241202569943534716226660893675219833111813511146503854895025120655772636145473604426859498074396932331297127377157347099713952291182653485155587137336629120242714302503763269501350911612952993785864681307226486008270881333538193703682598867893321238327053297625857382790097826460545598555131836688844628265133798491667839409761353766251798258249663458771950124384040359140849209733754642474488176184070023569580177410177696925077814893386672557898564589851056891960924398841569280696983352240225634570497312245269354193837004843183357196516626721575524193401933099018319309196582920969656247667683659647019595754739345514337413708761517323677204227385674279170698204549953095918872434939524094441678998846319845504852393662972079777452814399418256789457795712552426826089940863317371538896262889629402112108884427376568624527612130371017300785135715404533041507959447776143597437803742436646973247138410492124314138903579092416036406314038149831481905251720937103964026808994832572297954564042701757722904173234796073618787889913318305843069394825961318713816423467218730845133877219086975104942843769325024981656673816260615941768252509993741672883951744066932549653403101452225316189009235376486378482881344209870048096227171226407489571939002918573307460104360729190945767994614929290427981687729426487729952858434647775386906950148984133924540394144680263625402118614317031251117577642829914644533408920976961699098372652361768745605894704968170136974909523072082682887890730190018253425805343421705928713931737993142410852647390948284596418093614138475831136130576108462366837237695913492615824516221552134879244145041756848064120636520170386330129532777699023118648020067556905682295016354931992305914246396217025329747573114094220180199368035026495636955866425906762685687372110339156793839895765565193177883000241613539562437777840801748819373095020699900890899328088397430367736595524891300156633294077907139615464534088791510300651321934486673248275907946807879819425019582622320395131252014109960531260696555404248670549986786923021746989009547850725672978794769888831093487464426400718183160331655511534276155622405474473378049246214952133258527698847336269182649174338987824789278468918828054669982303689939783413747587025805716349413568433929396068192061773331791738208562436433635359863494496890781064019674074436583667071586924521182997893804077137501290858646578905771426833582768978554717687184427726120509266486102051535642840632368481807287940717127966820060727559555904040233178749447346454760628189541512139162918444297651066947969354016866010055196077687335396511614930937570968554559381513789569039251014953265628147011998326992200066392875374713135236421589265126204072887716578358405219646054105435443642166562244565042999010256586927279142752931172082793937751326106052881235373451068372939893580871243869385934389175713376300720319760816604464683937725806909237297523486702916910426369262090199605204121024077648190316014085863558427609537086558164273995349346546314504040199528537252004957805254656251154109252437991326262713609099402902262062836752132305065183934057450112099341464918433323646569371725914489324159006242020612885732926133596808726500045628284557574596592120530341310111827501306961509835515632004310784601906565493806542525229161991819959602752327702249855738824899882707465936355768582560518068964285376850772012220347920993936179268206590142165615925306737944568949070853263568196831861772268249911472615732035807646298116244013316737892788689229032593349861797021994981925739617673075834417098559222170171825712777534491508205278430904619460835217402005838672849709411023266953921445461066215006410674740207009189911951376466904481267253691537162290791385403937560077835153374167747942100384002308951850994548779039346122220865060160500351776264831611153325587705073541279249909859373473787081194253055121436979749914951860535920403830235716352727630874693219622190064260886183676103346002255477477813641012691906569686495012688376296907233961276287223041141813610060264044030035996988919945827397624114613744804059697062576764723766065541618574690527229238228275186799156983390747671146103022776606020061246876477728819096791613354019881402757992174167678799231603963569492851513633647219540611171767387372555728522940054361785176502307544693869307873499110352182532929726044553210797887711449898870911511237250604238753734841257086064069052058452122754533848008205302450456517669518576913200042816758054924811780519832646032445792829730129105318385636821206215531288668564956512613892261367064093953334570526986959692350353094224543865278677673027540402702246384483553239914751363441044050092330361271496081355490531539021002299595756583705381261965683144286057956696622154721695620870013727768536960840704833325132793112232507148630206951245395003735723346807094656483089209801534878705633491092366057554050864111521441481434630437273271045027768661953107858323334857840297160925215326092558932655600672124359464255065996771770388445396181632879614460817789272171836908880126778207430106422524634807454300476492885553409062185153654355474125476152769772667769772777058315801412185688011705028365275543214803488004442979998062157904564161957212784508928489806426497427090579129069217807298769477975112447305991406050629946894280931034216416629935614828130998870745292716048433630818404126469637925843094185442216359084576146078558562473814931427078266215185541603870206876980461747400808324343665382354555109449498431093494759944672673665352517662706772194183191977196378015702169933675083760057163454643671776723387588643405644871566964321041282595645349841388412890420682047007615596916843038999348366793542549210328113363184722592305554383058206941675629992013373175489122037230349072681068534454035993561823576312837767640631013125335212141994611869350833176587852047112364331226765129964171325217513553261867681942338790365468908001827135283584888444111761234101179918709236507184857856221021104009776994453121795022479578069506532965940383987369907240797679040826794007618729547835963492793904576973661643405359792219285870574957481696694062334272619733518136626063735982575552496509807260123668283605928341855848026958413772558970883789942910549800331113884603401939166122186696058491571485733568286149500019097591125218800396419762163559375743718011480559442298730418196808085647265713547612831629200449880315402105530597076666362749328308916880932359290081787411985738317192616728834918402429721290434965526942726402559641463525914348400675867690350382320572934132981593533044446496829441367323442158380761694831219333119819061096142952201536170298575105594326461468505452684975764807808009221335811378197749271768545075538328768874474591593731162470601091244609829424841287520224462594477638749491997840446829257360968534549843266536862844489365704111817793806441616531223600214918768769467398407517176307516849856359201486892943105940202457969622924566644881967576294349535326382171613395757790766370764569570259738800438415805894336137106551859987600754924187211714889295221737721146081154344982665479872580056674724051122007383459271575727715218589946948117940644466399432370044291140747218180224825837736017346685300744985564715420036123593397312914458591522887408719508708632218837288262822884631843717261903305777147651564143822306791847386039147683108141358275755853643597721650028277803713422869688787349795096031108899196143386664068450697420787700280509367203387232629637856038653216432348815557557018469089074647879122436375556668678067610544955017260791142930831285761254481944449473244819093795369008206384631678225064809531810406570254327604385703505922818919878065865412184299217273720955103242251079718077833042609086794273428955735559252723805511440438001239041687716445180226491681641927401106451622431101700056691121733189423400547959684669804298017362570406733282129962153684881404102194463424646220745575643960452985313071409084608499653767803793201899140865814662175319337665970114330608625009829566917638846056762972931464911493704624469351984039534449135141193667933301936617663652555149174982307987072280860859626112660504289296966535652516688885572112276802772743708917389639772257564890533401038855931125679991516589025016486961427207005916056166159702451989051832969278935550303934681219761582183980483960562523091462638447386296039848924386187298507775928792722068554807210497817653286210187476766897248841139560349480376727036316921007350834073865261684507482496448597428134936480372426116704266870831925040997615319076855770327421785010006441984124207396400139603601583810565928413684574119102736420274163723488214524101347716529603128408658419787951116511529827814620379139855006399960326591248525308493690313130100799977191362230866011099929142871249388541612038020411340188887219693477904497527454288072803509305828754420755134816660927879353566521255620139988249628478726214432362853676502591450468377635282587652139156480972141929675549384375582600253168536356731379262475878049445944183429172756988376226261846365452743497662411138451305481449836311789784489732076719508784158618879692955819733250699951402601511675529750575437810242238957925786562128432731202200716730574069286869363930186765958251326499145950260917069347519408975357464016830811798846452473618956056479426358070562563281189269663026479535951097127659136233180866921535788607812759910537171402204506186075374866306350591483916467656723205714516886170790984695932236724946737583099607042589220481550799132752088583781117685214269334786921895240622657921043620348852926267984013953216458791151579050460579710838983371864038024417511347226472547010794793996953554669619726763255229914654933499663234185951450360980344092212206712567698723427940708857070474293173329188523896721971353924492426178641188637790962814486917869468177591717150669111480020759432012061969637795103227089029566085562225452602610460736131368869009281721068198618553780982018471154163630326265699283424155023600978046417108525537612728905335045506135684143775854429677977014660294387687225115363801191758154028120818255606485410787933598921064427244898618961629413418001295130683638609294100083136673372153008352696235737175330738653338204842190308186449184093723944033405244909554558016406460761581010301767488475017661908692946098769201691202181688291040870709560951470416921147027413390052253340834812870353031023919699978597413908593605433599697075604460134242453682496098772581311024732798562072126572499003468293886872304895562253204463602639854225258416464324271611419817802482595563544907219226583863662663750835944314877635156145710745528016159677048442714194435183275698407552677926411261765250615965235457187956673170913319358761628255920783080185206890151504713340386100310055914817852110384754542933389188444120517943969970194112695119526564919594189975418393234647424290702718875223534393673633663200307232747037407123982562024662651974090199762452056198557625760008708173083288344381831070054514493545885422678578551915372292379555494333410174420169600090696415612732297770221217951868376359082255128816470021992348864043959153018464004714321186360622527011541122283802778538911098490201342741014121559769965438877197485376431158229838533123071751132961904559007938064276695819014842627991221792947987348901868471676503827328552059082984529806259250352128451925927986593506132961946796252373972565584157853744567558998032405492186962888490332560851455344391660226257775512916200772796852629387937530454181080729285891989715381797343496187232927614747850192611450413274873242970583408471112333746274617274626582415324271059322506255302314738759251724787322881491455915605036334575424233779160374952502493022351481961381162563911415610326844958072508273431765944054098269765269344579863479709743124498271933113863873159636361218623497261409556079920628316999420072054811525353393946076850019909886553861433495781650089961649079678142901148387645682174914075623767618453775144031475411206760160726460556859257799322070337333398916369504346690694828436629980037414527627716547623825546170883189810868806847853705536480469350958818025360529740793538676511195079373282083146268960071075175520614433784114549950136432446328193346389050936545714506900864483440180428363390513578157273973334537284263372174065775771079830517555721036795976901889958494130195999573017901240193908681356585539661941371794487632079868800371607303220547423572266896801882123424391885984168972277652194032493227314793669234004848976059037958094696041754279613782553781223947646147832926976545162290281701100437846038756544151739433960048915318817576650500951697402415644771293656614253949368884230517400129920556854289853897942669956777027089146513736892206104415481662156804219838476730871787590279209175900695273456682026513373111518000181434120962601658629821076663523361774007837783423709152644063054071807843358061072961105550020415131696373046849213356837265400307509829089364612047891114753037049893952833457824082817386441322710002968311940203323456420826473276233830294639378998375836554559919340866235090967961134004867027123176526663710778725111860354037554487418693519733656621772359229396776463251562023487570113795712096237723431370212031004965152111976013176419408203437348512852602913334915125083119802850177855710725373149139215709105130965059885999931560863655477403551898166733535880048214665099741433761182777723351910741217572841592580872591315074606025634903777263373914461377038021318347447301113032670296917335047701632106616227830027269283365584011791419447808748253360714403296252285775009808599609040936312635621328162071453406104224112083010008587264252112262480142647519426184325853386753874054743491072710049754281159466017136122590440158991600229827801796035194080046513534752698777609527839984368086908989197839693532179980139135442552717910225397010810632143048511378291498511381969143043497500189980681644412123273328307192824362406733196554692677851193152775113446468905504248113361434984604849051258345683266441528489713972376040328212660253516693914082049947320486021627759791771234751097502403078935759937715095021751693555827072533911892334070223832077585802137174778378778391015234132098489423459613692340497998279304144463162707214796117456975719681239291913740982925805561955207434243295982898980529233366415419256367380689494201471241340525072204061794355252555225008748790086568314542835167750542294803274783044056438581591952666758282929705226127628711040134801787224801789684052407924360582742467443076721645270313451354167649668901274786801010295133862698649748212118629040337691568576240699296372493097201628707200189835423690364149270236961938547372480329855045112089192879829874467864129159417531675602533435310626745254507114181483239880607297140234725520713490798398982355268723950909365667878992383712578976248755990443228895388377317348941122757071410959790047919301046740750411435381782464630795989555638991884773781341347070246747362112048986226991888517456251732519341352038115863350123913054441910073628447567514161050410973505852762044489190978901984315485280533985777844313933883994310444465669244550885946314081751220331390681596592510546858013133838152176418210433429788826119630443111388796258746090226130900849975430395771243230616906262919403921439740270894777663702488155499322458825979020631257436910946393252806241642476868495455324938017639371615636847859823715902385421265840615367228607131702674740131145261063765383390315921943469817605358380310612887852051546933639241088467632009567089718367490578163085158138161966882222047570437590614338040725853862083565176998426774523195824182683698270160237414938363496629351576854061397342746470899685618170160551104880971554859118617189668025973541705423985135560018720335079060946421271143993196046527424050882225359773481519135438571253258540493946010865793798058620143366078825219717809025817370870916460452727977153509910340736425020386386718220522879694458387652947951048660717390229327455426785669776865939923416834122274663015062155320502655341460995249356050854921756549134830958906536175693817637473644183378974229700703545206663170929607591989627732423090252397443861014263098687733913882518684316501027964911497737582888913450341148865948670215492101084328080783428089417298008983297536940644969903125399863919581601468995220880662285408414864274786281975546629278814621607171381880180840572084715868906836919393381864278454537956719272397972364651667592011057995663962598535512763558768140213409829016296873429850792471846056874828331381259161962476156902875901072733103299140623864608333378638257926302391590003557609032477281338887339178096966601469615031754226751125993315529674213336300222964906480934582008181061802100227664580400278213336758573019011371754672763059044353131319036092489097246427928455549913490005180295707082919052556781889913899625138662319380053611346224294610248954072404857123256628888931722116432947816190554868054943441034090680716088028227959686950133643814268252170472870863010137301155236861416908375675747637239763185757038109443390564564468524183028148107998376918512127201935044041804604721626939445788377090105974693219720558114078775989772072009689382249303236830515862657281114637996983137517937623215111252349734305240622105244234353732905655163406669506165892878218707756794176080712973781335187117931650033155523822487730653444179453415395202424449703410120874072188109388268167512042299404948179449472732894770111574139441228455521828424922240658752689172272780607116754046973008037039618787796694882555614674384392570115829546661358678671897661297311267200072971553613027503556167817765442287442114729881614802705243806817653573275578602505847084013208837932816008769081300492491473682517035382219619039014999523495387105997351143478292339499187936608692301375596368532373806703591144243268561512109404259582639301678017128669239283231057658851714020211196957064799814031505633045141564414623163763809904402816256917576489142569714163598439317433270237812336938043012892626375382667795034169334323607500248175741808750388475094939454896209740485442635637164995949920980884294790363666297526003243856352945844728944547166209297495496616877414120882130477022816116456044007236351581149729739218966737382647204722642221242016560150284971306332795814302516013694825567014780935790889657134926158161346901806965089556310121218491805847922720691871696316330044858020102860657858591269974637661741463934159569539554203314628026518951167938074573315759846086173702687867602943677780500244673391332431669880354073232388281847501051641331189537036488422690270478052742490603492082954755054003457160184072574536938145531175354210726557835615499874447480427323457880061873149341566046352979779455075359304795687209316724536547208381685855606043801977030764246083489876101345709394877002946175792061952549255757109038525171488525265671045349813419803390641529876343695420256080277614421914318921393908834543131769685101840103844472348948869520981943531906506555354617335814045544837884752526253949665869992058417652780125341033896469818642430034146791380619028059607854888010789705516946215228773090104467462497979992627120951684779568482583341402266477210843362437593741610536734041954738964197895425335036301861400951534766961476255651873823292468547356935802896011536791787303553159378363082248615177770541577576561759358512016692943111138863582159667618830326104164651714846979385422621687161400122378213779774131268977266712992025922017408770076956283473932201088159356286281928563571893384958850603853158179760679479840878360975960149733420572704603521790605647603285569276273495182203236144112584182426247712012035776388895974318232827871314608053533574494297621796789034568169889553518504478325616380709476951699086247100019748809205009521943632378719764870339223811540363475488626845956159755193765410115014067001226927474393888589943859730245414801061235908036274585288493563251585384383242493252666087588908318700709100237377106576985056433928854337658342596750653715005333514489908293887737352051459333049626531415141386124437935885070944688045486975358170212908490787347806814366323322819415827345671356443171537967818058195852464840084032909981943781718177302317003989733050495387356116261023999433259780126893432605584710278764901070923443884634011735556865903585244919370181041626208504299258697435817098133894045934471937493877624232409852832762266604942385129709453245586252103600829286649724174919141988966129558076770979594795306013119159011773943104209049079424448868513086844493705909026006120649425744710353547657859242708130410618546219881830090634588187038755856274911587375421064667951346487586771543838018521348281915812462599335160198935595167968932852205824799421034512715877163345222995418839680448835529753361286837225935390079201666941339091168758803988828869216002373257361588207163516271332810518187602104852180675526648673908900907195138058626735124312215691637902277328705410842037841525683288718046987952513073266340278519059417338920358540395677035611329354482585628287610610698229721420961993509331312171187891078766872044548876089410174798647137882462153955933333275562009439580434537919782280590395959927436913793778664940964048777841748336432684026282932406260081908081804390914556351936856063045089142289645219987798849347477729132797266027658401667890136490508741142126861969862044126965282981087045479861559545338021201155646979976785738920186243599326777689454060508218838227909833627167124490026761178498264377033002081844590009717235204331994708242098771514449751017055643029542821819670009202515615844174205933658148134902693111517093872260026458630561325605792560927332265579346280805683443921373688405650434307396574061017779370141424615493070741360805442100295600095663588977899267630517718781943706761498217564186590116160865408635391513039201316805769034172596453692350806417446562351523929050409479953184074862151210561833854566176652606393713658802521666223576132201941701372664966073252010771947931265282763302413805164907174565964853748354669194523580315301969160480994606814904037819829732360930087135760798621425422096419004367905479049930078372421581954535418371129368658430553842717628035279128821129308351575656599944741788438381565148434229858704245592434693295232821803508333726283791830216591836181554217157448465778420134329982594566884558266171979012180849480332448787258183774805522268151011371745368417870280274452442905474518234674919564188551244421337783521423865979925988203287085109338386829906571994614906290257427686038850511032638544540419184958866538545040571323629681069146814847869659166861842756798460041868762298055562963045953227923051616721591968675849523635298935788507746081537321454642984792310511676357749494622952569497660359473962430995343310404994209677883827002714478494069037073249106444151696053256560586778757417472110827435774315194060757983563629143326397812218946287447798119807225646714664054850131009656786314880090303749338875364183165134982546694673316118123364854397649325026179549357204305402182974871251107404011611405899911093062492312813116340549262571356721818628932786138833718028535056503591952741400869510926167541476792668032109237467087213606278332922386413619594121339278036118276324106004740971111048140003623342714514483334641675466354699731494756643423659493496845884551524150756376605086632827424794136062876041290644913828519456402643153225858624043141838669590633245063000392213192647625962691510904457695301444054618037857503036686212462278639752746667870121003392984873375014475600322100622358029343774955032037012738468163061026570300872275462966796880890587127676361066225722352229739206443093524327228100859973095132528630601105497915644791845004618046762408928925680912930592960642357021061524646205023248966593987324933967376952023991760898474571843531936646529125848064480196520162838795189499336759241485626136995945307287254532463291529110128763770605570609531377527751867923292134955245133089867969165129073841302167573238637575820080363575728002754490327953079900799442541108725693188014667935595834676432868876966610097395749967836593397846346959948950610490383647409504695226063858046758073069912290474089879166872117147527644711604401952718169508289733537148530928937046384420893299771125856840846608339934045689026787516008775461267988015465856522061210953490796707365539702576199431376639960606061106406959330828171876426043573425361756943784848495250108266488395159700490598380812105221111091943323951136051446459834210799058082093716464523127704023160072138543723461267260997870385657091998507595634613248460188409850194287687902268734556500519121546544063829253851276317663922050938345204300773017029940362615434001322763910912988327863920412300445551684054889809080779174636092439334912641164240093880746356607262336695842764583698268734815881961058571835767462009650526065929263548291499045768307210893245857073701660717398194485028842603963660746031184786225831056580870870305567595861341700745402965687634774176431051751036732869245558582082372038601781739405175130437994868822320044378043103170921034261674998000073016094814586374488778522273076330495383944345382770608760763542098445008306247630253572781032783461766970544287155315340016497076657195985041748199087201490875686037783591994719343352772947285537925787684832301101859365800717291186967617655053775030293033830706448912811412025506150896411007623824574488655182581058140345320124754723269087547507078577659732542844459353044992070014538748948226556442223696365544194225441338212225477497535494624827680533336983284156138692363443358553868471111430498248398991803165458638289353799130535222833430137953372954016257623228081138499491876144141322933767106563492528814528239506209022357876684650116660097382753660405446941653422239052108314585847035529352219928272760574821266065291385530345549744551470344939486863429459658431024190785923680224560763936784166270518555178702904073557304620639692453307795782245949710420188043000183881429008173039450507342787013124466860092778581811040911511729374873627887874907465285565434748886831064110051023020875107768918781525622735251550379532444857787277617001964853703555167655209119339343762866284619844026295252183678522367475108809781507098978413086245881522660963551401874495836926917799047120726494905737264286005211403581231076006699518536124862746756375896225299116496066876508261734178484789337295056739007878617925351440621045366250640463728815698232317500596261080921955211150859302955654967538862612972339914628358476048627627027309739202001432248707582337354915246085608210328882974183906478869923273691360048837436615223517058437705545210815513361262142911815615301758882573594892507108879262128641392443309383797333867806131795237315266773820858024701433527009243803266951742119507670884326346442749127558907746863582162166042741315170212458586056233631493164646913946562497471741958354218607748711057338458433689939645913740603382159352243594751626239188685307822821763983237306180204246560477527943104796189724299533029792497481684052893791044947004590864991872727345413508101983881864673609392571930511968645601855782450218231065889437986522432050677379966196955472440585922417953006820451795370043472451762893566770508490213107736625751697335527462302943031203596260953423574397249659211010657817826108745318874803187430823573699195156340957162700992444929749105489851519658664740148225106335367949737142510229341882585117371994499115097583746130105505064197721531929354875371191630262030328588658528480193509225875775597425276584011721342323648084027143356367542046375182552524944329657043861387865901965738802868401894087672816714137033661732650120578653915780703088714261519075001492576112927675193096728453971160213606303090542243966320674323582797889332324405779199278484633339777737655901870574806828678347965624146102899508487399692970750432753029972872297327934442988646412725348160603779707298299173029296308695801996312413304939350493325412355071054461182591141116454534710329881047844067780138077131465400099386306481266614330858206811395838319169545558259426895769841428893743467084107946318932539106963955780706021245974898293564613560788983472419979478564362042094613412387613198865352358312996862268948608408456655606876954501274486631405054735351746873009806322780468912246821460806727627708402402266155485024008952891657117617439020337584877842911289623247059191874691042005848326140677333751027195653994697162517248312230633919328707983800748485726516123434933273356664473358556430235280883924348278760886164943289399166399210488307847777048045728491456303353265070029588906265915498509407972767567129795010098229476228961891591441520032283878773485130979081019129267227103778898053964156362364169154985768408398468861684375407065121039062506128107663799047908879674778069738473170475253442156390387201238806323688037017949308954900776331523063548374256816653361606641980030188287123767481898330246836371488309259283375902278942588060087286038859168849730693948020511221766359138251524278670094406942355120201568377778851824670025651708509249623747726813694284350062938814429987905301056217375459182679973217735029368928065210025396268807498092643458011655715886700443503976505323478287327368840863540002740676783821963522226539290939807367391364082898722017776747168118195856133721583119054682936083236976113450281757830202934845982925000895682630271263295866292147653142233351793093387951357095346377183684092444422096319331295620305575517340067973740614162107923633423805646850092037167152642556371853889571416419772387422610596667396997173168169415435095283193556417705668622215217991151355639707143312893657553844648326201206424338016955862698561022460646069330793847858814367407000599769703649019273328826135329363112403650698652160638987250267238087403396744397830258296894256896741864336134979475245526291426522842419243083388103580053787023999542172113686550275341362211693140694669513186928102574795985605145005021715913317751609957865551981886193211282110709442287240442481153406055895958355815232012184605820563592699303478851132068626627588771446035996656108430725696500563064489187599466596772847171539573612108180841547273142661748933134174632662354222072600146012701206934639520564445543291662986660783089068118790090815295063626782075614388815781351134695366303878412092346942868730839320432333872775496805210302821544324723388845215343727250128589747691460808314404125868181540049187772287869801853454537006526655649170915429522756709222217474112062720656622989806032891672068743654948246108697367225547404812889242471854323605753411672850757552057131156697954584887398742228135887985840783135060548290551482785294891121905383195624228719484759407859398047901094194070671764439032730712135887385049993638838205501683402777496070276844880281912220636888636811043569529300652195528261526991271637277388418993287130563464688227398288763198645709836308917786487086676185485680047672552675414742851028145807403152992197814557756843681110185317498167016426647884090262682824448258027532094549915104518517716546311804904567985713257528117913656278158111288816562285876030875974963849435275676612168959261485030785362045274507752950631012480341804584059432926079854435620093708091821523920371790678121992280496069738238743312626730306795943960954957189577217915597300588693646845576676092450906088202212235719254536715191834872587423919410890444115959932760044506556206461164655665487594247369252336955993030355095817626176231849561906494839673002037763874369343999829430209147073618947932692762445186560239559053705128978163455423320114975994896278424327483788032701418676952621180975006405149755889650293004867605208010491537885413909424531691719987628941277221129464568294860281493181560249677887949813777216229359437811004448060797672429276249510784153446429150842764520002042769470698041775832209097020291657347251582904630910359037842977572651720877244740952267166306005469716387943171196873484688738186656751279298575016363411314627530499019135646823804329970695770150789337728658035712790913767420805655493624646 diff --git a/src/pkg/compress/zlib/example_test.go b/src/pkg/compress/zlib/example_test.go deleted file mode 100644 index 70408895f..000000000 --- a/src/pkg/compress/zlib/example_test.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package zlib_test - -import ( - "bytes" - "compress/zlib" - "fmt" - "io" - "os" -) - -func ExampleNewWriter() { - var b bytes.Buffer - - w := zlib.NewWriter(&b) - w.Write([]byte("hello, world\n")) - w.Close() - fmt.Println(b.Bytes()) - // Output: [120 156 202 72 205 201 201 215 81 40 207 47 202 73 225 2 4 0 0 255 255 33 231 4 147] -} - -func ExampleNewReader() { - buff := []byte{120, 156, 202, 72, 205, 201, 201, 215, 81, 40, 207, - 47, 202, 73, 225, 2, 4, 0, 0, 255, 255, 33, 231, 4, 147} - b := bytes.NewReader(buff) - - r, err := zlib.NewReader(b) - if err != nil { - panic(err) - } - io.Copy(os.Stdout, r) - // Output: hello, world - r.Close() -} diff --git a/src/pkg/compress/zlib/reader.go b/src/pkg/compress/zlib/reader.go deleted file mode 100644 index 9e1aafda9..000000000 --- a/src/pkg/compress/zlib/reader.go +++ /dev/null @@ -1,132 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* -Package zlib implements reading and writing of zlib format compressed data, -as specified in RFC 1950. - -The implementation provides filters that uncompress during reading -and compress during writing. For example, to write compressed data -to a buffer: - - var b bytes.Buffer - w := zlib.NewWriter(&b) - w.Write([]byte("hello, world\n")) - w.Close() - -and to read that data back: - - r, err := zlib.NewReader(&b) - io.Copy(os.Stdout, r) - r.Close() -*/ -package zlib - -import ( - "bufio" - "compress/flate" - "errors" - "hash" - "hash/adler32" - "io" -) - -const zlibDeflate = 8 - -var ( - // ErrChecksum is returned when reading ZLIB data that has an invalid checksum. - ErrChecksum = errors.New("zlib: invalid checksum") - // ErrDictionary is returned when reading ZLIB data that has an invalid dictionary. - ErrDictionary = errors.New("zlib: invalid dictionary") - // ErrHeader is returned when reading ZLIB data that has an invalid header. - ErrHeader = errors.New("zlib: invalid header") -) - -type reader struct { - r flate.Reader - decompressor io.ReadCloser - digest hash.Hash32 - err error - scratch [4]byte -} - -// NewReader creates a new io.ReadCloser. -// Reads from the returned io.ReadCloser read and decompress data from r. -// The implementation buffers input and may read more data than necessary from r. -// It is the caller's responsibility to call Close on the ReadCloser when done. -func NewReader(r io.Reader) (io.ReadCloser, error) { - return NewReaderDict(r, nil) -} - -// NewReaderDict is like NewReader but uses a preset dictionary. -// NewReaderDict ignores the dictionary if the compressed data does not refer to it. -func NewReaderDict(r io.Reader, dict []byte) (io.ReadCloser, error) { - z := new(reader) - if fr, ok := r.(flate.Reader); ok { - z.r = fr - } else { - z.r = bufio.NewReader(r) - } - _, err := io.ReadFull(z.r, z.scratch[0:2]) - if err != nil { - return nil, err - } - h := uint(z.scratch[0])<<8 | uint(z.scratch[1]) - if (z.scratch[0]&0x0f != zlibDeflate) || (h%31 != 0) { - return nil, ErrHeader - } - if z.scratch[1]&0x20 != 0 { - _, err = io.ReadFull(z.r, z.scratch[0:4]) - if err != nil { - return nil, err - } - checksum := uint32(z.scratch[0])<<24 | uint32(z.scratch[1])<<16 | uint32(z.scratch[2])<<8 | uint32(z.scratch[3]) - if checksum != adler32.Checksum(dict) { - return nil, ErrDictionary - } - z.decompressor = flate.NewReaderDict(z.r, dict) - } else { - z.decompressor = flate.NewReader(z.r) - } - z.digest = adler32.New() - return z, nil -} - -func (z *reader) Read(p []byte) (n int, err error) { - if z.err != nil { - return 0, z.err - } - if len(p) == 0 { - return 0, nil - } - - n, err = z.decompressor.Read(p) - z.digest.Write(p[0:n]) - if n != 0 || err != io.EOF { - z.err = err - return - } - - // Finished file; check checksum. - if _, err := io.ReadFull(z.r, z.scratch[0:4]); err != nil { - z.err = err - return 0, err - } - // ZLIB (RFC 1950) is big-endian, unlike GZIP (RFC 1952). - checksum := uint32(z.scratch[0])<<24 | uint32(z.scratch[1])<<16 | uint32(z.scratch[2])<<8 | uint32(z.scratch[3]) - if checksum != z.digest.Sum32() { - z.err = ErrChecksum - return 0, z.err - } - return -} - -// Calling Close does not close the wrapped io.Reader originally passed to NewReader. -func (z *reader) Close() error { - if z.err != nil { - return z.err - } - z.err = z.decompressor.Close() - return z.err -} diff --git a/src/pkg/compress/zlib/reader_test.go b/src/pkg/compress/zlib/reader_test.go deleted file mode 100644 index 218ccba14..000000000 --- a/src/pkg/compress/zlib/reader_test.go +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package zlib - -import ( - "bytes" - "io" - "testing" -) - -type zlibTest struct { - desc string - raw string - compressed []byte - dict []byte - err error -} - -// Compare-to-golden test data was generated by the ZLIB example program at -// http://www.zlib.net/zpipe.c - -var zlibTests = []zlibTest{ - { - "empty", - "", - []byte{0x78, 0x9c, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01}, - nil, - nil, - }, - { - "goodbye", - "goodbye, world", - []byte{ - 0x78, 0x9c, 0x4b, 0xcf, 0xcf, 0x4f, 0x49, 0xaa, - 0x4c, 0xd5, 0x51, 0x28, 0xcf, 0x2f, 0xca, 0x49, - 0x01, 0x00, 0x28, 0xa5, 0x05, 0x5e, - }, - nil, - nil, - }, - { - "bad header", - "", - []byte{0x78, 0x9f, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01}, - nil, - ErrHeader, - }, - { - "bad checksum", - "", - []byte{0x78, 0x9c, 0x03, 0x00, 0x00, 0x00, 0x00, 0xff}, - nil, - ErrChecksum, - }, - { - "not enough data", - "", - []byte{0x78, 0x9c, 0x03, 0x00, 0x00, 0x00}, - nil, - io.ErrUnexpectedEOF, - }, - { - "excess data is silently ignored", - "", - []byte{ - 0x78, 0x9c, 0x03, 0x00, 0x00, 0x00, 0x00, 0x01, - 0x78, 0x9c, 0xff, - }, - nil, - nil, - }, - { - "dictionary", - "Hello, World!\n", - []byte{ - 0x78, 0xbb, 0x1c, 0x32, 0x04, 0x27, 0xf3, 0x00, - 0xb1, 0x75, 0x20, 0x1c, 0x45, 0x2e, 0x00, 0x24, - 0x12, 0x04, 0x74, - }, - []byte{ - 0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x0a, - }, - nil, - }, - { - "wrong dictionary", - "", - []byte{ - 0x78, 0xbb, 0x1c, 0x32, 0x04, 0x27, 0xf3, 0x00, - 0xb1, 0x75, 0x20, 0x1c, 0x45, 0x2e, 0x00, 0x24, - 0x12, 0x04, 0x74, - }, - []byte{ - 0x48, 0x65, 0x6c, 0x6c, - }, - ErrDictionary, - }, -} - -func TestDecompressor(t *testing.T) { - b := new(bytes.Buffer) - for _, tt := range zlibTests { - in := bytes.NewReader(tt.compressed) - zlib, err := NewReaderDict(in, tt.dict) - if err != nil { - if err != tt.err { - t.Errorf("%s: NewReader: %s", tt.desc, err) - } - continue - } - defer zlib.Close() - b.Reset() - n, err := io.Copy(b, zlib) - if err != nil { - if err != tt.err { - t.Errorf("%s: io.Copy: %v want %v", tt.desc, err, tt.err) - } - continue - } - s := b.String() - if s != tt.raw { - t.Errorf("%s: got %d-byte %q want %d-byte %q", tt.desc, n, s, len(tt.raw), tt.raw) - } - } -} diff --git a/src/pkg/compress/zlib/writer.go b/src/pkg/compress/zlib/writer.go deleted file mode 100644 index 3b4313a8b..000000000 --- a/src/pkg/compress/zlib/writer.go +++ /dev/null @@ -1,198 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package zlib - -import ( - "compress/flate" - "fmt" - "hash" - "hash/adler32" - "io" -) - -// These constants are copied from the flate package, so that code that imports -// "compress/zlib" does not also have to import "compress/flate". -const ( - NoCompression = flate.NoCompression - BestSpeed = flate.BestSpeed - BestCompression = flate.BestCompression - DefaultCompression = flate.DefaultCompression -) - -// A Writer takes data written to it and writes the compressed -// form of that data to an underlying writer (see NewWriter). -type Writer struct { - w io.Writer - level int - dict []byte - compressor *flate.Writer - digest hash.Hash32 - err error - scratch [4]byte - wroteHeader bool -} - -// NewWriter creates a new Writer. -// Writes to the returned Writer are compressed and written to w. -// -// It is the caller's responsibility to call Close on the WriteCloser when done. -// Writes may be buffered and not flushed until Close. -func NewWriter(w io.Writer) *Writer { - z, _ := NewWriterLevelDict(w, DefaultCompression, nil) - return z -} - -// NewWriterLevel is like NewWriter but specifies the compression level instead -// of assuming DefaultCompression. -// -// The compression level can be DefaultCompression, NoCompression, or any -// integer value between BestSpeed and BestCompression inclusive. The error -// returned will be nil if the level is valid. -func NewWriterLevel(w io.Writer, level int) (*Writer, error) { - return NewWriterLevelDict(w, level, nil) -} - -// NewWriterLevelDict is like NewWriterLevel but specifies a dictionary to -// compress with. -// -// The dictionary may be nil. If not, its contents should not be modified until -// the Writer is closed. -func NewWriterLevelDict(w io.Writer, level int, dict []byte) (*Writer, error) { - if level < DefaultCompression || level > BestCompression { - return nil, fmt.Errorf("zlib: invalid compression level: %d", level) - } - return &Writer{ - w: w, - level: level, - dict: dict, - }, nil -} - -// Reset clears the state of the Writer z such that it is equivalent to its -// initial state from NewWriterLevel or NewWriterLevelDict, but instead writing -// to w. -func (z *Writer) Reset(w io.Writer) { - z.w = w - // z.level and z.dict left unchanged. - if z.compressor != nil { - z.compressor.Reset(w) - } - if z.digest != nil { - z.digest.Reset() - } - z.err = nil - z.scratch = [4]byte{} - z.wroteHeader = false -} - -// writeHeader writes the ZLIB header. -func (z *Writer) writeHeader() (err error) { - z.wroteHeader = true - // ZLIB has a two-byte header (as documented in RFC 1950). - // The first four bits is the CINFO (compression info), which is 7 for the default deflate window size. - // The next four bits is the CM (compression method), which is 8 for deflate. - z.scratch[0] = 0x78 - // The next two bits is the FLEVEL (compression level). The four values are: - // 0=fastest, 1=fast, 2=default, 3=best. - // The next bit, FDICT, is set if a dictionary is given. - // The final five FCHECK bits form a mod-31 checksum. - switch z.level { - case 0, 1: - z.scratch[1] = 0 << 6 - case 2, 3, 4, 5: - z.scratch[1] = 1 << 6 - case 6, -1: - z.scratch[1] = 2 << 6 - case 7, 8, 9: - z.scratch[1] = 3 << 6 - default: - panic("unreachable") - } - if z.dict != nil { - z.scratch[1] |= 1 << 5 - } - z.scratch[1] += uint8(31 - (uint16(z.scratch[0])<<8+uint16(z.scratch[1]))%31) - if _, err = z.w.Write(z.scratch[0:2]); err != nil { - return err - } - if z.dict != nil { - // The next four bytes are the Adler-32 checksum of the dictionary. - checksum := adler32.Checksum(z.dict) - z.scratch[0] = uint8(checksum >> 24) - z.scratch[1] = uint8(checksum >> 16) - z.scratch[2] = uint8(checksum >> 8) - z.scratch[3] = uint8(checksum >> 0) - if _, err = z.w.Write(z.scratch[0:4]); err != nil { - return err - } - } - if z.compressor == nil { - // Initialize deflater unless the Writer is being reused - // after a Reset call. - z.compressor, err = flate.NewWriterDict(z.w, z.level, z.dict) - if err != nil { - return err - } - z.digest = adler32.New() - } - return nil -} - -// Write writes a compressed form of p to the underlying io.Writer. The -// compressed bytes are not necessarily flushed until the Writer is closed or -// explicitly flushed. -func (z *Writer) Write(p []byte) (n int, err error) { - if !z.wroteHeader { - z.err = z.writeHeader() - } - if z.err != nil { - return 0, z.err - } - if len(p) == 0 { - return 0, nil - } - n, err = z.compressor.Write(p) - if err != nil { - z.err = err - return - } - z.digest.Write(p) - return -} - -// Flush flushes the Writer to its underlying io.Writer. -func (z *Writer) Flush() error { - if !z.wroteHeader { - z.err = z.writeHeader() - } - if z.err != nil { - return z.err - } - z.err = z.compressor.Flush() - return z.err -} - -// Close closes the Writer, flushing any unwritten data to the underlying -// io.Writer, but does not close the underlying io.Writer. -func (z *Writer) Close() error { - if !z.wroteHeader { - z.err = z.writeHeader() - } - if z.err != nil { - return z.err - } - z.err = z.compressor.Close() - if z.err != nil { - return z.err - } - checksum := z.digest.Sum32() - // ZLIB (RFC 1950) is big-endian, unlike GZIP (RFC 1952). - z.scratch[0] = uint8(checksum >> 24) - z.scratch[1] = uint8(checksum >> 16) - z.scratch[2] = uint8(checksum >> 8) - z.scratch[3] = uint8(checksum >> 0) - _, z.err = z.w.Write(z.scratch[0:4]) - return z.err -} diff --git a/src/pkg/compress/zlib/writer_test.go b/src/pkg/compress/zlib/writer_test.go deleted file mode 100644 index 71ba81aaa..000000000 --- a/src/pkg/compress/zlib/writer_test.go +++ /dev/null @@ -1,205 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package zlib - -import ( - "bytes" - "fmt" - "io" - "io/ioutil" - "os" - "testing" -) - -var filenames = []string{ - "../testdata/e.txt", - "../testdata/pi.txt", -} - -var data = []string{ - "test a reasonable sized string that can be compressed", -} - -// Tests that compressing and then decompressing the given file at the given compression level and dictionary -// yields equivalent bytes to the original file. -func testFileLevelDict(t *testing.T, fn string, level int, d string) { - // Read the file, as golden output. - golden, err := os.Open(fn) - if err != nil { - t.Errorf("%s (level=%d, dict=%q): %v", fn, level, d, err) - return - } - defer golden.Close() - b0, err0 := ioutil.ReadAll(golden) - if err0 != nil { - t.Errorf("%s (level=%d, dict=%q): %v", fn, level, d, err0) - return - } - testLevelDict(t, fn, b0, level, d) -} - -func testLevelDict(t *testing.T, fn string, b0 []byte, level int, d string) { - // Make dictionary, if given. - var dict []byte - if d != "" { - dict = []byte(d) - } - - // Push data through a pipe that compresses at the write end, and decompresses at the read end. - piper, pipew := io.Pipe() - defer piper.Close() - go func() { - defer pipew.Close() - zlibw, err := NewWriterLevelDict(pipew, level, dict) - if err != nil { - t.Errorf("%s (level=%d, dict=%q): %v", fn, level, d, err) - return - } - defer zlibw.Close() - _, err = zlibw.Write(b0) - if err != nil { - t.Errorf("%s (level=%d, dict=%q): %v", fn, level, d, err) - return - } - }() - zlibr, err := NewReaderDict(piper, dict) - if err != nil { - t.Errorf("%s (level=%d, dict=%q): %v", fn, level, d, err) - return - } - defer zlibr.Close() - - // Compare the decompressed data. - b1, err1 := ioutil.ReadAll(zlibr) - if err1 != nil { - t.Errorf("%s (level=%d, dict=%q): %v", fn, level, d, err1) - return - } - if len(b0) != len(b1) { - t.Errorf("%s (level=%d, dict=%q): length mismatch %d versus %d", fn, level, d, len(b0), len(b1)) - return - } - for i := 0; i < len(b0); i++ { - if b0[i] != b1[i] { - t.Errorf("%s (level=%d, dict=%q): mismatch at %d, 0x%02x versus 0x%02x\n", fn, level, d, i, b0[i], b1[i]) - return - } - } -} - -func testFileLevelDictReset(t *testing.T, fn string, level int, dict []byte) { - var b0 []byte - var err error - if fn != "" { - b0, err = ioutil.ReadFile(fn) - if err != nil { - t.Errorf("%s (level=%d): %v", fn, level, err) - return - } - } - - // Compress once. - buf := new(bytes.Buffer) - var zlibw *Writer - if dict == nil { - zlibw, err = NewWriterLevel(buf, level) - } else { - zlibw, err = NewWriterLevelDict(buf, level, dict) - } - if err == nil { - _, err = zlibw.Write(b0) - } - if err == nil { - err = zlibw.Close() - } - if err != nil { - t.Errorf("%s (level=%d): %v", fn, level, err) - return - } - out := buf.String() - - // Reset and compress again. - buf2 := new(bytes.Buffer) - zlibw.Reset(buf2) - _, err = zlibw.Write(b0) - if err == nil { - err = zlibw.Close() - } - if err != nil { - t.Errorf("%s (level=%d): %v", fn, level, err) - return - } - out2 := buf2.String() - - if out2 != out { - t.Errorf("%s (level=%d): different output after reset (got %d bytes, expected %d", - fn, level, len(out2), len(out)) - } -} - -func TestWriter(t *testing.T) { - for i, s := range data { - b := []byte(s) - tag := fmt.Sprintf("#%d", i) - testLevelDict(t, tag, b, DefaultCompression, "") - testLevelDict(t, tag, b, NoCompression, "") - for level := BestSpeed; level <= BestCompression; level++ { - testLevelDict(t, tag, b, level, "") - } - } -} - -func TestWriterBig(t *testing.T) { - for _, fn := range filenames { - testFileLevelDict(t, fn, DefaultCompression, "") - testFileLevelDict(t, fn, NoCompression, "") - for level := BestSpeed; level <= BestCompression; level++ { - testFileLevelDict(t, fn, level, "") - } - } -} - -func TestWriterDict(t *testing.T) { - const dictionary = "0123456789." - for _, fn := range filenames { - testFileLevelDict(t, fn, DefaultCompression, dictionary) - testFileLevelDict(t, fn, NoCompression, dictionary) - for level := BestSpeed; level <= BestCompression; level++ { - testFileLevelDict(t, fn, level, dictionary) - } - } -} - -func TestWriterReset(t *testing.T) { - const dictionary = "0123456789." - for _, fn := range filenames { - testFileLevelDictReset(t, fn, NoCompression, nil) - testFileLevelDictReset(t, fn, DefaultCompression, nil) - testFileLevelDictReset(t, fn, NoCompression, []byte(dictionary)) - testFileLevelDictReset(t, fn, DefaultCompression, []byte(dictionary)) - if !testing.Short() { - for level := BestSpeed; level <= BestCompression; level++ { - testFileLevelDictReset(t, fn, level, nil) - } - } - } -} - -func TestWriterDictIsUsed(t *testing.T) { - var input = []byte("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.") - var buf bytes.Buffer - compressor, err := NewWriterLevelDict(&buf, BestCompression, input) - if err != nil { - t.Errorf("error in NewWriterLevelDict: %s", err) - return - } - compressor.Write(input) - compressor.Close() - const expectedMaxSize = 25 - output := buf.Bytes() - if len(output) > expectedMaxSize { - t.Errorf("result too large (got %d, want <= %d bytes). Is the dictionary being used?", len(output), expectedMaxSize) - } -} diff --git a/src/pkg/container/heap/example_intheap_test.go b/src/pkg/container/heap/example_intheap_test.go deleted file mode 100644 index 02d3d8668..000000000 --- a/src/pkg/container/heap/example_intheap_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This example demonstrates an integer heap built using the heap interface. -package heap_test - -import ( - "container/heap" - "fmt" -) - -// An IntHeap is a min-heap of ints. -type IntHeap []int - -func (h IntHeap) Len() int { return len(h) } -func (h IntHeap) Less(i, j int) bool { return h[i] < h[j] } -func (h IntHeap) Swap(i, j int) { h[i], h[j] = h[j], h[i] } - -func (h *IntHeap) Push(x interface{}) { - // Push and Pop use pointer receivers because they modify the slice's length, - // not just its contents. - *h = append(*h, x.(int)) -} - -func (h *IntHeap) Pop() interface{} { - old := *h - n := len(old) - x := old[n-1] - *h = old[0 : n-1] - return x -} - -// This example inserts several ints into an IntHeap, checks the minimum, -// and removes them in order of priority. -func Example_intHeap() { - h := &IntHeap{2, 1, 5} - heap.Init(h) - heap.Push(h, 3) - fmt.Printf("minimum: %d\n", (*h)[0]) - for h.Len() > 0 { - fmt.Printf("%d ", heap.Pop(h)) - } - // Output: - // minimum: 1 - // 1 2 3 5 -} diff --git a/src/pkg/container/heap/example_pq_test.go b/src/pkg/container/heap/example_pq_test.go deleted file mode 100644 index 7017095cb..000000000 --- a/src/pkg/container/heap/example_pq_test.go +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This example demonstrates a priority queue built using the heap interface. -package heap_test - -import ( - "container/heap" - "fmt" -) - -// An Item is something we manage in a priority queue. -type Item struct { - value string // The value of the item; arbitrary. - priority int // The priority of the item in the queue. - // The index is needed by update and is maintained by the heap.Interface methods. - index int // The index of the item in the heap. -} - -// A PriorityQueue implements heap.Interface and holds Items. -type PriorityQueue []*Item - -func (pq PriorityQueue) Len() int { return len(pq) } - -func (pq PriorityQueue) Less(i, j int) bool { - // We want Pop to give us the highest, not lowest, priority so we use greater than here. - return pq[i].priority > pq[j].priority -} - -func (pq PriorityQueue) Swap(i, j int) { - pq[i], pq[j] = pq[j], pq[i] - pq[i].index = i - pq[j].index = j -} - -func (pq *PriorityQueue) Push(x interface{}) { - n := len(*pq) - item := x.(*Item) - item.index = n - *pq = append(*pq, item) -} - -func (pq *PriorityQueue) Pop() interface{} { - old := *pq - n := len(old) - item := old[n-1] - item.index = -1 // for safety - *pq = old[0 : n-1] - return item -} - -// update modifies the priority and value of an Item in the queue. -func (pq *PriorityQueue) update(item *Item, value string, priority int) { - item.value = value - item.priority = priority - heap.Fix(pq, item.index) -} - -// This example creates a PriorityQueue with some items, adds and manipulates an item, -// and then removes the items in priority order. -func Example_priorityQueue() { - // Some items and their priorities. - items := map[string]int{ - "banana": 3, "apple": 2, "pear": 4, - } - - // Create a priority queue, put the items in it, and - // establish the priority queue (heap) invariants. - pq := make(PriorityQueue, len(items)) - i := 0 - for value, priority := range items { - pq[i] = &Item{ - value: value, - priority: priority, - index: i, - } - i++ - } - heap.Init(&pq) - - // Insert a new item and then modify its priority. - item := &Item{ - value: "orange", - priority: 1, - } - heap.Push(&pq, item) - pq.update(item, item.value, 5) - - // Take the items out; they arrive in decreasing priority order. - for pq.Len() > 0 { - item := heap.Pop(&pq).(*Item) - fmt.Printf("%.2d:%s ", item.priority, item.value) - } - // Output: - // 05:orange 04:pear 03:banana 02:apple -} diff --git a/src/pkg/container/heap/heap.go b/src/pkg/container/heap/heap.go deleted file mode 100644 index c467a1191..000000000 --- a/src/pkg/container/heap/heap.go +++ /dev/null @@ -1,117 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package heap provides heap operations for any type that implements -// heap.Interface. A heap is a tree with the property that each node is the -// minimum-valued node in its subtree. -// -// The minimum element in the tree is the root, at index 0. -// -// A heap is a common way to implement a priority queue. To build a priority -// queue, implement the Heap interface with the (negative) priority as the -// ordering for the Less method, so Push adds items while Pop removes the -// highest-priority item from the queue. The Examples include such an -// implementation; the file example_pq_test.go has the complete source. -// -package heap - -import "sort" - -// Any type that implements heap.Interface may be used as a -// min-heap with the following invariants (established after -// Init has been called or if the data is empty or sorted): -// -// !h.Less(j, i) for 0 <= i < h.Len() and 2*i+1 <= j <= 2*i+2 and j < h.Len() -// -// Note that Push and Pop in this interface are for package heap's -// implementation to call. To add and remove things from the heap, -// use heap.Push and heap.Pop. -type Interface interface { - sort.Interface - Push(x interface{}) // add x as element Len() - Pop() interface{} // remove and return element Len() - 1. -} - -// A heap must be initialized before any of the heap operations -// can be used. Init is idempotent with respect to the heap invariants -// and may be called whenever the heap invariants may have been invalidated. -// Its complexity is O(n) where n = h.Len(). -// -func Init(h Interface) { - // heapify - n := h.Len() - for i := n/2 - 1; i >= 0; i-- { - down(h, i, n) - } -} - -// Push pushes the element x onto the heap. The complexity is -// O(log(n)) where n = h.Len(). -// -func Push(h Interface, x interface{}) { - h.Push(x) - up(h, h.Len()-1) -} - -// Pop removes the minimum element (according to Less) from the heap -// and returns it. The complexity is O(log(n)) where n = h.Len(). -// It is equivalent to Remove(h, 0). -// -func Pop(h Interface) interface{} { - n := h.Len() - 1 - h.Swap(0, n) - down(h, 0, n) - return h.Pop() -} - -// Remove removes the element at index i from the heap. -// The complexity is O(log(n)) where n = h.Len(). -// -func Remove(h Interface, i int) interface{} { - n := h.Len() - 1 - if n != i { - h.Swap(i, n) - down(h, i, n) - up(h, i) - } - return h.Pop() -} - -// Fix re-establishes the heap ordering after the element at index i has changed its value. -// Changing the value of the element at index i and then calling Fix is equivalent to, -// but less expensive than, calling Remove(h, i) followed by a Push of the new value. -// The complexity is O(log(n)) where n = h.Len(). -func Fix(h Interface, i int) { - down(h, i, h.Len()) - up(h, i) -} - -func up(h Interface, j int) { - for { - i := (j - 1) / 2 // parent - if i == j || !h.Less(j, i) { - break - } - h.Swap(i, j) - j = i - } -} - -func down(h Interface, i, n int) { - for { - j1 := 2*i + 1 - if j1 >= n || j1 < 0 { // j1 < 0 after int overflow - break - } - j := j1 // left child - if j2 := j1 + 1; j2 < n && !h.Less(j1, j2) { - j = j2 // = 2*i + 2 // right child - } - if !h.Less(j, i) { - break - } - h.Swap(i, j) - i = j - } -} diff --git a/src/pkg/container/heap/heap_test.go b/src/pkg/container/heap/heap_test.go deleted file mode 100644 index b3d054c5f..000000000 --- a/src/pkg/container/heap/heap_test.go +++ /dev/null @@ -1,213 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package heap - -import ( - "math/rand" - "testing" -) - -type myHeap []int - -func (h *myHeap) Less(i, j int) bool { - return (*h)[i] < (*h)[j] -} - -func (h *myHeap) Swap(i, j int) { - (*h)[i], (*h)[j] = (*h)[j], (*h)[i] -} - -func (h *myHeap) Len() int { - return len(*h) -} - -func (h *myHeap) Pop() (v interface{}) { - *h, v = (*h)[:h.Len()-1], (*h)[h.Len()-1] - return -} - -func (h *myHeap) Push(v interface{}) { - *h = append(*h, v.(int)) -} - -func (h myHeap) verify(t *testing.T, i int) { - n := h.Len() - j1 := 2*i + 1 - j2 := 2*i + 2 - if j1 < n { - if h.Less(j1, i) { - t.Errorf("heap invariant invalidated [%d] = %d > [%d] = %d", i, h[i], j1, h[j1]) - return - } - h.verify(t, j1) - } - if j2 < n { - if h.Less(j2, i) { - t.Errorf("heap invariant invalidated [%d] = %d > [%d] = %d", i, h[i], j1, h[j2]) - return - } - h.verify(t, j2) - } -} - -func TestInit0(t *testing.T) { - h := new(myHeap) - for i := 20; i > 0; i-- { - h.Push(0) // all elements are the same - } - Init(h) - h.verify(t, 0) - - for i := 1; h.Len() > 0; i++ { - x := Pop(h).(int) - h.verify(t, 0) - if x != 0 { - t.Errorf("%d.th pop got %d; want %d", i, x, 0) - } - } -} - -func TestInit1(t *testing.T) { - h := new(myHeap) - for i := 20; i > 0; i-- { - h.Push(i) // all elements are different - } - Init(h) - h.verify(t, 0) - - for i := 1; h.Len() > 0; i++ { - x := Pop(h).(int) - h.verify(t, 0) - if x != i { - t.Errorf("%d.th pop got %d; want %d", i, x, i) - } - } -} - -func Test(t *testing.T) { - h := new(myHeap) - h.verify(t, 0) - - for i := 20; i > 10; i-- { - h.Push(i) - } - Init(h) - h.verify(t, 0) - - for i := 10; i > 0; i-- { - Push(h, i) - h.verify(t, 0) - } - - for i := 1; h.Len() > 0; i++ { - x := Pop(h).(int) - if i < 20 { - Push(h, 20+i) - } - h.verify(t, 0) - if x != i { - t.Errorf("%d.th pop got %d; want %d", i, x, i) - } - } -} - -func TestRemove0(t *testing.T) { - h := new(myHeap) - for i := 0; i < 10; i++ { - h.Push(i) - } - h.verify(t, 0) - - for h.Len() > 0 { - i := h.Len() - 1 - x := Remove(h, i).(int) - if x != i { - t.Errorf("Remove(%d) got %d; want %d", i, x, i) - } - h.verify(t, 0) - } -} - -func TestRemove1(t *testing.T) { - h := new(myHeap) - for i := 0; i < 10; i++ { - h.Push(i) - } - h.verify(t, 0) - - for i := 0; h.Len() > 0; i++ { - x := Remove(h, 0).(int) - if x != i { - t.Errorf("Remove(0) got %d; want %d", x, i) - } - h.verify(t, 0) - } -} - -func TestRemove2(t *testing.T) { - N := 10 - - h := new(myHeap) - for i := 0; i < N; i++ { - h.Push(i) - } - h.verify(t, 0) - - m := make(map[int]bool) - for h.Len() > 0 { - m[Remove(h, (h.Len()-1)/2).(int)] = true - h.verify(t, 0) - } - - if len(m) != N { - t.Errorf("len(m) = %d; want %d", len(m), N) - } - for i := 0; i < len(m); i++ { - if !m[i] { - t.Errorf("m[%d] doesn't exist", i) - } - } -} - -func BenchmarkDup(b *testing.B) { - const n = 10000 - h := make(myHeap, n) - for i := 0; i < b.N; i++ { - for j := 0; j < n; j++ { - Push(&h, 0) // all elements are the same - } - for h.Len() > 0 { - Pop(&h) - } - } -} - -func TestFix(t *testing.T) { - h := new(myHeap) - h.verify(t, 0) - - for i := 200; i > 0; i -= 10 { - Push(h, i) - } - h.verify(t, 0) - - if (*h)[0] != 10 { - t.Fatalf("Expected head to be 10, was %d", (*h)[0]) - } - (*h)[0] = 210 - Fix(h, 0) - h.verify(t, 0) - - for i := 100; i > 0; i-- { - elem := rand.Intn(h.Len()) - if i&1 == 0 { - (*h)[elem] *= 2 - } else { - (*h)[elem] /= 2 - } - Fix(h, elem) - h.verify(t, 0) - } -} diff --git a/src/pkg/container/list/example_test.go b/src/pkg/container/list/example_test.go deleted file mode 100644 index 362178401..000000000 --- a/src/pkg/container/list/example_test.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package list_test - -import ( - "container/list" - "fmt" -) - -func Example() { - // Create a new list and put some numbers in it. - l := list.New() - e4 := l.PushBack(4) - e1 := l.PushFront(1) - l.InsertBefore(3, e4) - l.InsertAfter(2, e1) - - // Iterate through list and print its contents. - for e := l.Front(); e != nil; e = e.Next() { - fmt.Println(e.Value) - } - - // Output: - // 1 - // 2 - // 3 - // 4 -} diff --git a/src/pkg/container/list/list.go b/src/pkg/container/list/list.go deleted file mode 100644 index 0256768ef..000000000 --- a/src/pkg/container/list/list.go +++ /dev/null @@ -1,216 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package list implements a doubly linked list. -// -// To iterate over a list (where l is a *List): -// for e := l.Front(); e != nil; e = e.Next() { -// // do something with e.Value -// } -// -package list - -// Element is an element of a linked list. -type Element struct { - // Next and previous pointers in the doubly-linked list of elements. - // To simplify the implementation, internally a list l is implemented - // as a ring, such that &l.root is both the next element of the last - // list element (l.Back()) and the previous element of the first list - // element (l.Front()). - next, prev *Element - - // The list to which this element belongs. - list *List - - // The value stored with this element. - Value interface{} -} - -// Next returns the next list element or nil. -func (e *Element) Next() *Element { - if p := e.next; e.list != nil && p != &e.list.root { - return p - } - return nil -} - -// Prev returns the previous list element or nil. -func (e *Element) Prev() *Element { - if p := e.prev; e.list != nil && p != &e.list.root { - return p - } - return nil -} - -// List represents a doubly linked list. -// The zero value for List is an empty list ready to use. -type List struct { - root Element // sentinel list element, only &root, root.prev, and root.next are used - len int // current list length excluding (this) sentinel element -} - -// Init initializes or clears list l. -func (l *List) Init() *List { - l.root.next = &l.root - l.root.prev = &l.root - l.len = 0 - return l -} - -// New returns an initialized list. -func New() *List { return new(List).Init() } - -// Len returns the number of elements of list l. -// The complexity is O(1). -func (l *List) Len() int { return l.len } - -// Front returns the first element of list l or nil. -func (l *List) Front() *Element { - if l.len == 0 { - return nil - } - return l.root.next -} - -// Back returns the last element of list l or nil. -func (l *List) Back() *Element { - if l.len == 0 { - return nil - } - return l.root.prev -} - -// lazyInit lazily initializes a zero List value. -func (l *List) lazyInit() { - if l.root.next == nil { - l.Init() - } -} - -// insert inserts e after at, increments l.len, and returns e. -func (l *List) insert(e, at *Element) *Element { - n := at.next - at.next = e - e.prev = at - e.next = n - n.prev = e - e.list = l - l.len++ - return e -} - -// insertValue is a convenience wrapper for insert(&Element{Value: v}, at). -func (l *List) insertValue(v interface{}, at *Element) *Element { - return l.insert(&Element{Value: v}, at) -} - -// remove removes e from its list, decrements l.len, and returns e. -func (l *List) remove(e *Element) *Element { - e.prev.next = e.next - e.next.prev = e.prev - e.next = nil // avoid memory leaks - e.prev = nil // avoid memory leaks - e.list = nil - l.len-- - return e -} - -// Remove removes e from l if e is an element of list l. -// It returns the element value e.Value. -func (l *List) Remove(e *Element) interface{} { - if e.list == l { - // if e.list == l, l must have been initialized when e was inserted - // in l or l == nil (e is a zero Element) and l.remove will crash - l.remove(e) - } - return e.Value -} - -// PushFront inserts a new element e with value v at the front of list l and returns e. -func (l *List) PushFront(v interface{}) *Element { - l.lazyInit() - return l.insertValue(v, &l.root) -} - -// PushBack inserts a new element e with value v at the back of list l and returns e. -func (l *List) PushBack(v interface{}) *Element { - l.lazyInit() - return l.insertValue(v, l.root.prev) -} - -// InsertBefore inserts a new element e with value v immediately before mark and returns e. -// If mark is not an element of l, the list is not modified. -func (l *List) InsertBefore(v interface{}, mark *Element) *Element { - if mark.list != l { - return nil - } - // see comment in List.Remove about initialization of l - return l.insertValue(v, mark.prev) -} - -// InsertAfter inserts a new element e with value v immediately after mark and returns e. -// If mark is not an element of l, the list is not modified. -func (l *List) InsertAfter(v interface{}, mark *Element) *Element { - if mark.list != l { - return nil - } - // see comment in List.Remove about initialization of l - return l.insertValue(v, mark) -} - -// MoveToFront moves element e to the front of list l. -// If e is not an element of l, the list is not modified. -func (l *List) MoveToFront(e *Element) { - if e.list != l || l.root.next == e { - return - } - // see comment in List.Remove about initialization of l - l.insert(l.remove(e), &l.root) -} - -// MoveToBack moves element e to the back of list l. -// If e is not an element of l, the list is not modified. -func (l *List) MoveToBack(e *Element) { - if e.list != l || l.root.prev == e { - return - } - // see comment in List.Remove about initialization of l - l.insert(l.remove(e), l.root.prev) -} - -// MoveBefore moves element e to its new position before mark. -// If e or mark is not an element of l, or e == mark, the list is not modified. -func (l *List) MoveBefore(e, mark *Element) { - if e.list != l || e == mark || mark.list != l { - return - } - l.insert(l.remove(e), mark.prev) -} - -// MoveAfter moves element e to its new position after mark. -// If e or mark is not an element of l, or e == mark, the list is not modified. -func (l *List) MoveAfter(e, mark *Element) { - if e.list != l || e == mark || mark.list != l { - return - } - l.insert(l.remove(e), mark) -} - -// PushBackList inserts a copy of an other list at the back of list l. -// The lists l and other may be the same. -func (l *List) PushBackList(other *List) { - l.lazyInit() - for i, e := other.Len(), other.Front(); i > 0; i, e = i-1, e.Next() { - l.insertValue(e.Value, l.root.prev) - } -} - -// PushFrontList inserts a copy of an other list at the front of list l. -// The lists l and other may be the same. -func (l *List) PushFrontList(other *List) { - l.lazyInit() - for i, e := other.Len(), other.Back(); i > 0; i, e = i-1, e.Prev() { - l.insertValue(e.Value, &l.root) - } -} diff --git a/src/pkg/container/list/list_test.go b/src/pkg/container/list/list_test.go deleted file mode 100644 index 4d8bfc2bf..000000000 --- a/src/pkg/container/list/list_test.go +++ /dev/null @@ -1,343 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package list - -import "testing" - -func checkListLen(t *testing.T, l *List, len int) bool { - if n := l.Len(); n != len { - t.Errorf("l.Len() = %d, want %d", n, len) - return false - } - return true -} - -func checkListPointers(t *testing.T, l *List, es []*Element) { - root := &l.root - - if !checkListLen(t, l, len(es)) { - return - } - - // zero length lists must be the zero value or properly initialized (sentinel circle) - if len(es) == 0 { - if l.root.next != nil && l.root.next != root || l.root.prev != nil && l.root.prev != root { - t.Errorf("l.root.next = %p, l.root.prev = %p; both should both be nil or %p", l.root.next, l.root.prev, root) - } - return - } - // len(es) > 0 - - // check internal and external prev/next connections - for i, e := range es { - prev := root - Prev := (*Element)(nil) - if i > 0 { - prev = es[i-1] - Prev = prev - } - if p := e.prev; p != prev { - t.Errorf("elt[%d](%p).prev = %p, want %p", i, e, p, prev) - } - if p := e.Prev(); p != Prev { - t.Errorf("elt[%d](%p).Prev() = %p, want %p", i, e, p, Prev) - } - - next := root - Next := (*Element)(nil) - if i < len(es)-1 { - next = es[i+1] - Next = next - } - if n := e.next; n != next { - t.Errorf("elt[%d](%p).next = %p, want %p", i, e, n, next) - } - if n := e.Next(); n != Next { - t.Errorf("elt[%d](%p).Next() = %p, want %p", i, e, n, Next) - } - } -} - -func TestList(t *testing.T) { - l := New() - checkListPointers(t, l, []*Element{}) - - // Single element list - e := l.PushFront("a") - checkListPointers(t, l, []*Element{e}) - l.MoveToFront(e) - checkListPointers(t, l, []*Element{e}) - l.MoveToBack(e) - checkListPointers(t, l, []*Element{e}) - l.Remove(e) - checkListPointers(t, l, []*Element{}) - - // Bigger list - e2 := l.PushFront(2) - e1 := l.PushFront(1) - e3 := l.PushBack(3) - e4 := l.PushBack("banana") - checkListPointers(t, l, []*Element{e1, e2, e3, e4}) - - l.Remove(e2) - checkListPointers(t, l, []*Element{e1, e3, e4}) - - l.MoveToFront(e3) // move from middle - checkListPointers(t, l, []*Element{e3, e1, e4}) - - l.MoveToFront(e1) - l.MoveToBack(e3) // move from middle - checkListPointers(t, l, []*Element{e1, e4, e3}) - - l.MoveToFront(e3) // move from back - checkListPointers(t, l, []*Element{e3, e1, e4}) - l.MoveToFront(e3) // should be no-op - checkListPointers(t, l, []*Element{e3, e1, e4}) - - l.MoveToBack(e3) // move from front - checkListPointers(t, l, []*Element{e1, e4, e3}) - l.MoveToBack(e3) // should be no-op - checkListPointers(t, l, []*Element{e1, e4, e3}) - - e2 = l.InsertBefore(2, e1) // insert before front - checkListPointers(t, l, []*Element{e2, e1, e4, e3}) - l.Remove(e2) - e2 = l.InsertBefore(2, e4) // insert before middle - checkListPointers(t, l, []*Element{e1, e2, e4, e3}) - l.Remove(e2) - e2 = l.InsertBefore(2, e3) // insert before back - checkListPointers(t, l, []*Element{e1, e4, e2, e3}) - l.Remove(e2) - - e2 = l.InsertAfter(2, e1) // insert after front - checkListPointers(t, l, []*Element{e1, e2, e4, e3}) - l.Remove(e2) - e2 = l.InsertAfter(2, e4) // insert after middle - checkListPointers(t, l, []*Element{e1, e4, e2, e3}) - l.Remove(e2) - e2 = l.InsertAfter(2, e3) // insert after back - checkListPointers(t, l, []*Element{e1, e4, e3, e2}) - l.Remove(e2) - - // Check standard iteration. - sum := 0 - for e := l.Front(); e != nil; e = e.Next() { - if i, ok := e.Value.(int); ok { - sum += i - } - } - if sum != 4 { - t.Errorf("sum over l = %d, want 4", sum) - } - - // Clear all elements by iterating - var next *Element - for e := l.Front(); e != nil; e = next { - next = e.Next() - l.Remove(e) - } - checkListPointers(t, l, []*Element{}) -} - -func checkList(t *testing.T, l *List, es []interface{}) { - if !checkListLen(t, l, len(es)) { - return - } - - i := 0 - for e := l.Front(); e != nil; e = e.Next() { - le := e.Value.(int) - if le != es[i] { - t.Errorf("elt[%d].Value = %v, want %v", i, le, es[i]) - } - i++ - } -} - -func TestExtending(t *testing.T) { - l1 := New() - l2 := New() - - l1.PushBack(1) - l1.PushBack(2) - l1.PushBack(3) - - l2.PushBack(4) - l2.PushBack(5) - - l3 := New() - l3.PushBackList(l1) - checkList(t, l3, []interface{}{1, 2, 3}) - l3.PushBackList(l2) - checkList(t, l3, []interface{}{1, 2, 3, 4, 5}) - - l3 = New() - l3.PushFrontList(l2) - checkList(t, l3, []interface{}{4, 5}) - l3.PushFrontList(l1) - checkList(t, l3, []interface{}{1, 2, 3, 4, 5}) - - checkList(t, l1, []interface{}{1, 2, 3}) - checkList(t, l2, []interface{}{4, 5}) - - l3 = New() - l3.PushBackList(l1) - checkList(t, l3, []interface{}{1, 2, 3}) - l3.PushBackList(l3) - checkList(t, l3, []interface{}{1, 2, 3, 1, 2, 3}) - - l3 = New() - l3.PushFrontList(l1) - checkList(t, l3, []interface{}{1, 2, 3}) - l3.PushFrontList(l3) - checkList(t, l3, []interface{}{1, 2, 3, 1, 2, 3}) - - l3 = New() - l1.PushBackList(l3) - checkList(t, l1, []interface{}{1, 2, 3}) - l1.PushFrontList(l3) - checkList(t, l1, []interface{}{1, 2, 3}) -} - -func TestRemove(t *testing.T) { - l := New() - e1 := l.PushBack(1) - e2 := l.PushBack(2) - checkListPointers(t, l, []*Element{e1, e2}) - e := l.Front() - l.Remove(e) - checkListPointers(t, l, []*Element{e2}) - l.Remove(e) - checkListPointers(t, l, []*Element{e2}) -} - -func TestIssue4103(t *testing.T) { - l1 := New() - l1.PushBack(1) - l1.PushBack(2) - - l2 := New() - l2.PushBack(3) - l2.PushBack(4) - - e := l1.Front() - l2.Remove(e) // l2 should not change because e is not an element of l2 - if n := l2.Len(); n != 2 { - t.Errorf("l2.Len() = %d, want 2", n) - } - - l1.InsertBefore(8, e) - if n := l1.Len(); n != 3 { - t.Errorf("l1.Len() = %d, want 3", n) - } -} - -func TestIssue6349(t *testing.T) { - l := New() - l.PushBack(1) - l.PushBack(2) - - e := l.Front() - l.Remove(e) - if e.Value != 1 { - t.Errorf("e.value = %d, want 1", e.Value) - } - if e.Next() != nil { - t.Errorf("e.Next() != nil") - } - if e.Prev() != nil { - t.Errorf("e.Prev() != nil") - } -} - -func TestMove(t *testing.T) { - l := New() - e1 := l.PushBack(1) - e2 := l.PushBack(2) - e3 := l.PushBack(3) - e4 := l.PushBack(4) - - l.MoveAfter(e3, e3) - checkListPointers(t, l, []*Element{e1, e2, e3, e4}) - l.MoveBefore(e2, e2) - checkListPointers(t, l, []*Element{e1, e2, e3, e4}) - - l.MoveAfter(e3, e2) - checkListPointers(t, l, []*Element{e1, e2, e3, e4}) - l.MoveBefore(e2, e3) - checkListPointers(t, l, []*Element{e1, e2, e3, e4}) - - l.MoveBefore(e2, e4) - checkListPointers(t, l, []*Element{e1, e3, e2, e4}) - e1, e2, e3, e4 = e1, e3, e2, e4 - - l.MoveBefore(e4, e1) - checkListPointers(t, l, []*Element{e4, e1, e2, e3}) - e1, e2, e3, e4 = e4, e1, e2, e3 - - l.MoveAfter(e4, e1) - checkListPointers(t, l, []*Element{e1, e4, e2, e3}) - e1, e2, e3, e4 = e1, e4, e2, e3 - - l.MoveAfter(e2, e3) - checkListPointers(t, l, []*Element{e1, e3, e2, e4}) - e1, e2, e3, e4 = e1, e3, e2, e4 -} - -// Test PushFront, PushBack, PushFrontList, PushBackList with uninitialized List -func TestZeroList(t *testing.T) { - var l1 = new(List) - l1.PushFront(1) - checkList(t, l1, []interface{}{1}) - - var l2 = new(List) - l2.PushBack(1) - checkList(t, l2, []interface{}{1}) - - var l3 = new(List) - l3.PushFrontList(l1) - checkList(t, l3, []interface{}{1}) - - var l4 = new(List) - l4.PushBackList(l2) - checkList(t, l4, []interface{}{1}) -} - -// Test that a list l is not modified when calling InsertBefore with a mark that is not an element of l. -func TestInsertBeforeUnknownMark(t *testing.T) { - var l List - l.PushBack(1) - l.PushBack(2) - l.PushBack(3) - l.InsertBefore(1, new(Element)) - checkList(t, &l, []interface{}{1, 2, 3}) -} - -// Test that a list l is not modified when calling InsertAfter with a mark that is not an element of l. -func TestInsertAfterUnknownMark(t *testing.T) { - var l List - l.PushBack(1) - l.PushBack(2) - l.PushBack(3) - l.InsertAfter(1, new(Element)) - checkList(t, &l, []interface{}{1, 2, 3}) -} - -// Test that a list l is not modified when calling MoveAfter or MoveBefore with a mark that is not an element of l. -func TestMoveUnkownMark(t *testing.T) { - var l1 List - e1 := l1.PushBack(1) - - var l2 List - e2 := l2.PushBack(2) - - l1.MoveAfter(e1, e2) - checkList(t, &l1, []interface{}{1}) - checkList(t, &l2, []interface{}{2}) - - l1.MoveBefore(e1, e2) - checkList(t, &l1, []interface{}{1}) - checkList(t, &l2, []interface{}{2}) -} diff --git a/src/pkg/container/ring/ring.go b/src/pkg/container/ring/ring.go deleted file mode 100644 index 6d3b3e5b3..000000000 --- a/src/pkg/container/ring/ring.go +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package ring implements operations on circular lists. -package ring - -// A Ring is an element of a circular list, or ring. -// Rings do not have a beginning or end; a pointer to any ring element -// serves as reference to the entire ring. Empty rings are represented -// as nil Ring pointers. The zero value for a Ring is a one-element -// ring with a nil Value. -// -type Ring struct { - next, prev *Ring - Value interface{} // for use by client; untouched by this library -} - -func (r *Ring) init() *Ring { - r.next = r - r.prev = r - return r -} - -// Next returns the next ring element. r must not be empty. -func (r *Ring) Next() *Ring { - if r.next == nil { - return r.init() - } - return r.next -} - -// Prev returns the previous ring element. r must not be empty. -func (r *Ring) Prev() *Ring { - if r.next == nil { - return r.init() - } - return r.prev -} - -// Move moves n % r.Len() elements backward (n < 0) or forward (n >= 0) -// in the ring and returns that ring element. r must not be empty. -// -func (r *Ring) Move(n int) *Ring { - if r.next == nil { - return r.init() - } - switch { - case n < 0: - for ; n < 0; n++ { - r = r.prev - } - case n > 0: - for ; n > 0; n-- { - r = r.next - } - } - return r -} - -// New creates a ring of n elements. -func New(n int) *Ring { - if n <= 0 { - return nil - } - r := new(Ring) - p := r - for i := 1; i < n; i++ { - p.next = &Ring{prev: p} - p = p.next - } - p.next = r - r.prev = p - return r -} - -// Link connects ring r with ring s such that r.Next() -// becomes s and returns the original value for r.Next(). -// r must not be empty. -// -// If r and s point to the same ring, linking -// them removes the elements between r and s from the ring. -// The removed elements form a subring and the result is a -// reference to that subring (if no elements were removed, -// the result is still the original value for r.Next(), -// and not nil). -// -// If r and s point to different rings, linking -// them creates a single ring with the elements of s inserted -// after r. The result points to the element following the -// last element of s after insertion. -// -func (r *Ring) Link(s *Ring) *Ring { - n := r.Next() - if s != nil { - p := s.Prev() - // Note: Cannot use multiple assignment because - // evaluation order of LHS is not specified. - r.next = s - s.prev = r - n.prev = p - p.next = n - } - return n -} - -// Unlink removes n % r.Len() elements from the ring r, starting -// at r.Next(). If n % r.Len() == 0, r remains unchanged. -// The result is the removed subring. r must not be empty. -// -func (r *Ring) Unlink(n int) *Ring { - if n <= 0 { - return nil - } - return r.Link(r.Move(n + 1)) -} - -// Len computes the number of elements in ring r. -// It executes in time proportional to the number of elements. -// -func (r *Ring) Len() int { - n := 0 - if r != nil { - n = 1 - for p := r.Next(); p != r; p = p.next { - n++ - } - } - return n -} - -// Do calls function f on each element of the ring, in forward order. -// The behavior of Do is undefined if f changes *r. -func (r *Ring) Do(f func(interface{})) { - if r != nil { - f(r.Value) - for p := r.Next(); p != r; p = p.next { - f(p.Value) - } - } -} diff --git a/src/pkg/container/ring/ring_test.go b/src/pkg/container/ring/ring_test.go deleted file mode 100644 index 552f0e24b..000000000 --- a/src/pkg/container/ring/ring_test.go +++ /dev/null @@ -1,228 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ring - -import ( - "fmt" - "testing" -) - -// For debugging - keep around. -func dump(r *Ring) { - if r == nil { - fmt.Println("empty") - return - } - i, n := 0, r.Len() - for p := r; i < n; p = p.next { - fmt.Printf("%4d: %p = {<- %p | %p ->}\n", i, p, p.prev, p.next) - i++ - } - fmt.Println() -} - -func verify(t *testing.T, r *Ring, N int, sum int) { - // Len - n := r.Len() - if n != N { - t.Errorf("r.Len() == %d; expected %d", n, N) - } - - // iteration - n = 0 - s := 0 - r.Do(func(p interface{}) { - n++ - if p != nil { - s += p.(int) - } - }) - if n != N { - t.Errorf("number of forward iterations == %d; expected %d", n, N) - } - if sum >= 0 && s != sum { - t.Errorf("forward ring sum = %d; expected %d", s, sum) - } - - if r == nil { - return - } - - // connections - if r.next != nil { - var p *Ring // previous element - for q := r; p == nil || q != r; q = q.next { - if p != nil && p != q.prev { - t.Errorf("prev = %p, expected q.prev = %p\n", p, q.prev) - } - p = q - } - if p != r.prev { - t.Errorf("prev = %p, expected r.prev = %p\n", p, r.prev) - } - } - - // Next, Prev - if r.Next() != r.next { - t.Errorf("r.Next() != r.next") - } - if r.Prev() != r.prev { - t.Errorf("r.Prev() != r.prev") - } - - // Move - if r.Move(0) != r { - t.Errorf("r.Move(0) != r") - } - if r.Move(N) != r { - t.Errorf("r.Move(%d) != r", N) - } - if r.Move(-N) != r { - t.Errorf("r.Move(%d) != r", -N) - } - for i := 0; i < 10; i++ { - ni := N + i - mi := ni % N - if r.Move(ni) != r.Move(mi) { - t.Errorf("r.Move(%d) != r.Move(%d)", ni, mi) - } - if r.Move(-ni) != r.Move(-mi) { - t.Errorf("r.Move(%d) != r.Move(%d)", -ni, -mi) - } - } -} - -func TestCornerCases(t *testing.T) { - var ( - r0 *Ring - r1 Ring - ) - // Basics - verify(t, r0, 0, 0) - verify(t, &r1, 1, 0) - // Insert - r1.Link(r0) - verify(t, r0, 0, 0) - verify(t, &r1, 1, 0) - // Insert - r1.Link(r0) - verify(t, r0, 0, 0) - verify(t, &r1, 1, 0) - // Unlink - r1.Unlink(0) - verify(t, &r1, 1, 0) -} - -func makeN(n int) *Ring { - r := New(n) - for i := 1; i <= n; i++ { - r.Value = i - r = r.Next() - } - return r -} - -func sumN(n int) int { return (n*n + n) / 2 } - -func TestNew(t *testing.T) { - for i := 0; i < 10; i++ { - r := New(i) - verify(t, r, i, -1) - } - for i := 0; i < 10; i++ { - r := makeN(i) - verify(t, r, i, sumN(i)) - } -} - -func TestLink1(t *testing.T) { - r1a := makeN(1) - var r1b Ring - r2a := r1a.Link(&r1b) - verify(t, r2a, 2, 1) - if r2a != r1a { - t.Errorf("a) 2-element link failed") - } - - r2b := r2a.Link(r2a.Next()) - verify(t, r2b, 2, 1) - if r2b != r2a.Next() { - t.Errorf("b) 2-element link failed") - } - - r1c := r2b.Link(r2b) - verify(t, r1c, 1, 1) - verify(t, r2b, 1, 0) -} - -func TestLink2(t *testing.T) { - var r0 *Ring - r1a := &Ring{Value: 42} - r1b := &Ring{Value: 77} - r10 := makeN(10) - - r1a.Link(r0) - verify(t, r1a, 1, 42) - - r1a.Link(r1b) - verify(t, r1a, 2, 42+77) - - r10.Link(r0) - verify(t, r10, 10, sumN(10)) - - r10.Link(r1a) - verify(t, r10, 12, sumN(10)+42+77) -} - -func TestLink3(t *testing.T) { - var r Ring - n := 1 - for i := 1; i < 100; i++ { - n += i - verify(t, r.Link(New(i)), n, -1) - } -} - -func TestUnlink(t *testing.T) { - r10 := makeN(10) - s10 := r10.Move(6) - - sum10 := sumN(10) - - verify(t, r10, 10, sum10) - verify(t, s10, 10, sum10) - - r0 := r10.Unlink(0) - verify(t, r0, 0, 0) - - r1 := r10.Unlink(1) - verify(t, r1, 1, 2) - verify(t, r10, 9, sum10-2) - - r9 := r10.Unlink(9) - verify(t, r9, 9, sum10-2) - verify(t, r10, 9, sum10-2) -} - -func TestLinkUnlink(t *testing.T) { - for i := 1; i < 4; i++ { - ri := New(i) - for j := 0; j < i; j++ { - rj := ri.Unlink(j) - verify(t, rj, j, -1) - verify(t, ri, i-j, -1) - ri.Link(rj) - verify(t, ri, i, -1) - } - } -} - -// Test that calling Move() on an empty Ring initializes it. -func TestMoveEmptyRing(t *testing.T) { - var r Ring - - r.Move(1) - verify(t, &r, 1, 0) -} diff --git a/src/pkg/crypto/aes/aes_test.go b/src/pkg/crypto/aes/aes_test.go deleted file mode 100644 index 363180931..000000000 --- a/src/pkg/crypto/aes/aes_test.go +++ /dev/null @@ -1,421 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package aes - -import ( - "testing" -) - -// See const.go for overview of math here. - -// Test that powx is initialized correctly. -// (Can adapt this code to generate it too.) -func TestPowx(t *testing.T) { - p := 1 - for i := 0; i < len(powx); i++ { - if powx[i] != byte(p) { - t.Errorf("powx[%d] = %#x, want %#x", i, powx[i], p) - } - p <<= 1 - if p&0x100 != 0 { - p ^= poly - } - } -} - -// Multiply b and c as GF(2) polynomials modulo poly -func mul(b, c uint32) uint32 { - i := b - j := c - s := uint32(0) - for k := uint32(1); k < 0x100 && j != 0; k <<= 1 { - // Invariant: k == 1<>8 - } - } -} - -// Test that decryption tables are correct. -// (Can adapt this code to generate them too.) -func TestTd(t *testing.T) { - for i := 0; i < 256; i++ { - s := uint32(sbox1[i]) - s9 := mul(s, 0x9) - sb := mul(s, 0xb) - sd := mul(s, 0xd) - se := mul(s, 0xe) - w := se<<24 | s9<<16 | sd<<8 | sb - td := [][256]uint32{td0, td1, td2, td3} - for j := 0; j < 4; j++ { - if x := td[j][i]; x != w { - t.Fatalf("td[%d][%d] = %#x, want %#x", j, i, x, w) - } - w = w<<24 | w>>8 - } - } -} - -// Test vectors are from FIPS 197: -// http://www.csrc.nist.gov/publications/fips/fips197/fips-197.pdf - -// Appendix A of FIPS 197: Key expansion examples -type KeyTest struct { - key []byte - enc []uint32 - dec []uint32 // decryption expansion; not in FIPS 197, computed from C implementation. -} - -var keyTests = []KeyTest{ - { - // A.1. Expansion of a 128-bit Cipher Key - []byte{0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}, - []uint32{ - 0x2b7e1516, 0x28aed2a6, 0xabf71588, 0x09cf4f3c, - 0xa0fafe17, 0x88542cb1, 0x23a33939, 0x2a6c7605, - 0xf2c295f2, 0x7a96b943, 0x5935807a, 0x7359f67f, - 0x3d80477d, 0x4716fe3e, 0x1e237e44, 0x6d7a883b, - 0xef44a541, 0xa8525b7f, 0xb671253b, 0xdb0bad00, - 0xd4d1c6f8, 0x7c839d87, 0xcaf2b8bc, 0x11f915bc, - 0x6d88a37a, 0x110b3efd, 0xdbf98641, 0xca0093fd, - 0x4e54f70e, 0x5f5fc9f3, 0x84a64fb2, 0x4ea6dc4f, - 0xead27321, 0xb58dbad2, 0x312bf560, 0x7f8d292f, - 0xac7766f3, 0x19fadc21, 0x28d12941, 0x575c006e, - 0xd014f9a8, 0xc9ee2589, 0xe13f0cc8, 0xb6630ca6, - }, - []uint32{ - 0xd014f9a8, 0xc9ee2589, 0xe13f0cc8, 0xb6630ca6, - 0xc7b5a63, 0x1319eafe, 0xb0398890, 0x664cfbb4, - 0xdf7d925a, 0x1f62b09d, 0xa320626e, 0xd6757324, - 0x12c07647, 0xc01f22c7, 0xbc42d2f3, 0x7555114a, - 0x6efcd876, 0xd2df5480, 0x7c5df034, 0xc917c3b9, - 0x6ea30afc, 0xbc238cf6, 0xae82a4b4, 0xb54a338d, - 0x90884413, 0xd280860a, 0x12a12842, 0x1bc89739, - 0x7c1f13f7, 0x4208c219, 0xc021ae48, 0x969bf7b, - 0xcc7505eb, 0x3e17d1ee, 0x82296c51, 0xc9481133, - 0x2b3708a7, 0xf262d405, 0xbc3ebdbf, 0x4b617d62, - 0x2b7e1516, 0x28aed2a6, 0xabf71588, 0x9cf4f3c, - }, - }, - { - // A.2. Expansion of a 192-bit Cipher Key - []byte{ - 0x8e, 0x73, 0xb0, 0xf7, 0xda, 0x0e, 0x64, 0x52, 0xc8, 0x10, 0xf3, 0x2b, 0x80, 0x90, 0x79, 0xe5, - 0x62, 0xf8, 0xea, 0xd2, 0x52, 0x2c, 0x6b, 0x7b, - }, - []uint32{ - 0x8e73b0f7, 0xda0e6452, 0xc810f32b, 0x809079e5, - 0x62f8ead2, 0x522c6b7b, 0xfe0c91f7, 0x2402f5a5, - 0xec12068e, 0x6c827f6b, 0x0e7a95b9, 0x5c56fec2, - 0x4db7b4bd, 0x69b54118, 0x85a74796, 0xe92538fd, - 0xe75fad44, 0xbb095386, 0x485af057, 0x21efb14f, - 0xa448f6d9, 0x4d6dce24, 0xaa326360, 0x113b30e6, - 0xa25e7ed5, 0x83b1cf9a, 0x27f93943, 0x6a94f767, - 0xc0a69407, 0xd19da4e1, 0xec1786eb, 0x6fa64971, - 0x485f7032, 0x22cb8755, 0xe26d1352, 0x33f0b7b3, - 0x40beeb28, 0x2f18a259, 0x6747d26b, 0x458c553e, - 0xa7e1466c, 0x9411f1df, 0x821f750a, 0xad07d753, - 0xca400538, 0x8fcc5006, 0x282d166a, 0xbc3ce7b5, - 0xe98ba06f, 0x448c773c, 0x8ecc7204, 0x01002202, - }, - nil, - }, - { - // A.3. Expansion of a 256-bit Cipher Key - []byte{ - 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81, - 0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4, - }, - []uint32{ - 0x603deb10, 0x15ca71be, 0x2b73aef0, 0x857d7781, - 0x1f352c07, 0x3b6108d7, 0x2d9810a3, 0x0914dff4, - 0x9ba35411, 0x8e6925af, 0xa51a8b5f, 0x2067fcde, - 0xa8b09c1a, 0x93d194cd, 0xbe49846e, 0xb75d5b9a, - 0xd59aecb8, 0x5bf3c917, 0xfee94248, 0xde8ebe96, - 0xb5a9328a, 0x2678a647, 0x98312229, 0x2f6c79b3, - 0x812c81ad, 0xdadf48ba, 0x24360af2, 0xfab8b464, - 0x98c5bfc9, 0xbebd198e, 0x268c3ba7, 0x09e04214, - 0x68007bac, 0xb2df3316, 0x96e939e4, 0x6c518d80, - 0xc814e204, 0x76a9fb8a, 0x5025c02d, 0x59c58239, - 0xde136967, 0x6ccc5a71, 0xfa256395, 0x9674ee15, - 0x5886ca5d, 0x2e2f31d7, 0x7e0af1fa, 0x27cf73c3, - 0x749c47ab, 0x18501dda, 0xe2757e4f, 0x7401905a, - 0xcafaaae3, 0xe4d59b34, 0x9adf6ace, 0xbd10190d, - 0xfe4890d1, 0xe6188d0b, 0x046df344, 0x706c631e, - }, - nil, - }, -} - -// Test key expansion against FIPS 197 examples. -func TestExpandKey(t *testing.T) { -L: - for i, tt := range keyTests { - enc := make([]uint32, len(tt.enc)) - var dec []uint32 - if tt.dec != nil { - dec = make([]uint32, len(tt.dec)) - } - // This test could only test Go version of expandKey because asm - // version might use different memory layout for expanded keys - // This is OK because we don't expose expanded keys to the outside - expandKeyGo(tt.key, enc, dec) - for j, v := range enc { - if v != tt.enc[j] { - t.Errorf("key %d: enc[%d] = %#x, want %#x", i, j, v, tt.enc[j]) - continue L - } - } - if dec != nil { - for j, v := range dec { - if v != tt.dec[j] { - t.Errorf("key %d: dec[%d] = %#x, want %#x", i, j, v, tt.dec[j]) - continue L - } - } - } - } -} - -// Appendix B, C of FIPS 197: Cipher examples, Example vectors. -type CryptTest struct { - key []byte - in []byte - out []byte -} - -var encryptTests = []CryptTest{ - { - // Appendix B. - []byte{0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c}, - []byte{0x32, 0x43, 0xf6, 0xa8, 0x88, 0x5a, 0x30, 0x8d, 0x31, 0x31, 0x98, 0xa2, 0xe0, 0x37, 0x07, 0x34}, - []byte{0x39, 0x25, 0x84, 0x1d, 0x02, 0xdc, 0x09, 0xfb, 0xdc, 0x11, 0x85, 0x97, 0x19, 0x6a, 0x0b, 0x32}, - }, - { - // Appendix C.1. AES-128 - []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}, - []byte{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, - []byte{0x69, 0xc4, 0xe0, 0xd8, 0x6a, 0x7b, 0x04, 0x30, 0xd8, 0xcd, 0xb7, 0x80, 0x70, 0xb4, 0xc5, 0x5a}, - }, - { - // Appendix C.2. AES-192 - []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, - }, - []byte{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, - []byte{0xdd, 0xa9, 0x7c, 0xa4, 0x86, 0x4c, 0xdf, 0xe0, 0x6e, 0xaf, 0x70, 0xa0, 0xec, 0x0d, 0x71, 0x91}, - }, - { - // Appendix C.3. AES-256 - []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - }, - []byte{0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}, - []byte{0x8e, 0xa2, 0xb7, 0xca, 0x51, 0x67, 0x45, 0xbf, 0xea, 0xfc, 0x49, 0x90, 0x4b, 0x49, 0x60, 0x89}, - }, -} - -// Test encryptBlock against FIPS 197 examples. -func TestEncryptBlock(t *testing.T) { - for i, tt := range encryptTests { - n := len(tt.key) + 28 - enc := make([]uint32, n) - dec := make([]uint32, n) - expandKey(tt.key, enc, dec) - out := make([]byte, len(tt.in)) - encryptBlock(enc, out, tt.in) - for j, v := range out { - if v != tt.out[j] { - t.Errorf("encryptBlock %d: out[%d] = %#x, want %#x", i, j, v, tt.out[j]) - break - } - } - } -} - -// Test decryptBlock against FIPS 197 examples. -func TestDecryptBlock(t *testing.T) { - for i, tt := range encryptTests { - n := len(tt.key) + 28 - enc := make([]uint32, n) - dec := make([]uint32, n) - expandKey(tt.key, enc, dec) - plain := make([]byte, len(tt.in)) - decryptBlock(dec, plain, tt.out) - for j, v := range plain { - if v != tt.in[j] { - t.Errorf("decryptBlock %d: plain[%d] = %#x, want %#x", i, j, v, tt.in[j]) - break - } - } - } -} - -// Test Cipher Encrypt method against FIPS 197 examples. -func TestCipherEncrypt(t *testing.T) { - for i, tt := range encryptTests { - c, err := NewCipher(tt.key) - if err != nil { - t.Errorf("NewCipher(%d bytes) = %s", len(tt.key), err) - continue - } - out := make([]byte, len(tt.in)) - c.Encrypt(out, tt.in) - for j, v := range out { - if v != tt.out[j] { - t.Errorf("Cipher.Encrypt %d: out[%d] = %#x, want %#x", i, j, v, tt.out[j]) - break - } - } - } -} - -// Test Cipher Decrypt against FIPS 197 examples. -func TestCipherDecrypt(t *testing.T) { - for i, tt := range encryptTests { - c, err := NewCipher(tt.key) - if err != nil { - t.Errorf("NewCipher(%d bytes) = %s", len(tt.key), err) - continue - } - plain := make([]byte, len(tt.in)) - c.Decrypt(plain, tt.out) - for j, v := range plain { - if v != tt.in[j] { - t.Errorf("decryptBlock %d: plain[%d] = %#x, want %#x", i, j, v, tt.in[j]) - break - } - } - } -} - -// Test short input/output. -// Assembly used to not notice. -// See issue 7928. -func TestShortBlocks(t *testing.T) { - bytes := func(n int) []byte { return make([]byte, n) } - - c, _ := NewCipher(bytes(16)) - - mustPanic(t, "crypto/aes: input not full block", func() { c.Encrypt(bytes(1), bytes(1)) }) - mustPanic(t, "crypto/aes: input not full block", func() { c.Decrypt(bytes(1), bytes(1)) }) - mustPanic(t, "crypto/aes: input not full block", func() { c.Encrypt(bytes(100), bytes(1)) }) - mustPanic(t, "crypto/aes: input not full block", func() { c.Decrypt(bytes(100), bytes(1)) }) - mustPanic(t, "crypto/aes: output not full block", func() { c.Encrypt(bytes(1), bytes(100)) }) - mustPanic(t, "crypto/aes: output not full block", func() { c.Decrypt(bytes(1), bytes(100)) }) -} - -func mustPanic(t *testing.T, msg string, f func()) { - defer func() { - err := recover() - if err == nil { - t.Errorf("function did not panic, wanted %q", msg) - } else if err != msg { - t.Errorf("got panic %v, wanted %q", err, msg) - } - }() - f() -} - -func BenchmarkEncrypt(b *testing.B) { - tt := encryptTests[0] - c, err := NewCipher(tt.key) - if err != nil { - b.Fatal("NewCipher:", err) - } - out := make([]byte, len(tt.in)) - b.SetBytes(int64(len(out))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - c.Encrypt(out, tt.in) - } -} - -func BenchmarkDecrypt(b *testing.B) { - tt := encryptTests[0] - c, err := NewCipher(tt.key) - if err != nil { - b.Fatal("NewCipher:", err) - } - out := make([]byte, len(tt.out)) - b.SetBytes(int64(len(out))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - c.Decrypt(out, tt.out) - } -} - -func BenchmarkExpand(b *testing.B) { - tt := encryptTests[0] - n := len(tt.key) + 28 - c := &aesCipher{make([]uint32, n), make([]uint32, n)} - b.ResetTimer() - for i := 0; i < b.N; i++ { - expandKey(tt.key, c.enc, c.dec) - } -} diff --git a/src/pkg/crypto/aes/asm_amd64.s b/src/pkg/crypto/aes/asm_amd64.s deleted file mode 100644 index 6a6e6ac4b..000000000 --- a/src/pkg/crypto/aes/asm_amd64.s +++ /dev/null @@ -1,289 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "textflag.h" - -// func hasAsm() bool -// returns whether AES-NI is supported -TEXT ·hasAsm(SB),NOSPLIT,$0 - XORQ AX, AX - INCL AX - CPUID - SHRQ $25, CX - ANDQ $1, CX - MOVB CX, ret+0(FP) - RET - -// func encryptBlockAsm(nr int, xk *uint32, dst, src *byte) -TEXT ·encryptBlockAsm(SB),NOSPLIT,$0 - MOVQ nr+0(FP), CX - MOVQ xk+8(FP), AX - MOVQ dst+16(FP), DX - MOVQ src+24(FP), BX - MOVUPS 0(AX), X1 - MOVUPS 0(BX), X0 - ADDQ $16, AX - PXOR X1, X0 - SUBQ $12, CX - JE Lenc196 - JB Lenc128 -Lenc256: - MOVUPS 0(AX), X1 - AESENC X1, X0 - MOVUPS 16(AX), X1 - AESENC X1, X0 - ADDQ $32, AX -Lenc196: - MOVUPS 0(AX), X1 - AESENC X1, X0 - MOVUPS 16(AX), X1 - AESENC X1, X0 - ADDQ $32, AX -Lenc128: - MOVUPS 0(AX), X1 - AESENC X1, X0 - MOVUPS 16(AX), X1 - AESENC X1, X0 - MOVUPS 32(AX), X1 - AESENC X1, X0 - MOVUPS 48(AX), X1 - AESENC X1, X0 - MOVUPS 64(AX), X1 - AESENC X1, X0 - MOVUPS 80(AX), X1 - AESENC X1, X0 - MOVUPS 96(AX), X1 - AESENC X1, X0 - MOVUPS 112(AX), X1 - AESENC X1, X0 - MOVUPS 128(AX), X1 - AESENC X1, X0 - MOVUPS 144(AX), X1 - AESENCLAST X1, X0 - MOVUPS X0, 0(DX) - RET - -// func decryptBlockAsm(nr int, xk *uint32, dst, src *byte) -TEXT ·decryptBlockAsm(SB),NOSPLIT,$0 - MOVQ nr+0(FP), CX - MOVQ xk+8(FP), AX - MOVQ dst+16(FP), DX - MOVQ src+24(FP), BX - MOVUPS 0(AX), X1 - MOVUPS 0(BX), X0 - ADDQ $16, AX - PXOR X1, X0 - SUBQ $12, CX - JE Ldec196 - JB Ldec128 -Ldec256: - MOVUPS 0(AX), X1 - AESDEC X1, X0 - MOVUPS 16(AX), X1 - AESDEC X1, X0 - ADDQ $32, AX -Ldec196: - MOVUPS 0(AX), X1 - AESDEC X1, X0 - MOVUPS 16(AX), X1 - AESDEC X1, X0 - ADDQ $32, AX -Ldec128: - MOVUPS 0(AX), X1 - AESDEC X1, X0 - MOVUPS 16(AX), X1 - AESDEC X1, X0 - MOVUPS 32(AX), X1 - AESDEC X1, X0 - MOVUPS 48(AX), X1 - AESDEC X1, X0 - MOVUPS 64(AX), X1 - AESDEC X1, X0 - MOVUPS 80(AX), X1 - AESDEC X1, X0 - MOVUPS 96(AX), X1 - AESDEC X1, X0 - MOVUPS 112(AX), X1 - AESDEC X1, X0 - MOVUPS 128(AX), X1 - AESDEC X1, X0 - MOVUPS 144(AX), X1 - AESDECLAST X1, X0 - MOVUPS X0, 0(DX) - RET - -// func expandKeyAsm(nr int, key *byte, enc, dec *uint32) { -// Note that round keys are stored in uint128 format, not uint32 -TEXT ·expandKeyAsm(SB),NOSPLIT,$0 - MOVQ nr+0(FP), CX - MOVQ key+8(FP), AX - MOVQ enc+16(FP), BX - MOVQ dec+24(FP), DX - MOVUPS (AX), X0 - // enc - MOVUPS X0, (BX) - ADDQ $16, BX - PXOR X4, X4 // _expand_key_* expect X4 to be zero - CMPL CX, $12 - JE Lexp_enc196 - JB Lexp_enc128 -Lexp_enc256: - MOVUPS 16(AX), X2 - MOVUPS X2, (BX) - ADDQ $16, BX - AESKEYGENASSIST $0x01, X2, X1 - CALL _expand_key_256a<>(SB) - AESKEYGENASSIST $0x01, X0, X1 - CALL _expand_key_256b<>(SB) - AESKEYGENASSIST $0x02, X2, X1 - CALL _expand_key_256a<>(SB) - AESKEYGENASSIST $0x02, X0, X1 - CALL _expand_key_256b<>(SB) - AESKEYGENASSIST $0x04, X2, X1 - CALL _expand_key_256a<>(SB) - AESKEYGENASSIST $0x04, X0, X1 - CALL _expand_key_256b<>(SB) - AESKEYGENASSIST $0x08, X2, X1 - CALL _expand_key_256a<>(SB) - AESKEYGENASSIST $0x08, X0, X1 - CALL _expand_key_256b<>(SB) - AESKEYGENASSIST $0x10, X2, X1 - CALL _expand_key_256a<>(SB) - AESKEYGENASSIST $0x10, X0, X1 - CALL _expand_key_256b<>(SB) - AESKEYGENASSIST $0x20, X2, X1 - CALL _expand_key_256a<>(SB) - AESKEYGENASSIST $0x20, X0, X1 - CALL _expand_key_256b<>(SB) - AESKEYGENASSIST $0x40, X2, X1 - CALL _expand_key_256a<>(SB) - JMP Lexp_dec -Lexp_enc196: - MOVQ 16(AX), X2 - AESKEYGENASSIST $0x01, X2, X1 - CALL _expand_key_192a<>(SB) - AESKEYGENASSIST $0x02, X2, X1 - CALL _expand_key_192b<>(SB) - AESKEYGENASSIST $0x04, X2, X1 - CALL _expand_key_192a<>(SB) - AESKEYGENASSIST $0x08, X2, X1 - CALL _expand_key_192b<>(SB) - AESKEYGENASSIST $0x10, X2, X1 - CALL _expand_key_192a<>(SB) - AESKEYGENASSIST $0x20, X2, X1 - CALL _expand_key_192b<>(SB) - AESKEYGENASSIST $0x40, X2, X1 - CALL _expand_key_192a<>(SB) - AESKEYGENASSIST $0x80, X2, X1 - CALL _expand_key_192b<>(SB) - JMP Lexp_dec -Lexp_enc128: - AESKEYGENASSIST $0x01, X0, X1 - CALL _expand_key_128<>(SB) - AESKEYGENASSIST $0x02, X0, X1 - CALL _expand_key_128<>(SB) - AESKEYGENASSIST $0x04, X0, X1 - CALL _expand_key_128<>(SB) - AESKEYGENASSIST $0x08, X0, X1 - CALL _expand_key_128<>(SB) - AESKEYGENASSIST $0x10, X0, X1 - CALL _expand_key_128<>(SB) - AESKEYGENASSIST $0x20, X0, X1 - CALL _expand_key_128<>(SB) - AESKEYGENASSIST $0x40, X0, X1 - CALL _expand_key_128<>(SB) - AESKEYGENASSIST $0x80, X0, X1 - CALL _expand_key_128<>(SB) - AESKEYGENASSIST $0x1b, X0, X1 - CALL _expand_key_128<>(SB) - AESKEYGENASSIST $0x36, X0, X1 - CALL _expand_key_128<>(SB) -Lexp_dec: - // dec - SUBQ $16, BX - MOVUPS (BX), X1 - MOVUPS X1, (DX) - DECQ CX -Lexp_dec_loop: - MOVUPS -16(BX), X1 - AESIMC X1, X0 - MOVUPS X0, 16(DX) - SUBQ $16, BX - ADDQ $16, DX - DECQ CX - JNZ Lexp_dec_loop - MOVUPS -16(BX), X0 - MOVUPS X0, 16(DX) - RET - -#define PSHUFD_X0_X0_ BYTE $0x66; BYTE $0x0f; BYTE $0x70; BYTE $0xc0 -#define PSHUFD_X1_X1_ BYTE $0x66; BYTE $0x0f; BYTE $0x70; BYTE $0xc9 -TEXT _expand_key_128<>(SB),NOSPLIT,$0 - PSHUFD $0xff, X1, X1 - SHUFPS $0x10, X0, X4 - PXOR X4, X0 - SHUFPS $0x8c, X0, X4 - PXOR X4, X0 - PXOR X1, X0 - MOVUPS X0, (BX) - ADDQ $16, BX - RET - -#define PSLLDQ_X5_ BYTE $0x66; BYTE $0x0f; BYTE $0x73; BYTE $0xfd -#define PSHUFD_X0_X3_ BYTE $0x66; BYTE $0x0f; BYTE $0x70; BYTE $0xd8 -TEXT _expand_key_192a<>(SB),NOSPLIT,$0 - PSHUFD $0x55, X1, X1 - SHUFPS $0x10, X0, X4 - PXOR X4, X0 - SHUFPS $0x8c, X0, X4 - PXOR X4, X0 - PXOR X1, X0 - - MOVAPS X2, X5 - MOVAPS X2, X6 - PSLLDQ_X5_; BYTE $0x4 - PSHUFD $0xff, X0, X3 - PXOR X3, X2 - PXOR X5, X2 - - MOVAPS X0, X1 - SHUFPS $0x44, X0, X6 - MOVUPS X6, (BX) - SHUFPS $0x4e, X2, X1 - MOVUPS X1, 16(BX) - ADDQ $32, BX - RET - -TEXT _expand_key_192b<>(SB),NOSPLIT,$0 - PSHUFD $0x55, X1, X1 - SHUFPS $0x10, X0, X4 - PXOR X4, X0 - SHUFPS $0x8c, X0, X4 - PXOR X4, X0 - PXOR X1, X0 - - MOVAPS X2, X5 - PSLLDQ_X5_; BYTE $0x4 - PSHUFD $0xff, X0, X3 - PXOR X3, X2 - PXOR X5, X2 - - MOVUPS X0, (BX) - ADDQ $16, BX - RET - -TEXT _expand_key_256a<>(SB),NOSPLIT,$0 - JMP _expand_key_128<>(SB) - -TEXT _expand_key_256b<>(SB),NOSPLIT,$0 - PSHUFD $0xaa, X1, X1 - SHUFPS $0x10, X2, X4 - PXOR X4, X2 - SHUFPS $0x8c, X2, X4 - PXOR X4, X2 - PXOR X1, X2 - - MOVUPS X2, (BX) - ADDQ $16, BX - RET diff --git a/src/pkg/crypto/aes/block.go b/src/pkg/crypto/aes/block.go deleted file mode 100644 index 57a7e9e25..000000000 --- a/src/pkg/crypto/aes/block.go +++ /dev/null @@ -1,176 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This Go implementation is derived in part from the reference -// ANSI C implementation, which carries the following notice: -// -// rijndael-alg-fst.c -// -// @version 3.0 (December 2000) -// -// Optimised ANSI C code for the Rijndael cipher (now AES) -// -// @author Vincent Rijmen -// @author Antoon Bosselaers -// @author Paulo Barreto -// -// This code is hereby placed in the public domain. -// -// THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''AS IS'' AND ANY EXPRESS -// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE -// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR -// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, -// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -// OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// See FIPS 197 for specification, and see Daemen and Rijmen's Rijndael submission -// for implementation details. -// http://www.csrc.nist.gov/publications/fips/fips197/fips-197.pdf -// http://csrc.nist.gov/archive/aes/rijndael/Rijndael-ammended.pdf - -package aes - -// Encrypt one block from src into dst, using the expanded key xk. -func encryptBlockGo(xk []uint32, dst, src []byte) { - var s0, s1, s2, s3, t0, t1, t2, t3 uint32 - - s0 = uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]) - s1 = uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]) - s2 = uint32(src[8])<<24 | uint32(src[9])<<16 | uint32(src[10])<<8 | uint32(src[11]) - s3 = uint32(src[12])<<24 | uint32(src[13])<<16 | uint32(src[14])<<8 | uint32(src[15]) - - // First round just XORs input with key. - s0 ^= xk[0] - s1 ^= xk[1] - s2 ^= xk[2] - s3 ^= xk[3] - - // Middle rounds shuffle using tables. - // Number of rounds is set by length of expanded key. - nr := len(xk)/4 - 2 // - 2: one above, one more below - k := 4 - for r := 0; r < nr; r++ { - t0 = xk[k+0] ^ te0[uint8(s0>>24)] ^ te1[uint8(s1>>16)] ^ te2[uint8(s2>>8)] ^ te3[uint8(s3)] - t1 = xk[k+1] ^ te0[uint8(s1>>24)] ^ te1[uint8(s2>>16)] ^ te2[uint8(s3>>8)] ^ te3[uint8(s0)] - t2 = xk[k+2] ^ te0[uint8(s2>>24)] ^ te1[uint8(s3>>16)] ^ te2[uint8(s0>>8)] ^ te3[uint8(s1)] - t3 = xk[k+3] ^ te0[uint8(s3>>24)] ^ te1[uint8(s0>>16)] ^ te2[uint8(s1>>8)] ^ te3[uint8(s2)] - k += 4 - s0, s1, s2, s3 = t0, t1, t2, t3 - } - - // Last round uses s-box directly and XORs to produce output. - s0 = uint32(sbox0[t0>>24])<<24 | uint32(sbox0[t1>>16&0xff])<<16 | uint32(sbox0[t2>>8&0xff])<<8 | uint32(sbox0[t3&0xff]) - s1 = uint32(sbox0[t1>>24])<<24 | uint32(sbox0[t2>>16&0xff])<<16 | uint32(sbox0[t3>>8&0xff])<<8 | uint32(sbox0[t0&0xff]) - s2 = uint32(sbox0[t2>>24])<<24 | uint32(sbox0[t3>>16&0xff])<<16 | uint32(sbox0[t0>>8&0xff])<<8 | uint32(sbox0[t1&0xff]) - s3 = uint32(sbox0[t3>>24])<<24 | uint32(sbox0[t0>>16&0xff])<<16 | uint32(sbox0[t1>>8&0xff])<<8 | uint32(sbox0[t2&0xff]) - - s0 ^= xk[k+0] - s1 ^= xk[k+1] - s2 ^= xk[k+2] - s3 ^= xk[k+3] - - dst[0], dst[1], dst[2], dst[3] = byte(s0>>24), byte(s0>>16), byte(s0>>8), byte(s0) - dst[4], dst[5], dst[6], dst[7] = byte(s1>>24), byte(s1>>16), byte(s1>>8), byte(s1) - dst[8], dst[9], dst[10], dst[11] = byte(s2>>24), byte(s2>>16), byte(s2>>8), byte(s2) - dst[12], dst[13], dst[14], dst[15] = byte(s3>>24), byte(s3>>16), byte(s3>>8), byte(s3) -} - -// Decrypt one block from src into dst, using the expanded key xk. -func decryptBlockGo(xk []uint32, dst, src []byte) { - var s0, s1, s2, s3, t0, t1, t2, t3 uint32 - - s0 = uint32(src[0])<<24 | uint32(src[1])<<16 | uint32(src[2])<<8 | uint32(src[3]) - s1 = uint32(src[4])<<24 | uint32(src[5])<<16 | uint32(src[6])<<8 | uint32(src[7]) - s2 = uint32(src[8])<<24 | uint32(src[9])<<16 | uint32(src[10])<<8 | uint32(src[11]) - s3 = uint32(src[12])<<24 | uint32(src[13])<<16 | uint32(src[14])<<8 | uint32(src[15]) - - // First round just XORs input with key. - s0 ^= xk[0] - s1 ^= xk[1] - s2 ^= xk[2] - s3 ^= xk[3] - - // Middle rounds shuffle using tables. - // Number of rounds is set by length of expanded key. - nr := len(xk)/4 - 2 // - 2: one above, one more below - k := 4 - for r := 0; r < nr; r++ { - t0 = xk[k+0] ^ td0[uint8(s0>>24)] ^ td1[uint8(s3>>16)] ^ td2[uint8(s2>>8)] ^ td3[uint8(s1)] - t1 = xk[k+1] ^ td0[uint8(s1>>24)] ^ td1[uint8(s0>>16)] ^ td2[uint8(s3>>8)] ^ td3[uint8(s2)] - t2 = xk[k+2] ^ td0[uint8(s2>>24)] ^ td1[uint8(s1>>16)] ^ td2[uint8(s0>>8)] ^ td3[uint8(s3)] - t3 = xk[k+3] ^ td0[uint8(s3>>24)] ^ td1[uint8(s2>>16)] ^ td2[uint8(s1>>8)] ^ td3[uint8(s0)] - k += 4 - s0, s1, s2, s3 = t0, t1, t2, t3 - } - - // Last round uses s-box directly and XORs to produce output. - s0 = uint32(sbox1[t0>>24])<<24 | uint32(sbox1[t3>>16&0xff])<<16 | uint32(sbox1[t2>>8&0xff])<<8 | uint32(sbox1[t1&0xff]) - s1 = uint32(sbox1[t1>>24])<<24 | uint32(sbox1[t0>>16&0xff])<<16 | uint32(sbox1[t3>>8&0xff])<<8 | uint32(sbox1[t2&0xff]) - s2 = uint32(sbox1[t2>>24])<<24 | uint32(sbox1[t1>>16&0xff])<<16 | uint32(sbox1[t0>>8&0xff])<<8 | uint32(sbox1[t3&0xff]) - s3 = uint32(sbox1[t3>>24])<<24 | uint32(sbox1[t2>>16&0xff])<<16 | uint32(sbox1[t1>>8&0xff])<<8 | uint32(sbox1[t0&0xff]) - - s0 ^= xk[k+0] - s1 ^= xk[k+1] - s2 ^= xk[k+2] - s3 ^= xk[k+3] - - dst[0], dst[1], dst[2], dst[3] = byte(s0>>24), byte(s0>>16), byte(s0>>8), byte(s0) - dst[4], dst[5], dst[6], dst[7] = byte(s1>>24), byte(s1>>16), byte(s1>>8), byte(s1) - dst[8], dst[9], dst[10], dst[11] = byte(s2>>24), byte(s2>>16), byte(s2>>8), byte(s2) - dst[12], dst[13], dst[14], dst[15] = byte(s3>>24), byte(s3>>16), byte(s3>>8), byte(s3) -} - -// Apply sbox0 to each byte in w. -func subw(w uint32) uint32 { - return uint32(sbox0[w>>24])<<24 | - uint32(sbox0[w>>16&0xff])<<16 | - uint32(sbox0[w>>8&0xff])<<8 | - uint32(sbox0[w&0xff]) -} - -// Rotate -func rotw(w uint32) uint32 { return w<<8 | w>>24 } - -// Key expansion algorithm. See FIPS-197, Figure 11. -// Their rcon[i] is our powx[i-1] << 24. -func expandKeyGo(key []byte, enc, dec []uint32) { - // Encryption key setup. - var i int - nk := len(key) / 4 - for i = 0; i < nk; i++ { - enc[i] = uint32(key[4*i])<<24 | uint32(key[4*i+1])<<16 | uint32(key[4*i+2])<<8 | uint32(key[4*i+3]) - } - for ; i < len(enc); i++ { - t := enc[i-1] - if i%nk == 0 { - t = subw(rotw(t)) ^ (uint32(powx[i/nk-1]) << 24) - } else if nk > 6 && i%nk == 4 { - t = subw(t) - } - enc[i] = enc[i-nk] ^ t - } - - // Derive decryption key from encryption key. - // Reverse the 4-word round key sets from enc to produce dec. - // All sets but the first and last get the MixColumn transform applied. - if dec == nil { - return - } - n := len(enc) - for i := 0; i < n; i += 4 { - ei := n - i - 4 - for j := 0; j < 4; j++ { - x := enc[ei+j] - if i > 0 && i+4 < n { - x = td0[sbox0[x>>24]] ^ td1[sbox0[x>>16&0xff]] ^ td2[sbox0[x>>8&0xff]] ^ td3[sbox0[x&0xff]] - } - dec[i+j] = x - } - } -} diff --git a/src/pkg/crypto/aes/cipher.go b/src/pkg/crypto/aes/cipher.go deleted file mode 100644 index 2c6bb0a89..000000000 --- a/src/pkg/crypto/aes/cipher.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package aes - -import ( - "crypto/cipher" - "strconv" -) - -// The AES block size in bytes. -const BlockSize = 16 - -// A cipher is an instance of AES encryption using a particular key. -type aesCipher struct { - enc []uint32 - dec []uint32 -} - -type KeySizeError int - -func (k KeySizeError) Error() string { - return "crypto/aes: invalid key size " + strconv.Itoa(int(k)) -} - -// NewCipher creates and returns a new cipher.Block. -// The key argument should be the AES key, -// either 16, 24, or 32 bytes to select -// AES-128, AES-192, or AES-256. -func NewCipher(key []byte) (cipher.Block, error) { - k := len(key) - switch k { - default: - return nil, KeySizeError(k) - case 16, 24, 32: - break - } - - n := k + 28 - c := &aesCipher{make([]uint32, n), make([]uint32, n)} - expandKey(key, c.enc, c.dec) - return c, nil -} - -func (c *aesCipher) BlockSize() int { return BlockSize } - -func (c *aesCipher) Encrypt(dst, src []byte) { - if len(src) < BlockSize { - panic("crypto/aes: input not full block") - } - if len(dst) < BlockSize { - panic("crypto/aes: output not full block") - } - encryptBlock(c.enc, dst, src) -} - -func (c *aesCipher) Decrypt(dst, src []byte) { - if len(src) < BlockSize { - panic("crypto/aes: input not full block") - } - if len(dst) < BlockSize { - panic("crypto/aes: output not full block") - } - decryptBlock(c.dec, dst, src) -} diff --git a/src/pkg/crypto/aes/cipher_asm.go b/src/pkg/crypto/aes/cipher_asm.go deleted file mode 100644 index 964eaaa6f..000000000 --- a/src/pkg/crypto/aes/cipher_asm.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build amd64 - -package aes - -// defined in asm_$GOARCH.s -func hasAsm() bool -func encryptBlockAsm(nr int, xk *uint32, dst, src *byte) -func decryptBlockAsm(nr int, xk *uint32, dst, src *byte) -func expandKeyAsm(nr int, key *byte, enc *uint32, dec *uint32) - -var useAsm = hasAsm() - -func encryptBlock(xk []uint32, dst, src []byte) { - if useAsm { - encryptBlockAsm(len(xk)/4-1, &xk[0], &dst[0], &src[0]) - } else { - encryptBlockGo(xk, dst, src) - } -} - -func decryptBlock(xk []uint32, dst, src []byte) { - if useAsm { - decryptBlockAsm(len(xk)/4-1, &xk[0], &dst[0], &src[0]) - } else { - decryptBlockGo(xk, dst, src) - } -} - -func expandKey(key []byte, enc, dec []uint32) { - if useAsm { - rounds := 10 - switch len(key) { - case 128 / 8: - rounds = 10 - case 192 / 8: - rounds = 12 - case 256 / 8: - rounds = 14 - } - expandKeyAsm(rounds, &key[0], &enc[0], &dec[0]) - } else { - expandKeyGo(key, enc, dec) - } -} diff --git a/src/pkg/crypto/aes/cipher_generic.go b/src/pkg/crypto/aes/cipher_generic.go deleted file mode 100644 index 1714e0f1e..000000000 --- a/src/pkg/crypto/aes/cipher_generic.go +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !amd64 - -package aes - -func encryptBlock(xk []uint32, dst, src []byte) { - encryptBlockGo(xk, dst, src) -} - -func decryptBlock(xk []uint32, dst, src []byte) { - decryptBlockGo(xk, dst, src) -} - -func expandKey(key []byte, enc, dec []uint32) { - expandKeyGo(key, enc, dec) -} diff --git a/src/pkg/crypto/aes/const.go b/src/pkg/crypto/aes/const.go deleted file mode 100644 index aee73a7c5..000000000 --- a/src/pkg/crypto/aes/const.go +++ /dev/null @@ -1,358 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package aes implements AES encryption (formerly Rijndael), as defined in -// U.S. Federal Information Processing Standards Publication 197. -package aes - -// This file contains AES constants - 8720 bytes of initialized data. - -// http://www.csrc.nist.gov/publications/fips/fips197/fips-197.pdf - -// AES is based on the mathematical behavior of binary polynomials -// (polynomials over GF(2)) modulo the irreducible polynomial x⁸ + x⁴ + x³ + x + 1. -// Addition of these binary polynomials corresponds to binary xor. -// Reducing mod poly corresponds to binary xor with poly every -// time a 0x100 bit appears. -const poly = 1<<8 | 1<<4 | 1<<3 | 1<<1 | 1<<0 // x⁸ + x⁴ + x³ + x + 1 - -// Powers of x mod poly in GF(2). -var powx = [16]byte{ - 0x01, - 0x02, - 0x04, - 0x08, - 0x10, - 0x20, - 0x40, - 0x80, - 0x1b, - 0x36, - 0x6c, - 0xd8, - 0xab, - 0x4d, - 0x9a, - 0x2f, -} - -// FIPS-197 Figure 7. S-box substitution values in hexadecimal format. -var sbox0 = [256]byte{ - 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, - 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, - 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, - 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, - 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, - 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, - 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, - 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, - 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, - 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, - 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, - 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, - 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, - 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, - 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, - 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16, -} - -// FIPS-197 Figure 14. Inverse S-box substitution values in hexadecimal format. -var sbox1 = [256]byte{ - 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb, - 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb, - 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e, - 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25, - 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92, - 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84, - 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06, - 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b, - 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73, - 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e, - 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b, - 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4, - 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f, - 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef, - 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61, - 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d, -} - -// Lookup tables for encryption. -// These can be recomputed by adapting the tests in aes_test.go. - -var te0 = [256]uint32{ - 0xc66363a5, 0xf87c7c84, 0xee777799, 0xf67b7b8d, 0xfff2f20d, 0xd66b6bbd, 0xde6f6fb1, 0x91c5c554, - 0x60303050, 0x02010103, 0xce6767a9, 0x562b2b7d, 0xe7fefe19, 0xb5d7d762, 0x4dababe6, 0xec76769a, - 0x8fcaca45, 0x1f82829d, 0x89c9c940, 0xfa7d7d87, 0xeffafa15, 0xb25959eb, 0x8e4747c9, 0xfbf0f00b, - 0x41adadec, 0xb3d4d467, 0x5fa2a2fd, 0x45afafea, 0x239c9cbf, 0x53a4a4f7, 0xe4727296, 0x9bc0c05b, - 0x75b7b7c2, 0xe1fdfd1c, 0x3d9393ae, 0x4c26266a, 0x6c36365a, 0x7e3f3f41, 0xf5f7f702, 0x83cccc4f, - 0x6834345c, 0x51a5a5f4, 0xd1e5e534, 0xf9f1f108, 0xe2717193, 0xabd8d873, 0x62313153, 0x2a15153f, - 0x0804040c, 0x95c7c752, 0x46232365, 0x9dc3c35e, 0x30181828, 0x379696a1, 0x0a05050f, 0x2f9a9ab5, - 0x0e070709, 0x24121236, 0x1b80809b, 0xdfe2e23d, 0xcdebeb26, 0x4e272769, 0x7fb2b2cd, 0xea75759f, - 0x1209091b, 0x1d83839e, 0x582c2c74, 0x341a1a2e, 0x361b1b2d, 0xdc6e6eb2, 0xb45a5aee, 0x5ba0a0fb, - 0xa45252f6, 0x763b3b4d, 0xb7d6d661, 0x7db3b3ce, 0x5229297b, 0xdde3e33e, 0x5e2f2f71, 0x13848497, - 0xa65353f5, 0xb9d1d168, 0x00000000, 0xc1eded2c, 0x40202060, 0xe3fcfc1f, 0x79b1b1c8, 0xb65b5bed, - 0xd46a6abe, 0x8dcbcb46, 0x67bebed9, 0x7239394b, 0x944a4ade, 0x984c4cd4, 0xb05858e8, 0x85cfcf4a, - 0xbbd0d06b, 0xc5efef2a, 0x4faaaae5, 0xedfbfb16, 0x864343c5, 0x9a4d4dd7, 0x66333355, 0x11858594, - 0x8a4545cf, 0xe9f9f910, 0x04020206, 0xfe7f7f81, 0xa05050f0, 0x783c3c44, 0x259f9fba, 0x4ba8a8e3, - 0xa25151f3, 0x5da3a3fe, 0x804040c0, 0x058f8f8a, 0x3f9292ad, 0x219d9dbc, 0x70383848, 0xf1f5f504, - 0x63bcbcdf, 0x77b6b6c1, 0xafdada75, 0x42212163, 0x20101030, 0xe5ffff1a, 0xfdf3f30e, 0xbfd2d26d, - 0x81cdcd4c, 0x180c0c14, 0x26131335, 0xc3ecec2f, 0xbe5f5fe1, 0x359797a2, 0x884444cc, 0x2e171739, - 0x93c4c457, 0x55a7a7f2, 0xfc7e7e82, 0x7a3d3d47, 0xc86464ac, 0xba5d5de7, 0x3219192b, 0xe6737395, - 0xc06060a0, 0x19818198, 0x9e4f4fd1, 0xa3dcdc7f, 0x44222266, 0x542a2a7e, 0x3b9090ab, 0x0b888883, - 0x8c4646ca, 0xc7eeee29, 0x6bb8b8d3, 0x2814143c, 0xa7dede79, 0xbc5e5ee2, 0x160b0b1d, 0xaddbdb76, - 0xdbe0e03b, 0x64323256, 0x743a3a4e, 0x140a0a1e, 0x924949db, 0x0c06060a, 0x4824246c, 0xb85c5ce4, - 0x9fc2c25d, 0xbdd3d36e, 0x43acacef, 0xc46262a6, 0x399191a8, 0x319595a4, 0xd3e4e437, 0xf279798b, - 0xd5e7e732, 0x8bc8c843, 0x6e373759, 0xda6d6db7, 0x018d8d8c, 0xb1d5d564, 0x9c4e4ed2, 0x49a9a9e0, - 0xd86c6cb4, 0xac5656fa, 0xf3f4f407, 0xcfeaea25, 0xca6565af, 0xf47a7a8e, 0x47aeaee9, 0x10080818, - 0x6fbabad5, 0xf0787888, 0x4a25256f, 0x5c2e2e72, 0x381c1c24, 0x57a6a6f1, 0x73b4b4c7, 0x97c6c651, - 0xcbe8e823, 0xa1dddd7c, 0xe874749c, 0x3e1f1f21, 0x964b4bdd, 0x61bdbddc, 0x0d8b8b86, 0x0f8a8a85, - 0xe0707090, 0x7c3e3e42, 0x71b5b5c4, 0xcc6666aa, 0x904848d8, 0x06030305, 0xf7f6f601, 0x1c0e0e12, - 0xc26161a3, 0x6a35355f, 0xae5757f9, 0x69b9b9d0, 0x17868691, 0x99c1c158, 0x3a1d1d27, 0x279e9eb9, - 0xd9e1e138, 0xebf8f813, 0x2b9898b3, 0x22111133, 0xd26969bb, 0xa9d9d970, 0x078e8e89, 0x339494a7, - 0x2d9b9bb6, 0x3c1e1e22, 0x15878792, 0xc9e9e920, 0x87cece49, 0xaa5555ff, 0x50282878, 0xa5dfdf7a, - 0x038c8c8f, 0x59a1a1f8, 0x09898980, 0x1a0d0d17, 0x65bfbfda, 0xd7e6e631, 0x844242c6, 0xd06868b8, - 0x824141c3, 0x299999b0, 0x5a2d2d77, 0x1e0f0f11, 0x7bb0b0cb, 0xa85454fc, 0x6dbbbbd6, 0x2c16163a, -} -var te1 = [256]uint32{ - 0xa5c66363, 0x84f87c7c, 0x99ee7777, 0x8df67b7b, 0x0dfff2f2, 0xbdd66b6b, 0xb1de6f6f, 0x5491c5c5, - 0x50603030, 0x03020101, 0xa9ce6767, 0x7d562b2b, 0x19e7fefe, 0x62b5d7d7, 0xe64dabab, 0x9aec7676, - 0x458fcaca, 0x9d1f8282, 0x4089c9c9, 0x87fa7d7d, 0x15effafa, 0xebb25959, 0xc98e4747, 0x0bfbf0f0, - 0xec41adad, 0x67b3d4d4, 0xfd5fa2a2, 0xea45afaf, 0xbf239c9c, 0xf753a4a4, 0x96e47272, 0x5b9bc0c0, - 0xc275b7b7, 0x1ce1fdfd, 0xae3d9393, 0x6a4c2626, 0x5a6c3636, 0x417e3f3f, 0x02f5f7f7, 0x4f83cccc, - 0x5c683434, 0xf451a5a5, 0x34d1e5e5, 0x08f9f1f1, 0x93e27171, 0x73abd8d8, 0x53623131, 0x3f2a1515, - 0x0c080404, 0x5295c7c7, 0x65462323, 0x5e9dc3c3, 0x28301818, 0xa1379696, 0x0f0a0505, 0xb52f9a9a, - 0x090e0707, 0x36241212, 0x9b1b8080, 0x3ddfe2e2, 0x26cdebeb, 0x694e2727, 0xcd7fb2b2, 0x9fea7575, - 0x1b120909, 0x9e1d8383, 0x74582c2c, 0x2e341a1a, 0x2d361b1b, 0xb2dc6e6e, 0xeeb45a5a, 0xfb5ba0a0, - 0xf6a45252, 0x4d763b3b, 0x61b7d6d6, 0xce7db3b3, 0x7b522929, 0x3edde3e3, 0x715e2f2f, 0x97138484, - 0xf5a65353, 0x68b9d1d1, 0x00000000, 0x2cc1eded, 0x60402020, 0x1fe3fcfc, 0xc879b1b1, 0xedb65b5b, - 0xbed46a6a, 0x468dcbcb, 0xd967bebe, 0x4b723939, 0xde944a4a, 0xd4984c4c, 0xe8b05858, 0x4a85cfcf, - 0x6bbbd0d0, 0x2ac5efef, 0xe54faaaa, 0x16edfbfb, 0xc5864343, 0xd79a4d4d, 0x55663333, 0x94118585, - 0xcf8a4545, 0x10e9f9f9, 0x06040202, 0x81fe7f7f, 0xf0a05050, 0x44783c3c, 0xba259f9f, 0xe34ba8a8, - 0xf3a25151, 0xfe5da3a3, 0xc0804040, 0x8a058f8f, 0xad3f9292, 0xbc219d9d, 0x48703838, 0x04f1f5f5, - 0xdf63bcbc, 0xc177b6b6, 0x75afdada, 0x63422121, 0x30201010, 0x1ae5ffff, 0x0efdf3f3, 0x6dbfd2d2, - 0x4c81cdcd, 0x14180c0c, 0x35261313, 0x2fc3ecec, 0xe1be5f5f, 0xa2359797, 0xcc884444, 0x392e1717, - 0x5793c4c4, 0xf255a7a7, 0x82fc7e7e, 0x477a3d3d, 0xacc86464, 0xe7ba5d5d, 0x2b321919, 0x95e67373, - 0xa0c06060, 0x98198181, 0xd19e4f4f, 0x7fa3dcdc, 0x66442222, 0x7e542a2a, 0xab3b9090, 0x830b8888, - 0xca8c4646, 0x29c7eeee, 0xd36bb8b8, 0x3c281414, 0x79a7dede, 0xe2bc5e5e, 0x1d160b0b, 0x76addbdb, - 0x3bdbe0e0, 0x56643232, 0x4e743a3a, 0x1e140a0a, 0xdb924949, 0x0a0c0606, 0x6c482424, 0xe4b85c5c, - 0x5d9fc2c2, 0x6ebdd3d3, 0xef43acac, 0xa6c46262, 0xa8399191, 0xa4319595, 0x37d3e4e4, 0x8bf27979, - 0x32d5e7e7, 0x438bc8c8, 0x596e3737, 0xb7da6d6d, 0x8c018d8d, 0x64b1d5d5, 0xd29c4e4e, 0xe049a9a9, - 0xb4d86c6c, 0xfaac5656, 0x07f3f4f4, 0x25cfeaea, 0xafca6565, 0x8ef47a7a, 0xe947aeae, 0x18100808, - 0xd56fbaba, 0x88f07878, 0x6f4a2525, 0x725c2e2e, 0x24381c1c, 0xf157a6a6, 0xc773b4b4, 0x5197c6c6, - 0x23cbe8e8, 0x7ca1dddd, 0x9ce87474, 0x213e1f1f, 0xdd964b4b, 0xdc61bdbd, 0x860d8b8b, 0x850f8a8a, - 0x90e07070, 0x427c3e3e, 0xc471b5b5, 0xaacc6666, 0xd8904848, 0x05060303, 0x01f7f6f6, 0x121c0e0e, - 0xa3c26161, 0x5f6a3535, 0xf9ae5757, 0xd069b9b9, 0x91178686, 0x5899c1c1, 0x273a1d1d, 0xb9279e9e, - 0x38d9e1e1, 0x13ebf8f8, 0xb32b9898, 0x33221111, 0xbbd26969, 0x70a9d9d9, 0x89078e8e, 0xa7339494, - 0xb62d9b9b, 0x223c1e1e, 0x92158787, 0x20c9e9e9, 0x4987cece, 0xffaa5555, 0x78502828, 0x7aa5dfdf, - 0x8f038c8c, 0xf859a1a1, 0x80098989, 0x171a0d0d, 0xda65bfbf, 0x31d7e6e6, 0xc6844242, 0xb8d06868, - 0xc3824141, 0xb0299999, 0x775a2d2d, 0x111e0f0f, 0xcb7bb0b0, 0xfca85454, 0xd66dbbbb, 0x3a2c1616, -} -var te2 = [256]uint32{ - 0x63a5c663, 0x7c84f87c, 0x7799ee77, 0x7b8df67b, 0xf20dfff2, 0x6bbdd66b, 0x6fb1de6f, 0xc55491c5, - 0x30506030, 0x01030201, 0x67a9ce67, 0x2b7d562b, 0xfe19e7fe, 0xd762b5d7, 0xabe64dab, 0x769aec76, - 0xca458fca, 0x829d1f82, 0xc94089c9, 0x7d87fa7d, 0xfa15effa, 0x59ebb259, 0x47c98e47, 0xf00bfbf0, - 0xadec41ad, 0xd467b3d4, 0xa2fd5fa2, 0xafea45af, 0x9cbf239c, 0xa4f753a4, 0x7296e472, 0xc05b9bc0, - 0xb7c275b7, 0xfd1ce1fd, 0x93ae3d93, 0x266a4c26, 0x365a6c36, 0x3f417e3f, 0xf702f5f7, 0xcc4f83cc, - 0x345c6834, 0xa5f451a5, 0xe534d1e5, 0xf108f9f1, 0x7193e271, 0xd873abd8, 0x31536231, 0x153f2a15, - 0x040c0804, 0xc75295c7, 0x23654623, 0xc35e9dc3, 0x18283018, 0x96a13796, 0x050f0a05, 0x9ab52f9a, - 0x07090e07, 0x12362412, 0x809b1b80, 0xe23ddfe2, 0xeb26cdeb, 0x27694e27, 0xb2cd7fb2, 0x759fea75, - 0x091b1209, 0x839e1d83, 0x2c74582c, 0x1a2e341a, 0x1b2d361b, 0x6eb2dc6e, 0x5aeeb45a, 0xa0fb5ba0, - 0x52f6a452, 0x3b4d763b, 0xd661b7d6, 0xb3ce7db3, 0x297b5229, 0xe33edde3, 0x2f715e2f, 0x84971384, - 0x53f5a653, 0xd168b9d1, 0x00000000, 0xed2cc1ed, 0x20604020, 0xfc1fe3fc, 0xb1c879b1, 0x5bedb65b, - 0x6abed46a, 0xcb468dcb, 0xbed967be, 0x394b7239, 0x4ade944a, 0x4cd4984c, 0x58e8b058, 0xcf4a85cf, - 0xd06bbbd0, 0xef2ac5ef, 0xaae54faa, 0xfb16edfb, 0x43c58643, 0x4dd79a4d, 0x33556633, 0x85941185, - 0x45cf8a45, 0xf910e9f9, 0x02060402, 0x7f81fe7f, 0x50f0a050, 0x3c44783c, 0x9fba259f, 0xa8e34ba8, - 0x51f3a251, 0xa3fe5da3, 0x40c08040, 0x8f8a058f, 0x92ad3f92, 0x9dbc219d, 0x38487038, 0xf504f1f5, - 0xbcdf63bc, 0xb6c177b6, 0xda75afda, 0x21634221, 0x10302010, 0xff1ae5ff, 0xf30efdf3, 0xd26dbfd2, - 0xcd4c81cd, 0x0c14180c, 0x13352613, 0xec2fc3ec, 0x5fe1be5f, 0x97a23597, 0x44cc8844, 0x17392e17, - 0xc45793c4, 0xa7f255a7, 0x7e82fc7e, 0x3d477a3d, 0x64acc864, 0x5de7ba5d, 0x192b3219, 0x7395e673, - 0x60a0c060, 0x81981981, 0x4fd19e4f, 0xdc7fa3dc, 0x22664422, 0x2a7e542a, 0x90ab3b90, 0x88830b88, - 0x46ca8c46, 0xee29c7ee, 0xb8d36bb8, 0x143c2814, 0xde79a7de, 0x5ee2bc5e, 0x0b1d160b, 0xdb76addb, - 0xe03bdbe0, 0x32566432, 0x3a4e743a, 0x0a1e140a, 0x49db9249, 0x060a0c06, 0x246c4824, 0x5ce4b85c, - 0xc25d9fc2, 0xd36ebdd3, 0xacef43ac, 0x62a6c462, 0x91a83991, 0x95a43195, 0xe437d3e4, 0x798bf279, - 0xe732d5e7, 0xc8438bc8, 0x37596e37, 0x6db7da6d, 0x8d8c018d, 0xd564b1d5, 0x4ed29c4e, 0xa9e049a9, - 0x6cb4d86c, 0x56faac56, 0xf407f3f4, 0xea25cfea, 0x65afca65, 0x7a8ef47a, 0xaee947ae, 0x08181008, - 0xbad56fba, 0x7888f078, 0x256f4a25, 0x2e725c2e, 0x1c24381c, 0xa6f157a6, 0xb4c773b4, 0xc65197c6, - 0xe823cbe8, 0xdd7ca1dd, 0x749ce874, 0x1f213e1f, 0x4bdd964b, 0xbddc61bd, 0x8b860d8b, 0x8a850f8a, - 0x7090e070, 0x3e427c3e, 0xb5c471b5, 0x66aacc66, 0x48d89048, 0x03050603, 0xf601f7f6, 0x0e121c0e, - 0x61a3c261, 0x355f6a35, 0x57f9ae57, 0xb9d069b9, 0x86911786, 0xc15899c1, 0x1d273a1d, 0x9eb9279e, - 0xe138d9e1, 0xf813ebf8, 0x98b32b98, 0x11332211, 0x69bbd269, 0xd970a9d9, 0x8e89078e, 0x94a73394, - 0x9bb62d9b, 0x1e223c1e, 0x87921587, 0xe920c9e9, 0xce4987ce, 0x55ffaa55, 0x28785028, 0xdf7aa5df, - 0x8c8f038c, 0xa1f859a1, 0x89800989, 0x0d171a0d, 0xbfda65bf, 0xe631d7e6, 0x42c68442, 0x68b8d068, - 0x41c38241, 0x99b02999, 0x2d775a2d, 0x0f111e0f, 0xb0cb7bb0, 0x54fca854, 0xbbd66dbb, 0x163a2c16, -} -var te3 = [256]uint32{ - 0x6363a5c6, 0x7c7c84f8, 0x777799ee, 0x7b7b8df6, 0xf2f20dff, 0x6b6bbdd6, 0x6f6fb1de, 0xc5c55491, - 0x30305060, 0x01010302, 0x6767a9ce, 0x2b2b7d56, 0xfefe19e7, 0xd7d762b5, 0xababe64d, 0x76769aec, - 0xcaca458f, 0x82829d1f, 0xc9c94089, 0x7d7d87fa, 0xfafa15ef, 0x5959ebb2, 0x4747c98e, 0xf0f00bfb, - 0xadadec41, 0xd4d467b3, 0xa2a2fd5f, 0xafafea45, 0x9c9cbf23, 0xa4a4f753, 0x727296e4, 0xc0c05b9b, - 0xb7b7c275, 0xfdfd1ce1, 0x9393ae3d, 0x26266a4c, 0x36365a6c, 0x3f3f417e, 0xf7f702f5, 0xcccc4f83, - 0x34345c68, 0xa5a5f451, 0xe5e534d1, 0xf1f108f9, 0x717193e2, 0xd8d873ab, 0x31315362, 0x15153f2a, - 0x04040c08, 0xc7c75295, 0x23236546, 0xc3c35e9d, 0x18182830, 0x9696a137, 0x05050f0a, 0x9a9ab52f, - 0x0707090e, 0x12123624, 0x80809b1b, 0xe2e23ddf, 0xebeb26cd, 0x2727694e, 0xb2b2cd7f, 0x75759fea, - 0x09091b12, 0x83839e1d, 0x2c2c7458, 0x1a1a2e34, 0x1b1b2d36, 0x6e6eb2dc, 0x5a5aeeb4, 0xa0a0fb5b, - 0x5252f6a4, 0x3b3b4d76, 0xd6d661b7, 0xb3b3ce7d, 0x29297b52, 0xe3e33edd, 0x2f2f715e, 0x84849713, - 0x5353f5a6, 0xd1d168b9, 0x00000000, 0xeded2cc1, 0x20206040, 0xfcfc1fe3, 0xb1b1c879, 0x5b5bedb6, - 0x6a6abed4, 0xcbcb468d, 0xbebed967, 0x39394b72, 0x4a4ade94, 0x4c4cd498, 0x5858e8b0, 0xcfcf4a85, - 0xd0d06bbb, 0xefef2ac5, 0xaaaae54f, 0xfbfb16ed, 0x4343c586, 0x4d4dd79a, 0x33335566, 0x85859411, - 0x4545cf8a, 0xf9f910e9, 0x02020604, 0x7f7f81fe, 0x5050f0a0, 0x3c3c4478, 0x9f9fba25, 0xa8a8e34b, - 0x5151f3a2, 0xa3a3fe5d, 0x4040c080, 0x8f8f8a05, 0x9292ad3f, 0x9d9dbc21, 0x38384870, 0xf5f504f1, - 0xbcbcdf63, 0xb6b6c177, 0xdada75af, 0x21216342, 0x10103020, 0xffff1ae5, 0xf3f30efd, 0xd2d26dbf, - 0xcdcd4c81, 0x0c0c1418, 0x13133526, 0xecec2fc3, 0x5f5fe1be, 0x9797a235, 0x4444cc88, 0x1717392e, - 0xc4c45793, 0xa7a7f255, 0x7e7e82fc, 0x3d3d477a, 0x6464acc8, 0x5d5de7ba, 0x19192b32, 0x737395e6, - 0x6060a0c0, 0x81819819, 0x4f4fd19e, 0xdcdc7fa3, 0x22226644, 0x2a2a7e54, 0x9090ab3b, 0x8888830b, - 0x4646ca8c, 0xeeee29c7, 0xb8b8d36b, 0x14143c28, 0xdede79a7, 0x5e5ee2bc, 0x0b0b1d16, 0xdbdb76ad, - 0xe0e03bdb, 0x32325664, 0x3a3a4e74, 0x0a0a1e14, 0x4949db92, 0x06060a0c, 0x24246c48, 0x5c5ce4b8, - 0xc2c25d9f, 0xd3d36ebd, 0xacacef43, 0x6262a6c4, 0x9191a839, 0x9595a431, 0xe4e437d3, 0x79798bf2, - 0xe7e732d5, 0xc8c8438b, 0x3737596e, 0x6d6db7da, 0x8d8d8c01, 0xd5d564b1, 0x4e4ed29c, 0xa9a9e049, - 0x6c6cb4d8, 0x5656faac, 0xf4f407f3, 0xeaea25cf, 0x6565afca, 0x7a7a8ef4, 0xaeaee947, 0x08081810, - 0xbabad56f, 0x787888f0, 0x25256f4a, 0x2e2e725c, 0x1c1c2438, 0xa6a6f157, 0xb4b4c773, 0xc6c65197, - 0xe8e823cb, 0xdddd7ca1, 0x74749ce8, 0x1f1f213e, 0x4b4bdd96, 0xbdbddc61, 0x8b8b860d, 0x8a8a850f, - 0x707090e0, 0x3e3e427c, 0xb5b5c471, 0x6666aacc, 0x4848d890, 0x03030506, 0xf6f601f7, 0x0e0e121c, - 0x6161a3c2, 0x35355f6a, 0x5757f9ae, 0xb9b9d069, 0x86869117, 0xc1c15899, 0x1d1d273a, 0x9e9eb927, - 0xe1e138d9, 0xf8f813eb, 0x9898b32b, 0x11113322, 0x6969bbd2, 0xd9d970a9, 0x8e8e8907, 0x9494a733, - 0x9b9bb62d, 0x1e1e223c, 0x87879215, 0xe9e920c9, 0xcece4987, 0x5555ffaa, 0x28287850, 0xdfdf7aa5, - 0x8c8c8f03, 0xa1a1f859, 0x89898009, 0x0d0d171a, 0xbfbfda65, 0xe6e631d7, 0x4242c684, 0x6868b8d0, - 0x4141c382, 0x9999b029, 0x2d2d775a, 0x0f0f111e, 0xb0b0cb7b, 0x5454fca8, 0xbbbbd66d, 0x16163a2c, -} - -// Lookup tables for decryption. -// These can be recomputed by adapting the tests in aes_test.go. - -var td0 = [256]uint32{ - 0x51f4a750, 0x7e416553, 0x1a17a4c3, 0x3a275e96, 0x3bab6bcb, 0x1f9d45f1, 0xacfa58ab, 0x4be30393, - 0x2030fa55, 0xad766df6, 0x88cc7691, 0xf5024c25, 0x4fe5d7fc, 0xc52acbd7, 0x26354480, 0xb562a38f, - 0xdeb15a49, 0x25ba1b67, 0x45ea0e98, 0x5dfec0e1, 0xc32f7502, 0x814cf012, 0x8d4697a3, 0x6bd3f9c6, - 0x038f5fe7, 0x15929c95, 0xbf6d7aeb, 0x955259da, 0xd4be832d, 0x587421d3, 0x49e06929, 0x8ec9c844, - 0x75c2896a, 0xf48e7978, 0x99583e6b, 0x27b971dd, 0xbee14fb6, 0xf088ad17, 0xc920ac66, 0x7dce3ab4, - 0x63df4a18, 0xe51a3182, 0x97513360, 0x62537f45, 0xb16477e0, 0xbb6bae84, 0xfe81a01c, 0xf9082b94, - 0x70486858, 0x8f45fd19, 0x94de6c87, 0x527bf8b7, 0xab73d323, 0x724b02e2, 0xe31f8f57, 0x6655ab2a, - 0xb2eb2807, 0x2fb5c203, 0x86c57b9a, 0xd33708a5, 0x302887f2, 0x23bfa5b2, 0x02036aba, 0xed16825c, - 0x8acf1c2b, 0xa779b492, 0xf307f2f0, 0x4e69e2a1, 0x65daf4cd, 0x0605bed5, 0xd134621f, 0xc4a6fe8a, - 0x342e539d, 0xa2f355a0, 0x058ae132, 0xa4f6eb75, 0x0b83ec39, 0x4060efaa, 0x5e719f06, 0xbd6e1051, - 0x3e218af9, 0x96dd063d, 0xdd3e05ae, 0x4de6bd46, 0x91548db5, 0x71c45d05, 0x0406d46f, 0x605015ff, - 0x1998fb24, 0xd6bde997, 0x894043cc, 0x67d99e77, 0xb0e842bd, 0x07898b88, 0xe7195b38, 0x79c8eedb, - 0xa17c0a47, 0x7c420fe9, 0xf8841ec9, 0x00000000, 0x09808683, 0x322bed48, 0x1e1170ac, 0x6c5a724e, - 0xfd0efffb, 0x0f853856, 0x3daed51e, 0x362d3927, 0x0a0fd964, 0x685ca621, 0x9b5b54d1, 0x24362e3a, - 0x0c0a67b1, 0x9357e70f, 0xb4ee96d2, 0x1b9b919e, 0x80c0c54f, 0x61dc20a2, 0x5a774b69, 0x1c121a16, - 0xe293ba0a, 0xc0a02ae5, 0x3c22e043, 0x121b171d, 0x0e090d0b, 0xf28bc7ad, 0x2db6a8b9, 0x141ea9c8, - 0x57f11985, 0xaf75074c, 0xee99ddbb, 0xa37f60fd, 0xf701269f, 0x5c72f5bc, 0x44663bc5, 0x5bfb7e34, - 0x8b432976, 0xcb23c6dc, 0xb6edfc68, 0xb8e4f163, 0xd731dcca, 0x42638510, 0x13972240, 0x84c61120, - 0x854a247d, 0xd2bb3df8, 0xaef93211, 0xc729a16d, 0x1d9e2f4b, 0xdcb230f3, 0x0d8652ec, 0x77c1e3d0, - 0x2bb3166c, 0xa970b999, 0x119448fa, 0x47e96422, 0xa8fc8cc4, 0xa0f03f1a, 0x567d2cd8, 0x223390ef, - 0x87494ec7, 0xd938d1c1, 0x8ccaa2fe, 0x98d40b36, 0xa6f581cf, 0xa57ade28, 0xdab78e26, 0x3fadbfa4, - 0x2c3a9de4, 0x5078920d, 0x6a5fcc9b, 0x547e4662, 0xf68d13c2, 0x90d8b8e8, 0x2e39f75e, 0x82c3aff5, - 0x9f5d80be, 0x69d0937c, 0x6fd52da9, 0xcf2512b3, 0xc8ac993b, 0x10187da7, 0xe89c636e, 0xdb3bbb7b, - 0xcd267809, 0x6e5918f4, 0xec9ab701, 0x834f9aa8, 0xe6956e65, 0xaaffe67e, 0x21bccf08, 0xef15e8e6, - 0xbae79bd9, 0x4a6f36ce, 0xea9f09d4, 0x29b07cd6, 0x31a4b2af, 0x2a3f2331, 0xc6a59430, 0x35a266c0, - 0x744ebc37, 0xfc82caa6, 0xe090d0b0, 0x33a7d815, 0xf104984a, 0x41ecdaf7, 0x7fcd500e, 0x1791f62f, - 0x764dd68d, 0x43efb04d, 0xccaa4d54, 0xe49604df, 0x9ed1b5e3, 0x4c6a881b, 0xc12c1fb8, 0x4665517f, - 0x9d5eea04, 0x018c355d, 0xfa877473, 0xfb0b412e, 0xb3671d5a, 0x92dbd252, 0xe9105633, 0x6dd64713, - 0x9ad7618c, 0x37a10c7a, 0x59f8148e, 0xeb133c89, 0xcea927ee, 0xb761c935, 0xe11ce5ed, 0x7a47b13c, - 0x9cd2df59, 0x55f2733f, 0x1814ce79, 0x73c737bf, 0x53f7cdea, 0x5ffdaa5b, 0xdf3d6f14, 0x7844db86, - 0xcaaff381, 0xb968c43e, 0x3824342c, 0xc2a3405f, 0x161dc372, 0xbce2250c, 0x283c498b, 0xff0d9541, - 0x39a80171, 0x080cb3de, 0xd8b4e49c, 0x6456c190, 0x7bcb8461, 0xd532b670, 0x486c5c74, 0xd0b85742, -} -var td1 = [256]uint32{ - 0x5051f4a7, 0x537e4165, 0xc31a17a4, 0x963a275e, 0xcb3bab6b, 0xf11f9d45, 0xabacfa58, 0x934be303, - 0x552030fa, 0xf6ad766d, 0x9188cc76, 0x25f5024c, 0xfc4fe5d7, 0xd7c52acb, 0x80263544, 0x8fb562a3, - 0x49deb15a, 0x6725ba1b, 0x9845ea0e, 0xe15dfec0, 0x02c32f75, 0x12814cf0, 0xa38d4697, 0xc66bd3f9, - 0xe7038f5f, 0x9515929c, 0xebbf6d7a, 0xda955259, 0x2dd4be83, 0xd3587421, 0x2949e069, 0x448ec9c8, - 0x6a75c289, 0x78f48e79, 0x6b99583e, 0xdd27b971, 0xb6bee14f, 0x17f088ad, 0x66c920ac, 0xb47dce3a, - 0x1863df4a, 0x82e51a31, 0x60975133, 0x4562537f, 0xe0b16477, 0x84bb6bae, 0x1cfe81a0, 0x94f9082b, - 0x58704868, 0x198f45fd, 0x8794de6c, 0xb7527bf8, 0x23ab73d3, 0xe2724b02, 0x57e31f8f, 0x2a6655ab, - 0x07b2eb28, 0x032fb5c2, 0x9a86c57b, 0xa5d33708, 0xf2302887, 0xb223bfa5, 0xba02036a, 0x5ced1682, - 0x2b8acf1c, 0x92a779b4, 0xf0f307f2, 0xa14e69e2, 0xcd65daf4, 0xd50605be, 0x1fd13462, 0x8ac4a6fe, - 0x9d342e53, 0xa0a2f355, 0x32058ae1, 0x75a4f6eb, 0x390b83ec, 0xaa4060ef, 0x065e719f, 0x51bd6e10, - 0xf93e218a, 0x3d96dd06, 0xaedd3e05, 0x464de6bd, 0xb591548d, 0x0571c45d, 0x6f0406d4, 0xff605015, - 0x241998fb, 0x97d6bde9, 0xcc894043, 0x7767d99e, 0xbdb0e842, 0x8807898b, 0x38e7195b, 0xdb79c8ee, - 0x47a17c0a, 0xe97c420f, 0xc9f8841e, 0x00000000, 0x83098086, 0x48322bed, 0xac1e1170, 0x4e6c5a72, - 0xfbfd0eff, 0x560f8538, 0x1e3daed5, 0x27362d39, 0x640a0fd9, 0x21685ca6, 0xd19b5b54, 0x3a24362e, - 0xb10c0a67, 0x0f9357e7, 0xd2b4ee96, 0x9e1b9b91, 0x4f80c0c5, 0xa261dc20, 0x695a774b, 0x161c121a, - 0x0ae293ba, 0xe5c0a02a, 0x433c22e0, 0x1d121b17, 0x0b0e090d, 0xadf28bc7, 0xb92db6a8, 0xc8141ea9, - 0x8557f119, 0x4caf7507, 0xbbee99dd, 0xfda37f60, 0x9ff70126, 0xbc5c72f5, 0xc544663b, 0x345bfb7e, - 0x768b4329, 0xdccb23c6, 0x68b6edfc, 0x63b8e4f1, 0xcad731dc, 0x10426385, 0x40139722, 0x2084c611, - 0x7d854a24, 0xf8d2bb3d, 0x11aef932, 0x6dc729a1, 0x4b1d9e2f, 0xf3dcb230, 0xec0d8652, 0xd077c1e3, - 0x6c2bb316, 0x99a970b9, 0xfa119448, 0x2247e964, 0xc4a8fc8c, 0x1aa0f03f, 0xd8567d2c, 0xef223390, - 0xc787494e, 0xc1d938d1, 0xfe8ccaa2, 0x3698d40b, 0xcfa6f581, 0x28a57ade, 0x26dab78e, 0xa43fadbf, - 0xe42c3a9d, 0x0d507892, 0x9b6a5fcc, 0x62547e46, 0xc2f68d13, 0xe890d8b8, 0x5e2e39f7, 0xf582c3af, - 0xbe9f5d80, 0x7c69d093, 0xa96fd52d, 0xb3cf2512, 0x3bc8ac99, 0xa710187d, 0x6ee89c63, 0x7bdb3bbb, - 0x09cd2678, 0xf46e5918, 0x01ec9ab7, 0xa8834f9a, 0x65e6956e, 0x7eaaffe6, 0x0821bccf, 0xe6ef15e8, - 0xd9bae79b, 0xce4a6f36, 0xd4ea9f09, 0xd629b07c, 0xaf31a4b2, 0x312a3f23, 0x30c6a594, 0xc035a266, - 0x37744ebc, 0xa6fc82ca, 0xb0e090d0, 0x1533a7d8, 0x4af10498, 0xf741ecda, 0x0e7fcd50, 0x2f1791f6, - 0x8d764dd6, 0x4d43efb0, 0x54ccaa4d, 0xdfe49604, 0xe39ed1b5, 0x1b4c6a88, 0xb8c12c1f, 0x7f466551, - 0x049d5eea, 0x5d018c35, 0x73fa8774, 0x2efb0b41, 0x5ab3671d, 0x5292dbd2, 0x33e91056, 0x136dd647, - 0x8c9ad761, 0x7a37a10c, 0x8e59f814, 0x89eb133c, 0xeecea927, 0x35b761c9, 0xede11ce5, 0x3c7a47b1, - 0x599cd2df, 0x3f55f273, 0x791814ce, 0xbf73c737, 0xea53f7cd, 0x5b5ffdaa, 0x14df3d6f, 0x867844db, - 0x81caaff3, 0x3eb968c4, 0x2c382434, 0x5fc2a340, 0x72161dc3, 0x0cbce225, 0x8b283c49, 0x41ff0d95, - 0x7139a801, 0xde080cb3, 0x9cd8b4e4, 0x906456c1, 0x617bcb84, 0x70d532b6, 0x74486c5c, 0x42d0b857, -} -var td2 = [256]uint32{ - 0xa75051f4, 0x65537e41, 0xa4c31a17, 0x5e963a27, 0x6bcb3bab, 0x45f11f9d, 0x58abacfa, 0x03934be3, - 0xfa552030, 0x6df6ad76, 0x769188cc, 0x4c25f502, 0xd7fc4fe5, 0xcbd7c52a, 0x44802635, 0xa38fb562, - 0x5a49deb1, 0x1b6725ba, 0x0e9845ea, 0xc0e15dfe, 0x7502c32f, 0xf012814c, 0x97a38d46, 0xf9c66bd3, - 0x5fe7038f, 0x9c951592, 0x7aebbf6d, 0x59da9552, 0x832dd4be, 0x21d35874, 0x692949e0, 0xc8448ec9, - 0x896a75c2, 0x7978f48e, 0x3e6b9958, 0x71dd27b9, 0x4fb6bee1, 0xad17f088, 0xac66c920, 0x3ab47dce, - 0x4a1863df, 0x3182e51a, 0x33609751, 0x7f456253, 0x77e0b164, 0xae84bb6b, 0xa01cfe81, 0x2b94f908, - 0x68587048, 0xfd198f45, 0x6c8794de, 0xf8b7527b, 0xd323ab73, 0x02e2724b, 0x8f57e31f, 0xab2a6655, - 0x2807b2eb, 0xc2032fb5, 0x7b9a86c5, 0x08a5d337, 0x87f23028, 0xa5b223bf, 0x6aba0203, 0x825ced16, - 0x1c2b8acf, 0xb492a779, 0xf2f0f307, 0xe2a14e69, 0xf4cd65da, 0xbed50605, 0x621fd134, 0xfe8ac4a6, - 0x539d342e, 0x55a0a2f3, 0xe132058a, 0xeb75a4f6, 0xec390b83, 0xefaa4060, 0x9f065e71, 0x1051bd6e, - 0x8af93e21, 0x063d96dd, 0x05aedd3e, 0xbd464de6, 0x8db59154, 0x5d0571c4, 0xd46f0406, 0x15ff6050, - 0xfb241998, 0xe997d6bd, 0x43cc8940, 0x9e7767d9, 0x42bdb0e8, 0x8b880789, 0x5b38e719, 0xeedb79c8, - 0x0a47a17c, 0x0fe97c42, 0x1ec9f884, 0x00000000, 0x86830980, 0xed48322b, 0x70ac1e11, 0x724e6c5a, - 0xfffbfd0e, 0x38560f85, 0xd51e3dae, 0x3927362d, 0xd9640a0f, 0xa621685c, 0x54d19b5b, 0x2e3a2436, - 0x67b10c0a, 0xe70f9357, 0x96d2b4ee, 0x919e1b9b, 0xc54f80c0, 0x20a261dc, 0x4b695a77, 0x1a161c12, - 0xba0ae293, 0x2ae5c0a0, 0xe0433c22, 0x171d121b, 0x0d0b0e09, 0xc7adf28b, 0xa8b92db6, 0xa9c8141e, - 0x198557f1, 0x074caf75, 0xddbbee99, 0x60fda37f, 0x269ff701, 0xf5bc5c72, 0x3bc54466, 0x7e345bfb, - 0x29768b43, 0xc6dccb23, 0xfc68b6ed, 0xf163b8e4, 0xdccad731, 0x85104263, 0x22401397, 0x112084c6, - 0x247d854a, 0x3df8d2bb, 0x3211aef9, 0xa16dc729, 0x2f4b1d9e, 0x30f3dcb2, 0x52ec0d86, 0xe3d077c1, - 0x166c2bb3, 0xb999a970, 0x48fa1194, 0x642247e9, 0x8cc4a8fc, 0x3f1aa0f0, 0x2cd8567d, 0x90ef2233, - 0x4ec78749, 0xd1c1d938, 0xa2fe8cca, 0x0b3698d4, 0x81cfa6f5, 0xde28a57a, 0x8e26dab7, 0xbfa43fad, - 0x9de42c3a, 0x920d5078, 0xcc9b6a5f, 0x4662547e, 0x13c2f68d, 0xb8e890d8, 0xf75e2e39, 0xaff582c3, - 0x80be9f5d, 0x937c69d0, 0x2da96fd5, 0x12b3cf25, 0x993bc8ac, 0x7da71018, 0x636ee89c, 0xbb7bdb3b, - 0x7809cd26, 0x18f46e59, 0xb701ec9a, 0x9aa8834f, 0x6e65e695, 0xe67eaaff, 0xcf0821bc, 0xe8e6ef15, - 0x9bd9bae7, 0x36ce4a6f, 0x09d4ea9f, 0x7cd629b0, 0xb2af31a4, 0x23312a3f, 0x9430c6a5, 0x66c035a2, - 0xbc37744e, 0xcaa6fc82, 0xd0b0e090, 0xd81533a7, 0x984af104, 0xdaf741ec, 0x500e7fcd, 0xf62f1791, - 0xd68d764d, 0xb04d43ef, 0x4d54ccaa, 0x04dfe496, 0xb5e39ed1, 0x881b4c6a, 0x1fb8c12c, 0x517f4665, - 0xea049d5e, 0x355d018c, 0x7473fa87, 0x412efb0b, 0x1d5ab367, 0xd25292db, 0x5633e910, 0x47136dd6, - 0x618c9ad7, 0x0c7a37a1, 0x148e59f8, 0x3c89eb13, 0x27eecea9, 0xc935b761, 0xe5ede11c, 0xb13c7a47, - 0xdf599cd2, 0x733f55f2, 0xce791814, 0x37bf73c7, 0xcdea53f7, 0xaa5b5ffd, 0x6f14df3d, 0xdb867844, - 0xf381caaf, 0xc43eb968, 0x342c3824, 0x405fc2a3, 0xc372161d, 0x250cbce2, 0x498b283c, 0x9541ff0d, - 0x017139a8, 0xb3de080c, 0xe49cd8b4, 0xc1906456, 0x84617bcb, 0xb670d532, 0x5c74486c, 0x5742d0b8, -} -var td3 = [256]uint32{ - 0xf4a75051, 0x4165537e, 0x17a4c31a, 0x275e963a, 0xab6bcb3b, 0x9d45f11f, 0xfa58abac, 0xe303934b, - 0x30fa5520, 0x766df6ad, 0xcc769188, 0x024c25f5, 0xe5d7fc4f, 0x2acbd7c5, 0x35448026, 0x62a38fb5, - 0xb15a49de, 0xba1b6725, 0xea0e9845, 0xfec0e15d, 0x2f7502c3, 0x4cf01281, 0x4697a38d, 0xd3f9c66b, - 0x8f5fe703, 0x929c9515, 0x6d7aebbf, 0x5259da95, 0xbe832dd4, 0x7421d358, 0xe0692949, 0xc9c8448e, - 0xc2896a75, 0x8e7978f4, 0x583e6b99, 0xb971dd27, 0xe14fb6be, 0x88ad17f0, 0x20ac66c9, 0xce3ab47d, - 0xdf4a1863, 0x1a3182e5, 0x51336097, 0x537f4562, 0x6477e0b1, 0x6bae84bb, 0x81a01cfe, 0x082b94f9, - 0x48685870, 0x45fd198f, 0xde6c8794, 0x7bf8b752, 0x73d323ab, 0x4b02e272, 0x1f8f57e3, 0x55ab2a66, - 0xeb2807b2, 0xb5c2032f, 0xc57b9a86, 0x3708a5d3, 0x2887f230, 0xbfa5b223, 0x036aba02, 0x16825ced, - 0xcf1c2b8a, 0x79b492a7, 0x07f2f0f3, 0x69e2a14e, 0xdaf4cd65, 0x05bed506, 0x34621fd1, 0xa6fe8ac4, - 0x2e539d34, 0xf355a0a2, 0x8ae13205, 0xf6eb75a4, 0x83ec390b, 0x60efaa40, 0x719f065e, 0x6e1051bd, - 0x218af93e, 0xdd063d96, 0x3e05aedd, 0xe6bd464d, 0x548db591, 0xc45d0571, 0x06d46f04, 0x5015ff60, - 0x98fb2419, 0xbde997d6, 0x4043cc89, 0xd99e7767, 0xe842bdb0, 0x898b8807, 0x195b38e7, 0xc8eedb79, - 0x7c0a47a1, 0x420fe97c, 0x841ec9f8, 0x00000000, 0x80868309, 0x2bed4832, 0x1170ac1e, 0x5a724e6c, - 0x0efffbfd, 0x8538560f, 0xaed51e3d, 0x2d392736, 0x0fd9640a, 0x5ca62168, 0x5b54d19b, 0x362e3a24, - 0x0a67b10c, 0x57e70f93, 0xee96d2b4, 0x9b919e1b, 0xc0c54f80, 0xdc20a261, 0x774b695a, 0x121a161c, - 0x93ba0ae2, 0xa02ae5c0, 0x22e0433c, 0x1b171d12, 0x090d0b0e, 0x8bc7adf2, 0xb6a8b92d, 0x1ea9c814, - 0xf1198557, 0x75074caf, 0x99ddbbee, 0x7f60fda3, 0x01269ff7, 0x72f5bc5c, 0x663bc544, 0xfb7e345b, - 0x4329768b, 0x23c6dccb, 0xedfc68b6, 0xe4f163b8, 0x31dccad7, 0x63851042, 0x97224013, 0xc6112084, - 0x4a247d85, 0xbb3df8d2, 0xf93211ae, 0x29a16dc7, 0x9e2f4b1d, 0xb230f3dc, 0x8652ec0d, 0xc1e3d077, - 0xb3166c2b, 0x70b999a9, 0x9448fa11, 0xe9642247, 0xfc8cc4a8, 0xf03f1aa0, 0x7d2cd856, 0x3390ef22, - 0x494ec787, 0x38d1c1d9, 0xcaa2fe8c, 0xd40b3698, 0xf581cfa6, 0x7ade28a5, 0xb78e26da, 0xadbfa43f, - 0x3a9de42c, 0x78920d50, 0x5fcc9b6a, 0x7e466254, 0x8d13c2f6, 0xd8b8e890, 0x39f75e2e, 0xc3aff582, - 0x5d80be9f, 0xd0937c69, 0xd52da96f, 0x2512b3cf, 0xac993bc8, 0x187da710, 0x9c636ee8, 0x3bbb7bdb, - 0x267809cd, 0x5918f46e, 0x9ab701ec, 0x4f9aa883, 0x956e65e6, 0xffe67eaa, 0xbccf0821, 0x15e8e6ef, - 0xe79bd9ba, 0x6f36ce4a, 0x9f09d4ea, 0xb07cd629, 0xa4b2af31, 0x3f23312a, 0xa59430c6, 0xa266c035, - 0x4ebc3774, 0x82caa6fc, 0x90d0b0e0, 0xa7d81533, 0x04984af1, 0xecdaf741, 0xcd500e7f, 0x91f62f17, - 0x4dd68d76, 0xefb04d43, 0xaa4d54cc, 0x9604dfe4, 0xd1b5e39e, 0x6a881b4c, 0x2c1fb8c1, 0x65517f46, - 0x5eea049d, 0x8c355d01, 0x877473fa, 0x0b412efb, 0x671d5ab3, 0xdbd25292, 0x105633e9, 0xd647136d, - 0xd7618c9a, 0xa10c7a37, 0xf8148e59, 0x133c89eb, 0xa927eece, 0x61c935b7, 0x1ce5ede1, 0x47b13c7a, - 0xd2df599c, 0xf2733f55, 0x14ce7918, 0xc737bf73, 0xf7cdea53, 0xfdaa5b5f, 0x3d6f14df, 0x44db8678, - 0xaff381ca, 0x68c43eb9, 0x24342c38, 0xa3405fc2, 0x1dc37216, 0xe2250cbc, 0x3c498b28, 0x0d9541ff, - 0xa8017139, 0x0cb3de08, 0xb4e49cd8, 0x56c19064, 0xcb84617b, 0x32b670d5, 0x6c5c7448, 0xb85742d0, -} diff --git a/src/pkg/crypto/cipher/benchmark_test.go b/src/pkg/crypto/cipher/benchmark_test.go deleted file mode 100644 index 027b24851..000000000 --- a/src/pkg/crypto/cipher/benchmark_test.go +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cipher_test - -import ( - "crypto/aes" - "crypto/cipher" - "testing" -) - -func BenchmarkAESGCMSeal1K(b *testing.B) { - buf := make([]byte, 1024) - b.SetBytes(int64(len(buf))) - - var key [16]byte - var nonce [12]byte - aes, _ := aes.NewCipher(key[:]) - aesgcm, _ := cipher.NewGCM(aes) - var out []byte - - b.ResetTimer() - for i := 0; i < b.N; i++ { - out = aesgcm.Seal(out[:0], nonce[:], buf, nonce[:]) - } -} - -func BenchmarkAESGCMOpen1K(b *testing.B) { - buf := make([]byte, 1024) - b.SetBytes(int64(len(buf))) - - var key [16]byte - var nonce [12]byte - aes, _ := aes.NewCipher(key[:]) - aesgcm, _ := cipher.NewGCM(aes) - var out []byte - out = aesgcm.Seal(out[:0], nonce[:], buf, nonce[:]) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - _, err := aesgcm.Open(buf[:0], nonce[:], out, nonce[:]) - if err != nil { - b.Errorf("Open: %v", err) - } - } -} - -// If we test exactly 1K blocks, we would generate exact multiples of -// the cipher's block size, and the cipher stream fragments would -// always be wordsize aligned, whereas non-aligned is a more typical -// use-case. -const almost1K = 1024 - 5 - -func BenchmarkAESCFBEncrypt1K(b *testing.B) { - buf := make([]byte, almost1K) - b.SetBytes(int64(len(buf))) - - var key [16]byte - var iv [16]byte - aes, _ := aes.NewCipher(key[:]) - ctr := cipher.NewCFBEncrypter(aes, iv[:]) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - ctr.XORKeyStream(buf, buf) - } -} - -func BenchmarkAESCFBDecrypt1K(b *testing.B) { - buf := make([]byte, almost1K) - b.SetBytes(int64(len(buf))) - - var key [16]byte - var iv [16]byte - aes, _ := aes.NewCipher(key[:]) - ctr := cipher.NewCFBDecrypter(aes, iv[:]) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - ctr.XORKeyStream(buf, buf) - } -} - -func BenchmarkAESOFB1K(b *testing.B) { - buf := make([]byte, almost1K) - b.SetBytes(int64(len(buf))) - - var key [16]byte - var iv [16]byte - aes, _ := aes.NewCipher(key[:]) - ctr := cipher.NewOFB(aes, iv[:]) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - ctr.XORKeyStream(buf, buf) - } -} - -func BenchmarkAESCTR1K(b *testing.B) { - buf := make([]byte, almost1K) - b.SetBytes(int64(len(buf))) - - var key [16]byte - var iv [16]byte - aes, _ := aes.NewCipher(key[:]) - ctr := cipher.NewCTR(aes, iv[:]) - - b.ResetTimer() - for i := 0; i < b.N; i++ { - ctr.XORKeyStream(buf, buf) - } -} - -func BenchmarkAESCBCEncrypt1K(b *testing.B) { - buf := make([]byte, 1024) - b.SetBytes(int64(len(buf))) - - var key [16]byte - var iv [16]byte - aes, _ := aes.NewCipher(key[:]) - cbc := cipher.NewCBCEncrypter(aes, iv[:]) - for i := 0; i < b.N; i++ { - cbc.CryptBlocks(buf, buf) - } -} - -func BenchmarkAESCBCDecrypt1K(b *testing.B) { - buf := make([]byte, 1024) - b.SetBytes(int64(len(buf))) - - var key [16]byte - var iv [16]byte - aes, _ := aes.NewCipher(key[:]) - cbc := cipher.NewCBCDecrypter(aes, iv[:]) - for i := 0; i < b.N; i++ { - cbc.CryptBlocks(buf, buf) - } -} diff --git a/src/pkg/crypto/cipher/cbc.go b/src/pkg/crypto/cipher/cbc.go deleted file mode 100644 index 241e122ee..000000000 --- a/src/pkg/crypto/cipher/cbc.go +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Cipher block chaining (CBC) mode. - -// CBC provides confidentiality by xoring (chaining) each plaintext block -// with the previous ciphertext block before applying the block cipher. - -// See NIST SP 800-38A, pp 10-11 - -package cipher - -type cbc struct { - b Block - blockSize int - iv []byte - tmp []byte -} - -func newCBC(b Block, iv []byte) *cbc { - return &cbc{ - b: b, - blockSize: b.BlockSize(), - iv: dup(iv), - tmp: make([]byte, b.BlockSize()), - } -} - -type cbcEncrypter cbc - -// NewCBCEncrypter returns a BlockMode which encrypts in cipher block chaining -// mode, using the given Block. The length of iv must be the same as the -// Block's block size. -func NewCBCEncrypter(b Block, iv []byte) BlockMode { - if len(iv) != b.BlockSize() { - panic("cipher.NewCBCEncrypter: IV length must equal block size") - } - return (*cbcEncrypter)(newCBC(b, iv)) -} - -func (x *cbcEncrypter) BlockSize() int { return x.blockSize } - -func (x *cbcEncrypter) CryptBlocks(dst, src []byte) { - if len(src)%x.blockSize != 0 { - panic("crypto/cipher: input not full blocks") - } - if len(dst) < len(src) { - panic("crypto/cipher: output smaller than input") - } - - iv := x.iv - - for len(src) > 0 { - // Write the xor to dst, then encrypt in place. - xorBytes(dst[:x.blockSize], src[:x.blockSize], iv) - x.b.Encrypt(dst[:x.blockSize], dst[:x.blockSize]) - - // Move to the next block with this block as the next iv. - iv = dst[:x.blockSize] - src = src[x.blockSize:] - dst = dst[x.blockSize:] - } - - // Save the iv for the next CryptBlocks call. - copy(x.iv, iv) -} - -func (x *cbcEncrypter) SetIV(iv []byte) { - if len(iv) != len(x.iv) { - panic("cipher: incorrect length IV") - } - copy(x.iv, iv) -} - -type cbcDecrypter cbc - -// NewCBCDecrypter returns a BlockMode which decrypts in cipher block chaining -// mode, using the given Block. The length of iv must be the same as the -// Block's block size and must match the iv used to encrypt the data. -func NewCBCDecrypter(b Block, iv []byte) BlockMode { - if len(iv) != b.BlockSize() { - panic("cipher.NewCBCDecrypter: IV length must equal block size") - } - return (*cbcDecrypter)(newCBC(b, iv)) -} - -func (x *cbcDecrypter) BlockSize() int { return x.blockSize } - -func (x *cbcDecrypter) CryptBlocks(dst, src []byte) { - if len(src)%x.blockSize != 0 { - panic("crypto/cipher: input not full blocks") - } - if len(dst) < len(src) { - panic("crypto/cipher: output smaller than input") - } - if len(src) == 0 { - return - } - - // For each block, we need to xor the decrypted data with the previous block's ciphertext (the iv). - // To avoid making a copy each time, we loop over the blocks BACKWARDS. - end := len(src) - start := end - x.blockSize - prev := start - x.blockSize - - // Copy the last block of ciphertext in preparation as the new iv. - copy(x.tmp, src[start:end]) - - // Loop over all but the first block. - for start > 0 { - x.b.Decrypt(dst[start:end], src[start:end]) - xorBytes(dst[start:end], dst[start:end], src[prev:start]) - - end = start - start = prev - prev -= x.blockSize - } - - // The first block is special because it uses the saved iv. - x.b.Decrypt(dst[start:end], src[start:end]) - xorBytes(dst[start:end], dst[start:end], x.iv) - - // Set the new iv to the first block we copied earlier. - x.iv, x.tmp = x.tmp, x.iv -} - -func (x *cbcDecrypter) SetIV(iv []byte) { - if len(iv) != len(x.iv) { - panic("cipher: incorrect length IV") - } - copy(x.iv, iv) -} diff --git a/src/pkg/crypto/cipher/cbc_aes_test.go b/src/pkg/crypto/cipher/cbc_aes_test.go deleted file mode 100644 index bf9e7ad70..000000000 --- a/src/pkg/crypto/cipher/cbc_aes_test.go +++ /dev/null @@ -1,104 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// CBC AES test vectors. - -// See U.S. National Institute of Standards and Technology (NIST) -// Special Publication 800-38A, ``Recommendation for Block Cipher -// Modes of Operation,'' 2001 Edition, pp. 24-29. - -package cipher_test - -import ( - "bytes" - "crypto/aes" - "crypto/cipher" - "testing" -) - -var cbcAESTests = []struct { - name string - key []byte - iv []byte - in []byte - out []byte -}{ - // NIST SP 800-38A pp 27-29 - { - "CBC-AES128", - commonKey128, - commonIV, - commonInput, - []byte{ - 0x76, 0x49, 0xab, 0xac, 0x81, 0x19, 0xb2, 0x46, 0xce, 0xe9, 0x8e, 0x9b, 0x12, 0xe9, 0x19, 0x7d, - 0x50, 0x86, 0xcb, 0x9b, 0x50, 0x72, 0x19, 0xee, 0x95, 0xdb, 0x11, 0x3a, 0x91, 0x76, 0x78, 0xb2, - 0x73, 0xbe, 0xd6, 0xb8, 0xe3, 0xc1, 0x74, 0x3b, 0x71, 0x16, 0xe6, 0x9e, 0x22, 0x22, 0x95, 0x16, - 0x3f, 0xf1, 0xca, 0xa1, 0x68, 0x1f, 0xac, 0x09, 0x12, 0x0e, 0xca, 0x30, 0x75, 0x86, 0xe1, 0xa7, - }, - }, - { - "CBC-AES192", - commonKey192, - commonIV, - commonInput, - []byte{ - 0x4f, 0x02, 0x1d, 0xb2, 0x43, 0xbc, 0x63, 0x3d, 0x71, 0x78, 0x18, 0x3a, 0x9f, 0xa0, 0x71, 0xe8, - 0xb4, 0xd9, 0xad, 0xa9, 0xad, 0x7d, 0xed, 0xf4, 0xe5, 0xe7, 0x38, 0x76, 0x3f, 0x69, 0x14, 0x5a, - 0x57, 0x1b, 0x24, 0x20, 0x12, 0xfb, 0x7a, 0xe0, 0x7f, 0xa9, 0xba, 0xac, 0x3d, 0xf1, 0x02, 0xe0, - 0x08, 0xb0, 0xe2, 0x79, 0x88, 0x59, 0x88, 0x81, 0xd9, 0x20, 0xa9, 0xe6, 0x4f, 0x56, 0x15, 0xcd, - }, - }, - { - "CBC-AES256", - commonKey256, - commonIV, - commonInput, - []byte{ - 0xf5, 0x8c, 0x4c, 0x04, 0xd6, 0xe5, 0xf1, 0xba, 0x77, 0x9e, 0xab, 0xfb, 0x5f, 0x7b, 0xfb, 0xd6, - 0x9c, 0xfc, 0x4e, 0x96, 0x7e, 0xdb, 0x80, 0x8d, 0x67, 0x9f, 0x77, 0x7b, 0xc6, 0x70, 0x2c, 0x7d, - 0x39, 0xf2, 0x33, 0x69, 0xa9, 0xd9, 0xba, 0xcf, 0xa5, 0x30, 0xe2, 0x63, 0x04, 0x23, 0x14, 0x61, - 0xb2, 0xeb, 0x05, 0xe2, 0xc3, 0x9b, 0xe9, 0xfc, 0xda, 0x6c, 0x19, 0x07, 0x8c, 0x6a, 0x9d, 0x1b, - }, - }, -} - -func TestCBCEncrypterAES(t *testing.T) { - for _, test := range cbcAESTests { - c, err := aes.NewCipher(test.key) - if err != nil { - t.Errorf("%s: NewCipher(%d bytes) = %s", test.name, len(test.key), err) - continue - } - - encrypter := cipher.NewCBCEncrypter(c, test.iv) - - data := make([]byte, len(test.in)) - copy(data, test.in) - - encrypter.CryptBlocks(data, data) - if !bytes.Equal(test.out, data) { - t.Errorf("%s: CBCEncrypter\nhave %x\nwant %x", test.name, data, test.out) - } - } -} - -func TestCBCDecrypterAES(t *testing.T) { - for _, test := range cbcAESTests { - c, err := aes.NewCipher(test.key) - if err != nil { - t.Errorf("%s: NewCipher(%d bytes) = %s", test.name, len(test.key), err) - continue - } - - decrypter := cipher.NewCBCDecrypter(c, test.iv) - - data := make([]byte, len(test.out)) - copy(data, test.out) - - decrypter.CryptBlocks(data, data) - if !bytes.Equal(test.in, data) { - t.Errorf("%s: CBCDecrypter\nhave %x\nwant %x", test.name, data, test.in) - } - } -} diff --git a/src/pkg/crypto/cipher/cfb.go b/src/pkg/crypto/cipher/cfb.go deleted file mode 100644 index 9b4eebf5b..000000000 --- a/src/pkg/crypto/cipher/cfb.go +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// CFB (Cipher Feedback) Mode. - -package cipher - -type cfb struct { - b Block - next []byte - out []byte - outUsed int - - decrypt bool -} - -func (x *cfb) XORKeyStream(dst, src []byte) { - for len(src) > 0 { - if x.outUsed == len(x.out) { - x.b.Encrypt(x.out, x.next) - x.outUsed = 0 - } - - if x.decrypt { - // We can precompute a larger segment of the - // keystream on decryption. This will allow - // larger batches for xor, and we should be - // able to match CTR/OFB performance. - copy(x.next[x.outUsed:], src) - } - n := xorBytes(dst, src, x.out[x.outUsed:]) - if !x.decrypt { - copy(x.next[x.outUsed:], dst) - } - dst = dst[n:] - src = src[n:] - x.outUsed += n - } -} - -// NewCFBEncrypter returns a Stream which encrypts with cipher feedback mode, -// using the given Block. The iv must be the same length as the Block's block -// size. -func NewCFBEncrypter(block Block, iv []byte) Stream { - return newCFB(block, iv, false) -} - -// NewCFBDecrypter returns a Stream which decrypts with cipher feedback mode, -// using the given Block. The iv must be the same length as the Block's block -// size. -func NewCFBDecrypter(block Block, iv []byte) Stream { - return newCFB(block, iv, true) -} - -func newCFB(block Block, iv []byte, decrypt bool) Stream { - blockSize := block.BlockSize() - if len(iv) != blockSize { - // stack trace will indicate whether it was de or encryption - panic("cipher.newCFB: IV length must equal block size") - } - x := &cfb{ - b: block, - out: make([]byte, blockSize), - next: make([]byte, blockSize), - outUsed: blockSize, - decrypt: decrypt, - } - copy(x.next, iv) - - return x -} diff --git a/src/pkg/crypto/cipher/cfb_test.go b/src/pkg/crypto/cipher/cfb_test.go deleted file mode 100644 index 9b544bb21..000000000 --- a/src/pkg/crypto/cipher/cfb_test.go +++ /dev/null @@ -1,113 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cipher_test - -import ( - "bytes" - "crypto/aes" - "crypto/cipher" - "crypto/rand" - "encoding/hex" - "testing" -) - -// cfbTests contains the test vectors from -// http://csrc.nist.gov/publications/nistpubs/800-38a/sp800-38a.pdf, section -// F.3.13. -var cfbTests = []struct { - key, iv, plaintext, ciphertext string -}{ - { - "2b7e151628aed2a6abf7158809cf4f3c", - "000102030405060708090a0b0c0d0e0f", - "6bc1bee22e409f96e93d7e117393172a", - "3b3fd92eb72dad20333449f8e83cfb4a", - }, - { - "2b7e151628aed2a6abf7158809cf4f3c", - "3B3FD92EB72DAD20333449F8E83CFB4A", - "ae2d8a571e03ac9c9eb76fac45af8e51", - "c8a64537a0b3a93fcde3cdad9f1ce58b", - }, - { - "2b7e151628aed2a6abf7158809cf4f3c", - "C8A64537A0B3A93FCDE3CDAD9F1CE58B", - "30c81c46a35ce411e5fbc1191a0a52ef", - "26751f67a3cbb140b1808cf187a4f4df", - }, - { - "2b7e151628aed2a6abf7158809cf4f3c", - "26751F67A3CBB140B1808CF187A4F4DF", - "f69f2445df4f9b17ad2b417be66c3710", - "c04b05357c5d1c0eeac4c66f9ff7f2e6", - }, -} - -func TestCFBVectors(t *testing.T) { - for i, test := range cfbTests { - key, err := hex.DecodeString(test.key) - if err != nil { - t.Fatal(err) - } - iv, err := hex.DecodeString(test.iv) - if err != nil { - t.Fatal(err) - } - plaintext, err := hex.DecodeString(test.plaintext) - if err != nil { - t.Fatal(err) - } - expected, err := hex.DecodeString(test.ciphertext) - if err != nil { - t.Fatal(err) - } - - block, err := aes.NewCipher(key) - if err != nil { - t.Fatal(err) - } - - ciphertext := make([]byte, len(plaintext)) - cfb := cipher.NewCFBEncrypter(block, iv) - cfb.XORKeyStream(ciphertext, plaintext) - - if !bytes.Equal(ciphertext, expected) { - t.Errorf("#%d: wrong output: got %x, expected %x", i, ciphertext, expected) - } - - cfbdec := cipher.NewCFBDecrypter(block, iv) - plaintextCopy := make([]byte, len(ciphertext)) - cfbdec.XORKeyStream(plaintextCopy, ciphertext) - - if !bytes.Equal(plaintextCopy, plaintextCopy) { - t.Errorf("#%d: wrong plaintext: got %x, expected %x", i, plaintextCopy, plaintext) - } - } -} - -func TestCFBInverse(t *testing.T) { - block, err := aes.NewCipher(commonKey128) - if err != nil { - t.Error(err) - return - } - - plaintext := []byte("this is the plaintext. this is the plaintext.") - iv := make([]byte, block.BlockSize()) - rand.Reader.Read(iv) - cfb := cipher.NewCFBEncrypter(block, iv) - ciphertext := make([]byte, len(plaintext)) - copy(ciphertext, plaintext) - cfb.XORKeyStream(ciphertext, ciphertext) - - cfbdec := cipher.NewCFBDecrypter(block, iv) - plaintextCopy := make([]byte, len(plaintext)) - copy(plaintextCopy, ciphertext) - cfbdec.XORKeyStream(plaintextCopy, plaintextCopy) - - if !bytes.Equal(plaintextCopy, plaintext) { - t.Errorf("got: %x, want: %x", plaintextCopy, plaintext) - } -} diff --git a/src/pkg/crypto/cipher/cipher.go b/src/pkg/crypto/cipher/cipher.go deleted file mode 100644 index 67afdb1e0..000000000 --- a/src/pkg/crypto/cipher/cipher.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package cipher implements standard block cipher modes that can be wrapped -// around low-level block cipher implementations. -// See http://csrc.nist.gov/groups/ST/toolkit/BCM/current_modes.html -// and NIST Special Publication 800-38A. -package cipher - -// A Block represents an implementation of block cipher -// using a given key. It provides the capability to encrypt -// or decrypt individual blocks. The mode implementations -// extend that capability to streams of blocks. -type Block interface { - // BlockSize returns the cipher's block size. - BlockSize() int - - // Encrypt encrypts the first block in src into dst. - // Dst and src may point at the same memory. - Encrypt(dst, src []byte) - - // Decrypt decrypts the first block in src into dst. - // Dst and src may point at the same memory. - Decrypt(dst, src []byte) -} - -// A Stream represents a stream cipher. -type Stream interface { - // XORKeyStream XORs each byte in the given slice with a byte from the - // cipher's key stream. Dst and src may point to the same memory. - XORKeyStream(dst, src []byte) -} - -// A BlockMode represents a block cipher running in a block-based mode (CBC, -// ECB etc). -type BlockMode interface { - // BlockSize returns the mode's block size. - BlockSize() int - - // CryptBlocks encrypts or decrypts a number of blocks. The length of - // src must be a multiple of the block size. Dst and src may point to - // the same memory. - CryptBlocks(dst, src []byte) -} - -// Utility routines - -func dup(p []byte) []byte { - q := make([]byte, len(p)) - copy(q, p) - return q -} diff --git a/src/pkg/crypto/cipher/cipher_test.go b/src/pkg/crypto/cipher/cipher_test.go deleted file mode 100644 index 8da5bce93..000000000 --- a/src/pkg/crypto/cipher/cipher_test.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cipher_test - -import ( - "crypto/aes" - "crypto/cipher" - "testing" -) - -func TestCryptBlocks(t *testing.T) { - buf := make([]byte, 16) - block, _ := aes.NewCipher(buf) - - mode := cipher.NewCBCDecrypter(block, buf) - mustPanic(t, "crypto/cipher: input not full blocks", func() { mode.CryptBlocks(buf, buf[:3]) }) - mustPanic(t, "crypto/cipher: output smaller than input", func() { mode.CryptBlocks(buf[:3], buf) }) - - mode = cipher.NewCBCEncrypter(block, buf) - mustPanic(t, "crypto/cipher: input not full blocks", func() { mode.CryptBlocks(buf, buf[:3]) }) - mustPanic(t, "crypto/cipher: output smaller than input", func() { mode.CryptBlocks(buf[:3], buf) }) -} - -func mustPanic(t *testing.T, msg string, f func()) { - defer func() { - err := recover() - if err == nil { - t.Errorf("function did not panic, wanted %q", msg) - } else if err != msg { - t.Errorf("got panic %v, wanted %q", err, msg) - } - }() - f() -} diff --git a/src/pkg/crypto/cipher/common_test.go b/src/pkg/crypto/cipher/common_test.go deleted file mode 100644 index c75c919d1..000000000 --- a/src/pkg/crypto/cipher/common_test.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cipher_test - -// Common values for tests. - -var commonInput = []byte{ - 0x6b, 0xc1, 0xbe, 0xe2, 0x2e, 0x40, 0x9f, 0x96, 0xe9, 0x3d, 0x7e, 0x11, 0x73, 0x93, 0x17, 0x2a, - 0xae, 0x2d, 0x8a, 0x57, 0x1e, 0x03, 0xac, 0x9c, 0x9e, 0xb7, 0x6f, 0xac, 0x45, 0xaf, 0x8e, 0x51, - 0x30, 0xc8, 0x1c, 0x46, 0xa3, 0x5c, 0xe4, 0x11, 0xe5, 0xfb, 0xc1, 0x19, 0x1a, 0x0a, 0x52, 0xef, - 0xf6, 0x9f, 0x24, 0x45, 0xdf, 0x4f, 0x9b, 0x17, 0xad, 0x2b, 0x41, 0x7b, 0xe6, 0x6c, 0x37, 0x10, -} - -var commonKey128 = []byte{0x2b, 0x7e, 0x15, 0x16, 0x28, 0xae, 0xd2, 0xa6, 0xab, 0xf7, 0x15, 0x88, 0x09, 0xcf, 0x4f, 0x3c} - -var commonKey192 = []byte{ - 0x8e, 0x73, 0xb0, 0xf7, 0xda, 0x0e, 0x64, 0x52, 0xc8, 0x10, 0xf3, 0x2b, 0x80, 0x90, 0x79, 0xe5, - 0x62, 0xf8, 0xea, 0xd2, 0x52, 0x2c, 0x6b, 0x7b, -} - -var commonKey256 = []byte{ - 0x60, 0x3d, 0xeb, 0x10, 0x15, 0xca, 0x71, 0xbe, 0x2b, 0x73, 0xae, 0xf0, 0x85, 0x7d, 0x77, 0x81, - 0x1f, 0x35, 0x2c, 0x07, 0x3b, 0x61, 0x08, 0xd7, 0x2d, 0x98, 0x10, 0xa3, 0x09, 0x14, 0xdf, 0xf4, -} - -var commonIV = []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f} diff --git a/src/pkg/crypto/cipher/ctr.go b/src/pkg/crypto/cipher/ctr.go deleted file mode 100644 index 70ac40f6a..000000000 --- a/src/pkg/crypto/cipher/ctr.go +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Counter (CTR) mode. - -// CTR converts a block cipher into a stream cipher by -// repeatedly encrypting an incrementing counter and -// xoring the resulting stream of data with the input. - -// See NIST SP 800-38A, pp 13-15 - -package cipher - -type ctr struct { - b Block - ctr []byte - out []byte - outUsed int -} - -const streamBufferSize = 512 - -// NewCTR returns a Stream which encrypts/decrypts using the given Block in -// counter mode. The length of iv must be the same as the Block's block size. -func NewCTR(block Block, iv []byte) Stream { - if len(iv) != block.BlockSize() { - panic("cipher.NewCTR: IV length must equal block size") - } - bufSize := streamBufferSize - if bufSize < block.BlockSize() { - bufSize = block.BlockSize() - } - return &ctr{ - b: block, - ctr: dup(iv), - out: make([]byte, 0, bufSize), - outUsed: 0, - } -} - -func (x *ctr) refill() { - remain := len(x.out) - x.outUsed - if remain > x.outUsed { - return - } - copy(x.out, x.out[x.outUsed:]) - x.out = x.out[:cap(x.out)] - bs := x.b.BlockSize() - for remain < len(x.out)-bs { - x.b.Encrypt(x.out[remain:], x.ctr) - remain += bs - - // Increment counter - for i := len(x.ctr) - 1; i >= 0; i-- { - x.ctr[i]++ - if x.ctr[i] != 0 { - break - } - } - } - x.out = x.out[:remain] - x.outUsed = 0 -} - -func (x *ctr) XORKeyStream(dst, src []byte) { - for len(src) > 0 { - if x.outUsed >= len(x.out)-x.b.BlockSize() { - x.refill() - } - n := xorBytes(dst, src, x.out[x.outUsed:]) - dst = dst[n:] - src = src[n:] - x.outUsed += n - } -} diff --git a/src/pkg/crypto/cipher/ctr_aes_test.go b/src/pkg/crypto/cipher/ctr_aes_test.go deleted file mode 100644 index d019ae0d0..000000000 --- a/src/pkg/crypto/cipher/ctr_aes_test.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// CTR AES test vectors. - -// See U.S. National Institute of Standards and Technology (NIST) -// Special Publication 800-38A, ``Recommendation for Block Cipher -// Modes of Operation,'' 2001 Edition, pp. 55-58. - -package cipher_test - -import ( - "bytes" - "crypto/aes" - "crypto/cipher" - "testing" -) - -var commonCounter = []byte{0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff} - -var ctrAESTests = []struct { - name string - key []byte - iv []byte - in []byte - out []byte -}{ - // NIST SP 800-38A pp 55-58 - { - "CTR-AES128", - commonKey128, - commonCounter, - commonInput, - []byte{ - 0x87, 0x4d, 0x61, 0x91, 0xb6, 0x20, 0xe3, 0x26, 0x1b, 0xef, 0x68, 0x64, 0x99, 0x0d, 0xb6, 0xce, - 0x98, 0x06, 0xf6, 0x6b, 0x79, 0x70, 0xfd, 0xff, 0x86, 0x17, 0x18, 0x7b, 0xb9, 0xff, 0xfd, 0xff, - 0x5a, 0xe4, 0xdf, 0x3e, 0xdb, 0xd5, 0xd3, 0x5e, 0x5b, 0x4f, 0x09, 0x02, 0x0d, 0xb0, 0x3e, 0xab, - 0x1e, 0x03, 0x1d, 0xda, 0x2f, 0xbe, 0x03, 0xd1, 0x79, 0x21, 0x70, 0xa0, 0xf3, 0x00, 0x9c, 0xee, - }, - }, - { - "CTR-AES192", - commonKey192, - commonCounter, - commonInput, - []byte{ - 0x1a, 0xbc, 0x93, 0x24, 0x17, 0x52, 0x1c, 0xa2, 0x4f, 0x2b, 0x04, 0x59, 0xfe, 0x7e, 0x6e, 0x0b, - 0x09, 0x03, 0x39, 0xec, 0x0a, 0xa6, 0xfa, 0xef, 0xd5, 0xcc, 0xc2, 0xc6, 0xf4, 0xce, 0x8e, 0x94, - 0x1e, 0x36, 0xb2, 0x6b, 0xd1, 0xeb, 0xc6, 0x70, 0xd1, 0xbd, 0x1d, 0x66, 0x56, 0x20, 0xab, 0xf7, - 0x4f, 0x78, 0xa7, 0xf6, 0xd2, 0x98, 0x09, 0x58, 0x5a, 0x97, 0xda, 0xec, 0x58, 0xc6, 0xb0, 0x50, - }, - }, - { - "CTR-AES256", - commonKey256, - commonCounter, - commonInput, - []byte{ - 0x60, 0x1e, 0xc3, 0x13, 0x77, 0x57, 0x89, 0xa5, 0xb7, 0xa7, 0xf5, 0x04, 0xbb, 0xf3, 0xd2, 0x28, - 0xf4, 0x43, 0xe3, 0xca, 0x4d, 0x62, 0xb5, 0x9a, 0xca, 0x84, 0xe9, 0x90, 0xca, 0xca, 0xf5, 0xc5, - 0x2b, 0x09, 0x30, 0xda, 0xa2, 0x3d, 0xe9, 0x4c, 0xe8, 0x70, 0x17, 0xba, 0x2d, 0x84, 0x98, 0x8d, - 0xdf, 0xc9, 0xc5, 0x8d, 0xb6, 0x7a, 0xad, 0xa6, 0x13, 0xc2, 0xdd, 0x08, 0x45, 0x79, 0x41, 0xa6, - }, - }, -} - -func TestCTR_AES(t *testing.T) { - for _, tt := range ctrAESTests { - test := tt.name - - c, err := aes.NewCipher(tt.key) - if err != nil { - t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err) - continue - } - - for j := 0; j <= 5; j += 5 { - in := tt.in[0 : len(tt.in)-j] - ctr := cipher.NewCTR(c, tt.iv) - encrypted := make([]byte, len(in)) - ctr.XORKeyStream(encrypted, in) - if out := tt.out[0:len(in)]; !bytes.Equal(out, encrypted) { - t.Errorf("%s/%d: CTR\ninpt %x\nhave %x\nwant %x", test, len(in), in, encrypted, out) - } - } - - for j := 0; j <= 7; j += 7 { - in := tt.out[0 : len(tt.out)-j] - ctr := cipher.NewCTR(c, tt.iv) - plain := make([]byte, len(in)) - ctr.XORKeyStream(plain, in) - if out := tt.in[0:len(in)]; !bytes.Equal(out, plain) { - t.Errorf("%s/%d: CTRReader\nhave %x\nwant %x", test, len(out), plain, out) - } - } - - if t.Failed() { - break - } - } -} diff --git a/src/pkg/crypto/cipher/example_test.go b/src/pkg/crypto/cipher/example_test.go deleted file mode 100644 index 1cfa982df..000000000 --- a/src/pkg/crypto/cipher/example_test.go +++ /dev/null @@ -1,283 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cipher_test - -import ( - "crypto/aes" - "crypto/cipher" - "crypto/rand" - "encoding/hex" - "fmt" - "io" - "os" -) - -func ExampleNewCBCDecrypter() { - key := []byte("example key 1234") - ciphertext, _ := hex.DecodeString("f363f3ccdcb12bb883abf484ba77d9cd7d32b5baecb3d4b1b3e0e4beffdb3ded") - - block, err := aes.NewCipher(key) - if err != nil { - panic(err) - } - - // The IV needs to be unique, but not secure. Therefore it's common to - // include it at the beginning of the ciphertext. - if len(ciphertext) < aes.BlockSize { - panic("ciphertext too short") - } - iv := ciphertext[:aes.BlockSize] - ciphertext = ciphertext[aes.BlockSize:] - - // CBC mode always works in whole blocks. - if len(ciphertext)%aes.BlockSize != 0 { - panic("ciphertext is not a multiple of the block size") - } - - mode := cipher.NewCBCDecrypter(block, iv) - - // CryptBlocks can work in-place if the two arguments are the same. - mode.CryptBlocks(ciphertext, ciphertext) - - // If the original plaintext lengths are not a multiple of the block - // size, padding would have to be added when encrypting, which would be - // removed at this point. For an example, see - // https://tools.ietf.org/html/rfc5246#section-6.2.3.2. However, it's - // critical to note that ciphertexts must be authenticated (i.e. by - // using crypto/hmac) before being decrypted in order to avoid creating - // a padding oracle. - - fmt.Printf("%s\n", ciphertext) - // Output: exampleplaintext -} - -func ExampleNewCBCEncrypter() { - key := []byte("example key 1234") - plaintext := []byte("exampleplaintext") - - // CBC mode works on blocks so plaintexts may need to be padded to the - // next whole block. For an example of such padding, see - // https://tools.ietf.org/html/rfc5246#section-6.2.3.2. Here we'll - // assume that the plaintext is already of the correct length. - if len(plaintext)%aes.BlockSize != 0 { - panic("plaintext is not a multiple of the block size") - } - - block, err := aes.NewCipher(key) - if err != nil { - panic(err) - } - - // The IV needs to be unique, but not secure. Therefore it's common to - // include it at the beginning of the ciphertext. - ciphertext := make([]byte, aes.BlockSize+len(plaintext)) - iv := ciphertext[:aes.BlockSize] - if _, err := io.ReadFull(rand.Reader, iv); err != nil { - panic(err) - } - - mode := cipher.NewCBCEncrypter(block, iv) - mode.CryptBlocks(ciphertext[aes.BlockSize:], plaintext) - - // It's important to remember that ciphertexts must be authenticated - // (i.e. by using crypto/hmac) as well as being encrypted in order to - // be secure. - - fmt.Printf("%x\n", ciphertext) -} - -func ExampleNewCFBDecrypter() { - key := []byte("example key 1234") - ciphertext, _ := hex.DecodeString("22277966616d9bc47177bd02603d08c9a67d5380d0fe8cf3b44438dff7b9") - - block, err := aes.NewCipher(key) - if err != nil { - panic(err) - } - - // The IV needs to be unique, but not secure. Therefore it's common to - // include it at the beginning of the ciphertext. - if len(ciphertext) < aes.BlockSize { - panic("ciphertext too short") - } - iv := ciphertext[:aes.BlockSize] - ciphertext = ciphertext[aes.BlockSize:] - - stream := cipher.NewCFBDecrypter(block, iv) - - // XORKeyStream can work in-place if the two arguments are the same. - stream.XORKeyStream(ciphertext, ciphertext) - fmt.Printf("%s", ciphertext) - // Output: some plaintext -} - -func ExampleNewCFBEncrypter() { - key := []byte("example key 1234") - plaintext := []byte("some plaintext") - - block, err := aes.NewCipher(key) - if err != nil { - panic(err) - } - - // The IV needs to be unique, but not secure. Therefore it's common to - // include it at the beginning of the ciphertext. - ciphertext := make([]byte, aes.BlockSize+len(plaintext)) - iv := ciphertext[:aes.BlockSize] - if _, err := io.ReadFull(rand.Reader, iv); err != nil { - panic(err) - } - - stream := cipher.NewCFBEncrypter(block, iv) - stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext) - - // It's important to remember that ciphertexts must be authenticated - // (i.e. by using crypto/hmac) as well as being encrypted in order to - // be secure. -} - -func ExampleNewCTR() { - key := []byte("example key 1234") - plaintext := []byte("some plaintext") - - block, err := aes.NewCipher(key) - if err != nil { - panic(err) - } - - // The IV needs to be unique, but not secure. Therefore it's common to - // include it at the beginning of the ciphertext. - ciphertext := make([]byte, aes.BlockSize+len(plaintext)) - iv := ciphertext[:aes.BlockSize] - if _, err := io.ReadFull(rand.Reader, iv); err != nil { - panic(err) - } - - stream := cipher.NewCTR(block, iv) - stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext) - - // It's important to remember that ciphertexts must be authenticated - // (i.e. by using crypto/hmac) as well as being encrypted in order to - // be secure. - - // CTR mode is the same for both encryption and decryption, so we can - // also decrypt that ciphertext with NewCTR. - - plaintext2 := make([]byte, len(plaintext)) - stream = cipher.NewCTR(block, iv) - stream.XORKeyStream(plaintext2, ciphertext[aes.BlockSize:]) - - fmt.Printf("%s\n", plaintext2) - // Output: some plaintext -} - -func ExampleNewOFB() { - key := []byte("example key 1234") - plaintext := []byte("some plaintext") - - block, err := aes.NewCipher(key) - if err != nil { - panic(err) - } - - // The IV needs to be unique, but not secure. Therefore it's common to - // include it at the beginning of the ciphertext. - ciphertext := make([]byte, aes.BlockSize+len(plaintext)) - iv := ciphertext[:aes.BlockSize] - if _, err := io.ReadFull(rand.Reader, iv); err != nil { - panic(err) - } - - stream := cipher.NewOFB(block, iv) - stream.XORKeyStream(ciphertext[aes.BlockSize:], plaintext) - - // It's important to remember that ciphertexts must be authenticated - // (i.e. by using crypto/hmac) as well as being encrypted in order to - // be secure. - - // OFB mode is the same for both encryption and decryption, so we can - // also decrypt that ciphertext with NewOFB. - - plaintext2 := make([]byte, len(plaintext)) - stream = cipher.NewOFB(block, iv) - stream.XORKeyStream(plaintext2, ciphertext[aes.BlockSize:]) - - fmt.Printf("%s\n", plaintext2) - // Output: some plaintext -} - -func ExampleStreamReader() { - key := []byte("example key 1234") - - inFile, err := os.Open("encrypted-file") - if err != nil { - panic(err) - } - defer inFile.Close() - - block, err := aes.NewCipher(key) - if err != nil { - panic(err) - } - - // If the key is unique for each ciphertext, then it's ok to use a zero - // IV. - var iv [aes.BlockSize]byte - stream := cipher.NewOFB(block, iv[:]) - - outFile, err := os.OpenFile("decrypted-file", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) - if err != nil { - panic(err) - } - defer outFile.Close() - - reader := &cipher.StreamReader{S: stream, R: inFile} - // Copy the input file to the output file, decrypting as we go. - if _, err := io.Copy(outFile, reader); err != nil { - panic(err) - } - - // Note that this example is simplistic in that it omits any - // authentication of the encrypted data. If you were actually to use - // StreamReader in this manner, an attacker could flip arbitrary bits in - // the output. -} - -func ExampleStreamWriter() { - key := []byte("example key 1234") - - inFile, err := os.Open("plaintext-file") - if err != nil { - panic(err) - } - defer inFile.Close() - - block, err := aes.NewCipher(key) - if err != nil { - panic(err) - } - - // If the key is unique for each ciphertext, then it's ok to use a zero - // IV. - var iv [aes.BlockSize]byte - stream := cipher.NewOFB(block, iv[:]) - - outFile, err := os.OpenFile("encrypted-file", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) - if err != nil { - panic(err) - } - defer outFile.Close() - - writer := &cipher.StreamWriter{S: stream, W: outFile} - // Copy the input file to the output file, encrypting as we go. - if _, err := io.Copy(writer, inFile); err != nil { - panic(err) - } - - // Note that this example is simplistic in that it omits any - // authentication of the encrypted data. If you were actually to use - // StreamReader in this manner, an attacker could flip arbitrary bits in - // the decrypted result. -} diff --git a/src/pkg/crypto/cipher/gcm.go b/src/pkg/crypto/cipher/gcm.go deleted file mode 100644 index bdafd85fc..000000000 --- a/src/pkg/crypto/cipher/gcm.go +++ /dev/null @@ -1,343 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cipher - -import ( - "crypto/subtle" - "errors" -) - -// AEAD is a cipher mode providing authenticated encryption with associated -// data. -type AEAD interface { - // NonceSize returns the size of the nonce that must be passed to Seal - // and Open. - NonceSize() int - - // Overhead returns the maximum difference between the lengths of a - // plaintext and ciphertext. - Overhead() int - - // Seal encrypts and authenticates plaintext, authenticates the - // additional data and appends the result to dst, returning the updated - // slice. The nonce must be NonceSize() bytes long and unique for all - // time, for a given key. - // - // The plaintext and dst may alias exactly or not at all. - Seal(dst, nonce, plaintext, data []byte) []byte - - // Open decrypts and authenticates ciphertext, authenticates the - // additional data and, if successful, appends the resulting plaintext - // to dst, returning the updated slice. The nonce must be NonceSize() - // bytes long and both it and the additional data must match the - // value passed to Seal. - // - // The ciphertext and dst may alias exactly or not at all. - Open(dst, nonce, ciphertext, data []byte) ([]byte, error) -} - -// gcmFieldElement represents a value in GF(2¹²⁸). In order to reflect the GCM -// standard and make getUint64 suitable for marshaling these values, the bits -// are stored backwards. For example: -// the coefficient of x⁰ can be obtained by v.low >> 63. -// the coefficient of x⁶³ can be obtained by v.low & 1. -// the coefficient of x⁶⁴ can be obtained by v.high >> 63. -// the coefficient of x¹²⁷ can be obtained by v.high & 1. -type gcmFieldElement struct { - low, high uint64 -} - -// gcm represents a Galois Counter Mode with a specific key. See -// http://csrc.nist.gov/groups/ST/toolkit/BCM/documents/proposedmodes/gcm/gcm-revised-spec.pdf -type gcm struct { - cipher Block - // productTable contains the first sixteen powers of the key, H. - // However, they are in bit reversed order. See NewGCM. - productTable [16]gcmFieldElement -} - -// NewGCM returns the given 128-bit, block cipher wrapped in Galois Counter Mode. -func NewGCM(cipher Block) (AEAD, error) { - if cipher.BlockSize() != gcmBlockSize { - return nil, errors.New("cipher: NewGCM requires 128-bit block cipher") - } - - var key [gcmBlockSize]byte - cipher.Encrypt(key[:], key[:]) - - g := &gcm{cipher: cipher} - - // We precompute 16 multiples of |key|. However, when we do lookups - // into this table we'll be using bits from a field element and - // therefore the bits will be in the reverse order. So normally one - // would expect, say, 4*key to be in index 4 of the table but due to - // this bit ordering it will actually be in index 0010 (base 2) = 2. - x := gcmFieldElement{ - getUint64(key[:8]), - getUint64(key[8:]), - } - g.productTable[reverseBits(1)] = x - - for i := 2; i < 16; i += 2 { - g.productTable[reverseBits(i)] = gcmDouble(&g.productTable[reverseBits(i/2)]) - g.productTable[reverseBits(i+1)] = gcmAdd(&g.productTable[reverseBits(i)], &x) - } - - return g, nil -} - -const ( - gcmBlockSize = 16 - gcmTagSize = 16 - gcmNonceSize = 12 -) - -func (*gcm) NonceSize() int { - return gcmNonceSize -} - -func (*gcm) Overhead() int { - return gcmTagSize -} - -func (g *gcm) Seal(dst, nonce, plaintext, data []byte) []byte { - if len(nonce) != gcmNonceSize { - panic("cipher: incorrect nonce length given to GCM") - } - - ret, out := sliceForAppend(dst, len(plaintext)+gcmTagSize) - - // See GCM spec, section 7.1. - var counter, tagMask [gcmBlockSize]byte - copy(counter[:], nonce) - counter[gcmBlockSize-1] = 1 - - g.cipher.Encrypt(tagMask[:], counter[:]) - gcmInc32(&counter) - - g.counterCrypt(out, plaintext, &counter) - g.auth(out[len(plaintext):], out[:len(plaintext)], data, &tagMask) - - return ret -} - -var errOpen = errors.New("cipher: message authentication failed") - -func (g *gcm) Open(dst, nonce, ciphertext, data []byte) ([]byte, error) { - if len(nonce) != gcmNonceSize { - panic("cipher: incorrect nonce length given to GCM") - } - - if len(ciphertext) < gcmTagSize { - return nil, errOpen - } - tag := ciphertext[len(ciphertext)-gcmTagSize:] - ciphertext = ciphertext[:len(ciphertext)-gcmTagSize] - - // See GCM spec, section 7.1. - var counter, tagMask [gcmBlockSize]byte - copy(counter[:], nonce) - counter[gcmBlockSize-1] = 1 - - g.cipher.Encrypt(tagMask[:], counter[:]) - gcmInc32(&counter) - - var expectedTag [gcmTagSize]byte - g.auth(expectedTag[:], ciphertext, data, &tagMask) - - if subtle.ConstantTimeCompare(expectedTag[:], tag) != 1 { - return nil, errOpen - } - - ret, out := sliceForAppend(dst, len(ciphertext)) - g.counterCrypt(out, ciphertext, &counter) - - return ret, nil -} - -// reverseBits reverses the order of the bits of 4-bit number in i. -func reverseBits(i int) int { - i = ((i << 2) & 0xc) | ((i >> 2) & 0x3) - i = ((i << 1) & 0xa) | ((i >> 1) & 0x5) - return i -} - -// gcmAdd adds two elements of GF(2¹²⁸) and returns the sum. -func gcmAdd(x, y *gcmFieldElement) gcmFieldElement { - // Addition in a characteristic 2 field is just XOR. - return gcmFieldElement{x.low ^ y.low, x.high ^ y.high} -} - -// gcmDouble returns the result of doubling an element of GF(2¹²⁸). -func gcmDouble(x *gcmFieldElement) (double gcmFieldElement) { - msbSet := x.high&1 == 1 - - // Because of the bit-ordering, doubling is actually a right shift. - double.high = x.high >> 1 - double.high |= x.low << 63 - double.low = x.low >> 1 - - // If the most-significant bit was set before shifting then it, - // conceptually, becomes a term of x^128. This is greater than the - // irreducible polynomial so the result has to be reduced. The - // irreducible polynomial is 1+x+x^2+x^7+x^128. We can subtract that to - // eliminate the term at x^128 which also means subtracting the other - // four terms. In characteristic 2 fields, subtraction == addition == - // XOR. - if msbSet { - double.low ^= 0xe100000000000000 - } - - return -} - -var gcmReductionTable = []uint16{ - 0x0000, 0x1c20, 0x3840, 0x2460, 0x7080, 0x6ca0, 0x48c0, 0x54e0, - 0xe100, 0xfd20, 0xd940, 0xc560, 0x9180, 0x8da0, 0xa9c0, 0xb5e0, -} - -// mul sets y to y*H, where H is the GCM key, fixed during NewGCM. -func (g *gcm) mul(y *gcmFieldElement) { - var z gcmFieldElement - - for i := 0; i < 2; i++ { - word := y.high - if i == 1 { - word = y.low - } - - // Multiplication works by multiplying z by 16 and adding in - // one of the precomputed multiples of H. - for j := 0; j < 64; j += 4 { - msw := z.high & 0xf - z.high >>= 4 - z.high |= z.low << 60 - z.low >>= 4 - z.low ^= uint64(gcmReductionTable[msw]) << 48 - - // the values in |table| are ordered for - // little-endian bit positions. See the comment - // in NewGCM. - t := &g.productTable[word&0xf] - - z.low ^= t.low - z.high ^= t.high - word >>= 4 - } - } - - *y = z -} - -// updateBlocks extends y with more polynomial terms from blocks, based on -// Horner's rule. There must be a multiple of gcmBlockSize bytes in blocks. -func (g *gcm) updateBlocks(y *gcmFieldElement, blocks []byte) { - for len(blocks) > 0 { - y.low ^= getUint64(blocks) - y.high ^= getUint64(blocks[8:]) - g.mul(y) - blocks = blocks[gcmBlockSize:] - } -} - -// update extends y with more polynomial terms from data. If data is not a -// multiple of gcmBlockSize bytes long then the remainder is zero padded. -func (g *gcm) update(y *gcmFieldElement, data []byte) { - fullBlocks := (len(data) >> 4) << 4 - g.updateBlocks(y, data[:fullBlocks]) - - if len(data) != fullBlocks { - var partialBlock [gcmBlockSize]byte - copy(partialBlock[:], data[fullBlocks:]) - g.updateBlocks(y, partialBlock[:]) - } -} - -// gcmInc32 treats the final four bytes of counterBlock as a big-endian value -// and increments it. -func gcmInc32(counterBlock *[16]byte) { - for i := gcmBlockSize - 1; i >= gcmBlockSize-4; i-- { - counterBlock[i]++ - if counterBlock[i] != 0 { - break - } - } -} - -// sliceForAppend takes a slice and a requested number of bytes. It returns a -// slice with the contents of the given slice followed by that many bytes and a -// second slice that aliases into it and contains only the extra bytes. If the -// original slice has sufficient capacity then no allocation is performed. -func sliceForAppend(in []byte, n int) (head, tail []byte) { - if total := len(in) + n; cap(in) >= total { - head = in[:total] - } else { - head = make([]byte, total) - copy(head, in) - } - tail = head[len(in):] - return -} - -// counterCrypt crypts in to out using g.cipher in counter mode. -func (g *gcm) counterCrypt(out, in []byte, counter *[gcmBlockSize]byte) { - var mask [gcmBlockSize]byte - - for len(in) >= gcmBlockSize { - g.cipher.Encrypt(mask[:], counter[:]) - gcmInc32(counter) - - xorWords(out, in, mask[:]) - out = out[gcmBlockSize:] - in = in[gcmBlockSize:] - } - - if len(in) > 0 { - g.cipher.Encrypt(mask[:], counter[:]) - gcmInc32(counter) - xorBytes(out, in, mask[:]) - } -} - -// auth calculates GHASH(ciphertext, additionalData), masks the result with -// tagMask and writes the result to out. -func (g *gcm) auth(out, ciphertext, additionalData []byte, tagMask *[gcmTagSize]byte) { - var y gcmFieldElement - g.update(&y, additionalData) - g.update(&y, ciphertext) - - y.low ^= uint64(len(additionalData)) * 8 - y.high ^= uint64(len(ciphertext)) * 8 - - g.mul(&y) - - putUint64(out, y.low) - putUint64(out[8:], y.high) - - xorWords(out, out, tagMask[:]) -} - -func getUint64(data []byte) uint64 { - r := uint64(data[0])<<56 | - uint64(data[1])<<48 | - uint64(data[2])<<40 | - uint64(data[3])<<32 | - uint64(data[4])<<24 | - uint64(data[5])<<16 | - uint64(data[6])<<8 | - uint64(data[7]) - return r -} - -func putUint64(out []byte, v uint64) { - out[0] = byte(v >> 56) - out[1] = byte(v >> 48) - out[2] = byte(v >> 40) - out[3] = byte(v >> 32) - out[4] = byte(v >> 24) - out[5] = byte(v >> 16) - out[6] = byte(v >> 8) - out[7] = byte(v) -} diff --git a/src/pkg/crypto/cipher/gcm_test.go b/src/pkg/crypto/cipher/gcm_test.go deleted file mode 100644 index 0c502ce40..000000000 --- a/src/pkg/crypto/cipher/gcm_test.go +++ /dev/null @@ -1,159 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cipher_test - -import ( - "bytes" - "crypto/aes" - "crypto/cipher" - "encoding/hex" - "testing" -) - -// AES-GCM test vectors taken from gcmEncryptExtIV128.rsp from -// http://csrc.nist.gov/groups/STM/cavp/index.html. -var aesGCMTests = []struct { - key, nonce, plaintext, ad, result string -}{ - { - "11754cd72aec309bf52f7687212e8957", - "3c819d9a9bed087615030b65", - "", - "", - "250327c674aaf477aef2675748cf6971", - }, - { - "ca47248ac0b6f8372a97ac43508308ed", - "ffd2b598feabc9019262d2be", - "", - "", - "60d20404af527d248d893ae495707d1a", - }, - { - "77be63708971c4e240d1cb79e8d77feb", - "e0e00f19fed7ba0136a797f3", - "", - "7a43ec1d9c0a5a78a0b16533a6213cab", - "209fcc8d3675ed938e9c7166709dd946", - }, - { - "7680c5d3ca6154758e510f4d25b98820", - "f8f105f9c3df4965780321f8", - "", - "c94c410194c765e3dcc7964379758ed3", - "94dca8edfcf90bb74b153c8d48a17930", - }, - { - "7fddb57453c241d03efbed3ac44e371c", - "ee283a3fc75575e33efd4887", - "d5de42b461646c255c87bd2962d3b9a2", - "", - "2ccda4a5415cb91e135c2a0f78c9b2fdb36d1df9b9d5e596f83e8b7f52971cb3", - }, - { - "ab72c77b97cb5fe9a382d9fe81ffdbed", - "54cc7dc2c37ec006bcc6d1da", - "007c5e5b3e59df24a7c355584fc1518d", - "", - "0e1bde206a07a9c2c1b65300f8c649972b4401346697138c7a4891ee59867d0c", - }, - { - "fe47fcce5fc32665d2ae399e4eec72ba", - "5adb9609dbaeb58cbd6e7275", - "7c0e88c88899a779228465074797cd4c2e1498d259b54390b85e3eef1c02df60e743f1b840382c4bccaf3bafb4ca8429bea063", - "88319d6e1d3ffa5f987199166c8a9b56c2aeba5a", - "98f4826f05a265e6dd2be82db241c0fbbbf9ffb1c173aa83964b7cf5393043736365253ddbc5db8778371495da76d269e5db3e291ef1982e4defedaa2249f898556b47", - }, - { - "ec0c2ba17aa95cd6afffe949da9cc3a8", - "296bce5b50b7d66096d627ef", - "b85b3753535b825cbe5f632c0b843c741351f18aa484281aebec2f45bb9eea2d79d987b764b9611f6c0f8641843d5d58f3a242", - "f8d00f05d22bf68599bcdeb131292ad6e2df5d14", - "a7443d31c26bdf2a1c945e29ee4bd344a99cfaf3aa71f8b3f191f83c2adfc7a07162995506fde6309ffc19e716eddf1a828c5a890147971946b627c40016da1ecf3e77", - }, - { - "2c1f21cf0f6fb3661943155c3e3d8492", - "23cb5ff362e22426984d1907", - "42f758836986954db44bf37c6ef5e4ac0adaf38f27252a1b82d02ea949c8a1a2dbc0d68b5615ba7c1220ff6510e259f06655d8", - "5d3624879d35e46849953e45a32a624d6a6c536ed9857c613b572b0333e701557a713e3f010ecdf9a6bd6c9e3e44b065208645aff4aabee611b391528514170084ccf587177f4488f33cfb5e979e42b6e1cfc0a60238982a7aec", - "81824f0e0d523db30d3da369fdc0d60894c7a0a20646dd015073ad2732bd989b14a222b6ad57af43e1895df9dca2a5344a62cc57a3ee28136e94c74838997ae9823f3a", - }, - { - "d9f7d2411091f947b4d6f1e2d1f0fb2e", - "e1934f5db57cc983e6b180e7", - "73ed042327f70fe9c572a61545eda8b2a0c6e1d6c291ef19248e973aee6c312012f490c2c6f6166f4a59431e182663fcaea05a", - "0a8a18a7150e940c3d87b38e73baee9a5c049ee21795663e264b694a949822b639092d0e67015e86363583fcf0ca645af9f43375f05fdb4ce84f411dcbca73c2220dea03a20115d2e51398344b16bee1ed7c499b353d6c597af8", - "aaadbd5c92e9151ce3db7210b8714126b73e43436d242677afa50384f2149b831f1d573c7891c2a91fbc48db29967ec9542b2321b51ca862cb637cdd03b99a0f93b134", - }, - { - "fe9bb47deb3a61e423c2231841cfd1fb", - "4d328eb776f500a2f7fb47aa", - "f1cc3818e421876bb6b8bbd6c9", - "", - "b88c5c1977b35b517b0aeae96743fd4727fe5cdb4b5b42818dea7ef8c9", - }, - { - "6703df3701a7f54911ca72e24dca046a", - "12823ab601c350ea4bc2488c", - "793cd125b0b84a043e3ac67717", - "", - "b2051c80014f42f08735a7b0cd38e6bcd29962e5f2c13626b85a877101", - }, -} - -func TestAESGCM(t *testing.T) { - for i, test := range aesGCMTests { - key, _ := hex.DecodeString(test.key) - aes, err := aes.NewCipher(key) - if err != nil { - t.Fatal(err) - } - - nonce, _ := hex.DecodeString(test.nonce) - plaintext, _ := hex.DecodeString(test.plaintext) - ad, _ := hex.DecodeString(test.ad) - aesgcm, err := cipher.NewGCM(aes) - if err != nil { - t.Fatal(err) - } - - ct := aesgcm.Seal(nil, nonce, plaintext, ad) - if ctHex := hex.EncodeToString(ct); ctHex != test.result { - t.Errorf("#%d: got %s, want %s", i, ctHex, test.result) - continue - } - - plaintext2, err := aesgcm.Open(nil, nonce, ct, ad) - if err != nil { - t.Errorf("#%d: Open failed", i) - continue - } - - if !bytes.Equal(plaintext, plaintext2) { - t.Errorf("#%d: plaintext's don't match: got %x vs %x", i, plaintext2, plaintext) - continue - } - - if len(ad) > 0 { - ad[0] ^= 0x80 - if _, err := aesgcm.Open(nil, nonce, ct, ad); err == nil { - t.Errorf("#%d: Open was successful after altering additional data", i) - } - ad[0] ^= 0x80 - } - - nonce[0] ^= 0x80 - if _, err := aesgcm.Open(nil, nonce, ct, ad); err == nil { - t.Errorf("#%d: Open was successful after altering nonce", i) - } - nonce[0] ^= 0x80 - - ct[0] ^= 0x80 - if _, err := aesgcm.Open(nil, nonce, ct, ad); err == nil { - t.Errorf("#%d: Open was successful after altering ciphertext", i) - } - ct[0] ^= 0x80 - } -} diff --git a/src/pkg/crypto/cipher/io.go b/src/pkg/crypto/cipher/io.go deleted file mode 100644 index 3938c0a4c..000000000 --- a/src/pkg/crypto/cipher/io.go +++ /dev/null @@ -1,55 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cipher - -import "io" - -// The Stream* objects are so simple that all their members are public. Users -// can create them themselves. - -// StreamReader wraps a Stream into an io.Reader. It calls XORKeyStream -// to process each slice of data which passes through. -type StreamReader struct { - S Stream - R io.Reader -} - -func (r StreamReader) Read(dst []byte) (n int, err error) { - n, err = r.R.Read(dst) - r.S.XORKeyStream(dst[:n], dst[:n]) - return -} - -// StreamWriter wraps a Stream into an io.Writer. It calls XORKeyStream -// to process each slice of data which passes through. If any Write call -// returns short then the StreamWriter is out of sync and must be discarded. -// A StreamWriter has no internal buffering; Close does not need -// to be called to flush write data. -type StreamWriter struct { - S Stream - W io.Writer - Err error // unused -} - -func (w StreamWriter) Write(src []byte) (n int, err error) { - c := make([]byte, len(src)) - w.S.XORKeyStream(c, src) - n, err = w.W.Write(c) - if n != len(src) { - if err == nil { // should never happen - err = io.ErrShortWrite - } - } - return -} - -// Close closes the underlying Writer and returns its Close return value, if the Writer -// is also an io.Closer. Otherwise it returns nil. -func (w StreamWriter) Close() error { - if c, ok := w.W.(io.Closer); ok { - return c.Close() - } - return nil -} diff --git a/src/pkg/crypto/cipher/ofb.go b/src/pkg/crypto/cipher/ofb.go deleted file mode 100644 index e86ebcb23..000000000 --- a/src/pkg/crypto/cipher/ofb.go +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// OFB (Output Feedback) Mode. - -package cipher - -type ofb struct { - b Block - cipher []byte - out []byte - outUsed int -} - -// NewOFB returns a Stream that encrypts or decrypts using the block cipher b -// in output feedback mode. The initialization vector iv's length must be equal -// to b's block size. -func NewOFB(b Block, iv []byte) Stream { - blockSize := b.BlockSize() - if len(iv) != blockSize { - return nil - } - bufSize := streamBufferSize - if bufSize < blockSize { - bufSize = blockSize - } - x := &ofb{ - b: b, - cipher: make([]byte, blockSize), - out: make([]byte, 0, bufSize), - outUsed: 0, - } - - copy(x.cipher, iv) - return x -} - -func (x *ofb) refill() { - bs := x.b.BlockSize() - remain := len(x.out) - x.outUsed - if remain > x.outUsed { - return - } - copy(x.out, x.out[x.outUsed:]) - x.out = x.out[:cap(x.out)] - for remain < len(x.out)-bs { - x.b.Encrypt(x.cipher, x.cipher) - copy(x.out[remain:], x.cipher) - remain += bs - } - x.out = x.out[:remain] - x.outUsed = 0 -} - -func (x *ofb) XORKeyStream(dst, src []byte) { - for len(src) > 0 { - if x.outUsed >= len(x.out)-x.b.BlockSize() { - x.refill() - } - n := xorBytes(dst, src, x.out[x.outUsed:]) - dst = dst[n:] - src = src[n:] - x.outUsed += n - } -} diff --git a/src/pkg/crypto/cipher/ofb_test.go b/src/pkg/crypto/cipher/ofb_test.go deleted file mode 100644 index 8d3c5d3a3..000000000 --- a/src/pkg/crypto/cipher/ofb_test.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// OFB AES test vectors. - -// See U.S. National Institute of Standards and Technology (NIST) -// Special Publication 800-38A, ``Recommendation for Block Cipher -// Modes of Operation,'' 2001 Edition, pp. 52-55. - -package cipher_test - -import ( - "bytes" - "crypto/aes" - "crypto/cipher" - "testing" -) - -type ofbTest struct { - name string - key []byte - iv []byte - in []byte - out []byte -} - -var ofbTests = []ofbTest{ - // NIST SP 800-38A pp 52-55 - { - "OFB-AES128", - commonKey128, - commonIV, - commonInput, - []byte{ - 0x3b, 0x3f, 0xd9, 0x2e, 0xb7, 0x2d, 0xad, 0x20, 0x33, 0x34, 0x49, 0xf8, 0xe8, 0x3c, 0xfb, 0x4a, - 0x77, 0x89, 0x50, 0x8d, 0x16, 0x91, 0x8f, 0x03, 0xf5, 0x3c, 0x52, 0xda, 0xc5, 0x4e, 0xd8, 0x25, - 0x97, 0x40, 0x05, 0x1e, 0x9c, 0x5f, 0xec, 0xf6, 0x43, 0x44, 0xf7, 0xa8, 0x22, 0x60, 0xed, 0xcc, - 0x30, 0x4c, 0x65, 0x28, 0xf6, 0x59, 0xc7, 0x78, 0x66, 0xa5, 0x10, 0xd9, 0xc1, 0xd6, 0xae, 0x5e, - }, - }, - { - "OFB-AES192", - commonKey192, - commonIV, - commonInput, - []byte{ - 0xcd, 0xc8, 0x0d, 0x6f, 0xdd, 0xf1, 0x8c, 0xab, 0x34, 0xc2, 0x59, 0x09, 0xc9, 0x9a, 0x41, 0x74, - 0xfc, 0xc2, 0x8b, 0x8d, 0x4c, 0x63, 0x83, 0x7c, 0x09, 0xe8, 0x17, 0x00, 0xc1, 0x10, 0x04, 0x01, - 0x8d, 0x9a, 0x9a, 0xea, 0xc0, 0xf6, 0x59, 0x6f, 0x55, 0x9c, 0x6d, 0x4d, 0xaf, 0x59, 0xa5, 0xf2, - 0x6d, 0x9f, 0x20, 0x08, 0x57, 0xca, 0x6c, 0x3e, 0x9c, 0xac, 0x52, 0x4b, 0xd9, 0xac, 0xc9, 0x2a, - }, - }, - { - "OFB-AES256", - commonKey256, - commonIV, - commonInput, - []byte{ - 0xdc, 0x7e, 0x84, 0xbf, 0xda, 0x79, 0x16, 0x4b, 0x7e, 0xcd, 0x84, 0x86, 0x98, 0x5d, 0x38, 0x60, - 0x4f, 0xeb, 0xdc, 0x67, 0x40, 0xd2, 0x0b, 0x3a, 0xc8, 0x8f, 0x6a, 0xd8, 0x2a, 0x4f, 0xb0, 0x8d, - 0x71, 0xab, 0x47, 0xa0, 0x86, 0xe8, 0x6e, 0xed, 0xf3, 0x9d, 0x1c, 0x5b, 0xba, 0x97, 0xc4, 0x08, - 0x01, 0x26, 0x14, 0x1d, 0x67, 0xf3, 0x7b, 0xe8, 0x53, 0x8f, 0x5a, 0x8b, 0xe7, 0x40, 0xe4, 0x84, - }, - }, -} - -func TestOFB(t *testing.T) { - for _, tt := range ofbTests { - test := tt.name - - c, err := aes.NewCipher(tt.key) - if err != nil { - t.Errorf("%s: NewCipher(%d bytes) = %s", test, len(tt.key), err) - continue - } - - for j := 0; j <= 5; j += 5 { - plaintext := tt.in[0 : len(tt.in)-j] - ofb := cipher.NewOFB(c, tt.iv) - ciphertext := make([]byte, len(plaintext)) - ofb.XORKeyStream(ciphertext, plaintext) - if !bytes.Equal(ciphertext, tt.out[:len(plaintext)]) { - t.Errorf("%s/%d: encrypting\ninput % x\nhave % x\nwant % x", test, len(plaintext), plaintext, ciphertext, tt.out) - } - } - - for j := 0; j <= 5; j += 5 { - ciphertext := tt.out[0 : len(tt.in)-j] - ofb := cipher.NewOFB(c, tt.iv) - plaintext := make([]byte, len(ciphertext)) - ofb.XORKeyStream(plaintext, ciphertext) - if !bytes.Equal(plaintext, tt.in[:len(ciphertext)]) { - t.Errorf("%s/%d: decrypting\nhave % x\nwant % x", test, len(ciphertext), plaintext, tt.in) - } - } - - if t.Failed() { - break - } - } -} diff --git a/src/pkg/crypto/cipher/xor.go b/src/pkg/crypto/cipher/xor.go deleted file mode 100644 index f88dc8914..000000000 --- a/src/pkg/crypto/cipher/xor.go +++ /dev/null @@ -1,84 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cipher - -import ( - "runtime" - "unsafe" -) - -const wordSize = int(unsafe.Sizeof(uintptr(0))) -const supportsUnaligned = runtime.GOARCH == "386" || runtime.GOARCH == "amd64" - -// fastXORBytes xors in bulk. It only works on architectures that -// support unaligned read/writes. -func fastXORBytes(dst, a, b []byte) int { - n := len(a) - if len(b) < n { - n = len(b) - } - - w := n / wordSize - if w > 0 { - dw := *(*[]uintptr)(unsafe.Pointer(&dst)) - aw := *(*[]uintptr)(unsafe.Pointer(&a)) - bw := *(*[]uintptr)(unsafe.Pointer(&b)) - for i := 0; i < w; i++ { - dw[i] = aw[i] ^ bw[i] - } - } - - for i := (n - n%wordSize); i < n; i++ { - dst[i] = a[i] ^ b[i] - } - - return n -} - -func safeXORBytes(dst, a, b []byte) int { - n := len(a) - if len(b) < n { - n = len(b) - } - for i := 0; i < n; i++ { - dst[i] = a[i] ^ b[i] - } - return n -} - -// xorBytes xors the bytes in a and b. The destination is assumed to have enough -// space. Returns the number of bytes xor'd. -func xorBytes(dst, a, b []byte) int { - if supportsUnaligned { - return fastXORBytes(dst, a, b) - } else { - // TODO(hanwen): if (dst, a, b) have common alignment - // we could still try fastXORBytes. It is not clear - // how often this happens, and it's only worth it if - // the block encryption itself is hardware - // accelerated. - return safeXORBytes(dst, a, b) - } -} - -// fastXORWords XORs multiples of 4 or 8 bytes (depending on architecture.) -// The arguments are assumed to be of equal length. -func fastXORWords(dst, a, b []byte) { - dw := *(*[]uintptr)(unsafe.Pointer(&dst)) - aw := *(*[]uintptr)(unsafe.Pointer(&a)) - bw := *(*[]uintptr)(unsafe.Pointer(&b)) - n := len(b) / wordSize - for i := 0; i < n; i++ { - dw[i] = aw[i] ^ bw[i] - } -} - -func xorWords(dst, a, b []byte) { - if supportsUnaligned { - fastXORWords(dst, a, b) - } else { - safeXORBytes(dst, a, b) - } -} diff --git a/src/pkg/crypto/cipher/xor_test.go b/src/pkg/crypto/cipher/xor_test.go deleted file mode 100644 index cc1c9d72d..000000000 --- a/src/pkg/crypto/cipher/xor_test.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package cipher - -import ( - "bytes" - "testing" -) - -func TestXOR(t *testing.T) { - for alignP := 0; alignP < 2; alignP++ { - for alignQ := 0; alignQ < 2; alignQ++ { - for alignD := 0; alignD < 2; alignD++ { - p := make([]byte, 1024)[alignP:] - q := make([]byte, 1024)[alignQ:] - d1 := make([]byte, 1024+alignD)[alignD:] - d2 := make([]byte, 1024+alignD)[alignD:] - xorBytes(d1, p, q) - safeXORBytes(d2, p, q) - if bytes.Compare(d1, d2) != 0 { - t.Error("not equal") - } - } - } - } -} diff --git a/src/pkg/crypto/crypto.go b/src/pkg/crypto/crypto.go deleted file mode 100644 index 5a91baca0..000000000 --- a/src/pkg/crypto/crypto.go +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package crypto collects common cryptographic constants. -package crypto - -import ( - "hash" - "io" - "strconv" -) - -// Hash identifies a cryptographic hash function that is implemented in another -// package. -type Hash uint - -// HashFunc simply returns the value of h so that Hash implements SignerOpts. -func (h Hash) HashFunc() Hash { - return h -} - -const ( - MD4 Hash = 1 + iota // import code.google.com/p/go.crypto/md4 - MD5 // import crypto/md5 - SHA1 // import crypto/sha1 - SHA224 // import crypto/sha256 - SHA256 // import crypto/sha256 - SHA384 // import crypto/sha512 - SHA512 // import crypto/sha512 - MD5SHA1 // no implementation; MD5+SHA1 used for TLS RSA - RIPEMD160 // import code.google.com/p/go.crypto/ripemd160 - SHA3_224 // import code.google.com/p/go.crypto/sha3 - SHA3_256 // import code.google.com/p/go.crypto/sha3 - SHA3_384 // import code.google.com/p/go.crypto/sha3 - SHA3_512 // import code.google.com/p/go.crypto/sha3 - maxHash -) - -var digestSizes = []uint8{ - MD4: 16, - MD5: 16, - SHA1: 20, - SHA224: 28, - SHA256: 32, - SHA384: 48, - SHA512: 64, - SHA3_224: 28, - SHA3_256: 32, - SHA3_384: 48, - SHA3_512: 64, - MD5SHA1: 36, - RIPEMD160: 20, -} - -// Size returns the length, in bytes, of a digest resulting from the given hash -// function. It doesn't require that the hash function in question be linked -// into the program. -func (h Hash) Size() int { - if h > 0 && h < maxHash { - return int(digestSizes[h]) - } - panic("crypto: Size of unknown hash function") -} - -var hashes = make([]func() hash.Hash, maxHash) - -// New returns a new hash.Hash calculating the given hash function. New panics -// if the hash function is not linked into the binary. -func (h Hash) New() hash.Hash { - if h > 0 && h < maxHash { - f := hashes[h] - if f != nil { - return f() - } - } - panic("crypto: requested hash function #" + strconv.Itoa(int(h)) + " is unavailable") -} - -// Available reports whether the given hash function is linked into the binary. -func (h Hash) Available() bool { - return h < maxHash && hashes[h] != nil -} - -// RegisterHash registers a function that returns a new instance of the given -// hash function. This is intended to be called from the init function in -// packages that implement hash functions. -func RegisterHash(h Hash, f func() hash.Hash) { - if h >= maxHash { - panic("crypto: RegisterHash of unknown hash function") - } - hashes[h] = f -} - -// PublicKey represents a public key using an unspecified algorithm. -type PublicKey interface{} - -// PrivateKey represents a private key using an unspecified algorithm. -type PrivateKey interface{} - -// Signer is an interface for an opaque private key that can be used for -// signing operations. For example, an RSA key kept in a hardware module. -type Signer interface { - // Public returns the public key corresponding to the opaque, - // private key. - Public() PublicKey - - // Sign signs msg with the private key, possibly using entropy from - // rand. For an RSA key, the resulting signature should be either a - // PKCS#1 v1.5 or PSS signature (as indicated by opts). For an (EC)DSA - // key, it should be a DER-serialised, ASN.1 signature structure. - // - // Hash implements the SignerOpts interface and, in most cases, one can - // simply pass in the hash function used as opts. Sign may also attempt - // to type assert opts to other types in order to obtain algorithm - // specific values. See the documentation in each package for details. - Sign(rand io.Reader, msg []byte, opts SignerOpts) (signature []byte, err error) -} - -// SignerOpts contains options for signing with a Signer. -type SignerOpts interface { - // HashFunc returns an identifier for the hash function used to produce - // the message passed to Signer.Sign, or else zero to indicate that no - // hashing was done. - HashFunc() Hash -} diff --git a/src/pkg/crypto/des/block.go b/src/pkg/crypto/des/block.go deleted file mode 100644 index 26355a22e..000000000 --- a/src/pkg/crypto/des/block.go +++ /dev/null @@ -1,223 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package des - -import ( - "encoding/binary" -) - -func cryptBlock(subkeys []uint64, dst, src []byte, decrypt bool) { - b := binary.BigEndian.Uint64(src) - b = permuteInitialBlock(b) - left, right := uint32(b>>32), uint32(b) - - var subkey uint64 - for i := 0; i < 16; i++ { - if decrypt { - subkey = subkeys[15-i] - } else { - subkey = subkeys[i] - } - - left, right = right, left^feistel(right, subkey) - } - // switch left & right and perform final permutation - preOutput := (uint64(right) << 32) | uint64(left) - binary.BigEndian.PutUint64(dst, permuteFinalBlock(preOutput)) -} - -// Encrypt one block from src into dst, using the subkeys. -func encryptBlock(subkeys []uint64, dst, src []byte) { - cryptBlock(subkeys, dst, src, false) -} - -// Decrypt one block from src into dst, using the subkeys. -func decryptBlock(subkeys []uint64, dst, src []byte) { - cryptBlock(subkeys, dst, src, true) -} - -// DES Feistel function -func feistel(right uint32, key uint64) (result uint32) { - sBoxLocations := key ^ expandBlock(right) - var sBoxResult uint32 - for i := uint8(0); i < 8; i++ { - sBoxLocation := uint8(sBoxLocations>>42) & 0x3f - sBoxLocations <<= 6 - // row determined by 1st and 6th bit - // column is middle four bits - row := (sBoxLocation & 0x1) | ((sBoxLocation & 0x20) >> 4) - column := (sBoxLocation >> 1) & 0xf - sBoxResult ^= feistelBox[i][16*row+column] - } - return sBoxResult -} - -// feistelBox[s][16*i+j] contains the output of permutationFunction -// for sBoxes[s][i][j] << 4*(7-s) -var feistelBox [8][64]uint32 - -// general purpose function to perform DES block permutations -func permuteBlock(src uint64, permutation []uint8) (block uint64) { - for position, n := range permutation { - bit := (src >> n) & 1 - block |= bit << uint((len(permutation)-1)-position) - } - return -} - -func init() { - for s := range sBoxes { - for i := 0; i < 4; i++ { - for j := 0; j < 16; j++ { - f := uint64(sBoxes[s][i][j]) << (4 * (7 - uint(s))) - f = permuteBlock(uint64(f), permutationFunction[:]) - feistelBox[s][16*i+j] = uint32(f) - } - } - } -} - -// expandBlock expands an input block of 32 bits, -// producing an output block of 48 bits. -func expandBlock(src uint32) (block uint64) { - // rotate the 5 highest bits to the right. - src = (src << 5) | (src >> 27) - for i := 0; i < 8; i++ { - block <<= 6 - // take the 6 bits on the right - block |= uint64(src) & (1<<6 - 1) - // advance by 4 bits. - src = (src << 4) | (src >> 28) - } - return -} - -// permuteInitialBlock is equivalent to the permutation defined -// by initialPermutation. -func permuteInitialBlock(block uint64) uint64 { - // block = b7 b6 b5 b4 b3 b2 b1 b0 (8 bytes) - b1 := block >> 48 - b2 := block << 48 - block ^= b1 ^ b2 ^ b1<<48 ^ b2>>48 - - // block = b1 b0 b5 b4 b3 b2 b7 b6 - b1 = block >> 32 & 0xff00ff - b2 = (block & 0xff00ff00) - block ^= b1<<32 ^ b2 ^ b1<<8 ^ b2<<24 // exchange b0 b4 with b3 b7 - - // block is now b1 b3 b5 b7 b0 b2 b4 b7, the permutation: - // ... 8 - // ... 24 - // ... 40 - // ... 56 - // 7 6 5 4 3 2 1 0 - // 23 22 21 20 19 18 17 16 - // ... 32 - // ... 48 - - // exchange 4,5,6,7 with 32,33,34,35 etc. - b1 = block & 0x0f0f00000f0f0000 - b2 = block & 0x0000f0f00000f0f0 - block ^= b1 ^ b2 ^ b1>>12 ^ b2<<12 - - // block is the permutation: - // - // [+8] [+40] - // - // 7 6 5 4 - // 23 22 21 20 - // 3 2 1 0 - // 19 18 17 16 [+32] - - // exchange 0,1,4,5 with 18,19,22,23 - b1 = block & 0x3300330033003300 - b2 = block & 0x00cc00cc00cc00cc - block ^= b1 ^ b2 ^ b1>>6 ^ b2<<6 - - // block is the permutation: - // 15 14 - // 13 12 - // 11 10 - // 9 8 - // 7 6 - // 5 4 - // 3 2 - // 1 0 [+16] [+32] [+64] - - // exchange 0,2,4,6 with 9,11,13,15: - b1 = block & 0xaaaaaaaa55555555 - block ^= b1 ^ b1>>33 ^ b1<<33 - - // block is the permutation: - // 6 14 22 30 38 46 54 62 - // 4 12 20 28 36 44 52 60 - // 2 10 18 26 34 42 50 58 - // 0 8 16 24 32 40 48 56 - // 7 15 23 31 39 47 55 63 - // 5 13 21 29 37 45 53 61 - // 3 11 19 27 35 43 51 59 - // 1 9 17 25 33 41 49 57 - return block -} - -// permuteInitialBlock is equivalent to the permutation defined -// by finalPermutation. -func permuteFinalBlock(block uint64) uint64 { - // Perform the same bit exchanges as permuteInitialBlock - // but in reverse order. - b1 := block & 0xaaaaaaaa55555555 - block ^= b1 ^ b1>>33 ^ b1<<33 - - b1 = block & 0x3300330033003300 - b2 := block & 0x00cc00cc00cc00cc - block ^= b1 ^ b2 ^ b1>>6 ^ b2<<6 - - b1 = block & 0x0f0f00000f0f0000 - b2 = block & 0x0000f0f00000f0f0 - block ^= b1 ^ b2 ^ b1>>12 ^ b2<<12 - - b1 = block >> 32 & 0xff00ff - b2 = (block & 0xff00ff00) - block ^= b1<<32 ^ b2 ^ b1<<8 ^ b2<<24 - - b1 = block >> 48 - b2 = block << 48 - block ^= b1 ^ b2 ^ b1<<48 ^ b2>>48 - return block -} - -// creates 16 28-bit blocks rotated according -// to the rotation schedule -func ksRotate(in uint32) (out []uint32) { - out = make([]uint32, 16) - last := in - for i := 0; i < 16; i++ { - // 28-bit circular left shift - left := (last << (4 + ksRotations[i])) >> 4 - right := (last << 4) >> (32 - ksRotations[i]) - out[i] = left | right - last = out[i] - } - return -} - -// creates 16 56-bit subkeys from the original key -func (c *desCipher) generateSubkeys(keyBytes []byte) { - // apply PC1 permutation to key - key := binary.BigEndian.Uint64(keyBytes) - permutedKey := permuteBlock(key, permutedChoice1[:]) - - // rotate halves of permuted key according to the rotation schedule - leftRotations := ksRotate(uint32(permutedKey >> 28)) - rightRotations := ksRotate(uint32(permutedKey<<4) >> 4) - - // generate subkeys - for i := 0; i < 16; i++ { - // combine halves to form 56-bit input to PC2 - pc2Input := uint64(leftRotations[i])<<28 | uint64(rightRotations[i]) - // apply PC2 permutation to 7 byte input - c.subkeys[i] = permuteBlock(pc2Input, permutedChoice2[:]) - } -} diff --git a/src/pkg/crypto/des/cipher.go b/src/pkg/crypto/des/cipher.go deleted file mode 100644 index 2f929ca7b..000000000 --- a/src/pkg/crypto/des/cipher.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package des - -import ( - "crypto/cipher" - "strconv" -) - -// The DES block size in bytes. -const BlockSize = 8 - -type KeySizeError int - -func (k KeySizeError) Error() string { - return "crypto/des: invalid key size " + strconv.Itoa(int(k)) -} - -// desCipher is an instance of DES encryption. -type desCipher struct { - subkeys [16]uint64 -} - -// NewCipher creates and returns a new cipher.Block. -func NewCipher(key []byte) (cipher.Block, error) { - if len(key) != 8 { - return nil, KeySizeError(len(key)) - } - - c := new(desCipher) - c.generateSubkeys(key) - return c, nil -} - -func (c *desCipher) BlockSize() int { return BlockSize } - -func (c *desCipher) Encrypt(dst, src []byte) { encryptBlock(c.subkeys[:], dst, src) } - -func (c *desCipher) Decrypt(dst, src []byte) { decryptBlock(c.subkeys[:], dst, src) } - -// A tripleDESCipher is an instance of TripleDES encryption. -type tripleDESCipher struct { - cipher1, cipher2, cipher3 desCipher -} - -// NewTripleDESCipher creates and returns a new cipher.Block. -func NewTripleDESCipher(key []byte) (cipher.Block, error) { - if len(key) != 24 { - return nil, KeySizeError(len(key)) - } - - c := new(tripleDESCipher) - c.cipher1.generateSubkeys(key[:8]) - c.cipher2.generateSubkeys(key[8:16]) - c.cipher3.generateSubkeys(key[16:]) - return c, nil -} - -func (c *tripleDESCipher) BlockSize() int { return BlockSize } - -func (c *tripleDESCipher) Encrypt(dst, src []byte) { - c.cipher1.Encrypt(dst, src) - c.cipher2.Decrypt(dst, dst) - c.cipher3.Encrypt(dst, dst) -} - -func (c *tripleDESCipher) Decrypt(dst, src []byte) { - c.cipher3.Decrypt(dst, src) - c.cipher2.Encrypt(dst, dst) - c.cipher1.Decrypt(dst, dst) -} diff --git a/src/pkg/crypto/des/const.go b/src/pkg/crypto/des/const.go deleted file mode 100644 index 2bd485ee8..000000000 --- a/src/pkg/crypto/des/const.go +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package des implements the Data Encryption Standard (DES) and the -// Triple Data Encryption Algorithm (TDEA) as defined -// in U.S. Federal Information Processing Standards Publication 46-3. -package des - -// Used to perform an initial permutation of a 64-bit input block. -var initialPermutation = [64]byte{ - 6, 14, 22, 30, 38, 46, 54, 62, - 4, 12, 20, 28, 36, 44, 52, 60, - 2, 10, 18, 26, 34, 42, 50, 58, - 0, 8, 16, 24, 32, 40, 48, 56, - 7, 15, 23, 31, 39, 47, 55, 63, - 5, 13, 21, 29, 37, 45, 53, 61, - 3, 11, 19, 27, 35, 43, 51, 59, - 1, 9, 17, 25, 33, 41, 49, 57, -} - -// Used to perform a final permutation of a 4-bit preoutput block. This is the -// inverse of initialPermutation -var finalPermutation = [64]byte{ - 24, 56, 16, 48, 8, 40, 0, 32, - 25, 57, 17, 49, 9, 41, 1, 33, - 26, 58, 18, 50, 10, 42, 2, 34, - 27, 59, 19, 51, 11, 43, 3, 35, - 28, 60, 20, 52, 12, 44, 4, 36, - 29, 61, 21, 53, 13, 45, 5, 37, - 30, 62, 22, 54, 14, 46, 6, 38, - 31, 63, 23, 55, 15, 47, 7, 39, -} - -// Used to expand an input block of 32 bits, producing an output block of 48 -// bits. -var expansionFunction = [48]byte{ - 0, 31, 30, 29, 28, 27, 28, 27, - 26, 25, 24, 23, 24, 23, 22, 21, - 20, 19, 20, 19, 18, 17, 16, 15, - 16, 15, 14, 13, 12, 11, 12, 11, - 10, 9, 8, 7, 8, 7, 6, 5, - 4, 3, 4, 3, 2, 1, 0, 31, -} - -// Yields a 32-bit output from a 32-bit input -var permutationFunction = [32]byte{ - 16, 25, 12, 11, 3, 20, 4, 15, - 31, 17, 9, 6, 27, 14, 1, 22, - 30, 24, 8, 18, 0, 5, 29, 23, - 13, 19, 2, 26, 10, 21, 28, 7, -} - -// Used in the key schedule to select 56 bits -// from a 64-bit input. -var permutedChoice1 = [56]byte{ - 7, 15, 23, 31, 39, 47, 55, 63, - 6, 14, 22, 30, 38, 46, 54, 62, - 5, 13, 21, 29, 37, 45, 53, 61, - 4, 12, 20, 28, 1, 9, 17, 25, - 33, 41, 49, 57, 2, 10, 18, 26, - 34, 42, 50, 58, 3, 11, 19, 27, - 35, 43, 51, 59, 36, 44, 52, 60, -} - -// Used in the key schedule to produce each subkey by selecting 48 bits from -// the 56-bit input -var permutedChoice2 = [48]byte{ - 42, 39, 45, 32, 55, 51, 53, 28, - 41, 50, 35, 46, 33, 37, 44, 52, - 30, 48, 40, 49, 29, 36, 43, 54, - 15, 4, 25, 19, 9, 1, 26, 16, - 5, 11, 23, 8, 12, 7, 17, 0, - 22, 3, 10, 14, 6, 20, 27, 24, -} - -// 8 S-boxes composed of 4 rows and 16 columns -// Used in the DES cipher function -var sBoxes = [8][4][16]uint8{ - // S-box 1 - { - {14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7}, - {0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8}, - {4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0}, - {15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13}, - }, - // S-box 2 - { - {15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10}, - {3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5}, - {0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15}, - {13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9}, - }, - // S-box 3 - { - {10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8}, - {13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1}, - {13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7}, - {1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12}, - }, - // S-box 4 - { - {7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15}, - {13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9}, - {10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4}, - {3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14}, - }, - // S-box 5 - { - {2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9}, - {14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6}, - {4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14}, - {11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3}, - }, - // S-box 6 - { - {12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11}, - {10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8}, - {9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6}, - {4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13}, - }, - // S-box 7 - { - {4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1}, - {13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6}, - {1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2}, - {6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12}, - }, - // S-box 8 - { - {13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7}, - {1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2}, - {7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8}, - {2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11}, - }, -} - -// Size of left rotation per round in each half of the key schedule -var ksRotations = [16]uint8{1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1} diff --git a/src/pkg/crypto/des/des_test.go b/src/pkg/crypto/des/des_test.go deleted file mode 100644 index 2bd525afe..000000000 --- a/src/pkg/crypto/des/des_test.go +++ /dev/null @@ -1,1566 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package des - -import ( - "bytes" - "testing" -) - -type CryptTest struct { - key []byte - in []byte - out []byte -} - -// some custom tests for DES -var encryptDESTests = []CryptTest{ - { - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x8c, 0xa6, 0x4d, 0xe9, 0xc1, 0xb1, 0x23, 0xa7}}, - { - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, - []byte{0x35, 0x55, 0x50, 0xb2, 0x15, 0x0e, 0x24, 0x51}}, - { - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, - []byte{0x61, 0x7b, 0x3a, 0x0c, 0xe8, 0xf0, 0x71, 0x00}}, - { - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}, - []byte{0x92, 0x31, 0xf2, 0x36, 0xff, 0x9a, 0xa9, 0x5c}}, - { - []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xca, 0xaa, 0xaf, 0x4d, 0xea, 0xf1, 0xdb, 0xae}}, - { - []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, - []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, - []byte{0x73, 0x59, 0xb2, 0x16, 0x3e, 0x4e, 0xdc, 0x58}}, - { - []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, - []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, - []byte{0x6d, 0xce, 0x0d, 0xc9, 0x00, 0x65, 0x56, 0xa3}}, - { - []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, - []byte{0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}, - []byte{0x9e, 0x84, 0xc5, 0xf3, 0x17, 0x0f, 0x8e, 0xff}}, - { - []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xd5, 0xd4, 0x4f, 0xf7, 0x20, 0x68, 0x3d, 0x0d}}, - { - []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, - []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, - []byte{0x59, 0x73, 0x23, 0x56, 0xf3, 0x6f, 0xde, 0x06}}, - { - []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, - []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, - []byte{0x56, 0xcc, 0x09, 0xe7, 0xcf, 0xdc, 0x4c, 0xef}}, - { - []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, - []byte{0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}, - []byte{0x12, 0xc6, 0x26, 0xaf, 0x05, 0x8b, 0x43, 0x3b}}, - { - []byte{0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}, - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xa6, 0x8c, 0xdc, 0xa9, 0x0c, 0x90, 0x21, 0xf9}}, - { - []byte{0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}, - []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, - []byte{0x2a, 0x2b, 0xb0, 0x08, 0xdf, 0x97, 0xc2, 0xf2}}, - { - []byte{0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}, - []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, - []byte{0xed, 0x39, 0xd9, 0x50, 0xfa, 0x74, 0xbc, 0xc4}}, - { - []byte{0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}, - []byte{0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10}, - []byte{0xa9, 0x33, 0xf6, 0x18, 0x30, 0x23, 0xb3, 0x10}}, - { - []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, - []byte{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}, - []byte{0x17, 0x66, 0x8d, 0xfc, 0x72, 0x92, 0x53, 0x2d}}, - { - []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, - []byte{0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, - []byte{0xb4, 0xfd, 0x23, 0x16, 0x47, 0xa5, 0xbe, 0xc0}}, - { - []byte{0x0e, 0x32, 0x92, 0x32, 0xea, 0x6d, 0x0d, 0x73}, - []byte{0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87, 0x87}, - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, - { - []byte{0x73, 0x65, 0x63, 0x52, 0x33, 0x74, 0x24, 0x3b}, // "secR3t$;" - []byte{0x61, 0x20, 0x74, 0x65, 0x73, 0x74, 0x31, 0x32}, // "a test12" - []byte{0x37, 0x0d, 0xee, 0x2c, 0x1f, 0xb4, 0xf7, 0xa5}}, - { - []byte{0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68}, // "abcdefgh" - []byte{0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68}, // "abcdefgh" - []byte{0x2a, 0x8d, 0x69, 0xde, 0x9d, 0x5f, 0xdf, 0xf9}}, - { - []byte{0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68}, // "abcdefgh" - []byte{0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38}, // "12345678" - []byte{0x21, 0xc6, 0x0d, 0xa5, 0x34, 0x24, 0x8b, 0xce}}, - { - []byte{0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38}, // "12345678" - []byte{0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68}, // "abcdefgh" - []byte{0x94, 0xd4, 0x43, 0x6b, 0xc3, 0xb5, 0xb6, 0x93}}, - { - []byte{0x1f, 0x79, 0x90, 0x5f, 0x88, 0x01, 0xc8, 0x88}, // random - []byte{0xc7, 0x46, 0x18, 0x73, 0xaf, 0x48, 0x5f, 0xb3}, // random - []byte{0xb0, 0x93, 0x50, 0x88, 0xf9, 0x92, 0x44, 0x6a}}, - { - []byte{0xe6, 0xf4, 0xf2, 0xdb, 0x31, 0x42, 0x53, 0x01}, // random - []byte{0xff, 0x3d, 0x25, 0x50, 0x12, 0xe3, 0x4a, 0xc5}, // random - []byte{0x86, 0x08, 0xd3, 0xd1, 0x6c, 0x2f, 0xd2, 0x55}}, - { - []byte{0x69, 0xc1, 0x9d, 0xc1, 0x15, 0xc5, 0xfb, 0x2b}, // random - []byte{0x1a, 0x22, 0x5c, 0xaf, 0x1f, 0x1d, 0xa3, 0xf9}, // random - []byte{0x64, 0xba, 0x31, 0x67, 0x56, 0x91, 0x1e, 0xa7}}, - { - []byte{0x6e, 0x5e, 0xe2, 0x47, 0xc4, 0xbf, 0xf6, 0x51}, // random - []byte{0x11, 0xc9, 0x57, 0xff, 0x66, 0x89, 0x0e, 0xf0}, // random - []byte{0x94, 0xc5, 0x35, 0xb2, 0xc5, 0x8b, 0x39, 0x72}}, -} - -var weakKeyTests = []CryptTest{ - { - []byte{0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, - []byte{0x55, 0x74, 0xc0, 0xbd, 0x7c, 0xdf, 0xf7, 0x39}, // random - nil}, - { - []byte{0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe}, - []byte{0xe8, 0xe1, 0xa7, 0xc1, 0xde, 0x11, 0x89, 0xaa}, // random - nil}, - { - []byte{0xe0, 0xe0, 0xe0, 0xe0, 0xf1, 0xf1, 0xf1, 0xf1}, - []byte{0x50, 0x6a, 0x4b, 0x94, 0x3b, 0xed, 0x7d, 0xdc}, // random - nil}, - { - []byte{0x1f, 0x1f, 0x1f, 0x1f, 0x0e, 0x0e, 0x0e, 0x0e}, - []byte{0x88, 0x81, 0x56, 0x38, 0xec, 0x3b, 0x1c, 0x97}, // random - nil}, - { - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x17, 0xa0, 0x83, 0x62, 0x32, 0xfe, 0x9a, 0x0b}, // random - nil}, - { - []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, - []byte{0xca, 0x8f, 0xca, 0x1f, 0x50, 0xc5, 0x7b, 0x49}, // random - nil}, - { - []byte{0xe1, 0xe1, 0xe1, 0xe1, 0xf0, 0xf0, 0xf0, 0xf0}, - []byte{0xb1, 0xea, 0xad, 0x7d, 0xe7, 0xc3, 0x7a, 0x43}, // random - nil}, - { - []byte{0x1e, 0x1e, 0x1e, 0x1e, 0x0f, 0x0f, 0x0f, 0x0f}, - []byte{0xae, 0x74, 0x7d, 0x6f, 0xef, 0x16, 0xbb, 0x81}, // random - nil}, -} - -var semiWeakKeyTests = []CryptTest{ - // key and out contain the semi-weak key pair - { - []byte{0x01, 0x1f, 0x01, 0x1f, 0x01, 0x0e, 0x01, 0x0e}, - []byte{0x12, 0xfa, 0x31, 0x16, 0xf9, 0xc5, 0x0a, 0xe4}, // random - []byte{0x1f, 0x01, 0x1f, 0x01, 0x0e, 0x01, 0x0e, 0x01}}, - { - []byte{0x01, 0xe0, 0x01, 0xe0, 0x01, 0xf1, 0x01, 0xf1}, - []byte{0xb0, 0x4c, 0x7a, 0xee, 0xd2, 0xe5, 0x4d, 0xb7}, // random - []byte{0xe0, 0x01, 0xe0, 0x01, 0xf1, 0x01, 0xf1, 0x01}}, - { - []byte{0x01, 0xfe, 0x01, 0xfe, 0x01, 0xfe, 0x01, 0xfe}, - []byte{0xa4, 0x81, 0xcd, 0xb1, 0x64, 0x6f, 0xd3, 0xbc}, // random - []byte{0xfe, 0x01, 0xfe, 0x01, 0xfe, 0x01, 0xfe, 0x01}}, - { - []byte{0x1f, 0xe0, 0x1f, 0xe0, 0x0e, 0xf1, 0x0e, 0xf1}, - []byte{0xee, 0x27, 0xdd, 0x88, 0x4c, 0x22, 0xcd, 0xce}, // random - []byte{0xe0, 0x1f, 0xe0, 0x1f, 0xf1, 0x0e, 0xf1, 0x0e}}, - { - []byte{0x1f, 0xfe, 0x1f, 0xfe, 0x0e, 0xfe, 0x0e, 0xfe}, - []byte{0x19, 0x3d, 0xcf, 0x97, 0x70, 0xfb, 0xab, 0xe1}, // random - []byte{0xfe, 0x1f, 0xfe, 0x1f, 0xfe, 0x0e, 0xfe, 0x0e}}, - { - []byte{0xe0, 0xfe, 0xe0, 0xfe, 0xf1, 0xfe, 0xf1, 0xfe}, - []byte{0x7c, 0x82, 0x69, 0xe4, 0x1e, 0x86, 0x99, 0xd7}, // random - []byte{0xfe, 0xe0, 0xfe, 0xe0, 0xfe, 0xf1, 0xfe, 0xf1}}, -} - -// some custom tests for TripleDES -var encryptTripleDESTests = []CryptTest{ - { - []byte{ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x92, 0x95, 0xb5, 0x9b, 0xb3, 0x84, 0x73, 0x6e}}, - { - []byte{ - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, - []byte{0xc1, 0x97, 0xf5, 0x58, 0x74, 0x8a, 0x20, 0xe7}}, - { - []byte{ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x3e, 0x68, 0x0a, 0xa7, 0x8b, 0x75, 0xdf, 0x18}}, - { - []byte{ - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, - []byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, - []byte{0x6d, 0x6a, 0x4a, 0x64, 0x4c, 0x7b, 0x8c, 0x91}}, - { - []byte{ // "abcdefgh12345678ABCDEFGH" - 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, - 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, - 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48}, - []byte{0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30}, // "00000000" - []byte{0xe4, 0x61, 0xb7, 0x59, 0x68, 0x8b, 0xff, 0x66}}, - { - []byte{ // "abcdefgh12345678ABCDEFGH" - 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, - 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, - 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48}, - []byte{0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38}, // "12345678" - []byte{0xdb, 0xd0, 0x92, 0xde, 0xf8, 0x34, 0xff, 0x58}}, - { - []byte{ // "abcdefgh12345678ABCDEFGH" - 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, - 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, - 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48}, - []byte{0xf0, 0xc5, 0x82, 0x22, 0xd3, 0xe6, 0x12, 0xd2}, // random - []byte{0xba, 0xe4, 0x41, 0xb1, 0x3c, 0x37, 0x4d, 0xf4}}, - { - []byte{ // random - 0xd3, 0x7d, 0x45, 0xee, 0x22, 0xe9, 0xcf, 0x52, - 0xf4, 0x65, 0xa2, 0x4f, 0x70, 0xd1, 0x81, 0x8a, - 0x3d, 0xbe, 0x2f, 0x39, 0xc7, 0x71, 0xd2, 0xe9}, - []byte{0x49, 0x53, 0xc3, 0xe9, 0x78, 0xdf, 0x9f, 0xaf}, // random - []byte{0x53, 0x40, 0x51, 0x24, 0xd8, 0x3c, 0xf9, 0x88}}, - { - []byte{ // random - 0xcb, 0x10, 0x7d, 0xda, 0x7e, 0x96, 0x57, 0x0a, - 0xe8, 0xeb, 0xe8, 0x07, 0x8e, 0x87, 0xd3, 0x57, - 0xb2, 0x61, 0x12, 0xb8, 0x2a, 0x90, 0xb7, 0x2f}, - []byte{0xa3, 0xc2, 0x60, 0xb1, 0x0b, 0xb7, 0x28, 0x6e}, // random - []byte{0x56, 0x73, 0x7d, 0xfb, 0xb5, 0xa1, 0xc3, 0xde}}, -} - -// NIST Special Publication 800-20, Appendix A -// Key for use with Table A.1 tests -var tableA1Key = []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, -} - -// Table A.1 Resulting Ciphertext from the Variable Plaintext Known Answer Test -var tableA1Tests = []CryptTest{ - {nil, // 0 - []byte{0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x95, 0xf8, 0xa5, 0xe5, 0xdd, 0x31, 0xd9, 0x00}}, - {nil, // 1 - []byte{0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xdd, 0x7f, 0x12, 0x1c, 0xa5, 0x01, 0x56, 0x19}}, - {nil, // 2 - []byte{0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x2e, 0x86, 0x53, 0x10, 0x4f, 0x38, 0x34, 0xea}}, - {nil, // 3 - []byte{0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x4b, 0xd3, 0x88, 0xff, 0x6c, 0xd8, 0x1d, 0x4f}}, - {nil, // 4 - []byte{0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x20, 0xb9, 0xe7, 0x67, 0xb2, 0xfb, 0x14, 0x56}}, - {nil, // 5 - []byte{0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x55, 0x57, 0x93, 0x80, 0xd7, 0x71, 0x38, 0xef}}, - {nil, // 6 - []byte{0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x6c, 0xc5, 0xde, 0xfa, 0xaf, 0x04, 0x51, 0x2f}}, - {nil, // 7 - []byte{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x0d, 0x9f, 0x27, 0x9b, 0xa5, 0xd8, 0x72, 0x60}}, - {nil, // 8 - []byte{0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xd9, 0x03, 0x1b, 0x02, 0x71, 0xbd, 0x5a, 0x0a}}, - {nil, // 9 - []byte{0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x42, 0x42, 0x50, 0xb3, 0x7c, 0x3d, 0xd9, 0x51}}, - {nil, // 10 - []byte{0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xb8, 0x06, 0x1b, 0x7e, 0xcd, 0x9a, 0x21, 0xe5}}, - {nil, // 11 - []byte{0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xf1, 0x5d, 0x0f, 0x28, 0x6b, 0x65, 0xbd, 0x28}}, - {nil, // 12 - []byte{0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xad, 0xd0, 0xcc, 0x8d, 0x6e, 0x5d, 0xeb, 0xa1}}, - {nil, // 13 - []byte{0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xe6, 0xd5, 0xf8, 0x27, 0x52, 0xad, 0x63, 0xd1}}, - {nil, // 14 - []byte{0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xec, 0xbf, 0xe3, 0xbd, 0x3f, 0x59, 0x1a, 0x5e}}, - {nil, // 15 - []byte{0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xf3, 0x56, 0x83, 0x43, 0x79, 0xd1, 0x65, 0xcd}}, - {nil, // 16 - []byte{0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x2b, 0x9f, 0x98, 0x2f, 0x20, 0x03, 0x7f, 0xa9}}, - {nil, // 17 - []byte{0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x88, 0x9d, 0xe0, 0x68, 0xa1, 0x6f, 0x0b, 0xe6}}, - {nil, // 18 - []byte{0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xe1, 0x9e, 0x27, 0x5d, 0x84, 0x6a, 0x12, 0x98}}, - {nil, // 19 - []byte{0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x32, 0x9a, 0x8e, 0xd5, 0x23, 0xd7, 0x1a, 0xec}}, - {nil, // 20 - []byte{0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xe7, 0xfc, 0xe2, 0x25, 0x57, 0xd2, 0x3c, 0x97}}, - {nil, // 21 - []byte{0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0x12, 0xa9, 0xf5, 0x81, 0x7f, 0xf2, 0xd6, 0x5d}}, - {nil, // 22 - []byte{0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xa4, 0x84, 0xc3, 0xad, 0x38, 0xdc, 0x9c, 0x19}}, - {nil, // 23 - []byte{0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xfb, 0xe0, 0x0a, 0x8a, 0x1e, 0xf8, 0xad, 0x72}}, - {nil, // 24 - []byte{0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x00}, - []byte{0x75, 0x0d, 0x07, 0x94, 0x07, 0x52, 0x13, 0x63}}, - {nil, // 25 - []byte{0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00}, - []byte{0x64, 0xfe, 0xed, 0x9c, 0x72, 0x4c, 0x2f, 0xaf}}, - {nil, // 26 - []byte{0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00}, - []byte{0xf0, 0x2b, 0x26, 0x3b, 0x32, 0x8e, 0x2b, 0x60}}, - {nil, // 27 - []byte{0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00}, - []byte{0x9d, 0x64, 0x55, 0x5a, 0x9a, 0x10, 0xb8, 0x52}}, - {nil, // 28 - []byte{0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00}, - []byte{0xd1, 0x06, 0xff, 0x0b, 0xed, 0x52, 0x55, 0xd7}}, - {nil, // 29 - []byte{0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0x00}, - []byte{0xe1, 0x65, 0x2c, 0x6b, 0x13, 0x8c, 0x64, 0xa5}}, - {nil, // 30 - []byte{0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00}, - []byte{0xe4, 0x28, 0x58, 0x11, 0x86, 0xec, 0x8f, 0x46}}, - {nil, // 31 - []byte{0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00}, - []byte{0xae, 0xb5, 0xf5, 0xed, 0xe2, 0x2d, 0x1a, 0x36}}, - {nil, // 32 - []byte{0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00}, - []byte{0xe9, 0x43, 0xd7, 0x56, 0x8a, 0xec, 0x0c, 0x5c}}, - {nil, // 33 - []byte{0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00}, - []byte{0xdf, 0x98, 0xc8, 0x27, 0x6f, 0x54, 0xb0, 0x4b}}, - {nil, // 34 - []byte{0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00, 0x00}, - []byte{0xb1, 0x60, 0xe4, 0x68, 0x0f, 0x6c, 0x69, 0x6f}}, - {nil, // 35 - []byte{0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00}, - []byte{0xfa, 0x07, 0x52, 0xb0, 0x7d, 0x9c, 0x4a, 0xb8}}, - {nil, // 36 - []byte{0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00}, - []byte{0xca, 0x3a, 0x2b, 0x03, 0x6d, 0xbc, 0x85, 0x02}}, - {nil, // 37 - []byte{0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00}, - []byte{0x5e, 0x09, 0x05, 0x51, 0x7b, 0xb5, 0x9b, 0xcf}}, - {nil, // 38 - []byte{0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00}, - []byte{0x81, 0x4e, 0xeb, 0x3b, 0x91, 0xd9, 0x07, 0x26}}, - {nil, // 39 - []byte{0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00}, - []byte{0x4d, 0x49, 0xdb, 0x15, 0x32, 0x91, 0x9c, 0x9f}}, - {nil, // 40 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00}, - []byte{0x25, 0xeb, 0x5f, 0xc3, 0xf8, 0xcf, 0x06, 0x21}}, - {nil, // 41 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00}, - []byte{0xab, 0x6a, 0x20, 0xc0, 0x62, 0x0d, 0x1c, 0x6f}}, - {nil, // 42 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00}, - []byte{0x79, 0xe9, 0x0d, 0xbc, 0x98, 0xf9, 0x2c, 0xca}}, - {nil, // 43 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00}, - []byte{0x86, 0x6e, 0xce, 0xdd, 0x80, 0x72, 0xbb, 0x0e}}, - {nil, // 44 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00}, - []byte{0x8b, 0x54, 0x53, 0x6f, 0x2f, 0x3e, 0x64, 0xa8}}, - {nil, // 45 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00}, - []byte{0xea, 0x51, 0xd3, 0x97, 0x55, 0x95, 0xb8, 0x6b}}, - {nil, // 46 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00}, - []byte{0xca, 0xff, 0xc6, 0xac, 0x45, 0x42, 0xde, 0x31}}, - {nil, // 47 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00}, - []byte{0x8d, 0xd4, 0x5a, 0x2d, 0xdf, 0x90, 0x79, 0x6c}}, - {nil, // 48 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x00}, - []byte{0x10, 0x29, 0xd5, 0x5e, 0x88, 0x0e, 0xc2, 0xd0}}, - {nil, // 49 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00}, - []byte{0x5d, 0x86, 0xcb, 0x23, 0x63, 0x9d, 0xbe, 0xa9}}, - {nil, // 50 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00}, - []byte{0x1d, 0x1c, 0xa8, 0x53, 0xae, 0x7c, 0x0c, 0x5f}}, - {nil, // 51 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00}, - []byte{0xce, 0x33, 0x23, 0x29, 0x24, 0x8f, 0x32, 0x28}}, - {nil, // 52 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00}, - []byte{0x84, 0x05, 0xd1, 0xab, 0xe2, 0x4f, 0xb9, 0x42}}, - {nil, // 53 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00}, - []byte{0xe6, 0x43, 0xd7, 0x80, 0x90, 0xca, 0x42, 0x07}}, - {nil, // 54 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00}, - []byte{0x48, 0x22, 0x1b, 0x99, 0x37, 0x74, 0x8a, 0x23}}, - {nil, // 55 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00}, - []byte{0xdd, 0x7c, 0x0b, 0xbd, 0x61, 0xfa, 0xfd, 0x54}}, - {nil, // 56 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80}, - []byte{0x2f, 0xbc, 0x29, 0x1a, 0x57, 0x0d, 0xb5, 0xc4}}, - {nil, // 57 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40}, - []byte{0xe0, 0x7c, 0x30, 0xd7, 0xe4, 0xe2, 0x6e, 0x12}}, - {nil, // 58 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20}, - []byte{0x09, 0x53, 0xe2, 0x25, 0x8e, 0x8e, 0x90, 0xa1}}, - {nil, // 59 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10}, - []byte{0x5b, 0x71, 0x1b, 0xc4, 0xce, 0xeb, 0xf2, 0xee}}, - {nil, // 60 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08}, - []byte{0xcc, 0x08, 0x3f, 0x1e, 0x6d, 0x9e, 0x85, 0xf6}}, - {nil, // 61 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04}, - []byte{0xd2, 0xfd, 0x88, 0x67, 0xd5, 0x0d, 0x2d, 0xfe}}, - {nil, // 62 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02}, - []byte{0x06, 0xe7, 0xea, 0x22, 0xce, 0x92, 0x70, 0x8f}}, - {nil, // 63 - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}, - []byte{0x16, 0x6b, 0x40, 0xb4, 0x4a, 0xba, 0x4b, 0xd6}}, -} - -// Plaintext for use with Table A.2 tests -var tableA2Plaintext = []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} - -// Table A.2 Resulting Ciphertext from the Variable Key Known Answer Test -var tableA2Tests = []CryptTest{ - { // 0 - []byte{ - 0x80, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x80, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x80, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0x95, 0xa8, 0xd7, 0x28, 0x13, 0xda, 0xa9, 0x4d}}, - { // 1 - []byte{ - 0x40, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x40, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x40, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0x0e, 0xec, 0x14, 0x87, 0xdd, 0x8c, 0x26, 0xd5}}, - { // 2 - []byte{ - 0x20, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x20, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x20, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0x7a, 0xd1, 0x6f, 0xfb, 0x79, 0xc4, 0x59, 0x26}}, - { // 3 - []byte{ - 0x10, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x10, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x10, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0xd3, 0x74, 0x62, 0x94, 0xca, 0x6a, 0x6c, 0xf3}}, - { // 4 - []byte{ - 0x08, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x08, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x08, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0x80, 0x9f, 0x5f, 0x87, 0x3c, 0x1f, 0xd7, 0x61}}, - { // 5 - []byte{ - 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0xc0, 0x2f, 0xaf, 0xfe, 0xc9, 0x89, 0xd1, 0xfc}}, - { // 6 - []byte{ - 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0x46, 0x15, 0xaa, 0x1d, 0x33, 0xe7, 0x2f, 0x10}}, - { // 7 - []byte{ - 0x01, 0x80, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x80, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x80, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0x20, 0x55, 0x12, 0x33, 0x50, 0xc0, 0x08, 0x58}}, - { // 8 - []byte{ - 0x01, 0x40, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x40, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x40, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0xdf, 0x3b, 0x99, 0xd6, 0x57, 0x73, 0x97, 0xc8}}, - { // 9 - []byte{ - 0x01, 0x20, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x20, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x20, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0x31, 0xfe, 0x17, 0x36, 0x9b, 0x52, 0x88, 0xc9}}, - { // 10 - []byte{ - 0x01, 0x10, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x10, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x10, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0xdf, 0xdd, 0x3c, 0xc6, 0x4d, 0xae, 0x16, 0x42}}, - { // 11 - []byte{ - 0x01, 0x08, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x08, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x08, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0x17, 0x8c, 0x83, 0xce, 0x2b, 0x39, 0x9d, 0x94}}, - { // 12 - []byte{ - 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0x50, 0xf6, 0x36, 0x32, 0x4a, 0x9b, 0x7f, 0x80}}, - { // 13 - []byte{ - 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0xa8, 0x46, 0x8e, 0xe3, 0xbc, 0x18, 0xf0, 0x6d}}, - { // 14 - []byte{ - 0x01, 0x01, 0x80, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x80, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x80, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0xa2, 0xdc, 0x9e, 0x92, 0xfd, 0x3c, 0xde, 0x92}}, - { // 15 - []byte{ - 0x01, 0x01, 0x40, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x40, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x40, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0xca, 0xc0, 0x9f, 0x79, 0x7d, 0x03, 0x12, 0x87}}, - { // 16 - []byte{ - 0x01, 0x01, 0x20, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x20, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x20, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0x90, 0xba, 0x68, 0x0b, 0x22, 0xae, 0xb5, 0x25}}, - { // 17 - []byte{ - 0x01, 0x01, 0x10, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x10, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x10, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0xce, 0x7a, 0x24, 0xf3, 0x50, 0xe2, 0x80, 0xb6}}, - { // 18 - []byte{ - 0x01, 0x01, 0x08, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x08, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x08, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0x88, 0x2b, 0xff, 0x0a, 0xa0, 0x1a, 0x0b, 0x87}}, - { // 19 - []byte{ - 0x01, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0x25, 0x61, 0x02, 0x88, 0x92, 0x45, 0x11, 0xc2}}, - { // 20 - []byte{ - 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0xc7, 0x15, 0x16, 0xc2, 0x9c, 0x75, 0xd1, 0x70}}, - { // 21 - []byte{ - 0x01, 0x01, 0x01, 0x80, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x80, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x80, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0x51, 0x99, 0xc2, 0x9a, 0x52, 0xc9, 0xf0, 0x59}}, - { // 22 - []byte{ - 0x01, 0x01, 0x01, 0x40, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x40, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x40, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0xc2, 0x2f, 0x0a, 0x29, 0x4a, 0x71, 0xf2, 0x9f}}, - { // 23 - []byte{ - 0x01, 0x01, 0x01, 0x20, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x20, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x20, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0xee, 0x37, 0x14, 0x83, 0x71, 0x4c, 0x02, 0xea}}, - { // 24 - []byte{ - 0x01, 0x01, 0x01, 0x10, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x10, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x10, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0xa8, 0x1f, 0xbd, 0x44, 0x8f, 0x9e, 0x52, 0x2f}}, - { // 25 - []byte{ - 0x01, 0x01, 0x01, 0x08, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x08, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x08, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0x4f, 0x64, 0x4c, 0x92, 0xe1, 0x92, 0xdf, 0xed}}, - { // 26 - []byte{ - 0x01, 0x01, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x04, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0x1a, 0xfa, 0x9a, 0x66, 0xa6, 0xdf, 0x92, 0xae}}, - { // 27 - []byte{ - 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, 0x01}, - nil, - []byte{0xb3, 0xc1, 0xcc, 0x71, 0x5c, 0xb8, 0x79, 0xd8}}, - { // 28 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x80, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x80, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x80, 0x01, 0x01, 0x01}, - nil, - []byte{0x19, 0xd0, 0x32, 0xe6, 0x4a, 0xb0, 0xbd, 0x8b}}, - { // 29 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x40, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x40, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x40, 0x01, 0x01, 0x01}, - nil, - []byte{0x3c, 0xfa, 0xa7, 0xa7, 0xdc, 0x87, 0x20, 0xdc}}, - { // 30 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x20, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x20, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x20, 0x01, 0x01, 0x01}, - nil, - []byte{0xb7, 0x26, 0x5f, 0x7f, 0x44, 0x7a, 0xc6, 0xf3}}, - { // 31 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x10, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x10, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x10, 0x01, 0x01, 0x01}, - nil, - []byte{0x9d, 0xb7, 0x3b, 0x3c, 0x0d, 0x16, 0x3f, 0x54}}, - { // 32 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x08, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x08, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x08, 0x01, 0x01, 0x01}, - nil, - []byte{0x81, 0x81, 0xb6, 0x5b, 0xab, 0xf4, 0xa9, 0x75}}, - { // 33 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x01, 0x01}, - nil, - []byte{0x93, 0xc9, 0xb6, 0x40, 0x42, 0xea, 0xa2, 0x40}}, - { // 34 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, 0x01}, - nil, - []byte{0x55, 0x70, 0x53, 0x08, 0x29, 0x70, 0x55, 0x92}}, - { // 35 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x80, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x80, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x80, 0x01, 0x01}, - nil, - []byte{0x86, 0x38, 0x80, 0x9e, 0x87, 0x87, 0x87, 0xa0}}, - { // 36 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x40, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x40, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x40, 0x01, 0x01}, - nil, - []byte{0x41, 0xb9, 0xa7, 0x9a, 0xf7, 0x9a, 0xc2, 0x08}}, - { // 37 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x20, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x20, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x20, 0x01, 0x01}, - nil, - []byte{0x7a, 0x9b, 0xe4, 0x2f, 0x20, 0x09, 0xa8, 0x92}}, - { // 38 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x10, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x10, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x10, 0x01, 0x01}, - nil, - []byte{0x29, 0x03, 0x8d, 0x56, 0xba, 0x6d, 0x27, 0x45}}, - { // 39 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x08, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x08, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x08, 0x01, 0x01}, - nil, - []byte{0x54, 0x95, 0xc6, 0xab, 0xf1, 0xe5, 0xdf, 0x51}}, - { // 40 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, 0x01}, - nil, - []byte{0xae, 0x13, 0xdb, 0xd5, 0x61, 0x48, 0x89, 0x33}}, - { // 41 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, 0x01}, - nil, - []byte{0x02, 0x4d, 0x1f, 0xfa, 0x89, 0x04, 0xe3, 0x89}}, - { // 42 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x80, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x80, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x80, 0x01}, - nil, - []byte{0xd1, 0x39, 0x97, 0x12, 0xf9, 0x9b, 0xf0, 0x2e}}, - { // 43 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x40, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x40, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x40, 0x01}, - nil, - []byte{0x14, 0xc1, 0xd7, 0xc1, 0xcf, 0xfe, 0xc7, 0x9e}}, - { // 44 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x20, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x20, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x20, 0x01}, - nil, - []byte{0x1d, 0xe5, 0x27, 0x9d, 0xae, 0x3b, 0xed, 0x6f}}, - { // 45 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x10, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x10, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x10, 0x01}, - nil, - []byte{0xe9, 0x41, 0xa3, 0x3f, 0x85, 0x50, 0x13, 0x03}}, - { // 46 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x08, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x08, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x08, 0x01}, - nil, - []byte{0xda, 0x99, 0xdb, 0xbc, 0x9a, 0x03, 0xf3, 0x79}}, - { // 47 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x04, 0x01}, - nil, - []byte{0xb7, 0xfc, 0x92, 0xf9, 0x1d, 0x8e, 0x92, 0xe9}}, - { // 48 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, 0x01}, - nil, - []byte{0xae, 0x8e, 0x5c, 0xaa, 0x3c, 0xa0, 0x4e, 0x85}}, - { // 49 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x80, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x80, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x80}, - nil, - []byte{0x9c, 0xc6, 0x2d, 0xf4, 0x3b, 0x6e, 0xed, 0x74}}, - { // 50 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x40, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x40, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x40}, - nil, - []byte{0xd8, 0x63, 0xdb, 0xb5, 0xc5, 0x9a, 0x91, 0xa0}}, - { // 50 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x20, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x20, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x20}, - nil, - []byte{0xa1, 0xab, 0x21, 0x90, 0x54, 0x5b, 0x91, 0xd7}}, - { // 52 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x10, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x10, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x10}, - nil, - []byte{0x08, 0x75, 0x04, 0x1e, 0x64, 0xc5, 0x70, 0xf7}}, - { // 53 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x08, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x08, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x08}, - nil, - []byte{0x5a, 0x59, 0x45, 0x28, 0xbe, 0xbe, 0xf1, 0xcc}}, - { // 54 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x04, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x04, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x04}, - nil, - []byte{0xfc, 0xdb, 0x32, 0x91, 0xde, 0x21, 0xf0, 0xc0}}, - { // 55 - []byte{ - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02, - 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02}, - nil, - []byte{0x86, 0x9e, 0xfd, 0x7f, 0x9f, 0x26, 0x5a, 0x09}}, -} - -// Plaintext for use with Table A.3 tests -var tableA3Plaintext = []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} - -// Table A.3 Values To Be Used for the Permutation Operation Known Answer Test -var tableA3Tests = []CryptTest{ - { // 0 - []byte{ - 0x10, 0x46, 0x91, 0x34, 0x89, 0x98, 0x01, 0x31, - 0x10, 0x46, 0x91, 0x34, 0x89, 0x98, 0x01, 0x31, - 0x10, 0x46, 0x91, 0x34, 0x89, 0x98, 0x01, 0x31, - }, - nil, - []byte{0x88, 0xd5, 0x5e, 0x54, 0xf5, 0x4c, 0x97, 0xb4}}, - { // 1 - []byte{ - 0x10, 0x07, 0x10, 0x34, 0x89, 0x98, 0x80, 0x20, - 0x10, 0x07, 0x10, 0x34, 0x89, 0x98, 0x80, 0x20, - 0x10, 0x07, 0x10, 0x34, 0x89, 0x98, 0x80, 0x20, - }, - nil, - []byte{0x0c, 0x0c, 0xc0, 0x0c, 0x83, 0xea, 0x48, 0xfd}}, - { // 2 - []byte{ - 0x10, 0x07, 0x10, 0x34, 0xc8, 0x98, 0x01, 0x20, - 0x10, 0x07, 0x10, 0x34, 0xc8, 0x98, 0x01, 0x20, - 0x10, 0x07, 0x10, 0x34, 0xc8, 0x98, 0x01, 0x20, - }, - nil, - []byte{0x83, 0xbc, 0x8e, 0xf3, 0xa6, 0x57, 0x01, 0x83}}, - { // 3 - []byte{ - 0x10, 0x46, 0x10, 0x34, 0x89, 0x98, 0x80, 0x20, - 0x10, 0x46, 0x10, 0x34, 0x89, 0x98, 0x80, 0x20, - 0x10, 0x46, 0x10, 0x34, 0x89, 0x98, 0x80, 0x20, - }, - nil, - []byte{0xdf, 0x72, 0x5d, 0xca, 0xd9, 0x4e, 0xa2, 0xe9}}, - { // 4 - []byte{ - 0x10, 0x86, 0x91, 0x15, 0x19, 0x19, 0x01, 0x01, - 0x10, 0x86, 0x91, 0x15, 0x19, 0x19, 0x01, 0x01, - 0x10, 0x86, 0x91, 0x15, 0x19, 0x19, 0x01, 0x01, - }, - nil, - []byte{0xe6, 0x52, 0xb5, 0x3b, 0x55, 0x0b, 0xe8, 0xb0}}, - { // 5 - []byte{ - 0x10, 0x86, 0x91, 0x15, 0x19, 0x58, 0x01, 0x01, - 0x10, 0x86, 0x91, 0x15, 0x19, 0x58, 0x01, 0x01, - 0x10, 0x86, 0x91, 0x15, 0x19, 0x58, 0x01, 0x01, - }, - nil, - []byte{0xaf, 0x52, 0x71, 0x20, 0xc4, 0x85, 0xcb, 0xb0}}, - { // 6 - []byte{ - 0x51, 0x07, 0xb0, 0x15, 0x19, 0x58, 0x01, 0x01, - 0x51, 0x07, 0xb0, 0x15, 0x19, 0x58, 0x01, 0x01, - 0x51, 0x07, 0xb0, 0x15, 0x19, 0x58, 0x01, 0x01, - }, - nil, - []byte{0x0f, 0x04, 0xce, 0x39, 0x3d, 0xb9, 0x26, 0xd5}}, - { // 7 - []byte{ - 0x10, 0x07, 0xb0, 0x15, 0x19, 0x19, 0x01, 0x01, - 0x10, 0x07, 0xb0, 0x15, 0x19, 0x19, 0x01, 0x01, - 0x10, 0x07, 0xb0, 0x15, 0x19, 0x19, 0x01, 0x01, - }, - nil, - []byte{0xc9, 0xf0, 0x0f, 0xfc, 0x74, 0x07, 0x90, 0x67}}, - { // 8 - []byte{ - 0x31, 0x07, 0x91, 0x54, 0x98, 0x08, 0x01, 0x01, - 0x31, 0x07, 0x91, 0x54, 0x98, 0x08, 0x01, 0x01, - 0x31, 0x07, 0x91, 0x54, 0x98, 0x08, 0x01, 0x01, - }, - nil, - []byte{0x7c, 0xfd, 0x82, 0xa5, 0x93, 0x25, 0x2b, 0x4e}}, - { // 9 - []byte{ - 0x31, 0x07, 0x91, 0x94, 0x98, 0x08, 0x01, 0x01, - 0x31, 0x07, 0x91, 0x94, 0x98, 0x08, 0x01, 0x01, - 0x31, 0x07, 0x91, 0x94, 0x98, 0x08, 0x01, 0x01, - }, - nil, - []byte{0xcb, 0x49, 0xa2, 0xf9, 0xe9, 0x13, 0x63, 0xe3}}, - { // 10 - []byte{ - 0x10, 0x07, 0x91, 0x15, 0xb9, 0x08, 0x01, 0x40, - 0x10, 0x07, 0x91, 0x15, 0xb9, 0x08, 0x01, 0x40, - 0x10, 0x07, 0x91, 0x15, 0xb9, 0x08, 0x01, 0x40, - }, - nil, - []byte{0x00, 0xb5, 0x88, 0xbe, 0x70, 0xd2, 0x3f, 0x56}}, - { // 11 - []byte{ - 0x31, 0x07, 0x91, 0x15, 0x98, 0x08, 0x01, 0x40, - 0x31, 0x07, 0x91, 0x15, 0x98, 0x08, 0x01, 0x40, - 0x31, 0x07, 0x91, 0x15, 0x98, 0x08, 0x01, 0x40, - }, - nil, - []byte{0x40, 0x6a, 0x9a, 0x6a, 0xb4, 0x33, 0x99, 0xae}}, - { // 12 - []byte{ - 0x10, 0x07, 0xd0, 0x15, 0x89, 0x98, 0x01, 0x01, - 0x10, 0x07, 0xd0, 0x15, 0x89, 0x98, 0x01, 0x01, - 0x10, 0x07, 0xd0, 0x15, 0x89, 0x98, 0x01, 0x01, - }, - nil, - []byte{0x6c, 0xb7, 0x73, 0x61, 0x1d, 0xca, 0x9a, 0xda}}, - { // 13 - []byte{ - 0x91, 0x07, 0x91, 0x15, 0x89, 0x98, 0x01, 0x01, - 0x91, 0x07, 0x91, 0x15, 0x89, 0x98, 0x01, 0x01, - 0x91, 0x07, 0x91, 0x15, 0x89, 0x98, 0x01, 0x01, - }, - nil, - []byte{0x67, 0xfd, 0x21, 0xc1, 0x7d, 0xbb, 0x5d, 0x70}}, - { // 14 - []byte{ - 0x91, 0x07, 0xd0, 0x15, 0x89, 0x19, 0x01, 0x01, - 0x91, 0x07, 0xd0, 0x15, 0x89, 0x19, 0x01, 0x01, - 0x91, 0x07, 0xd0, 0x15, 0x89, 0x19, 0x01, 0x01, - }, - nil, - []byte{0x95, 0x92, 0xcb, 0x41, 0x10, 0x43, 0x07, 0x87}}, - { // 15 - []byte{ - 0x10, 0x07, 0xd0, 0x15, 0x98, 0x98, 0x01, 0x20, - 0x10, 0x07, 0xd0, 0x15, 0x98, 0x98, 0x01, 0x20, - 0x10, 0x07, 0xd0, 0x15, 0x98, 0x98, 0x01, 0x20, - }, - nil, - []byte{0xa6, 0xb7, 0xff, 0x68, 0xa3, 0x18, 0xdd, 0xd3}}, - { // 16 - []byte{ - 0x10, 0x07, 0x94, 0x04, 0x98, 0x19, 0x01, 0x01, - 0x10, 0x07, 0x94, 0x04, 0x98, 0x19, 0x01, 0x01, - 0x10, 0x07, 0x94, 0x04, 0x98, 0x19, 0x01, 0x01, - }, - nil, - []byte{0x4d, 0x10, 0x21, 0x96, 0xc9, 0x14, 0xca, 0x16}}, - { // 17 - []byte{ - 0x01, 0x07, 0x91, 0x04, 0x91, 0x19, 0x04, 0x01, - 0x01, 0x07, 0x91, 0x04, 0x91, 0x19, 0x04, 0x01, - 0x01, 0x07, 0x91, 0x04, 0x91, 0x19, 0x04, 0x01, - }, - nil, - []byte{0x2d, 0xfa, 0x9f, 0x45, 0x73, 0x59, 0x49, 0x65}}, - { // 18 - []byte{ - 0x01, 0x07, 0x91, 0x04, 0x91, 0x19, 0x01, 0x01, - 0x01, 0x07, 0x91, 0x04, 0x91, 0x19, 0x01, 0x01, - 0x01, 0x07, 0x91, 0x04, 0x91, 0x19, 0x01, 0x01, - }, - nil, - []byte{0xb4, 0x66, 0x04, 0x81, 0x6c, 0x0e, 0x07, 0x74}}, - { // 19 - []byte{ - 0x01, 0x07, 0x94, 0x04, 0x91, 0x19, 0x04, 0x01, - 0x01, 0x07, 0x94, 0x04, 0x91, 0x19, 0x04, 0x01, - 0x01, 0x07, 0x94, 0x04, 0x91, 0x19, 0x04, 0x01, - }, - nil, - []byte{0x6e, 0x7e, 0x62, 0x21, 0xa4, 0xf3, 0x4e, 0x87}}, - { // 20 - []byte{ - 0x19, 0x07, 0x92, 0x10, 0x98, 0x1a, 0x01, 0x01, - 0x19, 0x07, 0x92, 0x10, 0x98, 0x1a, 0x01, 0x01, - 0x19, 0x07, 0x92, 0x10, 0x98, 0x1a, 0x01, 0x01, - }, - nil, - []byte{0xaa, 0x85, 0xe7, 0x46, 0x43, 0x23, 0x31, 0x99}}, - { // 21 - []byte{ - 0x10, 0x07, 0x91, 0x19, 0x98, 0x19, 0x08, 0x01, - 0x10, 0x07, 0x91, 0x19, 0x98, 0x19, 0x08, 0x01, - 0x10, 0x07, 0x91, 0x19, 0x98, 0x19, 0x08, 0x01, - }, - nil, - []byte{0x2e, 0x5a, 0x19, 0xdb, 0x4d, 0x19, 0x62, 0xd6}}, - { // 22 - []byte{ - 0x10, 0x07, 0x91, 0x19, 0x98, 0x1a, 0x08, 0x01, - 0x10, 0x07, 0x91, 0x19, 0x98, 0x1a, 0x08, 0x01, - 0x10, 0x07, 0x91, 0x19, 0x98, 0x1a, 0x08, 0x01, - }, - nil, - []byte{0x23, 0xa8, 0x66, 0xa8, 0x09, 0xd3, 0x08, 0x94}}, - { // 23 - []byte{ - 0x10, 0x07, 0x92, 0x10, 0x98, 0x19, 0x01, 0x01, - 0x10, 0x07, 0x92, 0x10, 0x98, 0x19, 0x01, 0x01, - 0x10, 0x07, 0x92, 0x10, 0x98, 0x19, 0x01, 0x01, - }, - nil, - []byte{0xd8, 0x12, 0xd9, 0x61, 0xf0, 0x17, 0xd3, 0x20}}, - { // 24 - []byte{ - 0x10, 0x07, 0x91, 0x15, 0x98, 0x19, 0x01, 0x0b, - 0x10, 0x07, 0x91, 0x15, 0x98, 0x19, 0x01, 0x0b, - 0x10, 0x07, 0x91, 0x15, 0x98, 0x19, 0x01, 0x0b, - }, - nil, - []byte{0x05, 0x56, 0x05, 0x81, 0x6e, 0x58, 0x60, 0x8f}}, - { // 25 - []byte{ - 0x10, 0x04, 0x80, 0x15, 0x98, 0x19, 0x01, 0x01, - 0x10, 0x04, 0x80, 0x15, 0x98, 0x19, 0x01, 0x01, - 0x10, 0x04, 0x80, 0x15, 0x98, 0x19, 0x01, 0x01, - }, - nil, - []byte{0xab, 0xd8, 0x8e, 0x8b, 0x1b, 0x77, 0x16, 0xf1}}, - { // 26 - []byte{ - 0x10, 0x04, 0x80, 0x15, 0x98, 0x19, 0x01, 0x02, - 0x10, 0x04, 0x80, 0x15, 0x98, 0x19, 0x01, 0x02, - 0x10, 0x04, 0x80, 0x15, 0x98, 0x19, 0x01, 0x02, - }, - nil, - []byte{0x53, 0x7a, 0xc9, 0x5b, 0xe6, 0x9d, 0xa1, 0xe1}}, - { // 27 - []byte{ - 0x10, 0x04, 0x80, 0x15, 0x98, 0x19, 0x01, 0x08, - 0x10, 0x04, 0x80, 0x15, 0x98, 0x19, 0x01, 0x08, - 0x10, 0x04, 0x80, 0x15, 0x98, 0x19, 0x01, 0x08, - }, - nil, - []byte{0xae, 0xd0, 0xf6, 0xae, 0x3c, 0x25, 0xcd, 0xd8}}, - { // 28 - []byte{ - 0x10, 0x02, 0x91, 0x15, 0x98, 0x10, 0x01, 0x04, - 0x10, 0x02, 0x91, 0x15, 0x98, 0x10, 0x01, 0x04, - 0x10, 0x02, 0x91, 0x15, 0x98, 0x10, 0x01, 0x04, - }, - nil, - []byte{0xb3, 0xe3, 0x5a, 0x5e, 0xe5, 0x3e, 0x7b, 0x8d}}, - { // 29 - []byte{ - 0x10, 0x02, 0x91, 0x15, 0x98, 0x19, 0x01, 0x04, - 0x10, 0x02, 0x91, 0x15, 0x98, 0x19, 0x01, 0x04, - 0x10, 0x02, 0x91, 0x15, 0x98, 0x19, 0x01, 0x04, - }, - nil, - []byte{0x61, 0xc7, 0x9c, 0x71, 0x92, 0x1a, 0x2e, 0xf8}}, - { // 30 - []byte{ - 0x10, 0x02, 0x91, 0x15, 0x98, 0x10, 0x02, 0x01, - 0x10, 0x02, 0x91, 0x15, 0x98, 0x10, 0x02, 0x01, - 0x10, 0x02, 0x91, 0x15, 0x98, 0x10, 0x02, 0x01, - }, - nil, - []byte{0xe2, 0xf5, 0x72, 0x8f, 0x09, 0x95, 0x01, 0x3c}}, - { // 31 - []byte{ - 0x10, 0x02, 0x91, 0x16, 0x98, 0x10, 0x01, 0x01, - 0x10, 0x02, 0x91, 0x16, 0x98, 0x10, 0x01, 0x01, - 0x10, 0x02, 0x91, 0x16, 0x98, 0x10, 0x01, 0x01, - }, - nil, - []byte{0x1a, 0xea, 0xc3, 0x9a, 0x61, 0xf0, 0xa4, 0x64}}, -} - -// Table A.4 Values To Be Used for the Substitution Table Known Answer Test -var tableA4Tests = []CryptTest{ - { // 0 - []byte{ - 0x7c, 0xa1, 0x10, 0x45, 0x4a, 0x1a, 0x6e, 0x57, - 0x7c, 0xa1, 0x10, 0x45, 0x4a, 0x1a, 0x6e, 0x57, - 0x7c, 0xa1, 0x10, 0x45, 0x4a, 0x1a, 0x6e, 0x57}, - []byte{0x01, 0xa1, 0xd6, 0xd0, 0x39, 0x77, 0x67, 0x42}, - []byte{0x69, 0x0f, 0x5b, 0x0d, 0x9a, 0x26, 0x93, 0x9b}}, - { // 1 - []byte{ - 0x01, 0x31, 0xd9, 0x61, 0x9d, 0xc1, 0x37, 0x6e, - 0x01, 0x31, 0xd9, 0x61, 0x9d, 0xc1, 0x37, 0x6e, - 0x01, 0x31, 0xd9, 0x61, 0x9d, 0xc1, 0x37, 0x6e}, - []byte{0x5c, 0xd5, 0x4c, 0xa8, 0x3d, 0xef, 0x57, 0xda}, - []byte{0x7a, 0x38, 0x9d, 0x10, 0x35, 0x4b, 0xd2, 0x71}}, - { // 2 - []byte{ - 0x07, 0xa1, 0x13, 0x3e, 0x4a, 0x0b, 0x26, 0x86, - 0x07, 0xa1, 0x13, 0x3e, 0x4a, 0x0b, 0x26, 0x86, - 0x07, 0xa1, 0x13, 0x3e, 0x4a, 0x0b, 0x26, 0x86}, - []byte{0x02, 0x48, 0xd4, 0x38, 0x06, 0xf6, 0x71, 0x72}, - []byte{0x86, 0x8e, 0xbb, 0x51, 0xca, 0xb4, 0x59, 0x9a}}, - { // 3 - []byte{ - 0x38, 0x49, 0x67, 0x4c, 0x26, 0x02, 0x31, 0x9e, - 0x38, 0x49, 0x67, 0x4c, 0x26, 0x02, 0x31, 0x9e, - 0x38, 0x49, 0x67, 0x4c, 0x26, 0x02, 0x31, 0x9e}, - []byte{0x51, 0x45, 0x4b, 0x58, 0x2d, 0xdf, 0x44, 0x0a}, - []byte{0x71, 0x78, 0x87, 0x6e, 0x01, 0xf1, 0x9b, 0x2a}}, - { // 4 - []byte{ - 0x04, 0xb9, 0x15, 0xba, 0x43, 0xfe, 0xb5, 0xb6, - 0x04, 0xb9, 0x15, 0xba, 0x43, 0xfe, 0xb5, 0xb6, - 0x04, 0xb9, 0x15, 0xba, 0x43, 0xfe, 0xb5, 0xb6}, - []byte{0x42, 0xfd, 0x44, 0x30, 0x59, 0x57, 0x7f, 0xa2}, - []byte{0xaf, 0x37, 0xfb, 0x42, 0x1f, 0x8c, 0x40, 0x95}}, - { // 5 - []byte{ - 0x01, 0x13, 0xb9, 0x70, 0xfd, 0x34, 0xf2, 0xce, - 0x01, 0x13, 0xb9, 0x70, 0xfd, 0x34, 0xf2, 0xce, - 0x01, 0x13, 0xb9, 0x70, 0xfd, 0x34, 0xf2, 0xce}, - []byte{0x05, 0x9b, 0x5e, 0x08, 0x51, 0xcf, 0x14, 0x3a}, - []byte{0x86, 0xa5, 0x60, 0xf1, 0x0e, 0xc6, 0xd8, 0x5b}}, - { // 6 - []byte{ - 0x01, 0x70, 0xf1, 0x75, 0x46, 0x8f, 0xb5, 0xe6, - 0x01, 0x70, 0xf1, 0x75, 0x46, 0x8f, 0xb5, 0xe6, - 0x01, 0x70, 0xf1, 0x75, 0x46, 0x8f, 0xb5, 0xe6}, - []byte{0x07, 0x56, 0xd8, 0xe0, 0x77, 0x47, 0x61, 0xd2}, - []byte{0x0c, 0xd3, 0xda, 0x02, 0x00, 0x21, 0xdc, 0x09}}, - { // 7 - []byte{ - 0x43, 0x29, 0x7f, 0xad, 0x38, 0xe3, 0x73, 0xfe, - 0x43, 0x29, 0x7f, 0xad, 0x38, 0xe3, 0x73, 0xfe, - 0x43, 0x29, 0x7f, 0xad, 0x38, 0xe3, 0x73, 0xfe}, - []byte{0x76, 0x25, 0x14, 0xb8, 0x29, 0xbf, 0x48, 0x6a}, - []byte{0xea, 0x67, 0x6b, 0x2c, 0xb7, 0xdb, 0x2b, 0x7a}}, - { // 8 - []byte{ - 0x07, 0xa7, 0x13, 0x70, 0x45, 0xda, 0x2a, 0x16, - 0x07, 0xa7, 0x13, 0x70, 0x45, 0xda, 0x2a, 0x16, - 0x07, 0xa7, 0x13, 0x70, 0x45, 0xda, 0x2a, 0x16}, - []byte{0x3b, 0xdd, 0x11, 0x90, 0x49, 0x37, 0x28, 0x02}, - []byte{0xdf, 0xd6, 0x4a, 0x81, 0x5c, 0xaf, 0x1a, 0x0f}}, - { // 9 - []byte{ - 0x04, 0x68, 0x91, 0x04, 0xc2, 0xfd, 0x3b, 0x2f, - 0x04, 0x68, 0x91, 0x04, 0xc2, 0xfd, 0x3b, 0x2f, - 0x04, 0x68, 0x91, 0x04, 0xc2, 0xfd, 0x3b, 0x2f}, - []byte{0x26, 0x95, 0x5f, 0x68, 0x35, 0xaf, 0x60, 0x9a}, - []byte{0x5c, 0x51, 0x3c, 0x9c, 0x48, 0x86, 0xc0, 0x88}}, - { // 10 - []byte{ - 0x37, 0xd0, 0x6b, 0xb5, 0x16, 0xcb, 0x75, 0x46, - 0x37, 0xd0, 0x6b, 0xb5, 0x16, 0xcb, 0x75, 0x46, - 0x37, 0xd0, 0x6b, 0xb5, 0x16, 0xcb, 0x75, 0x46}, - []byte{0x16, 0x4d, 0x5e, 0x40, 0x4f, 0x27, 0x52, 0x32}, - []byte{0x0a, 0x2a, 0xee, 0xae, 0x3f, 0xf4, 0xab, 0x77}}, - { // 11 - []byte{ - 0x1f, 0x08, 0x26, 0x0d, 0x1a, 0xc2, 0x46, 0x5e, - 0x1f, 0x08, 0x26, 0x0d, 0x1a, 0xc2, 0x46, 0x5e, - 0x1f, 0x08, 0x26, 0x0d, 0x1a, 0xc2, 0x46, 0x5e}, - []byte{0x6b, 0x05, 0x6e, 0x18, 0x75, 0x9f, 0x5c, 0xca}, - []byte{0xef, 0x1b, 0xf0, 0x3e, 0x5d, 0xfa, 0x57, 0x5a}}, - { // 12 - []byte{ - 0x58, 0x40, 0x23, 0x64, 0x1a, 0xba, 0x61, 0x76, - 0x58, 0x40, 0x23, 0x64, 0x1a, 0xba, 0x61, 0x76, - 0x58, 0x40, 0x23, 0x64, 0x1a, 0xba, 0x61, 0x76}, - []byte{0x00, 0x4b, 0xd6, 0xef, 0x09, 0x17, 0x60, 0x62}, - []byte{0x88, 0xbf, 0x0d, 0xb6, 0xd7, 0x0d, 0xee, 0x56}}, - { // 13 - []byte{ - 0x02, 0x58, 0x16, 0x16, 0x46, 0x29, 0xb0, 0x07, - 0x02, 0x58, 0x16, 0x16, 0x46, 0x29, 0xb0, 0x07, - 0x02, 0x58, 0x16, 0x16, 0x46, 0x29, 0xb0, 0x07}, - []byte{0x48, 0x0d, 0x39, 0x00, 0x6e, 0xe7, 0x62, 0xf2}, - []byte{0xa1, 0xf9, 0x91, 0x55, 0x41, 0x02, 0x0b, 0x56}}, - { // 14 - []byte{ - 0x49, 0x79, 0x3e, 0xbc, 0x79, 0xb3, 0x25, 0x8f, - 0x49, 0x79, 0x3e, 0xbc, 0x79, 0xb3, 0x25, 0x8f, - 0x49, 0x79, 0x3e, 0xbc, 0x79, 0xb3, 0x25, 0x8f}, - []byte{0x43, 0x75, 0x40, 0xc8, 0x69, 0x8f, 0x3c, 0xfa}, - []byte{0x6f, 0xbf, 0x1c, 0xaf, 0xcf, 0xfd, 0x05, 0x56}}, - { // 15 - []byte{ - 0x4f, 0xb0, 0x5e, 0x15, 0x15, 0xab, 0x73, 0xa7, - 0x4f, 0xb0, 0x5e, 0x15, 0x15, 0xab, 0x73, 0xa7, - 0x4f, 0xb0, 0x5e, 0x15, 0x15, 0xab, 0x73, 0xa7}, - []byte{0x07, 0x2d, 0x43, 0xa0, 0x77, 0x07, 0x52, 0x92}, - []byte{0x2f, 0x22, 0xe4, 0x9b, 0xab, 0x7c, 0xa1, 0xac}}, - { // 16 - []byte{ - 0x49, 0xe9, 0x5d, 0x6d, 0x4c, 0xa2, 0x29, 0xbf, - 0x49, 0xe9, 0x5d, 0x6d, 0x4c, 0xa2, 0x29, 0xbf, - 0x49, 0xe9, 0x5d, 0x6d, 0x4c, 0xa2, 0x29, 0xbf}, - []byte{0x02, 0xfe, 0x55, 0x77, 0x81, 0x17, 0xf1, 0x2a}, - []byte{0x5a, 0x6b, 0x61, 0x2c, 0xc2, 0x6c, 0xce, 0x4a}}, - { // 17 - []byte{ - 0x01, 0x83, 0x10, 0xdc, 0x40, 0x9b, 0x26, 0xd6, - 0x01, 0x83, 0x10, 0xdc, 0x40, 0x9b, 0x26, 0xd6, - 0x01, 0x83, 0x10, 0xdc, 0x40, 0x9b, 0x26, 0xd6}, - []byte{0x1d, 0x9d, 0x5c, 0x50, 0x18, 0xf7, 0x28, 0xc2}, - []byte{0x5f, 0x4c, 0x03, 0x8e, 0xd1, 0x2b, 0x2e, 0x41}}, - { // 18 - []byte{ - 0x1c, 0x58, 0x7f, 0x1c, 0x13, 0x92, 0x4f, 0xef, - 0x1c, 0x58, 0x7f, 0x1c, 0x13, 0x92, 0x4f, 0xef, - 0x1c, 0x58, 0x7f, 0x1c, 0x13, 0x92, 0x4f, 0xef}, - []byte{0x30, 0x55, 0x32, 0x28, 0x6d, 0x6f, 0x29, 0x5a}, - []byte{0x63, 0xfa, 0xc0, 0xd0, 0x34, 0xd9, 0xf7, 0x93}}, -} - -func newCipher(key []byte) *desCipher { - c, err := NewCipher(key) - if err != nil { - panic("NewCipher failed: " + err.Error()) - } - return c.(*desCipher) -} - -// Use the known weak keys to test DES implementation -func TestWeakKeys(t *testing.T) { - for i, tt := range weakKeyTests { - var encrypt = func(in []byte) (out []byte) { - c := newCipher(tt.key) - out = make([]byte, len(in)) - encryptBlock(c.subkeys[:], out, in) - return - } - - // Encrypting twice with a DES weak - // key should reproduce the original input - result := encrypt(tt.in) - result = encrypt(result) - - if !bytes.Equal(result, tt.in) { - t.Errorf("#%d: result: %x want: %x", i, result, tt.in) - } - } -} - -// Use the known semi-weak key pairs to test DES implementation -func TestSemiWeakKeyPairs(t *testing.T) { - for i, tt := range semiWeakKeyTests { - var encrypt = func(key, in []byte) (out []byte) { - c := newCipher(key) - out = make([]byte, len(in)) - encryptBlock(c.subkeys[:], out, in) - return - } - - // Encrypting with one member of the semi-weak pair - // and then encrypting the result with the other member - // should reproduce the original input. - result := encrypt(tt.key, tt.in) - result = encrypt(tt.out, result) - - if !bytes.Equal(result, tt.in) { - t.Errorf("#%d: result: %x want: %x", i, result, tt.in) - } - } -} - -func TestDESEncryptBlock(t *testing.T) { - for i, tt := range encryptDESTests { - c := newCipher(tt.key) - out := make([]byte, len(tt.in)) - encryptBlock(c.subkeys[:], out, tt.in) - - if !bytes.Equal(out, tt.out) { - t.Errorf("#%d: result: %x want: %x", i, out, tt.out) - } - } -} - -func TestDESDecryptBlock(t *testing.T) { - for i, tt := range encryptDESTests { - c := newCipher(tt.key) - plain := make([]byte, len(tt.in)) - decryptBlock(c.subkeys[:], plain, tt.out) - - if !bytes.Equal(plain, tt.in) { - t.Errorf("#%d: result: %x want: %x", i, plain, tt.in) - } - } -} - -func TestEncryptTripleDES(t *testing.T) { - for i, tt := range encryptTripleDESTests { - c, _ := NewTripleDESCipher(tt.key) - out := make([]byte, len(tt.in)) - c.Encrypt(out, tt.in) - - if !bytes.Equal(out, tt.out) { - t.Errorf("#%d: result: %x want: %x", i, out, tt.out) - } - } -} - -func TestDecryptTripleDES(t *testing.T) { - for i, tt := range encryptTripleDESTests { - c, _ := NewTripleDESCipher(tt.key) - - plain := make([]byte, len(tt.in)) - c.Decrypt(plain, tt.out) - - if !bytes.Equal(plain, tt.in) { - t.Errorf("#%d: result: %x want: %x", i, plain, tt.in) - } - } -} - -// Defined in Pub 800-20 -func TestVariablePlaintextKnownAnswer(t *testing.T) { - for i, tt := range tableA1Tests { - c, _ := NewTripleDESCipher(tableA1Key) - - out := make([]byte, len(tt.in)) - c.Encrypt(out, tt.in) - - if !bytes.Equal(out, tt.out) { - t.Errorf("#%d: result: %x want: %x", i, out, tt.out) - } - } -} - -// Defined in Pub 800-20 -func TestVariableCiphertextKnownAnswer(t *testing.T) { - for i, tt := range tableA1Tests { - c, _ := NewTripleDESCipher(tableA1Key) - - plain := make([]byte, len(tt.out)) - c.Decrypt(plain, tt.out) - - if !bytes.Equal(plain, tt.in) { - t.Errorf("#%d: result: %x want: %x", i, plain, tt.in) - } - } -} - -// Defined in Pub 800-20 -// Encrypting the Table A.1 ciphertext with the -// 0x01... key produces the original plaintext -func TestInversePermutationKnownAnswer(t *testing.T) { - for i, tt := range tableA1Tests { - c, _ := NewTripleDESCipher(tableA1Key) - - plain := make([]byte, len(tt.in)) - c.Encrypt(plain, tt.out) - - if !bytes.Equal(plain, tt.in) { - t.Errorf("#%d: result: %x want: %x", i, plain, tt.in) - } - } -} - -// Defined in Pub 800-20 -// Decrypting the Table A.1 plaintext with the -// 0x01... key produces the corresponding ciphertext -func TestInitialPermutationKnownAnswer(t *testing.T) { - for i, tt := range tableA1Tests { - c, _ := NewTripleDESCipher(tableA1Key) - - out := make([]byte, len(tt.in)) - c.Decrypt(out, tt.in) - - if !bytes.Equal(out, tt.out) { - t.Errorf("#%d: result: %x want: %x", i, out, tt.out) - } - } -} - -// Defined in Pub 800-20 -func TestVariableKeyKnownAnswerEncrypt(t *testing.T) { - for i, tt := range tableA2Tests { - c, _ := NewTripleDESCipher(tt.key) - - out := make([]byte, len(tableA2Plaintext)) - c.Encrypt(out, tableA2Plaintext) - - if !bytes.Equal(out, tt.out) { - t.Errorf("#%d: result: %x want: %x", i, out, tt.out) - } - } -} - -// Defined in Pub 800-20 -func TestVariableKeyKnownAnswerDecrypt(t *testing.T) { - for i, tt := range tableA2Tests { - c, _ := NewTripleDESCipher(tt.key) - - out := make([]byte, len(tt.out)) - c.Decrypt(out, tt.out) - - if !bytes.Equal(out, tableA2Plaintext) { - t.Errorf("#%d: result: %x want: %x", i, out, tableA2Plaintext) - } - } -} - -// Defined in Pub 800-20 -func TestPermutationOperationKnownAnswerEncrypt(t *testing.T) { - for i, tt := range tableA3Tests { - c, _ := NewTripleDESCipher(tt.key) - - out := make([]byte, len(tableA3Plaintext)) - c.Encrypt(out, tableA3Plaintext) - - if !bytes.Equal(out, tt.out) { - t.Errorf("#%d: result: %x want: %x", i, out, tt.out) - } - } -} - -// Defined in Pub 800-20 -func TestPermutationOperationKnownAnswerDecrypt(t *testing.T) { - for i, tt := range tableA3Tests { - c, _ := NewTripleDESCipher(tt.key) - - out := make([]byte, len(tt.out)) - c.Decrypt(out, tt.out) - - if !bytes.Equal(out, tableA3Plaintext) { - t.Errorf("#%d: result: %x want: %x", i, out, tableA3Plaintext) - } - } -} - -// Defined in Pub 800-20 -func TestSubstitutionTableKnownAnswerEncrypt(t *testing.T) { - for i, tt := range tableA4Tests { - c, _ := NewTripleDESCipher(tt.key) - - out := make([]byte, len(tt.in)) - c.Encrypt(out, tt.in) - - if !bytes.Equal(out, tt.out) { - t.Errorf("#%d: result: %x want: %x", i, out, tt.out) - } - } -} - -// Defined in Pub 800-20 -func TestSubstitutionTableKnownAnswerDecrypt(t *testing.T) { - for i, tt := range tableA4Tests { - c, _ := NewTripleDESCipher(tt.key) - - out := make([]byte, len(tt.out)) - c.Decrypt(out, tt.out) - - if !bytes.Equal(out, tt.in) { - t.Errorf("#%d: result: %x want: %x", i, out, tt.in) - } - } -} - -func TestInitialPermute(t *testing.T) { - for i := uint(0); i < 64; i++ { - bit := uint64(1) << i - got := permuteInitialBlock(bit) - want := uint64(1) << finalPermutation[63-i] - if got != want { - t.Errorf("permute(%x) = %x, want %x", bit, got, want) - } - } -} - -func TestFinalPermute(t *testing.T) { - for i := uint(0); i < 64; i++ { - bit := uint64(1) << i - got := permuteFinalBlock(bit) - want := uint64(1) << initialPermutation[63-i] - if got != want { - t.Errorf("permute(%x) = %x, want %x", bit, got, want) - } - } -} - -func TestExpandBlock(t *testing.T) { - for i := uint(0); i < 32; i++ { - bit := uint32(1) << i - got := expandBlock(bit) - want := permuteBlock(uint64(bit), expansionFunction[:]) - if got != want { - t.Errorf("expand(%x) = %x, want %x", bit, got, want) - } - } -} - -func BenchmarkEncrypt(b *testing.B) { - tt := encryptDESTests[0] - c, err := NewCipher(tt.key) - if err != nil { - b.Fatal("NewCipher:", err) - } - out := make([]byte, len(tt.in)) - b.SetBytes(int64(len(out))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - c.Encrypt(out, tt.in) - } -} - -func BenchmarkDecrypt(b *testing.B) { - tt := encryptDESTests[0] - c, err := NewCipher(tt.key) - if err != nil { - b.Fatal("NewCipher:", err) - } - out := make([]byte, len(tt.out)) - b.SetBytes(int64(len(out))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - c.Decrypt(out, tt.out) - } -} diff --git a/src/pkg/crypto/des/example_test.go b/src/pkg/crypto/des/example_test.go deleted file mode 100644 index 336b59375..000000000 --- a/src/pkg/crypto/des/example_test.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package des_test - -import "crypto/des" - -func ExampleNewTripleDESCipher() { - // NewTripleDESCipher can also be used when EDE2 is required by - // duplicating the first 8 bytes of the 16-byte key. - ede2Key := []byte("example key 1234") - - var tripleDESKey []byte - tripleDESKey = append(tripleDESKey, ede2Key[:16]...) - tripleDESKey = append(tripleDESKey, ede2Key[:8]...) - - _, err := des.NewTripleDESCipher(tripleDESKey) - if err != nil { - panic(err) - } - - // See crypto/cipher for how to use a cipher.Block for encryption and - // decryption. -} diff --git a/src/pkg/crypto/dsa/dsa.go b/src/pkg/crypto/dsa/dsa.go deleted file mode 100644 index b7565a61b..000000000 --- a/src/pkg/crypto/dsa/dsa.go +++ /dev/null @@ -1,278 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package dsa implements the Digital Signature Algorithm, as defined in FIPS 186-3. -package dsa - -import ( - "errors" - "io" - "math/big" -) - -// Parameters represents the domain parameters for a key. These parameters can -// be shared across many keys. The bit length of Q must be a multiple of 8. -type Parameters struct { - P, Q, G *big.Int -} - -// PublicKey represents a DSA public key. -type PublicKey struct { - Parameters - Y *big.Int -} - -// PrivateKey represents a DSA private key. -type PrivateKey struct { - PublicKey - X *big.Int -} - -// ErrInvalidPublicKey results when a public key is not usable by this code. -// FIPS is quite strict about the format of DSA keys, but other code may be -// less so. Thus, when using keys which may have been generated by other code, -// this error must be handled. -var ErrInvalidPublicKey = errors.New("crypto/dsa: invalid public key") - -// ParameterSizes is a enumeration of the acceptable bit lengths of the primes -// in a set of DSA parameters. See FIPS 186-3, section 4.2. -type ParameterSizes int - -const ( - L1024N160 ParameterSizes = iota - L2048N224 - L2048N256 - L3072N256 -) - -// numMRTests is the number of Miller-Rabin primality tests that we perform. We -// pick the largest recommended number from table C.1 of FIPS 186-3. -const numMRTests = 64 - -// GenerateParameters puts a random, valid set of DSA parameters into params. -// This function takes many seconds, even on fast machines. -func GenerateParameters(params *Parameters, rand io.Reader, sizes ParameterSizes) (err error) { - // This function doesn't follow FIPS 186-3 exactly in that it doesn't - // use a verification seed to generate the primes. The verification - // seed doesn't appear to be exported or used by other code and - // omitting it makes the code cleaner. - - var L, N int - switch sizes { - case L1024N160: - L = 1024 - N = 160 - case L2048N224: - L = 2048 - N = 224 - case L2048N256: - L = 2048 - N = 256 - case L3072N256: - L = 3072 - N = 256 - default: - return errors.New("crypto/dsa: invalid ParameterSizes") - } - - qBytes := make([]byte, N/8) - pBytes := make([]byte, L/8) - - q := new(big.Int) - p := new(big.Int) - rem := new(big.Int) - one := new(big.Int) - one.SetInt64(1) - -GeneratePrimes: - for { - _, err = io.ReadFull(rand, qBytes) - if err != nil { - return - } - - qBytes[len(qBytes)-1] |= 1 - qBytes[0] |= 0x80 - q.SetBytes(qBytes) - - if !q.ProbablyPrime(numMRTests) { - continue - } - - for i := 0; i < 4*L; i++ { - _, err = io.ReadFull(rand, pBytes) - if err != nil { - return - } - - pBytes[len(pBytes)-1] |= 1 - pBytes[0] |= 0x80 - - p.SetBytes(pBytes) - rem.Mod(p, q) - rem.Sub(rem, one) - p.Sub(p, rem) - if p.BitLen() < L { - continue - } - - if !p.ProbablyPrime(numMRTests) { - continue - } - - params.P = p - params.Q = q - break GeneratePrimes - } - } - - h := new(big.Int) - h.SetInt64(2) - g := new(big.Int) - - pm1 := new(big.Int).Sub(p, one) - e := new(big.Int).Div(pm1, q) - - for { - g.Exp(h, e, p) - if g.Cmp(one) == 0 { - h.Add(h, one) - continue - } - - params.G = g - return - } -} - -// GenerateKey generates a public&private key pair. The Parameters of the -// PrivateKey must already be valid (see GenerateParameters). -func GenerateKey(priv *PrivateKey, rand io.Reader) error { - if priv.P == nil || priv.Q == nil || priv.G == nil { - return errors.New("crypto/dsa: parameters not set up before generating key") - } - - x := new(big.Int) - xBytes := make([]byte, priv.Q.BitLen()/8) - - for { - _, err := io.ReadFull(rand, xBytes) - if err != nil { - return err - } - x.SetBytes(xBytes) - if x.Sign() != 0 && x.Cmp(priv.Q) < 0 { - break - } - } - - priv.X = x - priv.Y = new(big.Int) - priv.Y.Exp(priv.G, x, priv.P) - return nil -} - -// fermatInverse calculates the inverse of k in GF(P) using Fermat's method. -// This has better constant-time properties than Euclid's method (implemented -// in math/big.Int.ModInverse) although math/big itself isn't strictly -// constant-time so it's not perfect. -func fermatInverse(k, P *big.Int) *big.Int { - two := big.NewInt(2) - pMinus2 := new(big.Int).Sub(P, two) - return new(big.Int).Exp(k, pMinus2, P) -} - -// Sign signs an arbitrary length hash (which should be the result of hashing a -// larger message) using the private key, priv. It returns the signature as a -// pair of integers. The security of the private key depends on the entropy of -// rand. -// -// Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated -// to the byte-length of the subgroup. This function does not perform that -// truncation itself. -func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) { - // FIPS 186-3, section 4.6 - - n := priv.Q.BitLen() - if n&7 != 0 { - err = ErrInvalidPublicKey - return - } - n >>= 3 - - for { - k := new(big.Int) - buf := make([]byte, n) - for { - _, err = io.ReadFull(rand, buf) - if err != nil { - return - } - k.SetBytes(buf) - if k.Sign() > 0 && k.Cmp(priv.Q) < 0 { - break - } - } - - kInv := fermatInverse(k, priv.Q) - - r = new(big.Int).Exp(priv.G, k, priv.P) - r.Mod(r, priv.Q) - - if r.Sign() == 0 { - continue - } - - z := k.SetBytes(hash) - - s = new(big.Int).Mul(priv.X, r) - s.Add(s, z) - s.Mod(s, priv.Q) - s.Mul(s, kInv) - s.Mod(s, priv.Q) - - if s.Sign() != 0 { - break - } - } - - return -} - -// Verify verifies the signature in r, s of hash using the public key, pub. It -// reports whether the signature is valid. -// -// Note that FIPS 186-3 section 4.6 specifies that the hash should be truncated -// to the byte-length of the subgroup. This function does not perform that -// truncation itself. -func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool { - // FIPS 186-3, section 4.7 - - if r.Sign() < 1 || r.Cmp(pub.Q) >= 0 { - return false - } - if s.Sign() < 1 || s.Cmp(pub.Q) >= 0 { - return false - } - - w := new(big.Int).ModInverse(s, pub.Q) - - n := pub.Q.BitLen() - if n&7 != 0 { - return false - } - z := new(big.Int).SetBytes(hash) - - u1 := new(big.Int).Mul(z, w) - u1.Mod(u1, pub.Q) - u2 := w.Mul(r, w) - u2.Mod(u2, pub.Q) - v := u1.Exp(pub.G, u1, pub.P) - u2.Exp(pub.Y, u2, pub.P) - v.Mul(v, u2) - v.Mod(v, pub.P) - v.Mod(v, pub.Q) - - return v.Cmp(r) == 0 -} diff --git a/src/pkg/crypto/dsa/dsa_test.go b/src/pkg/crypto/dsa/dsa_test.go deleted file mode 100644 index 568416d0d..000000000 --- a/src/pkg/crypto/dsa/dsa_test.go +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package dsa - -import ( - "crypto/rand" - "math/big" - "testing" -) - -func testSignAndVerify(t *testing.T, i int, priv *PrivateKey) { - hashed := []byte("testing") - r, s, err := Sign(rand.Reader, priv, hashed) - if err != nil { - t.Errorf("%d: error signing: %s", i, err) - return - } - - if !Verify(&priv.PublicKey, hashed, r, s) { - t.Errorf("%d: Verify failed", i) - } -} - -func testParameterGeneration(t *testing.T, sizes ParameterSizes, L, N int) { - var priv PrivateKey - params := &priv.Parameters - - err := GenerateParameters(params, rand.Reader, sizes) - if err != nil { - t.Errorf("%d: %s", int(sizes), err) - return - } - - if params.P.BitLen() != L { - t.Errorf("%d: params.BitLen got:%d want:%d", int(sizes), params.P.BitLen(), L) - } - - if params.Q.BitLen() != N { - t.Errorf("%d: q.BitLen got:%d want:%d", int(sizes), params.Q.BitLen(), L) - } - - one := new(big.Int) - one.SetInt64(1) - pm1 := new(big.Int).Sub(params.P, one) - quo, rem := new(big.Int).DivMod(pm1, params.Q, new(big.Int)) - if rem.Sign() != 0 { - t.Errorf("%d: p-1 mod q != 0", int(sizes)) - } - x := new(big.Int).Exp(params.G, quo, params.P) - if x.Cmp(one) == 0 { - t.Errorf("%d: invalid generator", int(sizes)) - } - - err = GenerateKey(&priv, rand.Reader) - if err != nil { - t.Errorf("error generating key: %s", err) - return - } - - testSignAndVerify(t, int(sizes), &priv) -} - -func TestParameterGeneration(t *testing.T) { - if testing.Short() { - t.Skip("skipping parameter generation test in short mode") - } - - testParameterGeneration(t, L1024N160, 1024, 160) - testParameterGeneration(t, L2048N224, 2048, 224) - testParameterGeneration(t, L2048N256, 2048, 256) - testParameterGeneration(t, L3072N256, 3072, 256) -} - -func TestSignAndVerify(t *testing.T) { - var priv PrivateKey - priv.P, _ = new(big.Int).SetString("A9B5B793FB4785793D246BAE77E8FF63CA52F442DA763C440259919FE1BC1D6065A9350637A04F75A2F039401D49F08E066C4D275A5A65DA5684BC563C14289D7AB8A67163BFBF79D85972619AD2CFF55AB0EE77A9002B0EF96293BDD0F42685EBB2C66C327079F6C98000FBCB79AACDE1BC6F9D5C7B1A97E3D9D54ED7951FEF", 16) - priv.Q, _ = new(big.Int).SetString("E1D3391245933D68A0714ED34BBCB7A1F422B9C1", 16) - priv.G, _ = new(big.Int).SetString("634364FC25248933D01D1993ECABD0657CC0CB2CEED7ED2E3E8AECDFCDC4A25C3B15E9E3B163ACA2984B5539181F3EFF1A5E8903D71D5B95DA4F27202B77D2C44B430BB53741A8D59A8F86887525C9F2A6A5980A195EAA7F2FF910064301DEF89D3AA213E1FAC7768D89365318E370AF54A112EFBA9246D9158386BA1B4EEFDA", 16) - priv.Y, _ = new(big.Int).SetString("32969E5780CFE1C849A1C276D7AEB4F38A23B591739AA2FE197349AEEBD31366AEE5EB7E6C6DDB7C57D02432B30DB5AA66D9884299FAA72568944E4EEDC92EA3FBC6F39F53412FBCC563208F7C15B737AC8910DBC2D9C9B8C001E72FDC40EB694AB1F06A5A2DBD18D9E36C66F31F566742F11EC0A52E9F7B89355C02FB5D32D2", 16) - priv.X, _ = new(big.Int).SetString("5078D4D29795CBE76D3AACFE48C9AF0BCDBEE91A", 16) - - testSignAndVerify(t, 0, &priv) -} diff --git a/src/pkg/crypto/ecdsa/ecdsa.go b/src/pkg/crypto/ecdsa/ecdsa.go deleted file mode 100644 index d6135531b..000000000 --- a/src/pkg/crypto/ecdsa/ecdsa.go +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package ecdsa implements the Elliptic Curve Digital Signature Algorithm, as -// defined in FIPS 186-3. -package ecdsa - -// References: -// [NSA]: Suite B implementer's guide to FIPS 186-3, -// http://www.nsa.gov/ia/_files/ecdsa.pdf -// [SECG]: SECG, SEC1 -// http://www.secg.org/download/aid-780/sec1-v2.pdf - -import ( - "crypto" - "crypto/elliptic" - "encoding/asn1" - "io" - "math/big" -) - -// PublicKey represents an ECDSA public key. -type PublicKey struct { - elliptic.Curve - X, Y *big.Int -} - -// PrivateKey represents a ECDSA private key. -type PrivateKey struct { - PublicKey - D *big.Int -} - -type ecdsaSignature struct { - R, S *big.Int -} - -// Public returns the public key corresponding to priv. -func (priv *PrivateKey) Public() crypto.PublicKey { - return &priv.PublicKey -} - -// Sign signs msg with priv, reading randomness from rand. This method is -// intended to support keys where the private part is kept in, for example, a -// hardware module. Common uses should use the Sign function in this package -// directly. -func (priv *PrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error) { - r, s, err := Sign(rand, priv, msg) - if err != nil { - return nil, err - } - - return asn1.Marshal(ecdsaSignature{r, s}) -} - -var one = new(big.Int).SetInt64(1) - -// randFieldElement returns a random element of the field underlying the given -// curve using the procedure given in [NSA] A.2.1. -func randFieldElement(c elliptic.Curve, rand io.Reader) (k *big.Int, err error) { - params := c.Params() - b := make([]byte, params.BitSize/8+8) - _, err = io.ReadFull(rand, b) - if err != nil { - return - } - - k = new(big.Int).SetBytes(b) - n := new(big.Int).Sub(params.N, one) - k.Mod(k, n) - k.Add(k, one) - return -} - -// GenerateKey generates a public and private key pair. -func GenerateKey(c elliptic.Curve, rand io.Reader) (priv *PrivateKey, err error) { - k, err := randFieldElement(c, rand) - if err != nil { - return - } - - priv = new(PrivateKey) - priv.PublicKey.Curve = c - priv.D = k - priv.PublicKey.X, priv.PublicKey.Y = c.ScalarBaseMult(k.Bytes()) - return -} - -// hashToInt converts a hash value to an integer. There is some disagreement -// about how this is done. [NSA] suggests that this is done in the obvious -// manner, but [SECG] truncates the hash to the bit-length of the curve order -// first. We follow [SECG] because that's what OpenSSL does. Additionally, -// OpenSSL right shifts excess bits from the number if the hash is too large -// and we mirror that too. -func hashToInt(hash []byte, c elliptic.Curve) *big.Int { - orderBits := c.Params().N.BitLen() - orderBytes := (orderBits + 7) / 8 - if len(hash) > orderBytes { - hash = hash[:orderBytes] - } - - ret := new(big.Int).SetBytes(hash) - excess := len(hash)*8 - orderBits - if excess > 0 { - ret.Rsh(ret, uint(excess)) - } - return ret -} - -// fermatInverse calculates the inverse of k in GF(P) using Fermat's method. -// This has better constant-time properties than Euclid's method (implemented -// in math/big.Int.ModInverse) although math/big itself isn't strictly -// constant-time so it's not perfect. -func fermatInverse(k, N *big.Int) *big.Int { - two := big.NewInt(2) - nMinus2 := new(big.Int).Sub(N, two) - return new(big.Int).Exp(k, nMinus2, N) -} - -// Sign signs an arbitrary length hash (which should be the result of hashing a -// larger message) using the private key, priv. It returns the signature as a -// pair of integers. The security of the private key depends on the entropy of -// rand. -func Sign(rand io.Reader, priv *PrivateKey, hash []byte) (r, s *big.Int, err error) { - // See [NSA] 3.4.1 - c := priv.PublicKey.Curve - N := c.Params().N - - var k, kInv *big.Int - for { - for { - k, err = randFieldElement(c, rand) - if err != nil { - r = nil - return - } - - kInv = fermatInverse(k, N) - r, _ = priv.Curve.ScalarBaseMult(k.Bytes()) - r.Mod(r, N) - if r.Sign() != 0 { - break - } - } - - e := hashToInt(hash, c) - s = new(big.Int).Mul(priv.D, r) - s.Add(s, e) - s.Mul(s, kInv) - s.Mod(s, N) - if s.Sign() != 0 { - break - } - } - - return -} - -// Verify verifies the signature in r, s of hash using the public key, pub. Its -// return value records whether the signature is valid. -func Verify(pub *PublicKey, hash []byte, r, s *big.Int) bool { - // See [NSA] 3.4.2 - c := pub.Curve - N := c.Params().N - - if r.Sign() == 0 || s.Sign() == 0 { - return false - } - if r.Cmp(N) >= 0 || s.Cmp(N) >= 0 { - return false - } - e := hashToInt(hash, c) - w := new(big.Int).ModInverse(s, N) - - u1 := e.Mul(e, w) - u1.Mod(u1, N) - u2 := w.Mul(r, w) - u2.Mod(u2, N) - - x1, y1 := c.ScalarBaseMult(u1.Bytes()) - x2, y2 := c.ScalarMult(pub.X, pub.Y, u2.Bytes()) - x, y := c.Add(x1, y1, x2, y2) - if x.Sign() == 0 && y.Sign() == 0 { - return false - } - x.Mod(x, N) - return x.Cmp(r) == 0 -} diff --git a/src/pkg/crypto/ecdsa/ecdsa_test.go b/src/pkg/crypto/ecdsa/ecdsa_test.go deleted file mode 100644 index 0c0643193..000000000 --- a/src/pkg/crypto/ecdsa/ecdsa_test.go +++ /dev/null @@ -1,191 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ecdsa - -import ( - "bufio" - "compress/bzip2" - "crypto/elliptic" - "crypto/rand" - "crypto/sha1" - "crypto/sha256" - "crypto/sha512" - "encoding/hex" - "hash" - "io" - "math/big" - "os" - "strings" - "testing" -) - -func testKeyGeneration(t *testing.T, c elliptic.Curve, tag string) { - priv, err := GenerateKey(c, rand.Reader) - if err != nil { - t.Errorf("%s: error: %s", tag, err) - return - } - if !c.IsOnCurve(priv.PublicKey.X, priv.PublicKey.Y) { - t.Errorf("%s: public key invalid: %s", tag, err) - } -} - -func TestKeyGeneration(t *testing.T) { - testKeyGeneration(t, elliptic.P224(), "p224") - if testing.Short() { - return - } - testKeyGeneration(t, elliptic.P256(), "p256") - testKeyGeneration(t, elliptic.P384(), "p384") - testKeyGeneration(t, elliptic.P521(), "p521") -} - -func testSignAndVerify(t *testing.T, c elliptic.Curve, tag string) { - priv, _ := GenerateKey(c, rand.Reader) - - hashed := []byte("testing") - r, s, err := Sign(rand.Reader, priv, hashed) - if err != nil { - t.Errorf("%s: error signing: %s", tag, err) - return - } - - if !Verify(&priv.PublicKey, hashed, r, s) { - t.Errorf("%s: Verify failed", tag) - } - - hashed[0] ^= 0xff - if Verify(&priv.PublicKey, hashed, r, s) { - t.Errorf("%s: Verify always works!", tag) - } -} - -func TestSignAndVerify(t *testing.T) { - testSignAndVerify(t, elliptic.P224(), "p224") - if testing.Short() { - return - } - testSignAndVerify(t, elliptic.P256(), "p256") - testSignAndVerify(t, elliptic.P384(), "p384") - testSignAndVerify(t, elliptic.P521(), "p521") -} - -func fromHex(s string) *big.Int { - r, ok := new(big.Int).SetString(s, 16) - if !ok { - panic("bad hex") - } - return r -} - -func TestVectors(t *testing.T) { - // This test runs the full set of NIST test vectors from - // http://csrc.nist.gov/groups/STM/cavp/documents/dss/186-3ecdsatestvectors.zip - // - // The SigVer.rsp file has been edited to remove test vectors for - // unsupported algorithms and has been compressed. - - if testing.Short() { - return - } - - f, err := os.Open("testdata/SigVer.rsp.bz2") - if err != nil { - t.Fatal(err) - } - - buf := bufio.NewReader(bzip2.NewReader(f)) - - lineNo := 1 - var h hash.Hash - var msg []byte - var hashed []byte - var r, s *big.Int - pub := new(PublicKey) - - for { - line, err := buf.ReadString('\n') - if len(line) == 0 { - if err == io.EOF { - break - } - t.Fatalf("error reading from input: %s", err) - } - lineNo++ - // Need to remove \r\n from the end of the line. - if !strings.HasSuffix(line, "\r\n") { - t.Fatalf("bad line ending (expected \\r\\n) on line %d", lineNo) - } - line = line[:len(line)-2] - - if len(line) == 0 || line[0] == '#' { - continue - } - - if line[0] == '[' { - line = line[1 : len(line)-1] - parts := strings.SplitN(line, ",", 2) - - switch parts[0] { - case "P-224": - pub.Curve = elliptic.P224() - case "P-256": - pub.Curve = elliptic.P256() - case "P-384": - pub.Curve = elliptic.P384() - case "P-521": - pub.Curve = elliptic.P521() - default: - pub.Curve = nil - } - - switch parts[1] { - case "SHA-1": - h = sha1.New() - case "SHA-224": - h = sha256.New224() - case "SHA-256": - h = sha256.New() - case "SHA-384": - h = sha512.New384() - case "SHA-512": - h = sha512.New() - default: - h = nil - } - - continue - } - - if h == nil || pub.Curve == nil { - continue - } - - switch { - case strings.HasPrefix(line, "Msg = "): - if msg, err = hex.DecodeString(line[6:]); err != nil { - t.Fatalf("failed to decode message on line %d: %s", lineNo, err) - } - case strings.HasPrefix(line, "Qx = "): - pub.X = fromHex(line[5:]) - case strings.HasPrefix(line, "Qy = "): - pub.Y = fromHex(line[5:]) - case strings.HasPrefix(line, "R = "): - r = fromHex(line[4:]) - case strings.HasPrefix(line, "S = "): - s = fromHex(line[4:]) - case strings.HasPrefix(line, "Result = "): - expected := line[9] == 'P' - h.Reset() - h.Write(msg) - hashed := h.Sum(hashed[:0]) - if Verify(pub, hashed, r, s) != expected { - t.Fatalf("incorrect result on line %d", lineNo) - } - default: - t.Fatalf("unknown variable on line %d: %s", lineNo, line) - } - } -} diff --git a/src/pkg/crypto/ecdsa/testdata/SigVer.rsp.bz2 b/src/pkg/crypto/ecdsa/testdata/SigVer.rsp.bz2 deleted file mode 100644 index 09fe2b427..000000000 Binary files a/src/pkg/crypto/ecdsa/testdata/SigVer.rsp.bz2 and /dev/null differ diff --git a/src/pkg/crypto/elliptic/elliptic.go b/src/pkg/crypto/elliptic/elliptic.go deleted file mode 100644 index ba673f80c..000000000 --- a/src/pkg/crypto/elliptic/elliptic.go +++ /dev/null @@ -1,373 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package elliptic implements several standard elliptic curves over prime -// fields. -package elliptic - -// This package operates, internally, on Jacobian coordinates. For a given -// (x, y) position on the curve, the Jacobian coordinates are (x1, y1, z1) -// where x = x1/z1² and y = y1/z1³. The greatest speedups come when the whole -// calculation can be performed within the transform (as in ScalarMult and -// ScalarBaseMult). But even for Add and Double, it's faster to apply and -// reverse the transform than to operate in affine coordinates. - -import ( - "io" - "math/big" - "sync" -) - -// A Curve represents a short-form Weierstrass curve with a=-3. -// See http://www.hyperelliptic.org/EFD/g1p/auto-shortw.html -type Curve interface { - // Params returns the parameters for the curve. - Params() *CurveParams - // IsOnCurve returns true if the given (x,y) lies on the curve. - IsOnCurve(x, y *big.Int) bool - // Add returns the sum of (x1,y1) and (x2,y2) - Add(x1, y1, x2, y2 *big.Int) (x, y *big.Int) - // Double returns 2*(x,y) - Double(x1, y1 *big.Int) (x, y *big.Int) - // ScalarMult returns k*(Bx,By) where k is a number in big-endian form. - ScalarMult(x1, y1 *big.Int, k []byte) (x, y *big.Int) - // ScalarBaseMult returns k*G, where G is the base point of the group - // and k is an integer in big-endian form. - ScalarBaseMult(k []byte) (x, y *big.Int) -} - -// CurveParams contains the parameters of an elliptic curve and also provides -// a generic, non-constant time implementation of Curve. -type CurveParams struct { - P *big.Int // the order of the underlying field - N *big.Int // the order of the base point - B *big.Int // the constant of the curve equation - Gx, Gy *big.Int // (x,y) of the base point - BitSize int // the size of the underlying field -} - -func (curve *CurveParams) Params() *CurveParams { - return curve -} - -func (curve *CurveParams) IsOnCurve(x, y *big.Int) bool { - // y² = x³ - 3x + b - y2 := new(big.Int).Mul(y, y) - y2.Mod(y2, curve.P) - - x3 := new(big.Int).Mul(x, x) - x3.Mul(x3, x) - - threeX := new(big.Int).Lsh(x, 1) - threeX.Add(threeX, x) - - x3.Sub(x3, threeX) - x3.Add(x3, curve.B) - x3.Mod(x3, curve.P) - - return x3.Cmp(y2) == 0 -} - -// zForAffine returns a Jacobian Z value for the affine point (x, y). If x and -// y are zero, it assumes that they represent the point at infinity because (0, -// 0) is not on the any of the curves handled here. -func zForAffine(x, y *big.Int) *big.Int { - z := new(big.Int) - if x.Sign() != 0 || y.Sign() != 0 { - z.SetInt64(1) - } - return z -} - -// affineFromJacobian reverses the Jacobian transform. See the comment at the -// top of the file. If the point is ∞ it returns 0, 0. -func (curve *CurveParams) affineFromJacobian(x, y, z *big.Int) (xOut, yOut *big.Int) { - if z.Sign() == 0 { - return new(big.Int), new(big.Int) - } - - zinv := new(big.Int).ModInverse(z, curve.P) - zinvsq := new(big.Int).Mul(zinv, zinv) - - xOut = new(big.Int).Mul(x, zinvsq) - xOut.Mod(xOut, curve.P) - zinvsq.Mul(zinvsq, zinv) - yOut = new(big.Int).Mul(y, zinvsq) - yOut.Mod(yOut, curve.P) - return -} - -func (curve *CurveParams) Add(x1, y1, x2, y2 *big.Int) (*big.Int, *big.Int) { - z1 := zForAffine(x1, y1) - z2 := zForAffine(x2, y2) - return curve.affineFromJacobian(curve.addJacobian(x1, y1, z1, x2, y2, z2)) -} - -// addJacobian takes two points in Jacobian coordinates, (x1, y1, z1) and -// (x2, y2, z2) and returns their sum, also in Jacobian form. -func (curve *CurveParams) addJacobian(x1, y1, z1, x2, y2, z2 *big.Int) (*big.Int, *big.Int, *big.Int) { - // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#addition-add-2007-bl - x3, y3, z3 := new(big.Int), new(big.Int), new(big.Int) - if z1.Sign() == 0 { - x3.Set(x2) - y3.Set(y2) - z3.Set(z2) - return x3, y3, z3 - } - if z2.Sign() == 0 { - x3.Set(x1) - y3.Set(y1) - z3.Set(z1) - return x3, y3, z3 - } - - z1z1 := new(big.Int).Mul(z1, z1) - z1z1.Mod(z1z1, curve.P) - z2z2 := new(big.Int).Mul(z2, z2) - z2z2.Mod(z2z2, curve.P) - - u1 := new(big.Int).Mul(x1, z2z2) - u1.Mod(u1, curve.P) - u2 := new(big.Int).Mul(x2, z1z1) - u2.Mod(u2, curve.P) - h := new(big.Int).Sub(u2, u1) - xEqual := h.Sign() == 0 - if h.Sign() == -1 { - h.Add(h, curve.P) - } - i := new(big.Int).Lsh(h, 1) - i.Mul(i, i) - j := new(big.Int).Mul(h, i) - - s1 := new(big.Int).Mul(y1, z2) - s1.Mul(s1, z2z2) - s1.Mod(s1, curve.P) - s2 := new(big.Int).Mul(y2, z1) - s2.Mul(s2, z1z1) - s2.Mod(s2, curve.P) - r := new(big.Int).Sub(s2, s1) - if r.Sign() == -1 { - r.Add(r, curve.P) - } - yEqual := r.Sign() == 0 - if xEqual && yEqual { - return curve.doubleJacobian(x1, y1, z1) - } - r.Lsh(r, 1) - v := new(big.Int).Mul(u1, i) - - x3.Set(r) - x3.Mul(x3, x3) - x3.Sub(x3, j) - x3.Sub(x3, v) - x3.Sub(x3, v) - x3.Mod(x3, curve.P) - - y3.Set(r) - v.Sub(v, x3) - y3.Mul(y3, v) - s1.Mul(s1, j) - s1.Lsh(s1, 1) - y3.Sub(y3, s1) - y3.Mod(y3, curve.P) - - z3.Add(z1, z2) - z3.Mul(z3, z3) - z3.Sub(z3, z1z1) - z3.Sub(z3, z2z2) - z3.Mul(z3, h) - z3.Mod(z3, curve.P) - - return x3, y3, z3 -} - -func (curve *CurveParams) Double(x1, y1 *big.Int) (*big.Int, *big.Int) { - z1 := zForAffine(x1, y1) - return curve.affineFromJacobian(curve.doubleJacobian(x1, y1, z1)) -} - -// doubleJacobian takes a point in Jacobian coordinates, (x, y, z), and -// returns its double, also in Jacobian form. -func (curve *CurveParams) doubleJacobian(x, y, z *big.Int) (*big.Int, *big.Int, *big.Int) { - // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b - delta := new(big.Int).Mul(z, z) - delta.Mod(delta, curve.P) - gamma := new(big.Int).Mul(y, y) - gamma.Mod(gamma, curve.P) - alpha := new(big.Int).Sub(x, delta) - if alpha.Sign() == -1 { - alpha.Add(alpha, curve.P) - } - alpha2 := new(big.Int).Add(x, delta) - alpha.Mul(alpha, alpha2) - alpha2.Set(alpha) - alpha.Lsh(alpha, 1) - alpha.Add(alpha, alpha2) - - beta := alpha2.Mul(x, gamma) - - x3 := new(big.Int).Mul(alpha, alpha) - beta8 := new(big.Int).Lsh(beta, 3) - x3.Sub(x3, beta8) - for x3.Sign() == -1 { - x3.Add(x3, curve.P) - } - x3.Mod(x3, curve.P) - - z3 := new(big.Int).Add(y, z) - z3.Mul(z3, z3) - z3.Sub(z3, gamma) - if z3.Sign() == -1 { - z3.Add(z3, curve.P) - } - z3.Sub(z3, delta) - if z3.Sign() == -1 { - z3.Add(z3, curve.P) - } - z3.Mod(z3, curve.P) - - beta.Lsh(beta, 2) - beta.Sub(beta, x3) - if beta.Sign() == -1 { - beta.Add(beta, curve.P) - } - y3 := alpha.Mul(alpha, beta) - - gamma.Mul(gamma, gamma) - gamma.Lsh(gamma, 3) - gamma.Mod(gamma, curve.P) - - y3.Sub(y3, gamma) - if y3.Sign() == -1 { - y3.Add(y3, curve.P) - } - y3.Mod(y3, curve.P) - - return x3, y3, z3 -} - -func (curve *CurveParams) ScalarMult(Bx, By *big.Int, k []byte) (*big.Int, *big.Int) { - Bz := new(big.Int).SetInt64(1) - x, y, z := new(big.Int), new(big.Int), new(big.Int) - - for _, byte := range k { - for bitNum := 0; bitNum < 8; bitNum++ { - x, y, z = curve.doubleJacobian(x, y, z) - if byte&0x80 == 0x80 { - x, y, z = curve.addJacobian(Bx, By, Bz, x, y, z) - } - byte <<= 1 - } - } - - return curve.affineFromJacobian(x, y, z) -} - -func (curve *CurveParams) ScalarBaseMult(k []byte) (*big.Int, *big.Int) { - return curve.ScalarMult(curve.Gx, curve.Gy, k) -} - -var mask = []byte{0xff, 0x1, 0x3, 0x7, 0xf, 0x1f, 0x3f, 0x7f} - -// GenerateKey returns a public/private key pair. The private key is -// generated using the given reader, which must return random data. -func GenerateKey(curve Curve, rand io.Reader) (priv []byte, x, y *big.Int, err error) { - bitSize := curve.Params().BitSize - byteLen := (bitSize + 7) >> 3 - priv = make([]byte, byteLen) - - for x == nil { - _, err = io.ReadFull(rand, priv) - if err != nil { - return - } - // We have to mask off any excess bits in the case that the size of the - // underlying field is not a whole number of bytes. - priv[0] &= mask[bitSize%8] - // This is because, in tests, rand will return all zeros and we don't - // want to get the point at infinity and loop forever. - priv[1] ^= 0x42 - x, y = curve.ScalarBaseMult(priv) - } - return -} - -// Marshal converts a point into the form specified in section 4.3.6 of ANSI X9.62. -func Marshal(curve Curve, x, y *big.Int) []byte { - byteLen := (curve.Params().BitSize + 7) >> 3 - - ret := make([]byte, 1+2*byteLen) - ret[0] = 4 // uncompressed point - - xBytes := x.Bytes() - copy(ret[1+byteLen-len(xBytes):], xBytes) - yBytes := y.Bytes() - copy(ret[1+2*byteLen-len(yBytes):], yBytes) - return ret -} - -// Unmarshal converts a point, serialized by Marshal, into an x, y pair. On error, x = nil. -func Unmarshal(curve Curve, data []byte) (x, y *big.Int) { - byteLen := (curve.Params().BitSize + 7) >> 3 - if len(data) != 1+2*byteLen { - return - } - if data[0] != 4 { // uncompressed form - return - } - x = new(big.Int).SetBytes(data[1 : 1+byteLen]) - y = new(big.Int).SetBytes(data[1+byteLen:]) - return -} - -var initonce sync.Once -var p384 *CurveParams -var p521 *CurveParams - -func initAll() { - initP224() - initP256() - initP384() - initP521() -} - -func initP384() { - // See FIPS 186-3, section D.2.4 - p384 = new(CurveParams) - p384.P, _ = new(big.Int).SetString("39402006196394479212279040100143613805079739270465446667948293404245721771496870329047266088258938001861606973112319", 10) - p384.N, _ = new(big.Int).SetString("39402006196394479212279040100143613805079739270465446667946905279627659399113263569398956308152294913554433653942643", 10) - p384.B, _ = new(big.Int).SetString("b3312fa7e23ee7e4988e056be3f82d19181d9c6efe8141120314088f5013875ac656398d8a2ed19d2a85c8edd3ec2aef", 16) - p384.Gx, _ = new(big.Int).SetString("aa87ca22be8b05378eb1c71ef320ad746e1d3b628ba79b9859f741e082542a385502f25dbf55296c3a545e3872760ab7", 16) - p384.Gy, _ = new(big.Int).SetString("3617de4a96262c6f5d9e98bf9292dc29f8f41dbd289a147ce9da3113b5f0b8c00a60b1ce1d7e819d7a431d7c90ea0e5f", 16) - p384.BitSize = 384 -} - -func initP521() { - // See FIPS 186-3, section D.2.5 - p521 = new(CurveParams) - p521.P, _ = new(big.Int).SetString("6864797660130609714981900799081393217269435300143305409394463459185543183397656052122559640661454554977296311391480858037121987999716643812574028291115057151", 10) - p521.N, _ = new(big.Int).SetString("6864797660130609714981900799081393217269435300143305409394463459185543183397655394245057746333217197532963996371363321113864768612440380340372808892707005449", 10) - p521.B, _ = new(big.Int).SetString("051953eb9618e1c9a1f929a21a0b68540eea2da725b99b315f3b8b489918ef109e156193951ec7e937b1652c0bd3bb1bf073573df883d2c34f1ef451fd46b503f00", 16) - p521.Gx, _ = new(big.Int).SetString("c6858e06b70404e9cd9e3ecb662395b4429c648139053fb521f828af606b4d3dbaa14b5e77efe75928fe1dc127a2ffa8de3348b3c1856a429bf97e7e31c2e5bd66", 16) - p521.Gy, _ = new(big.Int).SetString("11839296a789a3bc0045c8a5fb42c7d1bd998f54449579b446817afbd17273e662c97ee72995ef42640c550b9013fad0761353c7086a272c24088be94769fd16650", 16) - p521.BitSize = 521 -} - -// P256 returns a Curve which implements P-256 (see FIPS 186-3, section D.2.3) -func P256() Curve { - initonce.Do(initAll) - return p256 -} - -// P384 returns a Curve which implements P-384 (see FIPS 186-3, section D.2.4) -func P384() Curve { - initonce.Do(initAll) - return p384 -} - -// P521 returns a Curve which implements P-521 (see FIPS 186-3, section D.2.5) -func P521() Curve { - initonce.Do(initAll) - return p521 -} diff --git a/src/pkg/crypto/elliptic/elliptic_test.go b/src/pkg/crypto/elliptic/elliptic_test.go deleted file mode 100644 index 4dc27c92b..000000000 --- a/src/pkg/crypto/elliptic/elliptic_test.go +++ /dev/null @@ -1,458 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package elliptic - -import ( - "crypto/rand" - "encoding/hex" - "fmt" - "math/big" - "testing" -) - -func TestOnCurve(t *testing.T) { - p224 := P224() - if !p224.IsOnCurve(p224.Params().Gx, p224.Params().Gy) { - t.Errorf("FAIL") - } -} - -type baseMultTest struct { - k string - x, y string -} - -var p224BaseMultTests = []baseMultTest{ - { - "1", - "b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21", - "bd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34", - }, - { - "2", - "706a46dc76dcb76798e60e6d89474788d16dc18032d268fd1a704fa6", - "1c2b76a7bc25e7702a704fa986892849fca629487acf3709d2e4e8bb", - }, - { - "3", - "df1b1d66a551d0d31eff822558b9d2cc75c2180279fe0d08fd896d04", - "a3f7f03cadd0be444c0aa56830130ddf77d317344e1af3591981a925", - }, - { - "4", - "ae99feebb5d26945b54892092a8aee02912930fa41cd114e40447301", - "482580a0ec5bc47e88bc8c378632cd196cb3fa058a7114eb03054c9", - }, - { - "5", - "31c49ae75bce7807cdff22055d94ee9021fedbb5ab51c57526f011aa", - "27e8bff1745635ec5ba0c9f1c2ede15414c6507d29ffe37e790a079b", - }, - { - "6", - "1f2483f82572251fca975fea40db821df8ad82a3c002ee6c57112408", - "89faf0ccb750d99b553c574fad7ecfb0438586eb3952af5b4b153c7e", - }, - { - "7", - "db2f6be630e246a5cf7d99b85194b123d487e2d466b94b24a03c3e28", - "f3a30085497f2f611ee2517b163ef8c53b715d18bb4e4808d02b963", - }, - { - "8", - "858e6f9cc6c12c31f5df124aa77767b05c8bc021bd683d2b55571550", - "46dcd3ea5c43898c5c5fc4fdac7db39c2f02ebee4e3541d1e78047a", - }, - { - "9", - "2fdcccfee720a77ef6cb3bfbb447f9383117e3daa4a07e36ed15f78d", - "371732e4f41bf4f7883035e6a79fcedc0e196eb07b48171697517463", - }, - { - "10", - "aea9e17a306517eb89152aa7096d2c381ec813c51aa880e7bee2c0fd", - "39bb30eab337e0a521b6cba1abe4b2b3a3e524c14a3fe3eb116b655f", - }, - { - "11", - "ef53b6294aca431f0f3c22dc82eb9050324f1d88d377e716448e507c", - "20b510004092e96636cfb7e32efded8265c266dfb754fa6d6491a6da", - }, - { - "12", - "6e31ee1dc137f81b056752e4deab1443a481033e9b4c93a3044f4f7a", - "207dddf0385bfdeab6e9acda8da06b3bbef224a93ab1e9e036109d13", - }, - { - "13", - "34e8e17a430e43289793c383fac9774247b40e9ebd3366981fcfaeca", - "252819f71c7fb7fbcb159be337d37d3336d7feb963724fdfb0ecb767", - }, - { - "14", - "a53640c83dc208603ded83e4ecf758f24c357d7cf48088b2ce01e9fa", - "d5814cd724199c4a5b974a43685fbf5b8bac69459c9469bc8f23ccaf", - }, - { - "15", - "baa4d8635511a7d288aebeedd12ce529ff102c91f97f867e21916bf9", - "979a5f4759f80f4fb4ec2e34f5566d595680a11735e7b61046127989", - }, - { - "16", - "b6ec4fe1777382404ef679997ba8d1cc5cd8e85349259f590c4c66d", - "3399d464345906b11b00e363ef429221f2ec720d2f665d7dead5b482", - }, - { - "17", - "b8357c3a6ceef288310e17b8bfeff9200846ca8c1942497c484403bc", - "ff149efa6606a6bd20ef7d1b06bd92f6904639dce5174db6cc554a26", - }, - { - "18", - "c9ff61b040874c0568479216824a15eab1a838a797d189746226e4cc", - "ea98d60e5ffc9b8fcf999fab1df7e7ef7084f20ddb61bb045a6ce002", - }, - { - "19", - "a1e81c04f30ce201c7c9ace785ed44cc33b455a022f2acdbc6cae83c", - "dcf1f6c3db09c70acc25391d492fe25b4a180babd6cea356c04719cd", - }, - { - "20", - "fcc7f2b45df1cd5a3c0c0731ca47a8af75cfb0347e8354eefe782455", - "d5d7110274cba7cdee90e1a8b0d394c376a5573db6be0bf2747f530", - }, - { - "112233445566778899", - "61f077c6f62ed802dad7c2f38f5c67f2cc453601e61bd076bb46179e", - "2272f9e9f5933e70388ee652513443b5e289dd135dcc0d0299b225e4", - }, - { - "112233445566778899112233445566778899", - "29895f0af496bfc62b6ef8d8a65c88c613949b03668aab4f0429e35", - "3ea6e53f9a841f2019ec24bde1a75677aa9b5902e61081c01064de93", - }, - { - "6950511619965839450988900688150712778015737983940691968051900319680", - "ab689930bcae4a4aa5f5cb085e823e8ae30fd365eb1da4aba9cf0379", - "3345a121bbd233548af0d210654eb40bab788a03666419be6fbd34e7", - }, - { - "13479972933410060327035789020509431695094902435494295338570602119423", - "bdb6a8817c1f89da1c2f3dd8e97feb4494f2ed302a4ce2bc7f5f4025", - "4c7020d57c00411889462d77a5438bb4e97d177700bf7243a07f1680", - }, - { - "13479971751745682581351455311314208093898607229429740618390390702079", - "d58b61aa41c32dd5eba462647dba75c5d67c83606c0af2bd928446a9", - "d24ba6a837be0460dd107ae77725696d211446c5609b4595976b16bd", - }, - { - "13479972931865328106486971546324465392952975980343228160962702868479", - "dc9fa77978a005510980e929a1485f63716df695d7a0c18bb518df03", - "ede2b016f2ddffc2a8c015b134928275ce09e5661b7ab14ce0d1d403", - }, - { - "11795773708834916026404142434151065506931607341523388140225443265536", - "499d8b2829cfb879c901f7d85d357045edab55028824d0f05ba279ba", - "bf929537b06e4015919639d94f57838fa33fc3d952598dcdbb44d638", - }, - { - "784254593043826236572847595991346435467177662189391577090", - "8246c999137186632c5f9eddf3b1b0e1764c5e8bd0e0d8a554b9cb77", - "e80ed8660bc1cb17ac7d845be40a7a022d3306f116ae9f81fea65947", - }, - { - "13479767645505654746623887797783387853576174193480695826442858012671", - "6670c20afcceaea672c97f75e2e9dd5c8460e54bb38538ebb4bd30eb", - "f280d8008d07a4caf54271f993527d46ff3ff46fd1190a3f1faa4f74", - }, - { - "205688069665150753842126177372015544874550518966168735589597183", - "eca934247425cfd949b795cb5ce1eff401550386e28d1a4c5a8eb", - "d4c01040dba19628931bc8855370317c722cbd9ca6156985f1c2e9ce", - }, - { - "13479966930919337728895168462090683249159702977113823384618282123295", - "ef353bf5c73cd551b96d596fbc9a67f16d61dd9fe56af19de1fba9cd", - "21771b9cdce3e8430c09b3838be70b48c21e15bc09ee1f2d7945b91f", - }, - { - "50210731791415612487756441341851895584393717453129007497216", - "4036052a3091eb481046ad3289c95d3ac905ca0023de2c03ecd451cf", - "d768165a38a2b96f812586a9d59d4136035d9c853a5bf2e1c86a4993", - }, - { - "26959946667150639794667015087019625940457807714424391721682722368041", - "fcc7f2b45df1cd5a3c0c0731ca47a8af75cfb0347e8354eefe782455", - "f2a28eefd8b345832116f1e574f2c6b2c895aa8c24941f40d8b80ad1", - }, - { - "26959946667150639794667015087019625940457807714424391721682722368042", - "a1e81c04f30ce201c7c9ace785ed44cc33b455a022f2acdbc6cae83c", - "230e093c24f638f533dac6e2b6d01da3b5e7f45429315ca93fb8e634", - }, - { - "26959946667150639794667015087019625940457807714424391721682722368043", - "c9ff61b040874c0568479216824a15eab1a838a797d189746226e4cc", - "156729f1a003647030666054e208180f8f7b0df2249e44fba5931fff", - }, - { - "26959946667150639794667015087019625940457807714424391721682722368044", - "b8357c3a6ceef288310e17b8bfeff9200846ca8c1942497c484403bc", - "eb610599f95942df1082e4f9426d086fb9c6231ae8b24933aab5db", - }, - { - "26959946667150639794667015087019625940457807714424391721682722368045", - "b6ec4fe1777382404ef679997ba8d1cc5cd8e85349259f590c4c66d", - "cc662b9bcba6f94ee4ff1c9c10bd6ddd0d138df2d099a282152a4b7f", - }, - { - "26959946667150639794667015087019625940457807714424391721682722368046", - "baa4d8635511a7d288aebeedd12ce529ff102c91f97f867e21916bf9", - "6865a0b8a607f0b04b13d1cb0aa992a5a97f5ee8ca1849efb9ed8678", - }, - { - "26959946667150639794667015087019625940457807714424391721682722368047", - "a53640c83dc208603ded83e4ecf758f24c357d7cf48088b2ce01e9fa", - "2a7eb328dbe663b5a468b5bc97a040a3745396ba636b964370dc3352", - }, - { - "26959946667150639794667015087019625940457807714424391721682722368048", - "34e8e17a430e43289793c383fac9774247b40e9ebd3366981fcfaeca", - "dad7e608e380480434ea641cc82c82cbc92801469c8db0204f13489a", - }, - { - "26959946667150639794667015087019625940457807714424391721682722368049", - "6e31ee1dc137f81b056752e4deab1443a481033e9b4c93a3044f4f7a", - "df82220fc7a4021549165325725f94c3410ddb56c54e161fc9ef62ee", - }, - { - "26959946667150639794667015087019625940457807714424391721682722368050", - "ef53b6294aca431f0f3c22dc82eb9050324f1d88d377e716448e507c", - "df4aefffbf6d1699c930481cd102127c9a3d992048ab05929b6e5927", - }, - { - "26959946667150639794667015087019625940457807714424391721682722368051", - "aea9e17a306517eb89152aa7096d2c381ec813c51aa880e7bee2c0fd", - "c644cf154cc81f5ade49345e541b4d4b5c1adb3eb5c01c14ee949aa2", - }, - { - "26959946667150639794667015087019625940457807714424391721682722368052", - "2fdcccfee720a77ef6cb3bfbb447f9383117e3daa4a07e36ed15f78d", - "c8e8cd1b0be40b0877cfca1958603122f1e6914f84b7e8e968ae8b9e", - }, - { - "26959946667150639794667015087019625940457807714424391721682722368053", - "858e6f9cc6c12c31f5df124aa77767b05c8bc021bd683d2b55571550", - "fb9232c15a3bc7673a3a03b0253824c53d0fd1411b1cabe2e187fb87", - }, - { - "26959946667150639794667015087019625940457807714424391721682722368054", - "db2f6be630e246a5cf7d99b85194b123d487e2d466b94b24a03c3e28", - "f0c5cff7ab680d09ee11dae84e9c1072ac48ea2e744b1b7f72fd469e", - }, - { - "26959946667150639794667015087019625940457807714424391721682722368055", - "1f2483f82572251fca975fea40db821df8ad82a3c002ee6c57112408", - "76050f3348af2664aac3a8b05281304ebc7a7914c6ad50a4b4eac383", - }, - { - "26959946667150639794667015087019625940457807714424391721682722368056", - "31c49ae75bce7807cdff22055d94ee9021fedbb5ab51c57526f011aa", - "d817400e8ba9ca13a45f360e3d121eaaeb39af82d6001c8186f5f866", - }, - { - "26959946667150639794667015087019625940457807714424391721682722368057", - "ae99feebb5d26945b54892092a8aee02912930fa41cd114e40447301", - "fb7da7f5f13a43b81774373c879cd32d6934c05fa758eeb14fcfab38", - }, - { - "26959946667150639794667015087019625940457807714424391721682722368058", - "df1b1d66a551d0d31eff822558b9d2cc75c2180279fe0d08fd896d04", - "5c080fc3522f41bbb3f55a97cfecf21f882ce8cbb1e50ca6e67e56dc", - }, - { - "26959946667150639794667015087019625940457807714424391721682722368059", - "706a46dc76dcb76798e60e6d89474788d16dc18032d268fd1a704fa6", - "e3d4895843da188fd58fb0567976d7b50359d6b78530c8f62d1b1746", - }, - { - "26959946667150639794667015087019625940457807714424391721682722368060", - "b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21", - "42c89c774a08dc04b3dd201932bc8a5ea5f8b89bbb2a7e667aff81cd", - }, -} - -func TestBaseMult(t *testing.T) { - p224 := P224() - for i, e := range p224BaseMultTests { - k, ok := new(big.Int).SetString(e.k, 10) - if !ok { - t.Errorf("%d: bad value for k: %s", i, e.k) - } - x, y := p224.ScalarBaseMult(k.Bytes()) - if fmt.Sprintf("%x", x) != e.x || fmt.Sprintf("%x", y) != e.y { - t.Errorf("%d: bad output for k=%s: got (%x, %x), want (%s, %s)", i, e.k, x, y, e.x, e.y) - } - if testing.Short() && i > 5 { - break - } - } -} - -func TestGenericBaseMult(t *testing.T) { - // We use the P224 CurveParams directly in order to test the generic implementation. - p224 := P224().Params() - for i, e := range p224BaseMultTests { - k, ok := new(big.Int).SetString(e.k, 10) - if !ok { - t.Errorf("%d: bad value for k: %s", i, e.k) - } - x, y := p224.ScalarBaseMult(k.Bytes()) - if fmt.Sprintf("%x", x) != e.x || fmt.Sprintf("%x", y) != e.y { - t.Errorf("%d: bad output for k=%s: got (%x, %x), want (%s, %s)", i, e.k, x, y, e.x, e.y) - } - if testing.Short() && i > 5 { - break - } - } -} - -func TestP256BaseMult(t *testing.T) { - p256 := P256() - p256Generic := p256.Params() - - scalars := make([]*big.Int, 0, len(p224BaseMultTests)+1) - for _, e := range p224BaseMultTests { - k, _ := new(big.Int).SetString(e.k, 10) - scalars = append(scalars, k) - } - k := new(big.Int).SetInt64(1) - k.Lsh(k, 500) - scalars = append(scalars, k) - - for i, k := range scalars { - x, y := p256.ScalarBaseMult(k.Bytes()) - x2, y2 := p256Generic.ScalarBaseMult(k.Bytes()) - if x.Cmp(x2) != 0 || y.Cmp(y2) != 0 { - t.Errorf("#%d: got (%x, %x), want (%x, %x)", i, x, y, x2, y2) - } - - if testing.Short() && i > 5 { - break - } - } -} - -func TestP256Mult(t *testing.T) { - p256 := P256() - p256Generic := p256.Params() - - for i, e := range p224BaseMultTests { - x, _ := new(big.Int).SetString(e.x, 16) - y, _ := new(big.Int).SetString(e.y, 16) - k, _ := new(big.Int).SetString(e.k, 10) - - xx, yy := p256.ScalarMult(x, y, k.Bytes()) - xx2, yy2 := p256Generic.ScalarMult(x, y, k.Bytes()) - if xx.Cmp(xx2) != 0 || yy.Cmp(yy2) != 0 { - t.Errorf("#%d: got (%x, %x), want (%x, %x)", i, xx, yy, xx2, yy2) - } - if testing.Short() && i > 5 { - break - } - } -} - -func TestInfinity(t *testing.T) { - tests := []struct { - name string - curve Curve - }{ - {"p224", P224()}, - {"p256", P256()}, - } - - for _, test := range tests { - curve := test.curve - x, y := curve.ScalarBaseMult(nil) - if x.Sign() != 0 || y.Sign() != 0 { - t.Errorf("%s: x^0 != ∞", test.name) - } - x.SetInt64(0) - y.SetInt64(0) - - x2, y2 := curve.Double(x, y) - if x2.Sign() != 0 || y2.Sign() != 0 { - t.Errorf("%s: 2∞ != ∞", test.name) - } - - baseX := curve.Params().Gx - baseY := curve.Params().Gy - - x3, y3 := curve.Add(baseX, baseY, x, y) - if x3.Cmp(baseX) != 0 || y3.Cmp(baseY) != 0 { - t.Errorf("%s: x+∞ != x", test.name) - } - - x4, y4 := curve.Add(x, y, baseX, baseY) - if x4.Cmp(baseX) != 0 || y4.Cmp(baseY) != 0 { - t.Errorf("%s: ∞+x != x", test.name) - } - } -} - -func BenchmarkBaseMult(b *testing.B) { - b.ResetTimer() - p224 := P224() - e := p224BaseMultTests[25] - k, _ := new(big.Int).SetString(e.k, 10) - b.StartTimer() - for i := 0; i < b.N; i++ { - p224.ScalarBaseMult(k.Bytes()) - } -} - -func BenchmarkBaseMultP256(b *testing.B) { - b.ResetTimer() - p256 := P256() - e := p224BaseMultTests[25] - k, _ := new(big.Int).SetString(e.k, 10) - b.StartTimer() - for i := 0; i < b.N; i++ { - p256.ScalarBaseMult(k.Bytes()) - } -} - -func TestMarshal(t *testing.T) { - p224 := P224() - _, x, y, err := GenerateKey(p224, rand.Reader) - if err != nil { - t.Error(err) - return - } - serialized := Marshal(p224, x, y) - xx, yy := Unmarshal(p224, serialized) - if xx == nil { - t.Error("failed to unmarshal") - return - } - if xx.Cmp(x) != 0 || yy.Cmp(y) != 0 { - t.Error("unmarshal returned different values") - return - } -} - -func TestP224Overflow(t *testing.T) { - // This tests for a specific bug in the P224 implementation. - p224 := P224() - pointData, _ := hex.DecodeString("049B535B45FB0A2072398A6831834624C7E32CCFD5A4B933BCEAF77F1DD945E08BBE5178F5EDF5E733388F196D2A631D2E075BB16CBFEEA15B") - x, y := Unmarshal(p224, pointData) - if !p224.IsOnCurve(x, y) { - t.Error("P224 failed to validate a correct point") - } -} diff --git a/src/pkg/crypto/elliptic/p224.go b/src/pkg/crypto/elliptic/p224.go deleted file mode 100644 index 1f7ff3f9d..000000000 --- a/src/pkg/crypto/elliptic/p224.go +++ /dev/null @@ -1,765 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package elliptic - -// This is a constant-time, 32-bit implementation of P224. See FIPS 186-3, -// section D.2.2. -// -// See http://www.imperialviolet.org/2010/12/04/ecc.html ([1]) for background. - -import ( - "math/big" -) - -var p224 p224Curve - -type p224Curve struct { - *CurveParams - gx, gy, b p224FieldElement -} - -func initP224() { - // See FIPS 186-3, section D.2.2 - p224.CurveParams = new(CurveParams) - p224.P, _ = new(big.Int).SetString("26959946667150639794667015087019630673557916260026308143510066298881", 10) - p224.N, _ = new(big.Int).SetString("26959946667150639794667015087019625940457807714424391721682722368061", 10) - p224.B, _ = new(big.Int).SetString("b4050a850c04b3abf54132565044b0b7d7bfd8ba270b39432355ffb4", 16) - p224.Gx, _ = new(big.Int).SetString("b70e0cbd6bb4bf7f321390b94a03c1d356c21122343280d6115c1d21", 16) - p224.Gy, _ = new(big.Int).SetString("bd376388b5f723fb4c22dfe6cd4375a05a07476444d5819985007e34", 16) - p224.BitSize = 224 - - p224FromBig(&p224.gx, p224.Gx) - p224FromBig(&p224.gy, p224.Gy) - p224FromBig(&p224.b, p224.B) -} - -// P224 returns a Curve which implements P-224 (see FIPS 186-3, section D.2.2) -func P224() Curve { - initonce.Do(initAll) - return p224 -} - -func (curve p224Curve) Params() *CurveParams { - return curve.CurveParams -} - -func (curve p224Curve) IsOnCurve(bigX, bigY *big.Int) bool { - var x, y p224FieldElement - p224FromBig(&x, bigX) - p224FromBig(&y, bigY) - - // y² = x³ - 3x + b - var tmp p224LargeFieldElement - var x3 p224FieldElement - p224Square(&x3, &x, &tmp) - p224Mul(&x3, &x3, &x, &tmp) - - for i := 0; i < 8; i++ { - x[i] *= 3 - } - p224Sub(&x3, &x3, &x) - p224Reduce(&x3) - p224Add(&x3, &x3, &curve.b) - p224Contract(&x3, &x3) - - p224Square(&y, &y, &tmp) - p224Contract(&y, &y) - - for i := 0; i < 8; i++ { - if y[i] != x3[i] { - return false - } - } - return true -} - -func (p224Curve) Add(bigX1, bigY1, bigX2, bigY2 *big.Int) (x, y *big.Int) { - var x1, y1, z1, x2, y2, z2, x3, y3, z3 p224FieldElement - - p224FromBig(&x1, bigX1) - p224FromBig(&y1, bigY1) - if bigX1.Sign() != 0 || bigY1.Sign() != 0 { - z1[0] = 1 - } - p224FromBig(&x2, bigX2) - p224FromBig(&y2, bigY2) - if bigX2.Sign() != 0 || bigY2.Sign() != 0 { - z2[0] = 1 - } - - p224AddJacobian(&x3, &y3, &z3, &x1, &y1, &z1, &x2, &y2, &z2) - return p224ToAffine(&x3, &y3, &z3) -} - -func (p224Curve) Double(bigX1, bigY1 *big.Int) (x, y *big.Int) { - var x1, y1, z1, x2, y2, z2 p224FieldElement - - p224FromBig(&x1, bigX1) - p224FromBig(&y1, bigY1) - z1[0] = 1 - - p224DoubleJacobian(&x2, &y2, &z2, &x1, &y1, &z1) - return p224ToAffine(&x2, &y2, &z2) -} - -func (p224Curve) ScalarMult(bigX1, bigY1 *big.Int, scalar []byte) (x, y *big.Int) { - var x1, y1, z1, x2, y2, z2 p224FieldElement - - p224FromBig(&x1, bigX1) - p224FromBig(&y1, bigY1) - z1[0] = 1 - - p224ScalarMult(&x2, &y2, &z2, &x1, &y1, &z1, scalar) - return p224ToAffine(&x2, &y2, &z2) -} - -func (curve p224Curve) ScalarBaseMult(scalar []byte) (x, y *big.Int) { - var z1, x2, y2, z2 p224FieldElement - - z1[0] = 1 - p224ScalarMult(&x2, &y2, &z2, &curve.gx, &curve.gy, &z1, scalar) - return p224ToAffine(&x2, &y2, &z2) -} - -// Field element functions. -// -// The field that we're dealing with is ℤ/pℤ where p = 2**224 - 2**96 + 1. -// -// Field elements are represented by a FieldElement, which is a typedef to an -// array of 8 uint32's. The value of a FieldElement, a, is: -// a[0] + 2**28·a[1] + 2**56·a[1] + ... + 2**196·a[7] -// -// Using 28-bit limbs means that there's only 4 bits of headroom, which is less -// than we would really like. But it has the useful feature that we hit 2**224 -// exactly, making the reflections during a reduce much nicer. -type p224FieldElement [8]uint32 - -// p224P is the order of the field, represented as a p224FieldElement. -var p224P = [8]uint32{1, 0, 0, 0xffff000, 0xfffffff, 0xfffffff, 0xfffffff, 0xfffffff} - -// p224IsZero returns 1 if a == 0 mod p and 0 otherwise. -// -// a[i] < 2**29 -func p224IsZero(a *p224FieldElement) uint32 { - // Since a p224FieldElement contains 224 bits there are two possible - // representations of 0: 0 and p. - var minimal p224FieldElement - p224Contract(&minimal, a) - - var isZero, isP uint32 - for i, v := range minimal { - isZero |= v - isP |= v - p224P[i] - } - - // If either isZero or isP is 0, then we should return 1. - isZero |= isZero >> 16 - isZero |= isZero >> 8 - isZero |= isZero >> 4 - isZero |= isZero >> 2 - isZero |= isZero >> 1 - - isP |= isP >> 16 - isP |= isP >> 8 - isP |= isP >> 4 - isP |= isP >> 2 - isP |= isP >> 1 - - // For isZero and isP, the LSB is 0 iff all the bits are zero. - result := isZero & isP - result = (^result) & 1 - - return result -} - -// p224Add computes *out = a+b -// -// a[i] + b[i] < 2**32 -func p224Add(out, a, b *p224FieldElement) { - for i := 0; i < 8; i++ { - out[i] = a[i] + b[i] - } -} - -const two31p3 = 1<<31 + 1<<3 -const two31m3 = 1<<31 - 1<<3 -const two31m15m3 = 1<<31 - 1<<15 - 1<<3 - -// p224ZeroModP31 is 0 mod p where bit 31 is set in all limbs so that we can -// subtract smaller amounts without underflow. See the section "Subtraction" in -// [1] for reasoning. -var p224ZeroModP31 = []uint32{two31p3, two31m3, two31m3, two31m15m3, two31m3, two31m3, two31m3, two31m3} - -// p224Sub computes *out = a-b -// -// a[i], b[i] < 2**30 -// out[i] < 2**32 -func p224Sub(out, a, b *p224FieldElement) { - for i := 0; i < 8; i++ { - out[i] = a[i] + p224ZeroModP31[i] - b[i] - } -} - -// LargeFieldElement also represents an element of the field. The limbs are -// still spaced 28-bits apart and in little-endian order. So the limbs are at -// 0, 28, 56, ..., 392 bits, each 64-bits wide. -type p224LargeFieldElement [15]uint64 - -const two63p35 = 1<<63 + 1<<35 -const two63m35 = 1<<63 - 1<<35 -const two63m35m19 = 1<<63 - 1<<35 - 1<<19 - -// p224ZeroModP63 is 0 mod p where bit 63 is set in all limbs. See the section -// "Subtraction" in [1] for why. -var p224ZeroModP63 = [8]uint64{two63p35, two63m35, two63m35, two63m35, two63m35m19, two63m35, two63m35, two63m35} - -const bottom12Bits = 0xfff -const bottom28Bits = 0xfffffff - -// p224Mul computes *out = a*b -// -// a[i] < 2**29, b[i] < 2**30 (or vice versa) -// out[i] < 2**29 -func p224Mul(out, a, b *p224FieldElement, tmp *p224LargeFieldElement) { - for i := 0; i < 15; i++ { - tmp[i] = 0 - } - - for i := 0; i < 8; i++ { - for j := 0; j < 8; j++ { - tmp[i+j] += uint64(a[i]) * uint64(b[j]) - } - } - - p224ReduceLarge(out, tmp) -} - -// Square computes *out = a*a -// -// a[i] < 2**29 -// out[i] < 2**29 -func p224Square(out, a *p224FieldElement, tmp *p224LargeFieldElement) { - for i := 0; i < 15; i++ { - tmp[i] = 0 - } - - for i := 0; i < 8; i++ { - for j := 0; j <= i; j++ { - r := uint64(a[i]) * uint64(a[j]) - if i == j { - tmp[i+j] += r - } else { - tmp[i+j] += r << 1 - } - } - } - - p224ReduceLarge(out, tmp) -} - -// ReduceLarge converts a p224LargeFieldElement to a p224FieldElement. -// -// in[i] < 2**62 -func p224ReduceLarge(out *p224FieldElement, in *p224LargeFieldElement) { - for i := 0; i < 8; i++ { - in[i] += p224ZeroModP63[i] - } - - // Eliminate the coefficients at 2**224 and greater. - for i := 14; i >= 8; i-- { - in[i-8] -= in[i] - in[i-5] += (in[i] & 0xffff) << 12 - in[i-4] += in[i] >> 16 - } - in[8] = 0 - // in[0..8] < 2**64 - - // As the values become small enough, we start to store them in |out| - // and use 32-bit operations. - for i := 1; i < 8; i++ { - in[i+1] += in[i] >> 28 - out[i] = uint32(in[i] & bottom28Bits) - } - in[0] -= in[8] - out[3] += uint32(in[8]&0xffff) << 12 - out[4] += uint32(in[8] >> 16) - // in[0] < 2**64 - // out[3] < 2**29 - // out[4] < 2**29 - // out[1,2,5..7] < 2**28 - - out[0] = uint32(in[0] & bottom28Bits) - out[1] += uint32((in[0] >> 28) & bottom28Bits) - out[2] += uint32(in[0] >> 56) - // out[0] < 2**28 - // out[1..4] < 2**29 - // out[5..7] < 2**28 -} - -// Reduce reduces the coefficients of a to smaller bounds. -// -// On entry: a[i] < 2**31 + 2**30 -// On exit: a[i] < 2**29 -func p224Reduce(a *p224FieldElement) { - for i := 0; i < 7; i++ { - a[i+1] += a[i] >> 28 - a[i] &= bottom28Bits - } - top := a[7] >> 28 - a[7] &= bottom28Bits - - // top < 2**4 - mask := top - mask |= mask >> 2 - mask |= mask >> 1 - mask <<= 31 - mask = uint32(int32(mask) >> 31) - // Mask is all ones if top != 0, all zero otherwise - - a[0] -= top - a[3] += top << 12 - - // We may have just made a[0] negative but, if we did, then we must - // have added something to a[3], this it's > 2**12. Therefore we can - // carry down to a[0]. - a[3] -= 1 & mask - a[2] += mask & (1<<28 - 1) - a[1] += mask & (1<<28 - 1) - a[0] += mask & (1 << 28) -} - -// p224Invert calculates *out = in**-1 by computing in**(2**224 - 2**96 - 1), -// i.e. Fermat's little theorem. -func p224Invert(out, in *p224FieldElement) { - var f1, f2, f3, f4 p224FieldElement - var c p224LargeFieldElement - - p224Square(&f1, in, &c) // 2 - p224Mul(&f1, &f1, in, &c) // 2**2 - 1 - p224Square(&f1, &f1, &c) // 2**3 - 2 - p224Mul(&f1, &f1, in, &c) // 2**3 - 1 - p224Square(&f2, &f1, &c) // 2**4 - 2 - p224Square(&f2, &f2, &c) // 2**5 - 4 - p224Square(&f2, &f2, &c) // 2**6 - 8 - p224Mul(&f1, &f1, &f2, &c) // 2**6 - 1 - p224Square(&f2, &f1, &c) // 2**7 - 2 - for i := 0; i < 5; i++ { // 2**12 - 2**6 - p224Square(&f2, &f2, &c) - } - p224Mul(&f2, &f2, &f1, &c) // 2**12 - 1 - p224Square(&f3, &f2, &c) // 2**13 - 2 - for i := 0; i < 11; i++ { // 2**24 - 2**12 - p224Square(&f3, &f3, &c) - } - p224Mul(&f2, &f3, &f2, &c) // 2**24 - 1 - p224Square(&f3, &f2, &c) // 2**25 - 2 - for i := 0; i < 23; i++ { // 2**48 - 2**24 - p224Square(&f3, &f3, &c) - } - p224Mul(&f3, &f3, &f2, &c) // 2**48 - 1 - p224Square(&f4, &f3, &c) // 2**49 - 2 - for i := 0; i < 47; i++ { // 2**96 - 2**48 - p224Square(&f4, &f4, &c) - } - p224Mul(&f3, &f3, &f4, &c) // 2**96 - 1 - p224Square(&f4, &f3, &c) // 2**97 - 2 - for i := 0; i < 23; i++ { // 2**120 - 2**24 - p224Square(&f4, &f4, &c) - } - p224Mul(&f2, &f4, &f2, &c) // 2**120 - 1 - for i := 0; i < 6; i++ { // 2**126 - 2**6 - p224Square(&f2, &f2, &c) - } - p224Mul(&f1, &f1, &f2, &c) // 2**126 - 1 - p224Square(&f1, &f1, &c) // 2**127 - 2 - p224Mul(&f1, &f1, in, &c) // 2**127 - 1 - for i := 0; i < 97; i++ { // 2**224 - 2**97 - p224Square(&f1, &f1, &c) - } - p224Mul(out, &f1, &f3, &c) // 2**224 - 2**96 - 1 -} - -// p224Contract converts a FieldElement to its unique, minimal form. -// -// On entry, in[i] < 2**29 -// On exit, in[i] < 2**28 -func p224Contract(out, in *p224FieldElement) { - copy(out[:], in[:]) - - for i := 0; i < 7; i++ { - out[i+1] += out[i] >> 28 - out[i] &= bottom28Bits - } - top := out[7] >> 28 - out[7] &= bottom28Bits - - out[0] -= top - out[3] += top << 12 - - // We may just have made out[i] negative. So we carry down. If we made - // out[0] negative then we know that out[3] is sufficiently positive - // because we just added to it. - for i := 0; i < 3; i++ { - mask := uint32(int32(out[i]) >> 31) - out[i] += (1 << 28) & mask - out[i+1] -= 1 & mask - } - - // We might have pushed out[3] over 2**28 so we perform another, partial, - // carry chain. - for i := 3; i < 7; i++ { - out[i+1] += out[i] >> 28 - out[i] &= bottom28Bits - } - top = out[7] >> 28 - out[7] &= bottom28Bits - - // Eliminate top while maintaining the same value mod p. - out[0] -= top - out[3] += top << 12 - - // There are two cases to consider for out[3]: - // 1) The first time that we eliminated top, we didn't push out[3] over - // 2**28. In this case, the partial carry chain didn't change any values - // and top is zero. - // 2) We did push out[3] over 2**28 the first time that we eliminated top. - // The first value of top was in [0..16), therefore, prior to eliminating - // the first top, 0xfff1000 <= out[3] <= 0xfffffff. Therefore, after - // overflowing and being reduced by the second carry chain, out[3] <= - // 0xf000. Thus it cannot have overflowed when we eliminated top for the - // second time. - - // Again, we may just have made out[0] negative, so do the same carry down. - // As before, if we made out[0] negative then we know that out[3] is - // sufficiently positive. - for i := 0; i < 3; i++ { - mask := uint32(int32(out[i]) >> 31) - out[i] += (1 << 28) & mask - out[i+1] -= 1 & mask - } - - // Now we see if the value is >= p and, if so, subtract p. - - // First we build a mask from the top four limbs, which must all be - // equal to bottom28Bits if the whole value is >= p. If top4AllOnes - // ends up with any zero bits in the bottom 28 bits, then this wasn't - // true. - top4AllOnes := uint32(0xffffffff) - for i := 4; i < 8; i++ { - top4AllOnes &= out[i] - } - top4AllOnes |= 0xf0000000 - // Now we replicate any zero bits to all the bits in top4AllOnes. - top4AllOnes &= top4AllOnes >> 16 - top4AllOnes &= top4AllOnes >> 8 - top4AllOnes &= top4AllOnes >> 4 - top4AllOnes &= top4AllOnes >> 2 - top4AllOnes &= top4AllOnes >> 1 - top4AllOnes = uint32(int32(top4AllOnes<<31) >> 31) - - // Now we test whether the bottom three limbs are non-zero. - bottom3NonZero := out[0] | out[1] | out[2] - bottom3NonZero |= bottom3NonZero >> 16 - bottom3NonZero |= bottom3NonZero >> 8 - bottom3NonZero |= bottom3NonZero >> 4 - bottom3NonZero |= bottom3NonZero >> 2 - bottom3NonZero |= bottom3NonZero >> 1 - bottom3NonZero = uint32(int32(bottom3NonZero<<31) >> 31) - - // Everything depends on the value of out[3]. - // If it's > 0xffff000 and top4AllOnes != 0 then the whole value is >= p - // If it's = 0xffff000 and top4AllOnes != 0 and bottom3NonZero != 0, - // then the whole value is >= p - // If it's < 0xffff000, then the whole value is < p - n := out[3] - 0xffff000 - out3Equal := n - out3Equal |= out3Equal >> 16 - out3Equal |= out3Equal >> 8 - out3Equal |= out3Equal >> 4 - out3Equal |= out3Equal >> 2 - out3Equal |= out3Equal >> 1 - out3Equal = ^uint32(int32(out3Equal<<31) >> 31) - - // If out[3] > 0xffff000 then n's MSB will be zero. - out3GT := ^uint32(int32(n) >> 31) - - mask := top4AllOnes & ((out3Equal & bottom3NonZero) | out3GT) - out[0] -= 1 & mask - out[3] -= 0xffff000 & mask - out[4] -= 0xfffffff & mask - out[5] -= 0xfffffff & mask - out[6] -= 0xfffffff & mask - out[7] -= 0xfffffff & mask -} - -// Group element functions. -// -// These functions deal with group elements. The group is an elliptic curve -// group with a = -3 defined in FIPS 186-3, section D.2.2. - -// p224AddJacobian computes *out = a+b where a != b. -func p224AddJacobian(x3, y3, z3, x1, y1, z1, x2, y2, z2 *p224FieldElement) { - // See http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#addition-p224Add-2007-bl - var z1z1, z2z2, u1, u2, s1, s2, h, i, j, r, v p224FieldElement - var c p224LargeFieldElement - - z1IsZero := p224IsZero(z1) - z2IsZero := p224IsZero(z2) - - // Z1Z1 = Z1² - p224Square(&z1z1, z1, &c) - // Z2Z2 = Z2² - p224Square(&z2z2, z2, &c) - // U1 = X1*Z2Z2 - p224Mul(&u1, x1, &z2z2, &c) - // U2 = X2*Z1Z1 - p224Mul(&u2, x2, &z1z1, &c) - // S1 = Y1*Z2*Z2Z2 - p224Mul(&s1, z2, &z2z2, &c) - p224Mul(&s1, y1, &s1, &c) - // S2 = Y2*Z1*Z1Z1 - p224Mul(&s2, z1, &z1z1, &c) - p224Mul(&s2, y2, &s2, &c) - // H = U2-U1 - p224Sub(&h, &u2, &u1) - p224Reduce(&h) - xEqual := p224IsZero(&h) - // I = (2*H)² - for j := 0; j < 8; j++ { - i[j] = h[j] << 1 - } - p224Reduce(&i) - p224Square(&i, &i, &c) - // J = H*I - p224Mul(&j, &h, &i, &c) - // r = 2*(S2-S1) - p224Sub(&r, &s2, &s1) - p224Reduce(&r) - yEqual := p224IsZero(&r) - if xEqual == 1 && yEqual == 1 && z1IsZero == 0 && z2IsZero == 0 { - p224DoubleJacobian(x3, y3, z3, x1, y1, z1) - return - } - for i := 0; i < 8; i++ { - r[i] <<= 1 - } - p224Reduce(&r) - // V = U1*I - p224Mul(&v, &u1, &i, &c) - // Z3 = ((Z1+Z2)²-Z1Z1-Z2Z2)*H - p224Add(&z1z1, &z1z1, &z2z2) - p224Add(&z2z2, z1, z2) - p224Reduce(&z2z2) - p224Square(&z2z2, &z2z2, &c) - p224Sub(z3, &z2z2, &z1z1) - p224Reduce(z3) - p224Mul(z3, z3, &h, &c) - // X3 = r²-J-2*V - for i := 0; i < 8; i++ { - z1z1[i] = v[i] << 1 - } - p224Add(&z1z1, &j, &z1z1) - p224Reduce(&z1z1) - p224Square(x3, &r, &c) - p224Sub(x3, x3, &z1z1) - p224Reduce(x3) - // Y3 = r*(V-X3)-2*S1*J - for i := 0; i < 8; i++ { - s1[i] <<= 1 - } - p224Mul(&s1, &s1, &j, &c) - p224Sub(&z1z1, &v, x3) - p224Reduce(&z1z1) - p224Mul(&z1z1, &z1z1, &r, &c) - p224Sub(y3, &z1z1, &s1) - p224Reduce(y3) - - p224CopyConditional(x3, x2, z1IsZero) - p224CopyConditional(x3, x1, z2IsZero) - p224CopyConditional(y3, y2, z1IsZero) - p224CopyConditional(y3, y1, z2IsZero) - p224CopyConditional(z3, z2, z1IsZero) - p224CopyConditional(z3, z1, z2IsZero) -} - -// p224DoubleJacobian computes *out = a+a. -func p224DoubleJacobian(x3, y3, z3, x1, y1, z1 *p224FieldElement) { - var delta, gamma, beta, alpha, t p224FieldElement - var c p224LargeFieldElement - - p224Square(&delta, z1, &c) - p224Square(&gamma, y1, &c) - p224Mul(&beta, x1, &gamma, &c) - - // alpha = 3*(X1-delta)*(X1+delta) - p224Add(&t, x1, &delta) - for i := 0; i < 8; i++ { - t[i] += t[i] << 1 - } - p224Reduce(&t) - p224Sub(&alpha, x1, &delta) - p224Reduce(&alpha) - p224Mul(&alpha, &alpha, &t, &c) - - // Z3 = (Y1+Z1)²-gamma-delta - p224Add(z3, y1, z1) - p224Reduce(z3) - p224Square(z3, z3, &c) - p224Sub(z3, z3, &gamma) - p224Reduce(z3) - p224Sub(z3, z3, &delta) - p224Reduce(z3) - - // X3 = alpha²-8*beta - for i := 0; i < 8; i++ { - delta[i] = beta[i] << 3 - } - p224Reduce(&delta) - p224Square(x3, &alpha, &c) - p224Sub(x3, x3, &delta) - p224Reduce(x3) - - // Y3 = alpha*(4*beta-X3)-8*gamma² - for i := 0; i < 8; i++ { - beta[i] <<= 2 - } - p224Sub(&beta, &beta, x3) - p224Reduce(&beta) - p224Square(&gamma, &gamma, &c) - for i := 0; i < 8; i++ { - gamma[i] <<= 3 - } - p224Reduce(&gamma) - p224Mul(y3, &alpha, &beta, &c) - p224Sub(y3, y3, &gamma) - p224Reduce(y3) -} - -// p224CopyConditional sets *out = *in iff the least-significant-bit of control -// is true, and it runs in constant time. -func p224CopyConditional(out, in *p224FieldElement, control uint32) { - control <<= 31 - control = uint32(int32(control) >> 31) - - for i := 0; i < 8; i++ { - out[i] ^= (out[i] ^ in[i]) & control - } -} - -func p224ScalarMult(outX, outY, outZ, inX, inY, inZ *p224FieldElement, scalar []byte) { - var xx, yy, zz p224FieldElement - for i := 0; i < 8; i++ { - outX[i] = 0 - outY[i] = 0 - outZ[i] = 0 - } - - for _, byte := range scalar { - for bitNum := uint(0); bitNum < 8; bitNum++ { - p224DoubleJacobian(outX, outY, outZ, outX, outY, outZ) - bit := uint32((byte >> (7 - bitNum)) & 1) - p224AddJacobian(&xx, &yy, &zz, inX, inY, inZ, outX, outY, outZ) - p224CopyConditional(outX, &xx, bit) - p224CopyConditional(outY, &yy, bit) - p224CopyConditional(outZ, &zz, bit) - } - } -} - -// p224ToAffine converts from Jacobian to affine form. -func p224ToAffine(x, y, z *p224FieldElement) (*big.Int, *big.Int) { - var zinv, zinvsq, outx, outy p224FieldElement - var tmp p224LargeFieldElement - - if isPointAtInfinity := p224IsZero(z); isPointAtInfinity == 1 { - return new(big.Int), new(big.Int) - } - - p224Invert(&zinv, z) - p224Square(&zinvsq, &zinv, &tmp) - p224Mul(x, x, &zinvsq, &tmp) - p224Mul(&zinvsq, &zinvsq, &zinv, &tmp) - p224Mul(y, y, &zinvsq, &tmp) - - p224Contract(&outx, x) - p224Contract(&outy, y) - return p224ToBig(&outx), p224ToBig(&outy) -} - -// get28BitsFromEnd returns the least-significant 28 bits from buf>>shift, -// where buf is interpreted as a big-endian number. -func get28BitsFromEnd(buf []byte, shift uint) (uint32, []byte) { - var ret uint32 - - for i := uint(0); i < 4; i++ { - var b byte - if l := len(buf); l > 0 { - b = buf[l-1] - // We don't remove the byte if we're about to return and we're not - // reading all of it. - if i != 3 || shift == 4 { - buf = buf[:l-1] - } - } - ret |= uint32(b) << (8 * i) >> shift - } - ret &= bottom28Bits - return ret, buf -} - -// p224FromBig sets *out = *in. -func p224FromBig(out *p224FieldElement, in *big.Int) { - bytes := in.Bytes() - out[0], bytes = get28BitsFromEnd(bytes, 0) - out[1], bytes = get28BitsFromEnd(bytes, 4) - out[2], bytes = get28BitsFromEnd(bytes, 0) - out[3], bytes = get28BitsFromEnd(bytes, 4) - out[4], bytes = get28BitsFromEnd(bytes, 0) - out[5], bytes = get28BitsFromEnd(bytes, 4) - out[6], bytes = get28BitsFromEnd(bytes, 0) - out[7], bytes = get28BitsFromEnd(bytes, 4) -} - -// p224ToBig returns in as a big.Int. -func p224ToBig(in *p224FieldElement) *big.Int { - var buf [28]byte - buf[27] = byte(in[0]) - buf[26] = byte(in[0] >> 8) - buf[25] = byte(in[0] >> 16) - buf[24] = byte(((in[0] >> 24) & 0x0f) | (in[1]<<4)&0xf0) - - buf[23] = byte(in[1] >> 4) - buf[22] = byte(in[1] >> 12) - buf[21] = byte(in[1] >> 20) - - buf[20] = byte(in[2]) - buf[19] = byte(in[2] >> 8) - buf[18] = byte(in[2] >> 16) - buf[17] = byte(((in[2] >> 24) & 0x0f) | (in[3]<<4)&0xf0) - - buf[16] = byte(in[3] >> 4) - buf[15] = byte(in[3] >> 12) - buf[14] = byte(in[3] >> 20) - - buf[13] = byte(in[4]) - buf[12] = byte(in[4] >> 8) - buf[11] = byte(in[4] >> 16) - buf[10] = byte(((in[4] >> 24) & 0x0f) | (in[5]<<4)&0xf0) - - buf[9] = byte(in[5] >> 4) - buf[8] = byte(in[5] >> 12) - buf[7] = byte(in[5] >> 20) - - buf[6] = byte(in[6]) - buf[5] = byte(in[6] >> 8) - buf[4] = byte(in[6] >> 16) - buf[3] = byte(((in[6] >> 24) & 0x0f) | (in[7]<<4)&0xf0) - - buf[2] = byte(in[7] >> 4) - buf[1] = byte(in[7] >> 12) - buf[0] = byte(in[7] >> 20) - - return new(big.Int).SetBytes(buf[:]) -} diff --git a/src/pkg/crypto/elliptic/p224_test.go b/src/pkg/crypto/elliptic/p224_test.go deleted file mode 100644 index 4b26d1610..000000000 --- a/src/pkg/crypto/elliptic/p224_test.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package elliptic - -import ( - "math/big" - "testing" -) - -var toFromBigTests = []string{ - "0", - "1", - "23", - "b70e0cb46bb4bf7f321390b94a03c1d356c01122343280d6105c1d21", - "706a46d476dcb76798e6046d89474788d164c18032d268fd10704fa6", -} - -func p224AlternativeToBig(in *p224FieldElement) *big.Int { - ret := new(big.Int) - tmp := new(big.Int) - - for i := uint(0); i < 8; i++ { - tmp.SetInt64(int64(in[i])) - tmp.Lsh(tmp, 28*i) - ret.Add(ret, tmp) - } - ret.Mod(ret, p224.P) - return ret -} - -func TestToFromBig(t *testing.T) { - for i, test := range toFromBigTests { - n, _ := new(big.Int).SetString(test, 16) - var x p224FieldElement - p224FromBig(&x, n) - m := p224ToBig(&x) - if n.Cmp(m) != 0 { - t.Errorf("#%d: %x != %x", i, n, m) - } - q := p224AlternativeToBig(&x) - if n.Cmp(q) != 0 { - t.Errorf("#%d: %x != %x (alternative)", i, n, m) - } - } -} diff --git a/src/pkg/crypto/elliptic/p256.go b/src/pkg/crypto/elliptic/p256.go deleted file mode 100644 index 82be51e62..000000000 --- a/src/pkg/crypto/elliptic/p256.go +++ /dev/null @@ -1,1186 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package elliptic - -// This file contains a constant-time, 32-bit implementation of P256. - -import ( - "math/big" -) - -type p256Curve struct { - *CurveParams -} - -var ( - p256 p256Curve - // RInverse contains 1/R mod p - the inverse of the Montgomery constant - // (2**257). - p256RInverse *big.Int -) - -func initP256() { - // See FIPS 186-3, section D.2.3 - p256.CurveParams = new(CurveParams) - p256.P, _ = new(big.Int).SetString("115792089210356248762697446949407573530086143415290314195533631308867097853951", 10) - p256.N, _ = new(big.Int).SetString("115792089210356248762697446949407573529996955224135760342422259061068512044369", 10) - p256.B, _ = new(big.Int).SetString("5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b", 16) - p256.Gx, _ = new(big.Int).SetString("6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296", 16) - p256.Gy, _ = new(big.Int).SetString("4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5", 16) - p256.BitSize = 256 - - p256RInverse, _ = new(big.Int).SetString("7fffffff00000001fffffffe8000000100000000ffffffff0000000180000000", 16) -} - -func (curve p256Curve) Params() *CurveParams { - return curve.CurveParams -} - -// p256GetScalar endian-swaps the big-endian scalar value from in and writes it -// to out. If the scalar is equal or greater than the order of the group, it's -// reduced modulo that order. -func p256GetScalar(out *[32]byte, in []byte) { - n := new(big.Int).SetBytes(in) - var scalarBytes []byte - - if n.Cmp(p256.N) >= 0 { - n.Mod(n, p256.N) - scalarBytes = n.Bytes() - } else { - scalarBytes = in - } - - for i, v := range scalarBytes { - out[len(scalarBytes)-(1+i)] = v - } -} - -func (p256Curve) ScalarBaseMult(scalar []byte) (x, y *big.Int) { - var scalarReversed [32]byte - p256GetScalar(&scalarReversed, scalar) - - var x1, y1, z1 [p256Limbs]uint32 - p256ScalarBaseMult(&x1, &y1, &z1, &scalarReversed) - return p256ToAffine(&x1, &y1, &z1) -} - -func (p256Curve) ScalarMult(bigX, bigY *big.Int, scalar []byte) (x, y *big.Int) { - var scalarReversed [32]byte - p256GetScalar(&scalarReversed, scalar) - - var px, py, x1, y1, z1 [p256Limbs]uint32 - p256FromBig(&px, bigX) - p256FromBig(&py, bigY) - p256ScalarMult(&x1, &y1, &z1, &px, &py, &scalarReversed) - return p256ToAffine(&x1, &y1, &z1) -} - -// Field elements are represented as nine, unsigned 32-bit words. -// -// The value of an field element is: -// x[0] + (x[1] * 2**29) + (x[2] * 2**57) + ... + (x[8] * 2**228) -// -// That is, each limb is alternately 29 or 28-bits wide in little-endian -// order. -// -// This means that a field element hits 2**257, rather than 2**256 as we would -// like. A 28, 29, ... pattern would cause us to hit 2**256, but that causes -// problems when multiplying as terms end up one bit short of a limb which -// would require much bit-shifting to correct. -// -// Finally, the values stored in a field element are in Montgomery form. So the -// value |y| is stored as (y*R) mod p, where p is the P-256 prime and R is -// 2**257. - -const ( - p256Limbs = 9 - bottom29Bits = 0x1fffffff -) - -var ( - // p256One is the number 1 as a field element. - p256One = [p256Limbs]uint32{2, 0, 0, 0xffff800, 0x1fffffff, 0xfffffff, 0x1fbfffff, 0x1ffffff, 0} - p256Zero = [p256Limbs]uint32{0, 0, 0, 0, 0, 0, 0, 0, 0} - // p256P is the prime modulus as a field element. - p256P = [p256Limbs]uint32{0x1fffffff, 0xfffffff, 0x1fffffff, 0x3ff, 0, 0, 0x200000, 0xf000000, 0xfffffff} - // p2562P is the twice prime modulus as a field element. - p2562P = [p256Limbs]uint32{0x1ffffffe, 0xfffffff, 0x1fffffff, 0x7ff, 0, 0, 0x400000, 0xe000000, 0x1fffffff} -) - -// p256Precomputed contains precomputed values to aid the calculation of scalar -// multiples of the base point, G. It's actually two, equal length, tables -// concatenated. -// -// The first table contains (x,y) field element pairs for 16 multiples of the -// base point, G. -// -// Index | Index (binary) | Value -// 0 | 0000 | 0G (all zeros, omitted) -// 1 | 0001 | G -// 2 | 0010 | 2**64G -// 3 | 0011 | 2**64G + G -// 4 | 0100 | 2**128G -// 5 | 0101 | 2**128G + G -// 6 | 0110 | 2**128G + 2**64G -// 7 | 0111 | 2**128G + 2**64G + G -// 8 | 1000 | 2**192G -// 9 | 1001 | 2**192G + G -// 10 | 1010 | 2**192G + 2**64G -// 11 | 1011 | 2**192G + 2**64G + G -// 12 | 1100 | 2**192G + 2**128G -// 13 | 1101 | 2**192G + 2**128G + G -// 14 | 1110 | 2**192G + 2**128G + 2**64G -// 15 | 1111 | 2**192G + 2**128G + 2**64G + G -// -// The second table follows the same style, but the terms are 2**32G, -// 2**96G, 2**160G, 2**224G. -// -// This is ~2KB of data. -var p256Precomputed = [p256Limbs * 2 * 15 * 2]uint32{ - 0x11522878, 0xe730d41, 0xdb60179, 0x4afe2ff, 0x12883add, 0xcaddd88, 0x119e7edc, 0xd4a6eab, 0x3120bee, - 0x1d2aac15, 0xf25357c, 0x19e45cdd, 0x5c721d0, 0x1992c5a5, 0xa237487, 0x154ba21, 0x14b10bb, 0xae3fe3, - 0xd41a576, 0x922fc51, 0x234994f, 0x60b60d3, 0x164586ae, 0xce95f18, 0x1fe49073, 0x3fa36cc, 0x5ebcd2c, - 0xb402f2f, 0x15c70bf, 0x1561925c, 0x5a26704, 0xda91e90, 0xcdc1c7f, 0x1ea12446, 0xe1ade1e, 0xec91f22, - 0x26f7778, 0x566847e, 0xa0bec9e, 0x234f453, 0x1a31f21a, 0xd85e75c, 0x56c7109, 0xa267a00, 0xb57c050, - 0x98fb57, 0xaa837cc, 0x60c0792, 0xcfa5e19, 0x61bab9e, 0x589e39b, 0xa324c5, 0x7d6dee7, 0x2976e4b, - 0x1fc4124a, 0xa8c244b, 0x1ce86762, 0xcd61c7e, 0x1831c8e0, 0x75774e1, 0x1d96a5a9, 0x843a649, 0xc3ab0fa, - 0x6e2e7d5, 0x7673a2a, 0x178b65e8, 0x4003e9b, 0x1a1f11c2, 0x7816ea, 0xf643e11, 0x58c43df, 0xf423fc2, - 0x19633ffa, 0x891f2b2, 0x123c231c, 0x46add8c, 0x54700dd, 0x59e2b17, 0x172db40f, 0x83e277d, 0xb0dd609, - 0xfd1da12, 0x35c6e52, 0x19ede20c, 0xd19e0c0, 0x97d0f40, 0xb015b19, 0x449e3f5, 0xe10c9e, 0x33ab581, - 0x56a67ab, 0x577734d, 0x1dddc062, 0xc57b10d, 0x149b39d, 0x26a9e7b, 0xc35df9f, 0x48764cd, 0x76dbcca, - 0xca4b366, 0xe9303ab, 0x1a7480e7, 0x57e9e81, 0x1e13eb50, 0xf466cf3, 0x6f16b20, 0x4ba3173, 0xc168c33, - 0x15cb5439, 0x6a38e11, 0x73658bd, 0xb29564f, 0x3f6dc5b, 0x53b97e, 0x1322c4c0, 0x65dd7ff, 0x3a1e4f6, - 0x14e614aa, 0x9246317, 0x1bc83aca, 0xad97eed, 0xd38ce4a, 0xf82b006, 0x341f077, 0xa6add89, 0x4894acd, - 0x9f162d5, 0xf8410ef, 0x1b266a56, 0xd7f223, 0x3e0cb92, 0xe39b672, 0x6a2901a, 0x69a8556, 0x7e7c0, - 0x9b7d8d3, 0x309a80, 0x1ad05f7f, 0xc2fb5dd, 0xcbfd41d, 0x9ceb638, 0x1051825c, 0xda0cf5b, 0x812e881, - 0x6f35669, 0x6a56f2c, 0x1df8d184, 0x345820, 0x1477d477, 0x1645db1, 0xbe80c51, 0xc22be3e, 0xe35e65a, - 0x1aeb7aa0, 0xc375315, 0xf67bc99, 0x7fdd7b9, 0x191fc1be, 0x61235d, 0x2c184e9, 0x1c5a839, 0x47a1e26, - 0xb7cb456, 0x93e225d, 0x14f3c6ed, 0xccc1ac9, 0x17fe37f3, 0x4988989, 0x1a90c502, 0x2f32042, 0xa17769b, - 0xafd8c7c, 0x8191c6e, 0x1dcdb237, 0x16200c0, 0x107b32a1, 0x66c08db, 0x10d06a02, 0x3fc93, 0x5620023, - 0x16722b27, 0x68b5c59, 0x270fcfc, 0xfad0ecc, 0xe5de1c2, 0xeab466b, 0x2fc513c, 0x407f75c, 0xbaab133, - 0x9705fe9, 0xb88b8e7, 0x734c993, 0x1e1ff8f, 0x19156970, 0xabd0f00, 0x10469ea7, 0x3293ac0, 0xcdc98aa, - 0x1d843fd, 0xe14bfe8, 0x15be825f, 0x8b5212, 0xeb3fb67, 0x81cbd29, 0xbc62f16, 0x2b6fcc7, 0xf5a4e29, - 0x13560b66, 0xc0b6ac2, 0x51ae690, 0xd41e271, 0xf3e9bd4, 0x1d70aab, 0x1029f72, 0x73e1c35, 0xee70fbc, - 0xad81baf, 0x9ecc49a, 0x86c741e, 0xfe6be30, 0x176752e7, 0x23d416, 0x1f83de85, 0x27de188, 0x66f70b8, - 0x181cd51f, 0x96b6e4c, 0x188f2335, 0xa5df759, 0x17a77eb6, 0xfeb0e73, 0x154ae914, 0x2f3ec51, 0x3826b59, - 0xb91f17d, 0x1c72949, 0x1362bf0a, 0xe23fddf, 0xa5614b0, 0xf7d8f, 0x79061, 0x823d9d2, 0x8213f39, - 0x1128ae0b, 0xd095d05, 0xb85c0c2, 0x1ecb2ef, 0x24ddc84, 0xe35e901, 0x18411a4a, 0xf5ddc3d, 0x3786689, - 0x52260e8, 0x5ae3564, 0x542b10d, 0x8d93a45, 0x19952aa4, 0x996cc41, 0x1051a729, 0x4be3499, 0x52b23aa, - 0x109f307e, 0x6f5b6bb, 0x1f84e1e7, 0x77a0cfa, 0x10c4df3f, 0x25a02ea, 0xb048035, 0xe31de66, 0xc6ecaa3, - 0x28ea335, 0x2886024, 0x1372f020, 0xf55d35, 0x15e4684c, 0xf2a9e17, 0x1a4a7529, 0xcb7beb1, 0xb2a78a1, - 0x1ab21f1f, 0x6361ccf, 0x6c9179d, 0xb135627, 0x1267b974, 0x4408bad, 0x1cbff658, 0xe3d6511, 0xc7d76f, - 0x1cc7a69, 0xe7ee31b, 0x54fab4f, 0x2b914f, 0x1ad27a30, 0xcd3579e, 0xc50124c, 0x50daa90, 0xb13f72, - 0xb06aa75, 0x70f5cc6, 0x1649e5aa, 0x84a5312, 0x329043c, 0x41c4011, 0x13d32411, 0xb04a838, 0xd760d2d, - 0x1713b532, 0xbaa0c03, 0x84022ab, 0x6bcf5c1, 0x2f45379, 0x18ae070, 0x18c9e11e, 0x20bca9a, 0x66f496b, - 0x3eef294, 0x67500d2, 0xd7f613c, 0x2dbbeb, 0xb741038, 0xe04133f, 0x1582968d, 0xbe985f7, 0x1acbc1a, - 0x1a6a939f, 0x33e50f6, 0xd665ed4, 0xb4b7bd6, 0x1e5a3799, 0x6b33847, 0x17fa56ff, 0x65ef930, 0x21dc4a, - 0x2b37659, 0x450fe17, 0xb357b65, 0xdf5efac, 0x15397bef, 0x9d35a7f, 0x112ac15f, 0x624e62e, 0xa90ae2f, - 0x107eecd2, 0x1f69bbe, 0x77d6bce, 0x5741394, 0x13c684fc, 0x950c910, 0x725522b, 0xdc78583, 0x40eeabb, - 0x1fde328a, 0xbd61d96, 0xd28c387, 0x9e77d89, 0x12550c40, 0x759cb7d, 0x367ef34, 0xae2a960, 0x91b8bdc, - 0x93462a9, 0xf469ef, 0xb2e9aef, 0xd2ca771, 0x54e1f42, 0x7aaa49, 0x6316abb, 0x2413c8e, 0x5425bf9, - 0x1bed3e3a, 0xf272274, 0x1f5e7326, 0x6416517, 0xea27072, 0x9cedea7, 0x6e7633, 0x7c91952, 0xd806dce, - 0x8e2a7e1, 0xe421e1a, 0x418c9e1, 0x1dbc890, 0x1b395c36, 0xa1dc175, 0x1dc4ef73, 0x8956f34, 0xe4b5cf2, - 0x1b0d3a18, 0x3194a36, 0x6c2641f, 0xe44124c, 0xa2f4eaa, 0xa8c25ba, 0xf927ed7, 0x627b614, 0x7371cca, - 0xba16694, 0x417bc03, 0x7c0a7e3, 0x9c35c19, 0x1168a205, 0x8b6b00d, 0x10e3edc9, 0x9c19bf2, 0x5882229, - 0x1b2b4162, 0xa5cef1a, 0x1543622b, 0x9bd433e, 0x364e04d, 0x7480792, 0x5c9b5b3, 0xe85ff25, 0x408ef57, - 0x1814cfa4, 0x121b41b, 0xd248a0f, 0x3b05222, 0x39bb16a, 0xc75966d, 0xa038113, 0xa4a1769, 0x11fbc6c, - 0x917e50e, 0xeec3da8, 0x169d6eac, 0x10c1699, 0xa416153, 0xf724912, 0x15cd60b7, 0x4acbad9, 0x5efc5fa, - 0xf150ed7, 0x122b51, 0x1104b40a, 0xcb7f442, 0xfbb28ff, 0x6ac53ca, 0x196142cc, 0x7bf0fa9, 0x957651, - 0x4e0f215, 0xed439f8, 0x3f46bd5, 0x5ace82f, 0x110916b6, 0x6db078, 0xffd7d57, 0xf2ecaac, 0xca86dec, - 0x15d6b2da, 0x965ecc9, 0x1c92b4c2, 0x1f3811, 0x1cb080f5, 0x2d8b804, 0x19d1c12d, 0xf20bd46, 0x1951fa7, - 0xa3656c3, 0x523a425, 0xfcd0692, 0xd44ddc8, 0x131f0f5b, 0xaf80e4a, 0xcd9fc74, 0x99bb618, 0x2db944c, - 0xa673090, 0x1c210e1, 0x178c8d23, 0x1474383, 0x10b8743d, 0x985a55b, 0x2e74779, 0x576138, 0x9587927, - 0x133130fa, 0xbe05516, 0x9f4d619, 0xbb62570, 0x99ec591, 0xd9468fe, 0x1d07782d, 0xfc72e0b, 0x701b298, - 0x1863863b, 0x85954b8, 0x121a0c36, 0x9e7fedf, 0xf64b429, 0x9b9d71e, 0x14e2f5d8, 0xf858d3a, 0x942eea8, - 0xda5b765, 0x6edafff, 0xa9d18cc, 0xc65e4ba, 0x1c747e86, 0xe4ea915, 0x1981d7a1, 0x8395659, 0x52ed4e2, - 0x87d43b7, 0x37ab11b, 0x19d292ce, 0xf8d4692, 0x18c3053f, 0x8863e13, 0x4c146c0, 0x6bdf55a, 0x4e4457d, - 0x16152289, 0xac78ec2, 0x1a59c5a2, 0x2028b97, 0x71c2d01, 0x295851f, 0x404747b, 0x878558d, 0x7d29aa4, - 0x13d8341f, 0x8daefd7, 0x139c972d, 0x6b7ea75, 0xd4a9dde, 0xff163d8, 0x81d55d7, 0xa5bef68, 0xb7b30d8, - 0xbe73d6f, 0xaa88141, 0xd976c81, 0x7e7a9cc, 0x18beb771, 0xd773cbd, 0x13f51951, 0x9d0c177, 0x1c49a78, -} - -// Field element operations: - -// nonZeroToAllOnes returns: -// 0xffffffff for 0 < x <= 2**31 -// 0 for x == 0 or x > 2**31. -func nonZeroToAllOnes(x uint32) uint32 { - return ((x - 1) >> 31) - 1 -} - -// p256ReduceCarry adds a multiple of p in order to cancel |carry|, -// which is a term at 2**257. -// -// On entry: carry < 2**3, inout[0,2,...] < 2**29, inout[1,3,...] < 2**28. -// On exit: inout[0,2,..] < 2**30, inout[1,3,...] < 2**29. -func p256ReduceCarry(inout *[p256Limbs]uint32, carry uint32) { - carry_mask := nonZeroToAllOnes(carry) - - inout[0] += carry << 1 - inout[3] += 0x10000000 & carry_mask - // carry < 2**3 thus (carry << 11) < 2**14 and we added 2**28 in the - // previous line therefore this doesn't underflow. - inout[3] -= carry << 11 - inout[4] += (0x20000000 - 1) & carry_mask - inout[5] += (0x10000000 - 1) & carry_mask - inout[6] += (0x20000000 - 1) & carry_mask - inout[6] -= carry << 22 - // This may underflow if carry is non-zero but, if so, we'll fix it in the - // next line. - inout[7] -= 1 & carry_mask - inout[7] += carry << 25 -} - -// p256Sum sets out = in+in2. -// -// On entry, in[i]+in2[i] must not overflow a 32-bit word. -// On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29 -func p256Sum(out, in, in2 *[p256Limbs]uint32) { - carry := uint32(0) - for i := 0; ; i++ { - out[i] = in[i] + in2[i] - out[i] += carry - carry = out[i] >> 29 - out[i] &= bottom29Bits - - i++ - if i == p256Limbs { - break - } - - out[i] = in[i] + in2[i] - out[i] += carry - carry = out[i] >> 28 - out[i] &= bottom28Bits - } - - p256ReduceCarry(out, carry) -} - -const ( - two30m2 = 1<<30 - 1<<2 - two30p13m2 = 1<<30 + 1<<13 - 1<<2 - two31m2 = 1<<31 - 1<<2 - two31p24m2 = 1<<31 + 1<<24 - 1<<2 - two30m27m2 = 1<<30 - 1<<27 - 1<<2 -) - -// p256Zero31 is 0 mod p. -var p256Zero31 = [p256Limbs]uint32{two31m3, two30m2, two31m2, two30p13m2, two31m2, two30m2, two31p24m2, two30m27m2, two31m2} - -// p256Diff sets out = in-in2. -// -// On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29 and -// in2[0,2,...] < 2**30, in2[1,3,...] < 2**29. -// On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. -func p256Diff(out, in, in2 *[p256Limbs]uint32) { - var carry uint32 - - for i := 0; ; i++ { - out[i] = in[i] - in2[i] - out[i] += p256Zero31[i] - out[i] += carry - carry = out[i] >> 29 - out[i] &= bottom29Bits - - i++ - if i == p256Limbs { - break - } - - out[i] = in[i] - in2[i] - out[i] += p256Zero31[i] - out[i] += carry - carry = out[i] >> 28 - out[i] &= bottom28Bits - } - - p256ReduceCarry(out, carry) -} - -// p256ReduceDegree sets out = tmp/R mod p where tmp contains 64-bit words with -// the same 29,28,... bit positions as an field element. -// -// The values in field elements are in Montgomery form: x*R mod p where R = -// 2**257. Since we just multiplied two Montgomery values together, the result -// is x*y*R*R mod p. We wish to divide by R in order for the result also to be -// in Montgomery form. -// -// On entry: tmp[i] < 2**64 -// On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29 -func p256ReduceDegree(out *[p256Limbs]uint32, tmp [17]uint64) { - // The following table may be helpful when reading this code: - // - // Limb number: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10... - // Width (bits): 29| 28| 29| 28| 29| 28| 29| 28| 29| 28| 29 - // Start bit: 0 | 29| 57| 86|114|143|171|200|228|257|285 - // (odd phase): 0 | 28| 57| 85|114|142|171|199|228|256|285 - var tmp2 [18]uint32 - var carry, x, xMask uint32 - - // tmp contains 64-bit words with the same 29,28,29-bit positions as an - // field element. So the top of an element of tmp might overlap with - // another element two positions down. The following loop eliminates - // this overlap. - tmp2[0] = uint32(tmp[0]) & bottom29Bits - - tmp2[1] = uint32(tmp[0]) >> 29 - tmp2[1] |= (uint32(tmp[0]>>32) << 3) & bottom28Bits - tmp2[1] += uint32(tmp[1]) & bottom28Bits - carry = tmp2[1] >> 28 - tmp2[1] &= bottom28Bits - - for i := 2; i < 17; i++ { - tmp2[i] = (uint32(tmp[i-2] >> 32)) >> 25 - tmp2[i] += (uint32(tmp[i-1])) >> 28 - tmp2[i] += (uint32(tmp[i-1]>>32) << 4) & bottom29Bits - tmp2[i] += uint32(tmp[i]) & bottom29Bits - tmp2[i] += carry - carry = tmp2[i] >> 29 - tmp2[i] &= bottom29Bits - - i++ - if i == 17 { - break - } - tmp2[i] = uint32(tmp[i-2]>>32) >> 25 - tmp2[i] += uint32(tmp[i-1]) >> 29 - tmp2[i] += ((uint32(tmp[i-1] >> 32)) << 3) & bottom28Bits - tmp2[i] += uint32(tmp[i]) & bottom28Bits - tmp2[i] += carry - carry = tmp2[i] >> 28 - tmp2[i] &= bottom28Bits - } - - tmp2[17] = uint32(tmp[15]>>32) >> 25 - tmp2[17] += uint32(tmp[16]) >> 29 - tmp2[17] += uint32(tmp[16]>>32) << 3 - tmp2[17] += carry - - // Montgomery elimination of terms: - // - // Since R is 2**257, we can divide by R with a bitwise shift if we can - // ensure that the right-most 257 bits are all zero. We can make that true - // by adding multiplies of p without affecting the value. - // - // So we eliminate limbs from right to left. Since the bottom 29 bits of p - // are all ones, then by adding tmp2[0]*p to tmp2 we'll make tmp2[0] == 0. - // We can do that for 8 further limbs and then right shift to eliminate the - // extra factor of R. - for i := 0; ; i += 2 { - tmp2[i+1] += tmp2[i] >> 29 - x = tmp2[i] & bottom29Bits - xMask = nonZeroToAllOnes(x) - tmp2[i] = 0 - - // The bounds calculations for this loop are tricky. Each iteration of - // the loop eliminates two words by adding values to words to their - // right. - // - // The following table contains the amounts added to each word (as an - // offset from the value of i at the top of the loop). The amounts are - // accounted for from the first and second half of the loop separately - // and are written as, for example, 28 to mean a value <2**28. - // - // Word: 3 4 5 6 7 8 9 10 - // Added in top half: 28 11 29 21 29 28 - // 28 29 - // 29 - // Added in bottom half: 29 10 28 21 28 28 - // 29 - // - // The value that is currently offset 7 will be offset 5 for the next - // iteration and then offset 3 for the iteration after that. Therefore - // the total value added will be the values added at 7, 5 and 3. - // - // The following table accumulates these values. The sums at the bottom - // are written as, for example, 29+28, to mean a value < 2**29+2**28. - // - // Word: 3 4 5 6 7 8 9 10 11 12 13 - // 28 11 10 29 21 29 28 28 28 28 28 - // 29 28 11 28 29 28 29 28 29 28 - // 29 28 21 21 29 21 29 21 - // 10 29 28 21 28 21 28 - // 28 29 28 29 28 29 28 - // 11 10 29 10 29 10 - // 29 28 11 28 11 - // 29 29 - // -------------------------------------------- - // 30+ 31+ 30+ 31+ 30+ - // 28+ 29+ 28+ 29+ 21+ - // 21+ 28+ 21+ 28+ 10 - // 10 21+ 10 21+ - // 11 11 - // - // So the greatest amount is added to tmp2[10] and tmp2[12]. If - // tmp2[10/12] has an initial value of <2**29, then the maximum value - // will be < 2**31 + 2**30 + 2**28 + 2**21 + 2**11, which is < 2**32, - // as required. - tmp2[i+3] += (x << 10) & bottom28Bits - tmp2[i+4] += (x >> 18) - - tmp2[i+6] += (x << 21) & bottom29Bits - tmp2[i+7] += x >> 8 - - // At position 200, which is the starting bit position for word 7, we - // have a factor of 0xf000000 = 2**28 - 2**24. - tmp2[i+7] += 0x10000000 & xMask - tmp2[i+8] += (x - 1) & xMask - tmp2[i+7] -= (x << 24) & bottom28Bits - tmp2[i+8] -= x >> 4 - - tmp2[i+8] += 0x20000000 & xMask - tmp2[i+8] -= x - tmp2[i+8] += (x << 28) & bottom29Bits - tmp2[i+9] += ((x >> 1) - 1) & xMask - - if i+1 == p256Limbs { - break - } - tmp2[i+2] += tmp2[i+1] >> 28 - x = tmp2[i+1] & bottom28Bits - xMask = nonZeroToAllOnes(x) - tmp2[i+1] = 0 - - tmp2[i+4] += (x << 11) & bottom29Bits - tmp2[i+5] += (x >> 18) - - tmp2[i+7] += (x << 21) & bottom28Bits - tmp2[i+8] += x >> 7 - - // At position 199, which is the starting bit of the 8th word when - // dealing with a context starting on an odd word, we have a factor of - // 0x1e000000 = 2**29 - 2**25. Since we have not updated i, the 8th - // word from i+1 is i+8. - tmp2[i+8] += 0x20000000 & xMask - tmp2[i+9] += (x - 1) & xMask - tmp2[i+8] -= (x << 25) & bottom29Bits - tmp2[i+9] -= x >> 4 - - tmp2[i+9] += 0x10000000 & xMask - tmp2[i+9] -= x - tmp2[i+10] += (x - 1) & xMask - } - - // We merge the right shift with a carry chain. The words above 2**257 have - // widths of 28,29,... which we need to correct when copying them down. - carry = 0 - for i := 0; i < 8; i++ { - // The maximum value of tmp2[i + 9] occurs on the first iteration and - // is < 2**30+2**29+2**28. Adding 2**29 (from tmp2[i + 10]) is - // therefore safe. - out[i] = tmp2[i+9] - out[i] += carry - out[i] += (tmp2[i+10] << 28) & bottom29Bits - carry = out[i] >> 29 - out[i] &= bottom29Bits - - i++ - out[i] = tmp2[i+9] >> 1 - out[i] += carry - carry = out[i] >> 28 - out[i] &= bottom28Bits - } - - out[8] = tmp2[17] - out[8] += carry - carry = out[8] >> 29 - out[8] &= bottom29Bits - - p256ReduceCarry(out, carry) -} - -// p256Square sets out=in*in. -// -// On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29. -// On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. -func p256Square(out, in *[p256Limbs]uint32) { - var tmp [17]uint64 - - tmp[0] = uint64(in[0]) * uint64(in[0]) - tmp[1] = uint64(in[0]) * (uint64(in[1]) << 1) - tmp[2] = uint64(in[0])*(uint64(in[2])<<1) + - uint64(in[1])*(uint64(in[1])<<1) - tmp[3] = uint64(in[0])*(uint64(in[3])<<1) + - uint64(in[1])*(uint64(in[2])<<1) - tmp[4] = uint64(in[0])*(uint64(in[4])<<1) + - uint64(in[1])*(uint64(in[3])<<2) + - uint64(in[2])*uint64(in[2]) - tmp[5] = uint64(in[0])*(uint64(in[5])<<1) + - uint64(in[1])*(uint64(in[4])<<1) + - uint64(in[2])*(uint64(in[3])<<1) - tmp[6] = uint64(in[0])*(uint64(in[6])<<1) + - uint64(in[1])*(uint64(in[5])<<2) + - uint64(in[2])*(uint64(in[4])<<1) + - uint64(in[3])*(uint64(in[3])<<1) - tmp[7] = uint64(in[0])*(uint64(in[7])<<1) + - uint64(in[1])*(uint64(in[6])<<1) + - uint64(in[2])*(uint64(in[5])<<1) + - uint64(in[3])*(uint64(in[4])<<1) - // tmp[8] has the greatest value of 2**61 + 2**60 + 2**61 + 2**60 + 2**60, - // which is < 2**64 as required. - tmp[8] = uint64(in[0])*(uint64(in[8])<<1) + - uint64(in[1])*(uint64(in[7])<<2) + - uint64(in[2])*(uint64(in[6])<<1) + - uint64(in[3])*(uint64(in[5])<<2) + - uint64(in[4])*uint64(in[4]) - tmp[9] = uint64(in[1])*(uint64(in[8])<<1) + - uint64(in[2])*(uint64(in[7])<<1) + - uint64(in[3])*(uint64(in[6])<<1) + - uint64(in[4])*(uint64(in[5])<<1) - tmp[10] = uint64(in[2])*(uint64(in[8])<<1) + - uint64(in[3])*(uint64(in[7])<<2) + - uint64(in[4])*(uint64(in[6])<<1) + - uint64(in[5])*(uint64(in[5])<<1) - tmp[11] = uint64(in[3])*(uint64(in[8])<<1) + - uint64(in[4])*(uint64(in[7])<<1) + - uint64(in[5])*(uint64(in[6])<<1) - tmp[12] = uint64(in[4])*(uint64(in[8])<<1) + - uint64(in[5])*(uint64(in[7])<<2) + - uint64(in[6])*uint64(in[6]) - tmp[13] = uint64(in[5])*(uint64(in[8])<<1) + - uint64(in[6])*(uint64(in[7])<<1) - tmp[14] = uint64(in[6])*(uint64(in[8])<<1) + - uint64(in[7])*(uint64(in[7])<<1) - tmp[15] = uint64(in[7]) * (uint64(in[8]) << 1) - tmp[16] = uint64(in[8]) * uint64(in[8]) - - p256ReduceDegree(out, tmp) -} - -// p256Mul sets out=in*in2. -// -// On entry: in[0,2,...] < 2**30, in[1,3,...] < 2**29 and -// in2[0,2,...] < 2**30, in2[1,3,...] < 2**29. -// On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. -func p256Mul(out, in, in2 *[p256Limbs]uint32) { - var tmp [17]uint64 - - tmp[0] = uint64(in[0]) * uint64(in2[0]) - tmp[1] = uint64(in[0])*(uint64(in2[1])<<0) + - uint64(in[1])*(uint64(in2[0])<<0) - tmp[2] = uint64(in[0])*(uint64(in2[2])<<0) + - uint64(in[1])*(uint64(in2[1])<<1) + - uint64(in[2])*(uint64(in2[0])<<0) - tmp[3] = uint64(in[0])*(uint64(in2[3])<<0) + - uint64(in[1])*(uint64(in2[2])<<0) + - uint64(in[2])*(uint64(in2[1])<<0) + - uint64(in[3])*(uint64(in2[0])<<0) - tmp[4] = uint64(in[0])*(uint64(in2[4])<<0) + - uint64(in[1])*(uint64(in2[3])<<1) + - uint64(in[2])*(uint64(in2[2])<<0) + - uint64(in[3])*(uint64(in2[1])<<1) + - uint64(in[4])*(uint64(in2[0])<<0) - tmp[5] = uint64(in[0])*(uint64(in2[5])<<0) + - uint64(in[1])*(uint64(in2[4])<<0) + - uint64(in[2])*(uint64(in2[3])<<0) + - uint64(in[3])*(uint64(in2[2])<<0) + - uint64(in[4])*(uint64(in2[1])<<0) + - uint64(in[5])*(uint64(in2[0])<<0) - tmp[6] = uint64(in[0])*(uint64(in2[6])<<0) + - uint64(in[1])*(uint64(in2[5])<<1) + - uint64(in[2])*(uint64(in2[4])<<0) + - uint64(in[3])*(uint64(in2[3])<<1) + - uint64(in[4])*(uint64(in2[2])<<0) + - uint64(in[5])*(uint64(in2[1])<<1) + - uint64(in[6])*(uint64(in2[0])<<0) - tmp[7] = uint64(in[0])*(uint64(in2[7])<<0) + - uint64(in[1])*(uint64(in2[6])<<0) + - uint64(in[2])*(uint64(in2[5])<<0) + - uint64(in[3])*(uint64(in2[4])<<0) + - uint64(in[4])*(uint64(in2[3])<<0) + - uint64(in[5])*(uint64(in2[2])<<0) + - uint64(in[6])*(uint64(in2[1])<<0) + - uint64(in[7])*(uint64(in2[0])<<0) - // tmp[8] has the greatest value but doesn't overflow. See logic in - // p256Square. - tmp[8] = uint64(in[0])*(uint64(in2[8])<<0) + - uint64(in[1])*(uint64(in2[7])<<1) + - uint64(in[2])*(uint64(in2[6])<<0) + - uint64(in[3])*(uint64(in2[5])<<1) + - uint64(in[4])*(uint64(in2[4])<<0) + - uint64(in[5])*(uint64(in2[3])<<1) + - uint64(in[6])*(uint64(in2[2])<<0) + - uint64(in[7])*(uint64(in2[1])<<1) + - uint64(in[8])*(uint64(in2[0])<<0) - tmp[9] = uint64(in[1])*(uint64(in2[8])<<0) + - uint64(in[2])*(uint64(in2[7])<<0) + - uint64(in[3])*(uint64(in2[6])<<0) + - uint64(in[4])*(uint64(in2[5])<<0) + - uint64(in[5])*(uint64(in2[4])<<0) + - uint64(in[6])*(uint64(in2[3])<<0) + - uint64(in[7])*(uint64(in2[2])<<0) + - uint64(in[8])*(uint64(in2[1])<<0) - tmp[10] = uint64(in[2])*(uint64(in2[8])<<0) + - uint64(in[3])*(uint64(in2[7])<<1) + - uint64(in[4])*(uint64(in2[6])<<0) + - uint64(in[5])*(uint64(in2[5])<<1) + - uint64(in[6])*(uint64(in2[4])<<0) + - uint64(in[7])*(uint64(in2[3])<<1) + - uint64(in[8])*(uint64(in2[2])<<0) - tmp[11] = uint64(in[3])*(uint64(in2[8])<<0) + - uint64(in[4])*(uint64(in2[7])<<0) + - uint64(in[5])*(uint64(in2[6])<<0) + - uint64(in[6])*(uint64(in2[5])<<0) + - uint64(in[7])*(uint64(in2[4])<<0) + - uint64(in[8])*(uint64(in2[3])<<0) - tmp[12] = uint64(in[4])*(uint64(in2[8])<<0) + - uint64(in[5])*(uint64(in2[7])<<1) + - uint64(in[6])*(uint64(in2[6])<<0) + - uint64(in[7])*(uint64(in2[5])<<1) + - uint64(in[8])*(uint64(in2[4])<<0) - tmp[13] = uint64(in[5])*(uint64(in2[8])<<0) + - uint64(in[6])*(uint64(in2[7])<<0) + - uint64(in[7])*(uint64(in2[6])<<0) + - uint64(in[8])*(uint64(in2[5])<<0) - tmp[14] = uint64(in[6])*(uint64(in2[8])<<0) + - uint64(in[7])*(uint64(in2[7])<<1) + - uint64(in[8])*(uint64(in2[6])<<0) - tmp[15] = uint64(in[7])*(uint64(in2[8])<<0) + - uint64(in[8])*(uint64(in2[7])<<0) - tmp[16] = uint64(in[8]) * (uint64(in2[8]) << 0) - - p256ReduceDegree(out, tmp) -} - -func p256Assign(out, in *[p256Limbs]uint32) { - *out = *in -} - -// p256Invert calculates |out| = |in|^{-1} -// -// Based on Fermat's Little Theorem: -// a^p = a (mod p) -// a^{p-1} = 1 (mod p) -// a^{p-2} = a^{-1} (mod p) -func p256Invert(out, in *[p256Limbs]uint32) { - var ftmp, ftmp2 [p256Limbs]uint32 - - // each e_I will hold |in|^{2^I - 1} - var e2, e4, e8, e16, e32, e64 [p256Limbs]uint32 - - p256Square(&ftmp, in) // 2^1 - p256Mul(&ftmp, in, &ftmp) // 2^2 - 2^0 - p256Assign(&e2, &ftmp) - p256Square(&ftmp, &ftmp) // 2^3 - 2^1 - p256Square(&ftmp, &ftmp) // 2^4 - 2^2 - p256Mul(&ftmp, &ftmp, &e2) // 2^4 - 2^0 - p256Assign(&e4, &ftmp) - p256Square(&ftmp, &ftmp) // 2^5 - 2^1 - p256Square(&ftmp, &ftmp) // 2^6 - 2^2 - p256Square(&ftmp, &ftmp) // 2^7 - 2^3 - p256Square(&ftmp, &ftmp) // 2^8 - 2^4 - p256Mul(&ftmp, &ftmp, &e4) // 2^8 - 2^0 - p256Assign(&e8, &ftmp) - for i := 0; i < 8; i++ { - p256Square(&ftmp, &ftmp) - } // 2^16 - 2^8 - p256Mul(&ftmp, &ftmp, &e8) // 2^16 - 2^0 - p256Assign(&e16, &ftmp) - for i := 0; i < 16; i++ { - p256Square(&ftmp, &ftmp) - } // 2^32 - 2^16 - p256Mul(&ftmp, &ftmp, &e16) // 2^32 - 2^0 - p256Assign(&e32, &ftmp) - for i := 0; i < 32; i++ { - p256Square(&ftmp, &ftmp) - } // 2^64 - 2^32 - p256Assign(&e64, &ftmp) - p256Mul(&ftmp, &ftmp, in) // 2^64 - 2^32 + 2^0 - for i := 0; i < 192; i++ { - p256Square(&ftmp, &ftmp) - } // 2^256 - 2^224 + 2^192 - - p256Mul(&ftmp2, &e64, &e32) // 2^64 - 2^0 - for i := 0; i < 16; i++ { - p256Square(&ftmp2, &ftmp2) - } // 2^80 - 2^16 - p256Mul(&ftmp2, &ftmp2, &e16) // 2^80 - 2^0 - for i := 0; i < 8; i++ { - p256Square(&ftmp2, &ftmp2) - } // 2^88 - 2^8 - p256Mul(&ftmp2, &ftmp2, &e8) // 2^88 - 2^0 - for i := 0; i < 4; i++ { - p256Square(&ftmp2, &ftmp2) - } // 2^92 - 2^4 - p256Mul(&ftmp2, &ftmp2, &e4) // 2^92 - 2^0 - p256Square(&ftmp2, &ftmp2) // 2^93 - 2^1 - p256Square(&ftmp2, &ftmp2) // 2^94 - 2^2 - p256Mul(&ftmp2, &ftmp2, &e2) // 2^94 - 2^0 - p256Square(&ftmp2, &ftmp2) // 2^95 - 2^1 - p256Square(&ftmp2, &ftmp2) // 2^96 - 2^2 - p256Mul(&ftmp2, &ftmp2, in) // 2^96 - 3 - - p256Mul(out, &ftmp2, &ftmp) // 2^256 - 2^224 + 2^192 + 2^96 - 3 -} - -// p256Scalar3 sets out=3*out. -// -// On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29. -// On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. -func p256Scalar3(out *[p256Limbs]uint32) { - var carry uint32 - - for i := 0; ; i++ { - out[i] *= 3 - out[i] += carry - carry = out[i] >> 29 - out[i] &= bottom29Bits - - i++ - if i == p256Limbs { - break - } - - out[i] *= 3 - out[i] += carry - carry = out[i] >> 28 - out[i] &= bottom28Bits - } - - p256ReduceCarry(out, carry) -} - -// p256Scalar4 sets out=4*out. -// -// On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29. -// On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. -func p256Scalar4(out *[p256Limbs]uint32) { - var carry, nextCarry uint32 - - for i := 0; ; i++ { - nextCarry = out[i] >> 27 - out[i] <<= 2 - out[i] &= bottom29Bits - out[i] += carry - carry = nextCarry + (out[i] >> 29) - out[i] &= bottom29Bits - - i++ - if i == p256Limbs { - break - } - nextCarry = out[i] >> 26 - out[i] <<= 2 - out[i] &= bottom28Bits - out[i] += carry - carry = nextCarry + (out[i] >> 28) - out[i] &= bottom28Bits - } - - p256ReduceCarry(out, carry) -} - -// p256Scalar8 sets out=8*out. -// -// On entry: out[0,2,...] < 2**30, out[1,3,...] < 2**29. -// On exit: out[0,2,...] < 2**30, out[1,3,...] < 2**29. -func p256Scalar8(out *[p256Limbs]uint32) { - var carry, nextCarry uint32 - - for i := 0; ; i++ { - nextCarry = out[i] >> 26 - out[i] <<= 3 - out[i] &= bottom29Bits - out[i] += carry - carry = nextCarry + (out[i] >> 29) - out[i] &= bottom29Bits - - i++ - if i == p256Limbs { - break - } - nextCarry = out[i] >> 25 - out[i] <<= 3 - out[i] &= bottom28Bits - out[i] += carry - carry = nextCarry + (out[i] >> 28) - out[i] &= bottom28Bits - } - - p256ReduceCarry(out, carry) -} - -// Group operations: -// -// Elements of the elliptic curve group are represented in Jacobian -// coordinates: (x, y, z). An affine point (x', y') is x'=x/z**2, y'=y/z**3 in -// Jacobian form. - -// p256PointDouble sets {xOut,yOut,zOut} = 2*{x,y,z}. -// -// See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l -func p256PointDouble(xOut, yOut, zOut, x, y, z *[p256Limbs]uint32) { - var delta, gamma, alpha, beta, tmp, tmp2 [p256Limbs]uint32 - - p256Square(&delta, z) - p256Square(&gamma, y) - p256Mul(&beta, x, &gamma) - - p256Sum(&tmp, x, &delta) - p256Diff(&tmp2, x, &delta) - p256Mul(&alpha, &tmp, &tmp2) - p256Scalar3(&alpha) - - p256Sum(&tmp, y, z) - p256Square(&tmp, &tmp) - p256Diff(&tmp, &tmp, &gamma) - p256Diff(zOut, &tmp, &delta) - - p256Scalar4(&beta) - p256Square(xOut, &alpha) - p256Diff(xOut, xOut, &beta) - p256Diff(xOut, xOut, &beta) - - p256Diff(&tmp, &beta, xOut) - p256Mul(&tmp, &alpha, &tmp) - p256Square(&tmp2, &gamma) - p256Scalar8(&tmp2) - p256Diff(yOut, &tmp, &tmp2) -} - -// p256PointAddMixed sets {xOut,yOut,zOut} = {x1,y1,z1} + {x2,y2,1}. -// (i.e. the second point is affine.) -// -// See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl -// -// Note that this function does not handle P+P, infinity+P nor P+infinity -// correctly. -func p256PointAddMixed(xOut, yOut, zOut, x1, y1, z1, x2, y2 *[p256Limbs]uint32) { - var z1z1, z1z1z1, s2, u2, h, i, j, r, rr, v, tmp [p256Limbs]uint32 - - p256Square(&z1z1, z1) - p256Sum(&tmp, z1, z1) - - p256Mul(&u2, x2, &z1z1) - p256Mul(&z1z1z1, z1, &z1z1) - p256Mul(&s2, y2, &z1z1z1) - p256Diff(&h, &u2, x1) - p256Sum(&i, &h, &h) - p256Square(&i, &i) - p256Mul(&j, &h, &i) - p256Diff(&r, &s2, y1) - p256Sum(&r, &r, &r) - p256Mul(&v, x1, &i) - - p256Mul(zOut, &tmp, &h) - p256Square(&rr, &r) - p256Diff(xOut, &rr, &j) - p256Diff(xOut, xOut, &v) - p256Diff(xOut, xOut, &v) - - p256Diff(&tmp, &v, xOut) - p256Mul(yOut, &tmp, &r) - p256Mul(&tmp, y1, &j) - p256Diff(yOut, yOut, &tmp) - p256Diff(yOut, yOut, &tmp) -} - -// p256PointAdd sets {xOut,yOut,zOut} = {x1,y1,z1} + {x2,y2,z2}. -// -// See http://www.hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#addition-add-2007-bl -// -// Note that this function does not handle P+P, infinity+P nor P+infinity -// correctly. -func p256PointAdd(xOut, yOut, zOut, x1, y1, z1, x2, y2, z2 *[p256Limbs]uint32) { - var z1z1, z1z1z1, z2z2, z2z2z2, s1, s2, u1, u2, h, i, j, r, rr, v, tmp [p256Limbs]uint32 - - p256Square(&z1z1, z1) - p256Square(&z2z2, z2) - p256Mul(&u1, x1, &z2z2) - - p256Sum(&tmp, z1, z2) - p256Square(&tmp, &tmp) - p256Diff(&tmp, &tmp, &z1z1) - p256Diff(&tmp, &tmp, &z2z2) - - p256Mul(&z2z2z2, z2, &z2z2) - p256Mul(&s1, y1, &z2z2z2) - - p256Mul(&u2, x2, &z1z1) - p256Mul(&z1z1z1, z1, &z1z1) - p256Mul(&s2, y2, &z1z1z1) - p256Diff(&h, &u2, &u1) - p256Sum(&i, &h, &h) - p256Square(&i, &i) - p256Mul(&j, &h, &i) - p256Diff(&r, &s2, &s1) - p256Sum(&r, &r, &r) - p256Mul(&v, &u1, &i) - - p256Mul(zOut, &tmp, &h) - p256Square(&rr, &r) - p256Diff(xOut, &rr, &j) - p256Diff(xOut, xOut, &v) - p256Diff(xOut, xOut, &v) - - p256Diff(&tmp, &v, xOut) - p256Mul(yOut, &tmp, &r) - p256Mul(&tmp, &s1, &j) - p256Diff(yOut, yOut, &tmp) - p256Diff(yOut, yOut, &tmp) -} - -// p256CopyConditional sets out=in if mask = 0xffffffff in constant time. -// -// On entry: mask is either 0 or 0xffffffff. -func p256CopyConditional(out, in *[p256Limbs]uint32, mask uint32) { - for i := 0; i < p256Limbs; i++ { - tmp := mask & (in[i] ^ out[i]) - out[i] ^= tmp - } -} - -// p256SelectAffinePoint sets {out_x,out_y} to the index'th entry of table. -// On entry: index < 16, table[0] must be zero. -func p256SelectAffinePoint(xOut, yOut *[p256Limbs]uint32, table []uint32, index uint32) { - for i := range xOut { - xOut[i] = 0 - } - for i := range yOut { - yOut[i] = 0 - } - - for i := uint32(1); i < 16; i++ { - mask := i ^ index - mask |= mask >> 2 - mask |= mask >> 1 - mask &= 1 - mask-- - for j := range xOut { - xOut[j] |= table[0] & mask - table = table[1:] - } - for j := range yOut { - yOut[j] |= table[0] & mask - table = table[1:] - } - } -} - -// p256SelectJacobianPoint sets {out_x,out_y,out_z} to the index'th entry of -// table. -// On entry: index < 16, table[0] must be zero. -func p256SelectJacobianPoint(xOut, yOut, zOut *[p256Limbs]uint32, table *[16][3][p256Limbs]uint32, index uint32) { - for i := range xOut { - xOut[i] = 0 - } - for i := range yOut { - yOut[i] = 0 - } - for i := range zOut { - zOut[i] = 0 - } - - // The implicit value at index 0 is all zero. We don't need to perform that - // iteration of the loop because we already set out_* to zero. - for i := uint32(1); i < 16; i++ { - mask := i ^ index - mask |= mask >> 2 - mask |= mask >> 1 - mask &= 1 - mask-- - for j := range xOut { - xOut[j] |= table[i][0][j] & mask - } - for j := range yOut { - yOut[j] |= table[i][1][j] & mask - } - for j := range zOut { - zOut[j] |= table[i][2][j] & mask - } - } -} - -// p256GetBit returns the bit'th bit of scalar. -func p256GetBit(scalar *[32]uint8, bit uint) uint32 { - return uint32(((scalar[bit>>3]) >> (bit & 7)) & 1) -} - -// p256ScalarBaseMult sets {xOut,yOut,zOut} = scalar*G where scalar is a -// little-endian number. Note that the value of scalar must be less than the -// order of the group. -func p256ScalarBaseMult(xOut, yOut, zOut *[p256Limbs]uint32, scalar *[32]uint8) { - nIsInfinityMask := ^uint32(0) - var pIsNoninfiniteMask, mask, tableOffset uint32 - var px, py, tx, ty, tz [p256Limbs]uint32 - - for i := range xOut { - xOut[i] = 0 - } - for i := range yOut { - yOut[i] = 0 - } - for i := range zOut { - zOut[i] = 0 - } - - // The loop adds bits at positions 0, 64, 128 and 192, followed by - // positions 32,96,160 and 224 and does this 32 times. - for i := uint(0); i < 32; i++ { - if i != 0 { - p256PointDouble(xOut, yOut, zOut, xOut, yOut, zOut) - } - tableOffset = 0 - for j := uint(0); j <= 32; j += 32 { - bit0 := p256GetBit(scalar, 31-i+j) - bit1 := p256GetBit(scalar, 95-i+j) - bit2 := p256GetBit(scalar, 159-i+j) - bit3 := p256GetBit(scalar, 223-i+j) - index := bit0 | (bit1 << 1) | (bit2 << 2) | (bit3 << 3) - - p256SelectAffinePoint(&px, &py, p256Precomputed[tableOffset:], index) - tableOffset += 30 * p256Limbs - - // Since scalar is less than the order of the group, we know that - // {xOut,yOut,zOut} != {px,py,1}, unless both are zero, which we handle - // below. - p256PointAddMixed(&tx, &ty, &tz, xOut, yOut, zOut, &px, &py) - // The result of pointAddMixed is incorrect if {xOut,yOut,zOut} is zero - // (a.k.a. the point at infinity). We handle that situation by - // copying the point from the table. - p256CopyConditional(xOut, &px, nIsInfinityMask) - p256CopyConditional(yOut, &py, nIsInfinityMask) - p256CopyConditional(zOut, &p256One, nIsInfinityMask) - - // Equally, the result is also wrong if the point from the table is - // zero, which happens when the index is zero. We handle that by - // only copying from {tx,ty,tz} to {xOut,yOut,zOut} if index != 0. - pIsNoninfiniteMask = nonZeroToAllOnes(index) - mask = pIsNoninfiniteMask & ^nIsInfinityMask - p256CopyConditional(xOut, &tx, mask) - p256CopyConditional(yOut, &ty, mask) - p256CopyConditional(zOut, &tz, mask) - // If p was not zero, then n is now non-zero. - nIsInfinityMask &= ^pIsNoninfiniteMask - } - } -} - -// p256PointToAffine converts a Jacobian point to an affine point. If the input -// is the point at infinity then it returns (0, 0) in constant time. -func p256PointToAffine(xOut, yOut, x, y, z *[p256Limbs]uint32) { - var zInv, zInvSq [p256Limbs]uint32 - - p256Invert(&zInv, z) - p256Square(&zInvSq, &zInv) - p256Mul(xOut, x, &zInvSq) - p256Mul(&zInv, &zInv, &zInvSq) - p256Mul(yOut, y, &zInv) -} - -// p256ToAffine returns a pair of *big.Int containing the affine representation -// of {x,y,z}. -func p256ToAffine(x, y, z *[p256Limbs]uint32) (xOut, yOut *big.Int) { - var xx, yy [p256Limbs]uint32 - p256PointToAffine(&xx, &yy, x, y, z) - return p256ToBig(&xx), p256ToBig(&yy) -} - -// p256ScalarMult sets {xOut,yOut,zOut} = scalar*{x,y}. -func p256ScalarMult(xOut, yOut, zOut, x, y *[p256Limbs]uint32, scalar *[32]uint8) { - var px, py, pz, tx, ty, tz [p256Limbs]uint32 - var precomp [16][3][p256Limbs]uint32 - var nIsInfinityMask, index, pIsNoninfiniteMask, mask uint32 - - // We precompute 0,1,2,... times {x,y}. - precomp[1][0] = *x - precomp[1][1] = *y - precomp[1][2] = p256One - - for i := 2; i < 16; i += 2 { - p256PointDouble(&precomp[i][0], &precomp[i][1], &precomp[i][2], &precomp[i/2][0], &precomp[i/2][1], &precomp[i/2][2]) - p256PointAddMixed(&precomp[i+1][0], &precomp[i+1][1], &precomp[i+1][2], &precomp[i][0], &precomp[i][1], &precomp[i][2], x, y) - } - - for i := range xOut { - xOut[i] = 0 - } - for i := range yOut { - yOut[i] = 0 - } - for i := range zOut { - zOut[i] = 0 - } - nIsInfinityMask = ^uint32(0) - - // We add in a window of four bits each iteration and do this 64 times. - for i := 0; i < 64; i++ { - if i != 0 { - p256PointDouble(xOut, yOut, zOut, xOut, yOut, zOut) - p256PointDouble(xOut, yOut, zOut, xOut, yOut, zOut) - p256PointDouble(xOut, yOut, zOut, xOut, yOut, zOut) - p256PointDouble(xOut, yOut, zOut, xOut, yOut, zOut) - } - - index = uint32(scalar[31-i/2]) - if (i & 1) == 1 { - index &= 15 - } else { - index >>= 4 - } - - // See the comments in scalarBaseMult about handling infinities. - p256SelectJacobianPoint(&px, &py, &pz, &precomp, index) - p256PointAdd(&tx, &ty, &tz, xOut, yOut, zOut, &px, &py, &pz) - p256CopyConditional(xOut, &px, nIsInfinityMask) - p256CopyConditional(yOut, &py, nIsInfinityMask) - p256CopyConditional(zOut, &pz, nIsInfinityMask) - - pIsNoninfiniteMask = nonZeroToAllOnes(index) - mask = pIsNoninfiniteMask & ^nIsInfinityMask - p256CopyConditional(xOut, &tx, mask) - p256CopyConditional(yOut, &ty, mask) - p256CopyConditional(zOut, &tz, mask) - nIsInfinityMask &= ^pIsNoninfiniteMask - } -} - -// p256FromBig sets out = R*in. -func p256FromBig(out *[p256Limbs]uint32, in *big.Int) { - tmp := new(big.Int).Lsh(in, 257) - tmp.Mod(tmp, p256.P) - - for i := 0; i < p256Limbs; i++ { - if bits := tmp.Bits(); len(bits) > 0 { - out[i] = uint32(bits[0]) & bottom29Bits - } else { - out[i] = 0 - } - tmp.Rsh(tmp, 29) - - i++ - if i == p256Limbs { - break - } - - if bits := tmp.Bits(); len(bits) > 0 { - out[i] = uint32(bits[0]) & bottom28Bits - } else { - out[i] = 0 - } - tmp.Rsh(tmp, 28) - } -} - -// p256ToBig returns a *big.Int containing the value of in. -func p256ToBig(in *[p256Limbs]uint32) *big.Int { - result, tmp := new(big.Int), new(big.Int) - - result.SetInt64(int64(in[p256Limbs-1])) - for i := p256Limbs - 2; i >= 0; i-- { - if (i & 1) == 0 { - result.Lsh(result, 29) - } else { - result.Lsh(result, 28) - } - tmp.SetInt64(int64(in[i])) - result.Add(result, tmp) - } - - result.Mul(result, p256RInverse) - result.Mod(result, p256.P) - return result -} diff --git a/src/pkg/crypto/hmac/hmac.go b/src/pkg/crypto/hmac/hmac.go deleted file mode 100644 index b6f4919a7..000000000 --- a/src/pkg/crypto/hmac/hmac.go +++ /dev/null @@ -1,102 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* -Package hmac implements the Keyed-Hash Message Authentication Code (HMAC) as -defined in U.S. Federal Information Processing Standards Publication 198. -An HMAC is a cryptographic hash that uses a key to sign a message. -The receiver verifies the hash by recomputing it using the same key. - -Receivers should be careful to use Equal to compare MACs in order to avoid -timing side-channels: - - // CheckMAC returns true if messageMAC is a valid HMAC tag for message. - func CheckMAC(message, messageMAC, key []byte) bool { - mac := hmac.New(sha256.New, key) - mac.Write(message) - expectedMAC := mac.Sum(nil) - return hmac.Equal(messageMAC, expectedMAC) - } -*/ -package hmac - -import ( - "crypto/subtle" - "hash" -) - -// FIPS 198: -// http://csrc.nist.gov/publications/fips/fips198/fips-198a.pdf - -// key is zero padded to the block size of the hash function -// ipad = 0x36 byte repeated for key length -// opad = 0x5c byte repeated for key length -// hmac = H([key ^ opad] H([key ^ ipad] text)) - -type hmac struct { - size int - blocksize int - key, tmp []byte - outer, inner hash.Hash -} - -func (h *hmac) tmpPad(xor byte) { - for i, k := range h.key { - h.tmp[i] = xor ^ k - } - for i := len(h.key); i < h.blocksize; i++ { - h.tmp[i] = xor - } -} - -func (h *hmac) Sum(in []byte) []byte { - origLen := len(in) - in = h.inner.Sum(in) - h.tmpPad(0x5c) - copy(h.tmp[h.blocksize:], in[origLen:]) - h.outer.Reset() - h.outer.Write(h.tmp) - return h.outer.Sum(in[:origLen]) -} - -func (h *hmac) Write(p []byte) (n int, err error) { - return h.inner.Write(p) -} - -func (h *hmac) Size() int { return h.size } - -func (h *hmac) BlockSize() int { return h.blocksize } - -func (h *hmac) Reset() { - h.inner.Reset() - h.tmpPad(0x36) - h.inner.Write(h.tmp[:h.blocksize]) -} - -// New returns a new HMAC hash using the given hash.Hash type and key. -func New(h func() hash.Hash, key []byte) hash.Hash { - hm := new(hmac) - hm.outer = h() - hm.inner = h() - hm.size = hm.inner.Size() - hm.blocksize = hm.inner.BlockSize() - hm.tmp = make([]byte, hm.blocksize+hm.size) - if len(key) > hm.blocksize { - // If key is too big, hash it. - hm.outer.Write(key) - key = hm.outer.Sum(nil) - } - hm.key = make([]byte, len(key)) - copy(hm.key, key) - hm.Reset() - return hm -} - -// Equal compares two MACs for equality without leaking timing information. -func Equal(mac1, mac2 []byte) bool { - // We don't have to be constant time if the lengths of the MACs are - // different as that suggests that a completely different hash function - // was used. - return len(mac1) == len(mac2) && subtle.ConstantTimeCompare(mac1, mac2) == 1 -} diff --git a/src/pkg/crypto/hmac/hmac_test.go b/src/pkg/crypto/hmac/hmac_test.go deleted file mode 100644 index e80b7e0ba..000000000 --- a/src/pkg/crypto/hmac/hmac_test.go +++ /dev/null @@ -1,570 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package hmac - -import ( - "crypto/md5" - "crypto/sha1" - "crypto/sha256" - "crypto/sha512" - "fmt" - "hash" - "testing" -) - -type hmacTest struct { - hash func() hash.Hash - key []byte - in []byte - out string - size int - blocksize int -} - -var hmacTests = []hmacTest{ - // Tests from US FIPS 198 - // http://csrc.nist.gov/publications/fips/fips198/fips-198a.pdf - { - sha1.New, - []byte{ - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, - 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, - 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, - 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, - 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, - }, - []byte("Sample #1"), - "4f4ca3d5d68ba7cc0a1208c9c61e9c5da0403c0a", - sha1.Size, - sha1.BlockSize, - }, - { - sha1.New, - []byte{ - 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, - 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, - 0x40, 0x41, 0x42, 0x43, - }, - []byte("Sample #2"), - "0922d3405faa3d194f82a45830737d5cc6c75d24", - sha1.Size, - sha1.BlockSize, - }, - { - sha1.New, - []byte{ - 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, - 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, - 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, - 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, - 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, - 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, - 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, - 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, - 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, - 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, - 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, - 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, - 0xb0, 0xb1, 0xb2, 0xb3, - }, - []byte("Sample #3"), - "bcf41eab8bb2d802f3d05caf7cb092ecf8d1a3aa", - sha1.Size, - sha1.BlockSize, - }, - - // Test from Plan 9. - { - md5.New, - []byte("Jefe"), - []byte("what do ya want for nothing?"), - "750c783e6ab0b503eaa86e310a5db738", - md5.Size, - md5.BlockSize, - }, - - // Tests from RFC 4231 - { - sha256.New, - []byte{ - 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, - 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, 0x0b, - 0x0b, 0x0b, 0x0b, 0x0b, - }, - []byte("Hi There"), - "b0344c61d8db38535ca8afceaf0bf12b881dc200c9833da726e9376c2e32cff7", - sha256.Size, - sha256.BlockSize, - }, - { - sha256.New, - []byte("Jefe"), - []byte("what do ya want for nothing?"), - "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843", - sha256.Size, - sha256.BlockSize, - }, - { - sha256.New, - []byte{ - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, - }, - []byte{ - 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, - 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, - 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, - 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, - 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, - 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, 0xdd, - 0xdd, 0xdd, - }, - "773ea91e36800e46854db8ebd09181a72959098b3ef8c122d9635514ced565fe", - sha256.Size, - sha256.BlockSize, - }, - { - sha256.New, - []byte{ - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, - 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, - 0x19, - }, - []byte{ - 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, - 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, - 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, - 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, - 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, - 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, 0xcd, - 0xcd, 0xcd, - }, - "82558a389a443c0ea4cc819899f2083a85f0faa3e578f8077a2e3ff46729665b", - sha256.Size, - sha256.BlockSize, - }, - { - sha256.New, - []byte{ - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, - }, - []byte("Test Using Larger Than Block-Size Key - Hash Key First"), - "60e431591ee0b67f0d8a26aacbf5b77f8e0bc6213728c5140546040f0ee37f54", - sha256.Size, - sha256.BlockSize, - }, - { - sha256.New, - []byte{ - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, - 0xaa, 0xaa, 0xaa, - }, - []byte("This is a test using a larger than block-size key " + - "and a larger than block-size data. The key needs to " + - "be hashed before being used by the HMAC algorithm."), - "9b09ffa71b942fcb27635fbcd5b0e944bfdc63644f0713938a7f51535c3a35e2", - sha256.Size, - sha256.BlockSize, - }, - - // Tests from http://csrc.nist.gov/groups/ST/toolkit/examples.html - // (truncated tag tests are left out) - { - sha1.New, - []byte{ - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, - 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, - 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, - 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, - 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, - 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, - }, - []byte("Sample message for keylen=blocklen"), - "5fd596ee78d5553c8ff4e72d266dfd192366da29", - sha1.Size, - sha1.BlockSize, - }, - { - sha1.New, - []byte{ - 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, - 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, - 0x10, 0x11, 0x12, 0x13, - }, - []byte("Sample message for keylen= chunk { - aa, bb, cc, dd := a, b, c, d - - // This is a constant condition - it is not evaluated on each iteration. - if x86 { - // MD5 was designed so that x86 processors can just iterate - // over the block data directly as uint32s, and we generate - // less code and run 1.3x faster if we take advantage of that. - // My apologies. - X = (*[16]uint32)(unsafe.Pointer(&p[0])) - } else if littleEndian && uintptr(unsafe.Pointer(&p[0]))&(unsafe.Alignof(uint32(0))-1) == 0 { - X = (*[16]uint32)(unsafe.Pointer(&p[0])) - } else { - X = &xbuf - j := 0 - for i := 0; i < 16; i++ { - X[i&15] = uint32(p[j]) | uint32(p[j+1])<<8 | uint32(p[j+2])<<16 | uint32(p[j+3])<<24 - j += 4 - } - } - - {{if .Full}} - // Round 1. - {{range $i, $s := dup 4 .Shift1}} - {{index $.Table1 $i | printf "a += (((c^d)&b)^d) + X[%d] + %d" $i | relabel}} - {{printf "a = a<<%d | a>>(32-%d) + b" $s $s | relabel}} - {{rotate}} - {{end}} - - // Round 2. - {{range $i, $s := dup 4 .Shift2}} - {{index $.Table2 $i | printf "a += (((b^c)&d)^c) + X[(1+5*%d)&15] + %d" $i | relabel}} - {{printf "a = a<<%d | a>>(32-%d) + b" $s $s | relabel}} - {{rotate}} - {{end}} - - // Round 3. - {{range $i, $s := dup 4 .Shift3}} - {{index $.Table3 $i | printf "a += (b^c^d) + X[(5+3*%d)&15] + %d" $i | relabel}} - {{printf "a = a<<%d | a>>(32-%d) + b" $s $s | relabel}} - {{rotate}} - {{end}} - - // Round 4. - {{range $i, $s := dup 4 .Shift4}} - {{index $.Table4 $i | printf "a += (c^(b|^d)) + X[(7*%d)&15] + %d" $i | relabel}} - {{printf "a = a<<%d | a>>(32-%d) + b" $s $s | relabel}} - {{rotate}} - {{end}} - {{else}} - // Round 1. - for i := uint(0); i < 16; { - {{range $s := .Shift1}} - {{printf "a += (((c^d)&b)^d) + X[i&15] + t1[i&15]" | relabel}} - {{printf "a = a<<%d | a>>(32-%d) + b" $s $s | relabel}} - i++ - {{rotate}} - {{end}} - } - - // Round 2. - for i := uint(0); i < 16; { - {{range $s := .Shift2}} - {{printf "a += (((b^c)&d)^c) + X[(1+5*i)&15] + t2[i&15]" | relabel}} - {{printf "a = a<<%d | a>>(32-%d) + b" $s $s | relabel}} - i++ - {{rotate}} - {{end}} - } - - // Round 3. - for i := uint(0); i < 16; { - {{range $s := .Shift3}} - {{printf "a += (b^c^d) + X[(5+3*i)&15] + t3[i&15]" | relabel}} - {{printf "a = a<<%d | a>>(32-%d) + b" $s $s | relabel}} - i++ - {{rotate}} - {{end}} - } - - // Round 4. - for i := uint(0); i < 16; { - {{range $s := .Shift4}} - {{printf "a += (c^(b|^d)) + X[(7*i)&15] + t4[i&15]" | relabel}} - {{printf "a = a<<%d | a>>(32-%d) + b" $s $s | relabel}} - i++ - {{rotate}} - {{end}} - } - {{end}} - - a += aa - b += bb - c += cc - d += dd - - p = p[chunk:] - } - - dig.s[0] = a - dig.s[1] = b - dig.s[2] = c - dig.s[3] = d -} -` diff --git a/src/pkg/crypto/md5/md5.go b/src/pkg/crypto/md5/md5.go deleted file mode 100644 index 8c50c6d0b..000000000 --- a/src/pkg/crypto/md5/md5.go +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -//go:generate go run gen.go -full -output md5block.go - -// Package md5 implements the MD5 hash algorithm as defined in RFC 1321. -package md5 - -import ( - "crypto" - "hash" -) - -func init() { - crypto.RegisterHash(crypto.MD5, New) -} - -// The size of an MD5 checksum in bytes. -const Size = 16 - -// The blocksize of MD5 in bytes. -const BlockSize = 64 - -const ( - chunk = 64 - init0 = 0x67452301 - init1 = 0xEFCDAB89 - init2 = 0x98BADCFE - init3 = 0x10325476 -) - -// digest represents the partial evaluation of a checksum. -type digest struct { - s [4]uint32 - x [chunk]byte - nx int - len uint64 -} - -func (d *digest) Reset() { - d.s[0] = init0 - d.s[1] = init1 - d.s[2] = init2 - d.s[3] = init3 - d.nx = 0 - d.len = 0 -} - -// New returns a new hash.Hash computing the MD5 checksum. -func New() hash.Hash { - d := new(digest) - d.Reset() - return d -} - -func (d *digest) Size() int { return Size } - -func (d *digest) BlockSize() int { return BlockSize } - -func (d *digest) Write(p []byte) (nn int, err error) { - nn = len(p) - d.len += uint64(nn) - if d.nx > 0 { - n := len(p) - if n > chunk-d.nx { - n = chunk - d.nx - } - for i := 0; i < n; i++ { - d.x[d.nx+i] = p[i] - } - d.nx += n - if d.nx == chunk { - block(d, d.x[0:chunk]) - d.nx = 0 - } - p = p[n:] - } - if len(p) >= chunk { - n := len(p) &^ (chunk - 1) - block(d, p[:n]) - p = p[n:] - } - if len(p) > 0 { - d.nx = copy(d.x[:], p) - } - return -} - -func (d0 *digest) Sum(in []byte) []byte { - // Make a copy of d0 so that caller can keep writing and summing. - d := *d0 - hash := d.checkSum() - return append(in, hash[:]...) -} - -func (d *digest) checkSum() [Size]byte { - // Padding. Add a 1 bit and 0 bits until 56 bytes mod 64. - len := d.len - var tmp [64]byte - tmp[0] = 0x80 - if len%64 < 56 { - d.Write(tmp[0 : 56-len%64]) - } else { - d.Write(tmp[0 : 64+56-len%64]) - } - - // Length in bits. - len <<= 3 - for i := uint(0); i < 8; i++ { - tmp[i] = byte(len >> (8 * i)) - } - d.Write(tmp[0:8]) - - if d.nx != 0 { - panic("d.nx != 0") - } - - var digest [Size]byte - for i, s := range d.s { - digest[i*4] = byte(s) - digest[i*4+1] = byte(s >> 8) - digest[i*4+2] = byte(s >> 16) - digest[i*4+3] = byte(s >> 24) - } - - return digest -} - -// Sum returns the MD5 checksum of the data. -func Sum(data []byte) [Size]byte { - var d digest - d.Reset() - d.Write(data) - return d.checkSum() -} diff --git a/src/pkg/crypto/md5/md5_test.go b/src/pkg/crypto/md5/md5_test.go deleted file mode 100644 index e7faf4961..000000000 --- a/src/pkg/crypto/md5/md5_test.go +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package md5 - -import ( - "crypto/rand" - "fmt" - "io" - "testing" - "unsafe" -) - -type md5Test struct { - out string - in string -} - -var golden = []md5Test{ - {"d41d8cd98f00b204e9800998ecf8427e", ""}, - {"0cc175b9c0f1b6a831c399e269772661", "a"}, - {"187ef4436122d1cc2f40dc2b92f0eba0", "ab"}, - {"900150983cd24fb0d6963f7d28e17f72", "abc"}, - {"e2fc714c4727ee9395f324cd2e7f331f", "abcd"}, - {"ab56b4d92b40713acc5af89985d4b786", "abcde"}, - {"e80b5017098950fc58aad83c8c14978e", "abcdef"}, - {"7ac66c0f148de9519b8bd264312c4d64", "abcdefg"}, - {"e8dc4081b13434b45189a720b77b6818", "abcdefgh"}, - {"8aa99b1f439ff71293e95357bac6fd94", "abcdefghi"}, - {"a925576942e94b2ef57a066101b48876", "abcdefghij"}, - {"d747fc1719c7eacb84058196cfe56d57", "Discard medicine more than two years old."}, - {"bff2dcb37ef3a44ba43ab144768ca837", "He who has a shady past knows that nice guys finish last."}, - {"0441015ecb54a7342d017ed1bcfdbea5", "I wouldn't marry him with a ten foot pole."}, - {"9e3cac8e9e9757a60c3ea391130d3689", "Free! Free!/A trip/to Mars/for 900/empty jars/Burma Shave"}, - {"a0f04459b031f916a59a35cc482dc039", "The days of the digital watch are numbered. -Tom Stoppard"}, - {"e7a48e0fe884faf31475d2a04b1362cc", "Nepal premier won't resign."}, - {"637d2fe925c07c113800509964fb0e06", "For every action there is an equal and opposite government program."}, - {"834a8d18d5c6562119cf4c7f5086cb71", "His money is twice tainted: 'taint yours and 'taint mine."}, - {"de3a4d2fd6c73ec2db2abad23b444281", "There is no reason for any individual to have a computer in their home. -Ken Olsen, 1977"}, - {"acf203f997e2cf74ea3aff86985aefaf", "It's a tiny change to the code and not completely disgusting. - Bob Manchek"}, - {"e1c1384cb4d2221dfdd7c795a4222c9a", "size: a.out: bad magic"}, - {"c90f3ddecc54f34228c063d7525bf644", "The major problem is with sendmail. -Mark Horton"}, - {"cdf7ab6c1fd49bd9933c43f3ea5af185", "Give me a rock, paper and scissors and I will move the world. CCFestoon"}, - {"83bc85234942fc883c063cbd7f0ad5d0", "If the enemy is within range, then so are you."}, - {"277cbe255686b48dd7e8f389394d9299", "It's well we cannot hear the screams/That we create in others' dreams."}, - {"fd3fb0a7ffb8af16603f3d3af98f8e1f", "You remind me of a TV show, but that's all right: I watch it anyway."}, - {"469b13a78ebf297ecda64d4723655154", "C is as portable as Stonehedge!!"}, - {"63eb3a2f466410104731c4b037600110", "Even if I could be Shakespeare, I think I should still choose to be Faraday. - A. Huxley"}, - {"72c2ed7592debca1c90fc0100f931a2f", "The fugacity of a constituent in a mixture of gases at a given temperature is proportional to its mole fraction. Lewis-Randall Rule"}, - {"132f7619d33b523b1d9e5bd8e0928355", "How can you write a big system without C++? -Paul Glick"}, -} - -func TestGolden(t *testing.T) { - for i := 0; i < len(golden); i++ { - g := golden[i] - s := fmt.Sprintf("%x", Sum([]byte(g.in))) - if s != g.out { - t.Fatalf("Sum function: md5(%s) = %s want %s", g.in, s, g.out) - } - c := New() - buf := make([]byte, len(g.in)+4) - for j := 0; j < 3+4; j++ { - if j < 2 { - io.WriteString(c, g.in) - } else if j == 2 { - io.WriteString(c, g.in[0:len(g.in)/2]) - c.Sum(nil) - io.WriteString(c, g.in[len(g.in)/2:]) - } else if j > 2 { - // test unaligned write - buf = buf[1:] - copy(buf, g.in) - c.Write(buf[:len(g.in)]) - } - s := fmt.Sprintf("%x", c.Sum(nil)) - if s != g.out { - t.Fatalf("md5[%d](%s) = %s want %s", j, g.in, s, g.out) - } - c.Reset() - } - } -} - -func TestLarge(t *testing.T) { - const N = 10000 - ok := "2bb571599a4180e1d542f76904adc3df" // md5sum of "0123456789" * 1000 - block := make([]byte, 10004) - c := New() - for offset := 0; offset < 4; offset++ { - for i := 0; i < N; i++ { - block[offset+i] = '0' + byte(i%10) - } - for blockSize := 10; blockSize <= N; blockSize *= 10 { - blocks := N / blockSize - b := block[offset : offset+blockSize] - c.Reset() - for i := 0; i < blocks; i++ { - c.Write(b) - } - s := fmt.Sprintf("%x", c.Sum(nil)) - if s != ok { - t.Fatalf("md5 TestLarge offset=%d, blockSize=%d = %s want %s", offset, blockSize, s, ok) - } - } - } -} - -// Tests that blockGeneric (pure Go) and block (in assembly for amd64, 386, arm) match. -func TestBlockGeneric(t *testing.T) { - gen, asm := New().(*digest), New().(*digest) - buf := make([]byte, BlockSize*20) // arbitrary factor - rand.Read(buf) - blockGeneric(gen, buf) - block(asm, buf) - if *gen != *asm { - t.Error("block and blockGeneric resulted in different states") - } -} - -var bench = New() -var buf = make([]byte, 8192+1) -var sum = make([]byte, bench.Size()) - -func benchmarkSize(b *testing.B, size int, unaligned bool) { - b.SetBytes(int64(size)) - buf := buf - if unaligned { - if uintptr(unsafe.Pointer(&buf[0]))&(unsafe.Alignof(uint32(0))-1) == 0 { - buf = buf[1:] - } - } - b.ResetTimer() - for i := 0; i < b.N; i++ { - bench.Reset() - bench.Write(buf[:size]) - bench.Sum(sum[:0]) - } -} - -func BenchmarkHash8Bytes(b *testing.B) { - benchmarkSize(b, 8, false) -} - -func BenchmarkHash1K(b *testing.B) { - benchmarkSize(b, 1024, false) -} - -func BenchmarkHash8K(b *testing.B) { - benchmarkSize(b, 8192, false) -} - -func BenchmarkHash8BytesUnaligned(b *testing.B) { - benchmarkSize(b, 8, true) -} - -func BenchmarkHash1KUnaligned(b *testing.B) { - benchmarkSize(b, 1024, true) -} - -func BenchmarkHash8KUnaligned(b *testing.B) { - benchmarkSize(b, 8192, true) -} diff --git a/src/pkg/crypto/md5/md5block.go b/src/pkg/crypto/md5/md5block.go deleted file mode 100644 index 64e1e7c1e..000000000 --- a/src/pkg/crypto/md5/md5block.go +++ /dev/null @@ -1,265 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// DO NOT EDIT. -// Generate with: go run gen.go -full -output md5block.go - -package md5 - -import ( - "runtime" - "unsafe" -) - -const x86 = runtime.GOARCH == "amd64" || runtime.GOARCH == "386" - -var littleEndian bool - -func init() { - x := uint32(0x04030201) - y := [4]byte{0x1, 0x2, 0x3, 0x4} - littleEndian = *(*[4]byte)(unsafe.Pointer(&x)) == y -} - -func blockGeneric(dig *digest, p []byte) { - a := dig.s[0] - b := dig.s[1] - c := dig.s[2] - d := dig.s[3] - var X *[16]uint32 - var xbuf [16]uint32 - for len(p) >= chunk { - aa, bb, cc, dd := a, b, c, d - - // This is a constant condition - it is not evaluated on each iteration. - if x86 { - // MD5 was designed so that x86 processors can just iterate - // over the block data directly as uint32s, and we generate - // less code and run 1.3x faster if we take advantage of that. - // My apologies. - X = (*[16]uint32)(unsafe.Pointer(&p[0])) - } else if littleEndian && uintptr(unsafe.Pointer(&p[0]))&(unsafe.Alignof(uint32(0))-1) == 0 { - X = (*[16]uint32)(unsafe.Pointer(&p[0])) - } else { - X = &xbuf - j := 0 - for i := 0; i < 16; i++ { - X[i&15] = uint32(p[j]) | uint32(p[j+1])<<8 | uint32(p[j+2])<<16 | uint32(p[j+3])<<24 - j += 4 - } - } - - // Round 1. - - a += (((c ^ d) & b) ^ d) + X[0] + 3614090360 - a = a<<7 | a>>(32-7) + b - - d += (((b ^ c) & a) ^ c) + X[1] + 3905402710 - d = d<<12 | d>>(32-12) + a - - c += (((a ^ b) & d) ^ b) + X[2] + 606105819 - c = c<<17 | c>>(32-17) + d - - b += (((d ^ a) & c) ^ a) + X[3] + 3250441966 - b = b<<22 | b>>(32-22) + c - - a += (((c ^ d) & b) ^ d) + X[4] + 4118548399 - a = a<<7 | a>>(32-7) + b - - d += (((b ^ c) & a) ^ c) + X[5] + 1200080426 - d = d<<12 | d>>(32-12) + a - - c += (((a ^ b) & d) ^ b) + X[6] + 2821735955 - c = c<<17 | c>>(32-17) + d - - b += (((d ^ a) & c) ^ a) + X[7] + 4249261313 - b = b<<22 | b>>(32-22) + c - - a += (((c ^ d) & b) ^ d) + X[8] + 1770035416 - a = a<<7 | a>>(32-7) + b - - d += (((b ^ c) & a) ^ c) + X[9] + 2336552879 - d = d<<12 | d>>(32-12) + a - - c += (((a ^ b) & d) ^ b) + X[10] + 4294925233 - c = c<<17 | c>>(32-17) + d - - b += (((d ^ a) & c) ^ a) + X[11] + 2304563134 - b = b<<22 | b>>(32-22) + c - - a += (((c ^ d) & b) ^ d) + X[12] + 1804603682 - a = a<<7 | a>>(32-7) + b - - d += (((b ^ c) & a) ^ c) + X[13] + 4254626195 - d = d<<12 | d>>(32-12) + a - - c += (((a ^ b) & d) ^ b) + X[14] + 2792965006 - c = c<<17 | c>>(32-17) + d - - b += (((d ^ a) & c) ^ a) + X[15] + 1236535329 - b = b<<22 | b>>(32-22) + c - - // Round 2. - - a += (((b ^ c) & d) ^ c) + X[(1+5*0)&15] + 4129170786 - a = a<<5 | a>>(32-5) + b - - d += (((a ^ b) & c) ^ b) + X[(1+5*1)&15] + 3225465664 - d = d<<9 | d>>(32-9) + a - - c += (((d ^ a) & b) ^ a) + X[(1+5*2)&15] + 643717713 - c = c<<14 | c>>(32-14) + d - - b += (((c ^ d) & a) ^ d) + X[(1+5*3)&15] + 3921069994 - b = b<<20 | b>>(32-20) + c - - a += (((b ^ c) & d) ^ c) + X[(1+5*4)&15] + 3593408605 - a = a<<5 | a>>(32-5) + b - - d += (((a ^ b) & c) ^ b) + X[(1+5*5)&15] + 38016083 - d = d<<9 | d>>(32-9) + a - - c += (((d ^ a) & b) ^ a) + X[(1+5*6)&15] + 3634488961 - c = c<<14 | c>>(32-14) + d - - b += (((c ^ d) & a) ^ d) + X[(1+5*7)&15] + 3889429448 - b = b<<20 | b>>(32-20) + c - - a += (((b ^ c) & d) ^ c) + X[(1+5*8)&15] + 568446438 - a = a<<5 | a>>(32-5) + b - - d += (((a ^ b) & c) ^ b) + X[(1+5*9)&15] + 3275163606 - d = d<<9 | d>>(32-9) + a - - c += (((d ^ a) & b) ^ a) + X[(1+5*10)&15] + 4107603335 - c = c<<14 | c>>(32-14) + d - - b += (((c ^ d) & a) ^ d) + X[(1+5*11)&15] + 1163531501 - b = b<<20 | b>>(32-20) + c - - a += (((b ^ c) & d) ^ c) + X[(1+5*12)&15] + 2850285829 - a = a<<5 | a>>(32-5) + b - - d += (((a ^ b) & c) ^ b) + X[(1+5*13)&15] + 4243563512 - d = d<<9 | d>>(32-9) + a - - c += (((d ^ a) & b) ^ a) + X[(1+5*14)&15] + 1735328473 - c = c<<14 | c>>(32-14) + d - - b += (((c ^ d) & a) ^ d) + X[(1+5*15)&15] + 2368359562 - b = b<<20 | b>>(32-20) + c - - // Round 3. - - a += (b ^ c ^ d) + X[(5+3*0)&15] + 4294588738 - a = a<<4 | a>>(32-4) + b - - d += (a ^ b ^ c) + X[(5+3*1)&15] + 2272392833 - d = d<<11 | d>>(32-11) + a - - c += (d ^ a ^ b) + X[(5+3*2)&15] + 1839030562 - c = c<<16 | c>>(32-16) + d - - b += (c ^ d ^ a) + X[(5+3*3)&15] + 4259657740 - b = b<<23 | b>>(32-23) + c - - a += (b ^ c ^ d) + X[(5+3*4)&15] + 2763975236 - a = a<<4 | a>>(32-4) + b - - d += (a ^ b ^ c) + X[(5+3*5)&15] + 1272893353 - d = d<<11 | d>>(32-11) + a - - c += (d ^ a ^ b) + X[(5+3*6)&15] + 4139469664 - c = c<<16 | c>>(32-16) + d - - b += (c ^ d ^ a) + X[(5+3*7)&15] + 3200236656 - b = b<<23 | b>>(32-23) + c - - a += (b ^ c ^ d) + X[(5+3*8)&15] + 681279174 - a = a<<4 | a>>(32-4) + b - - d += (a ^ b ^ c) + X[(5+3*9)&15] + 3936430074 - d = d<<11 | d>>(32-11) + a - - c += (d ^ a ^ b) + X[(5+3*10)&15] + 3572445317 - c = c<<16 | c>>(32-16) + d - - b += (c ^ d ^ a) + X[(5+3*11)&15] + 76029189 - b = b<<23 | b>>(32-23) + c - - a += (b ^ c ^ d) + X[(5+3*12)&15] + 3654602809 - a = a<<4 | a>>(32-4) + b - - d += (a ^ b ^ c) + X[(5+3*13)&15] + 3873151461 - d = d<<11 | d>>(32-11) + a - - c += (d ^ a ^ b) + X[(5+3*14)&15] + 530742520 - c = c<<16 | c>>(32-16) + d - - b += (c ^ d ^ a) + X[(5+3*15)&15] + 3299628645 - b = b<<23 | b>>(32-23) + c - - // Round 4. - - a += (c ^ (b | ^d)) + X[(7*0)&15] + 4096336452 - a = a<<6 | a>>(32-6) + b - - d += (b ^ (a | ^c)) + X[(7*1)&15] + 1126891415 - d = d<<10 | d>>(32-10) + a - - c += (a ^ (d | ^b)) + X[(7*2)&15] + 2878612391 - c = c<<15 | c>>(32-15) + d - - b += (d ^ (c | ^a)) + X[(7*3)&15] + 4237533241 - b = b<<21 | b>>(32-21) + c - - a += (c ^ (b | ^d)) + X[(7*4)&15] + 1700485571 - a = a<<6 | a>>(32-6) + b - - d += (b ^ (a | ^c)) + X[(7*5)&15] + 2399980690 - d = d<<10 | d>>(32-10) + a - - c += (a ^ (d | ^b)) + X[(7*6)&15] + 4293915773 - c = c<<15 | c>>(32-15) + d - - b += (d ^ (c | ^a)) + X[(7*7)&15] + 2240044497 - b = b<<21 | b>>(32-21) + c - - a += (c ^ (b | ^d)) + X[(7*8)&15] + 1873313359 - a = a<<6 | a>>(32-6) + b - - d += (b ^ (a | ^c)) + X[(7*9)&15] + 4264355552 - d = d<<10 | d>>(32-10) + a - - c += (a ^ (d | ^b)) + X[(7*10)&15] + 2734768916 - c = c<<15 | c>>(32-15) + d - - b += (d ^ (c | ^a)) + X[(7*11)&15] + 1309151649 - b = b<<21 | b>>(32-21) + c - - a += (c ^ (b | ^d)) + X[(7*12)&15] + 4149444226 - a = a<<6 | a>>(32-6) + b - - d += (b ^ (a | ^c)) + X[(7*13)&15] + 3174756917 - d = d<<10 | d>>(32-10) + a - - c += (a ^ (d | ^b)) + X[(7*14)&15] + 718787259 - c = c<<15 | c>>(32-15) + d - - b += (d ^ (c | ^a)) + X[(7*15)&15] + 3951481745 - b = b<<21 | b>>(32-21) + c - - a += aa - b += bb - c += cc - d += dd - - p = p[chunk:] - } - - dig.s[0] = a - dig.s[1] = b - dig.s[2] = c - dig.s[3] = d -} diff --git a/src/pkg/crypto/md5/md5block_386.s b/src/pkg/crypto/md5/md5block_386.s deleted file mode 100644 index 8e426d148..000000000 --- a/src/pkg/crypto/md5/md5block_386.s +++ /dev/null @@ -1,182 +0,0 @@ -// Original source: -// http://www.zorinaq.com/papers/md5-amd64.html -// http://www.zorinaq.com/papers/md5-amd64.tar.bz2 -// -// Translated from Perl generating GNU assembly into -// #defines generating 8a assembly, and adjusted for 386, -// by the Go Authors. - -#include "textflag.h" - -// MD5 optimized for AMD64. -// -// Author: Marc Bevand -// Licence: I hereby disclaim the copyright on this code and place it -// in the public domain. - -#define ROUND1(a, b, c, d, index, const, shift) \ - XORL c, BP; \ - LEAL const(a)(DI*1), a; \ - ANDL b, BP; \ - XORL d, BP; \ - MOVL (index*4)(SI), DI; \ - ADDL BP, a; \ - ROLL $shift, a; \ - MOVL c, BP; \ - ADDL b, a - -#define ROUND2(a, b, c, d, index, const, shift) \ - LEAL const(a)(DI*1),a; \ - MOVL d, DI; \ - ANDL b, DI; \ - MOVL d, BP; \ - NOTL BP; \ - ANDL c, BP; \ - ORL DI, BP; \ - MOVL (index*4)(SI),DI; \ - ADDL BP, a; \ - ROLL $shift, a; \ - ADDL b, a - -#define ROUND3(a, b, c, d, index, const, shift) \ - LEAL const(a)(DI*1),a; \ - MOVL (index*4)(SI),DI; \ - XORL d, BP; \ - XORL b, BP; \ - ADDL BP, a; \ - ROLL $shift, a; \ - MOVL b, BP; \ - ADDL b, a - -#define ROUND4(a, b, c, d, index, const, shift) \ - LEAL const(a)(DI*1),a; \ - ORL b, BP; \ - XORL c, BP; \ - ADDL BP, a; \ - MOVL (index*4)(SI),DI; \ - MOVL $0xffffffff, BP; \ - ROLL $shift, a; \ - XORL c, BP; \ - ADDL b, a - -TEXT ·block(SB),NOSPLIT,$24-16 - MOVL dig+0(FP), BP - MOVL p+4(FP), SI - MOVL p_len+8(FP), DX - SHRL $6, DX - SHLL $6, DX - - LEAL (SI)(DX*1), DI - MOVL (0*4)(BP), AX - MOVL (1*4)(BP), BX - MOVL (2*4)(BP), CX - MOVL (3*4)(BP), DX - - CMPL SI, DI - JEQ end - - MOVL DI, 16(SP) - -loop: - MOVL AX, 0(SP) - MOVL BX, 4(SP) - MOVL CX, 8(SP) - MOVL DX, 12(SP) - - MOVL (0*4)(SI), DI - MOVL DX, BP - - ROUND1(AX,BX,CX,DX, 1,0xd76aa478, 7); - ROUND1(DX,AX,BX,CX, 2,0xe8c7b756,12); - ROUND1(CX,DX,AX,BX, 3,0x242070db,17); - ROUND1(BX,CX,DX,AX, 4,0xc1bdceee,22); - ROUND1(AX,BX,CX,DX, 5,0xf57c0faf, 7); - ROUND1(DX,AX,BX,CX, 6,0x4787c62a,12); - ROUND1(CX,DX,AX,BX, 7,0xa8304613,17); - ROUND1(BX,CX,DX,AX, 8,0xfd469501,22); - ROUND1(AX,BX,CX,DX, 9,0x698098d8, 7); - ROUND1(DX,AX,BX,CX,10,0x8b44f7af,12); - ROUND1(CX,DX,AX,BX,11,0xffff5bb1,17); - ROUND1(BX,CX,DX,AX,12,0x895cd7be,22); - ROUND1(AX,BX,CX,DX,13,0x6b901122, 7); - ROUND1(DX,AX,BX,CX,14,0xfd987193,12); - ROUND1(CX,DX,AX,BX,15,0xa679438e,17); - ROUND1(BX,CX,DX,AX, 0,0x49b40821,22); - - MOVL (1*4)(SI), DI - MOVL DX, BP - - ROUND2(AX,BX,CX,DX, 6,0xf61e2562, 5); - ROUND2(DX,AX,BX,CX,11,0xc040b340, 9); - ROUND2(CX,DX,AX,BX, 0,0x265e5a51,14); - ROUND2(BX,CX,DX,AX, 5,0xe9b6c7aa,20); - ROUND2(AX,BX,CX,DX,10,0xd62f105d, 5); - ROUND2(DX,AX,BX,CX,15, 0x2441453, 9); - ROUND2(CX,DX,AX,BX, 4,0xd8a1e681,14); - ROUND2(BX,CX,DX,AX, 9,0xe7d3fbc8,20); - ROUND2(AX,BX,CX,DX,14,0x21e1cde6, 5); - ROUND2(DX,AX,BX,CX, 3,0xc33707d6, 9); - ROUND2(CX,DX,AX,BX, 8,0xf4d50d87,14); - ROUND2(BX,CX,DX,AX,13,0x455a14ed,20); - ROUND2(AX,BX,CX,DX, 2,0xa9e3e905, 5); - ROUND2(DX,AX,BX,CX, 7,0xfcefa3f8, 9); - ROUND2(CX,DX,AX,BX,12,0x676f02d9,14); - ROUND2(BX,CX,DX,AX, 0,0x8d2a4c8a,20); - - MOVL (5*4)(SI), DI - MOVL CX, BP - - ROUND3(AX,BX,CX,DX, 8,0xfffa3942, 4); - ROUND3(DX,AX,BX,CX,11,0x8771f681,11); - ROUND3(CX,DX,AX,BX,14,0x6d9d6122,16); - ROUND3(BX,CX,DX,AX, 1,0xfde5380c,23); - ROUND3(AX,BX,CX,DX, 4,0xa4beea44, 4); - ROUND3(DX,AX,BX,CX, 7,0x4bdecfa9,11); - ROUND3(CX,DX,AX,BX,10,0xf6bb4b60,16); - ROUND3(BX,CX,DX,AX,13,0xbebfbc70,23); - ROUND3(AX,BX,CX,DX, 0,0x289b7ec6, 4); - ROUND3(DX,AX,BX,CX, 3,0xeaa127fa,11); - ROUND3(CX,DX,AX,BX, 6,0xd4ef3085,16); - ROUND3(BX,CX,DX,AX, 9, 0x4881d05,23); - ROUND3(AX,BX,CX,DX,12,0xd9d4d039, 4); - ROUND3(DX,AX,BX,CX,15,0xe6db99e5,11); - ROUND3(CX,DX,AX,BX, 2,0x1fa27cf8,16); - ROUND3(BX,CX,DX,AX, 0,0xc4ac5665,23); - - MOVL (0*4)(SI), DI - MOVL $0xffffffff, BP - XORL DX, BP - - ROUND4(AX,BX,CX,DX, 7,0xf4292244, 6); - ROUND4(DX,AX,BX,CX,14,0x432aff97,10); - ROUND4(CX,DX,AX,BX, 5,0xab9423a7,15); - ROUND4(BX,CX,DX,AX,12,0xfc93a039,21); - ROUND4(AX,BX,CX,DX, 3,0x655b59c3, 6); - ROUND4(DX,AX,BX,CX,10,0x8f0ccc92,10); - ROUND4(CX,DX,AX,BX, 1,0xffeff47d,15); - ROUND4(BX,CX,DX,AX, 8,0x85845dd1,21); - ROUND4(AX,BX,CX,DX,15,0x6fa87e4f, 6); - ROUND4(DX,AX,BX,CX, 6,0xfe2ce6e0,10); - ROUND4(CX,DX,AX,BX,13,0xa3014314,15); - ROUND4(BX,CX,DX,AX, 4,0x4e0811a1,21); - ROUND4(AX,BX,CX,DX,11,0xf7537e82, 6); - ROUND4(DX,AX,BX,CX, 2,0xbd3af235,10); - ROUND4(CX,DX,AX,BX, 9,0x2ad7d2bb,15); - ROUND4(BX,CX,DX,AX, 0,0xeb86d391,21); - - ADDL 0(SP), AX - ADDL 4(SP), BX - ADDL 8(SP), CX - ADDL 12(SP), DX - - ADDL $64, SI - CMPL SI, 16(SP) - JB loop - -end: - MOVL dig+0(FP), BP - MOVL AX, (0*4)(BP) - MOVL BX, (1*4)(BP) - MOVL CX, (2*4)(BP) - MOVL DX, (3*4)(BP) - RET diff --git a/src/pkg/crypto/md5/md5block_amd64.s b/src/pkg/crypto/md5/md5block_amd64.s deleted file mode 100644 index a3ae7d97b..000000000 --- a/src/pkg/crypto/md5/md5block_amd64.s +++ /dev/null @@ -1,179 +0,0 @@ -// Original source: -// http://www.zorinaq.com/papers/md5-amd64.html -// http://www.zorinaq.com/papers/md5-amd64.tar.bz2 -// -// Translated from Perl generating GNU assembly into -// #defines generating 6a assembly by the Go Authors. - -#include "textflag.h" - -// MD5 optimized for AMD64. -// -// Author: Marc Bevand -// Licence: I hereby disclaim the copyright on this code and place it -// in the public domain. - -TEXT ·block(SB),NOSPLIT,$0-32 - MOVQ dig+0(FP), BP - MOVQ p+8(FP), SI - MOVQ p_len+16(FP), DX - SHRQ $6, DX - SHLQ $6, DX - - LEAQ (SI)(DX*1), DI - MOVL (0*4)(BP), AX - MOVL (1*4)(BP), BX - MOVL (2*4)(BP), CX - MOVL (3*4)(BP), DX - - CMPQ SI, DI - JEQ end - -loop: - MOVL AX, R12 - MOVL BX, R13 - MOVL CX, R14 - MOVL DX, R15 - - MOVL (0*4)(SI), R8 - MOVL DX, R9 - -#define ROUND1(a, b, c, d, index, const, shift) \ - XORL c, R9; \ - LEAL const(a)(R8*1), a; \ - ANDL b, R9; \ - XORL d, R9; \ - MOVL (index*4)(SI), R8; \ - ADDL R9, a; \ - ROLL $shift, a; \ - MOVL c, R9; \ - ADDL b, a - - ROUND1(AX,BX,CX,DX, 1,0xd76aa478, 7); - ROUND1(DX,AX,BX,CX, 2,0xe8c7b756,12); - ROUND1(CX,DX,AX,BX, 3,0x242070db,17); - ROUND1(BX,CX,DX,AX, 4,0xc1bdceee,22); - ROUND1(AX,BX,CX,DX, 5,0xf57c0faf, 7); - ROUND1(DX,AX,BX,CX, 6,0x4787c62a,12); - ROUND1(CX,DX,AX,BX, 7,0xa8304613,17); - ROUND1(BX,CX,DX,AX, 8,0xfd469501,22); - ROUND1(AX,BX,CX,DX, 9,0x698098d8, 7); - ROUND1(DX,AX,BX,CX,10,0x8b44f7af,12); - ROUND1(CX,DX,AX,BX,11,0xffff5bb1,17); - ROUND1(BX,CX,DX,AX,12,0x895cd7be,22); - ROUND1(AX,BX,CX,DX,13,0x6b901122, 7); - ROUND1(DX,AX,BX,CX,14,0xfd987193,12); - ROUND1(CX,DX,AX,BX,15,0xa679438e,17); - ROUND1(BX,CX,DX,AX, 0,0x49b40821,22); - - MOVL (1*4)(SI), R8 - MOVL DX, R9 - MOVL DX, R10 - -#define ROUND2(a, b, c, d, index, const, shift) \ - NOTL R9; \ - LEAL const(a)(R8*1),a; \ - ANDL b, R10; \ - ANDL c, R9; \ - MOVL (index*4)(SI),R8; \ - ORL R9, R10; \ - MOVL c, R9; \ - ADDL R10, a; \ - MOVL c, R10; \ - ROLL $shift, a; \ - ADDL b, a - - ROUND2(AX,BX,CX,DX, 6,0xf61e2562, 5); - ROUND2(DX,AX,BX,CX,11,0xc040b340, 9); - ROUND2(CX,DX,AX,BX, 0,0x265e5a51,14); - ROUND2(BX,CX,DX,AX, 5,0xe9b6c7aa,20); - ROUND2(AX,BX,CX,DX,10,0xd62f105d, 5); - ROUND2(DX,AX,BX,CX,15, 0x2441453, 9); - ROUND2(CX,DX,AX,BX, 4,0xd8a1e681,14); - ROUND2(BX,CX,DX,AX, 9,0xe7d3fbc8,20); - ROUND2(AX,BX,CX,DX,14,0x21e1cde6, 5); - ROUND2(DX,AX,BX,CX, 3,0xc33707d6, 9); - ROUND2(CX,DX,AX,BX, 8,0xf4d50d87,14); - ROUND2(BX,CX,DX,AX,13,0x455a14ed,20); - ROUND2(AX,BX,CX,DX, 2,0xa9e3e905, 5); - ROUND2(DX,AX,BX,CX, 7,0xfcefa3f8, 9); - ROUND2(CX,DX,AX,BX,12,0x676f02d9,14); - ROUND2(BX,CX,DX,AX, 0,0x8d2a4c8a,20); - - MOVL (5*4)(SI), R8 - MOVL CX, R9 - -#define ROUND3(a, b, c, d, index, const, shift) \ - LEAL const(a)(R8*1),a; \ - MOVL (index*4)(SI),R8; \ - XORL d, R9; \ - XORL b, R9; \ - ADDL R9, a; \ - ROLL $shift, a; \ - MOVL b, R9; \ - ADDL b, a - - ROUND3(AX,BX,CX,DX, 8,0xfffa3942, 4); - ROUND3(DX,AX,BX,CX,11,0x8771f681,11); - ROUND3(CX,DX,AX,BX,14,0x6d9d6122,16); - ROUND3(BX,CX,DX,AX, 1,0xfde5380c,23); - ROUND3(AX,BX,CX,DX, 4,0xa4beea44, 4); - ROUND3(DX,AX,BX,CX, 7,0x4bdecfa9,11); - ROUND3(CX,DX,AX,BX,10,0xf6bb4b60,16); - ROUND3(BX,CX,DX,AX,13,0xbebfbc70,23); - ROUND3(AX,BX,CX,DX, 0,0x289b7ec6, 4); - ROUND3(DX,AX,BX,CX, 3,0xeaa127fa,11); - ROUND3(CX,DX,AX,BX, 6,0xd4ef3085,16); - ROUND3(BX,CX,DX,AX, 9, 0x4881d05,23); - ROUND3(AX,BX,CX,DX,12,0xd9d4d039, 4); - ROUND3(DX,AX,BX,CX,15,0xe6db99e5,11); - ROUND3(CX,DX,AX,BX, 2,0x1fa27cf8,16); - ROUND3(BX,CX,DX,AX, 0,0xc4ac5665,23); - - MOVL (0*4)(SI), R8 - MOVL $0xffffffff, R9 - XORL DX, R9 - -#define ROUND4(a, b, c, d, index, const, shift) \ - LEAL const(a)(R8*1),a; \ - ORL b, R9; \ - XORL c, R9; \ - ADDL R9, a; \ - MOVL (index*4)(SI),R8; \ - MOVL $0xffffffff, R9; \ - ROLL $shift, a; \ - XORL c, R9; \ - ADDL b, a - - ROUND4(AX,BX,CX,DX, 7,0xf4292244, 6); - ROUND4(DX,AX,BX,CX,14,0x432aff97,10); - ROUND4(CX,DX,AX,BX, 5,0xab9423a7,15); - ROUND4(BX,CX,DX,AX,12,0xfc93a039,21); - ROUND4(AX,BX,CX,DX, 3,0x655b59c3, 6); - ROUND4(DX,AX,BX,CX,10,0x8f0ccc92,10); - ROUND4(CX,DX,AX,BX, 1,0xffeff47d,15); - ROUND4(BX,CX,DX,AX, 8,0x85845dd1,21); - ROUND4(AX,BX,CX,DX,15,0x6fa87e4f, 6); - ROUND4(DX,AX,BX,CX, 6,0xfe2ce6e0,10); - ROUND4(CX,DX,AX,BX,13,0xa3014314,15); - ROUND4(BX,CX,DX,AX, 4,0x4e0811a1,21); - ROUND4(AX,BX,CX,DX,11,0xf7537e82, 6); - ROUND4(DX,AX,BX,CX, 2,0xbd3af235,10); - ROUND4(CX,DX,AX,BX, 9,0x2ad7d2bb,15); - ROUND4(BX,CX,DX,AX, 0,0xeb86d391,21); - - ADDL R12, AX - ADDL R13, BX - ADDL R14, CX - ADDL R15, DX - - ADDQ $64, SI - CMPQ SI, DI - JB loop - -end: - MOVL AX, (0*4)(BP) - MOVL BX, (1*4)(BP) - MOVL CX, (2*4)(BP) - MOVL DX, (3*4)(BP) - RET diff --git a/src/pkg/crypto/md5/md5block_amd64p32.s b/src/pkg/crypto/md5/md5block_amd64p32.s deleted file mode 100644 index d918a67c5..000000000 --- a/src/pkg/crypto/md5/md5block_amd64p32.s +++ /dev/null @@ -1,184 +0,0 @@ -// Original source: -// http://www.zorinaq.com/papers/md5-amd64.html -// http://www.zorinaq.com/papers/md5-amd64.tar.bz2 -// -// Translated from Perl generating GNU assembly into -// #defines generating 6a assembly by the Go Authors. -// -// Restrictions to make code safe for Native Client: -// replace BP with R11, reloaded before use at return. -// replace R15 with R11. - -#include "textflag.h" - -// MD5 optimized for AMD64. -// -// Author: Marc Bevand -// Licence: I hereby disclaim the copyright on this code and place it -// in the public domain. - -TEXT ·block(SB),NOSPLIT,$0-32 - MOVL dig+0(FP), R11 - MOVL p+4(FP), SI - MOVL p_len+8(FP), DX - SHRQ $6, DX - SHLQ $6, DX - - LEAQ (SI)(DX*1), DI - MOVL (0*4)(R11), AX - MOVL (1*4)(R11), BX - MOVL (2*4)(R11), CX - MOVL (3*4)(R11), DX - - CMPQ SI, DI - JEQ end - -loop: - MOVL AX, R12 - MOVL BX, R13 - MOVL CX, R14 - MOVL DX, R11 - - MOVL (0*4)(SI), R8 - MOVL DX, R9 - -#define ROUND1(a, b, c, d, index, const, shift) \ - XORL c, R9; \ - LEAL const(a)(R8*1), a; \ - ANDL b, R9; \ - XORL d, R9; \ - MOVL (index*4)(SI), R8; \ - ADDL R9, a; \ - ROLL $shift, a; \ - MOVL c, R9; \ - ADDL b, a - - ROUND1(AX,BX,CX,DX, 1,0xd76aa478, 7); - ROUND1(DX,AX,BX,CX, 2,0xe8c7b756,12); - ROUND1(CX,DX,AX,BX, 3,0x242070db,17); - ROUND1(BX,CX,DX,AX, 4,0xc1bdceee,22); - ROUND1(AX,BX,CX,DX, 5,0xf57c0faf, 7); - ROUND1(DX,AX,BX,CX, 6,0x4787c62a,12); - ROUND1(CX,DX,AX,BX, 7,0xa8304613,17); - ROUND1(BX,CX,DX,AX, 8,0xfd469501,22); - ROUND1(AX,BX,CX,DX, 9,0x698098d8, 7); - ROUND1(DX,AX,BX,CX,10,0x8b44f7af,12); - ROUND1(CX,DX,AX,BX,11,0xffff5bb1,17); - ROUND1(BX,CX,DX,AX,12,0x895cd7be,22); - ROUND1(AX,BX,CX,DX,13,0x6b901122, 7); - ROUND1(DX,AX,BX,CX,14,0xfd987193,12); - ROUND1(CX,DX,AX,BX,15,0xa679438e,17); - ROUND1(BX,CX,DX,AX, 0,0x49b40821,22); - - MOVL (1*4)(SI), R8 - MOVL DX, R9 - MOVL DX, R10 - -#define ROUND2(a, b, c, d, index, const, shift) \ - NOTL R9; \ - LEAL const(a)(R8*1),a; \ - ANDL b, R10; \ - ANDL c, R9; \ - MOVL (index*4)(SI),R8; \ - ORL R9, R10; \ - MOVL c, R9; \ - ADDL R10, a; \ - MOVL c, R10; \ - ROLL $shift, a; \ - ADDL b, a - - ROUND2(AX,BX,CX,DX, 6,0xf61e2562, 5); - ROUND2(DX,AX,BX,CX,11,0xc040b340, 9); - ROUND2(CX,DX,AX,BX, 0,0x265e5a51,14); - ROUND2(BX,CX,DX,AX, 5,0xe9b6c7aa,20); - ROUND2(AX,BX,CX,DX,10,0xd62f105d, 5); - ROUND2(DX,AX,BX,CX,15, 0x2441453, 9); - ROUND2(CX,DX,AX,BX, 4,0xd8a1e681,14); - ROUND2(BX,CX,DX,AX, 9,0xe7d3fbc8,20); - ROUND2(AX,BX,CX,DX,14,0x21e1cde6, 5); - ROUND2(DX,AX,BX,CX, 3,0xc33707d6, 9); - ROUND2(CX,DX,AX,BX, 8,0xf4d50d87,14); - ROUND2(BX,CX,DX,AX,13,0x455a14ed,20); - ROUND2(AX,BX,CX,DX, 2,0xa9e3e905, 5); - ROUND2(DX,AX,BX,CX, 7,0xfcefa3f8, 9); - ROUND2(CX,DX,AX,BX,12,0x676f02d9,14); - ROUND2(BX,CX,DX,AX, 0,0x8d2a4c8a,20); - - MOVL (5*4)(SI), R8 - MOVL CX, R9 - -#define ROUND3(a, b, c, d, index, const, shift) \ - LEAL const(a)(R8*1),a; \ - MOVL (index*4)(SI),R8; \ - XORL d, R9; \ - XORL b, R9; \ - ADDL R9, a; \ - ROLL $shift, a; \ - MOVL b, R9; \ - ADDL b, a - - ROUND3(AX,BX,CX,DX, 8,0xfffa3942, 4); - ROUND3(DX,AX,BX,CX,11,0x8771f681,11); - ROUND3(CX,DX,AX,BX,14,0x6d9d6122,16); - ROUND3(BX,CX,DX,AX, 1,0xfde5380c,23); - ROUND3(AX,BX,CX,DX, 4,0xa4beea44, 4); - ROUND3(DX,AX,BX,CX, 7,0x4bdecfa9,11); - ROUND3(CX,DX,AX,BX,10,0xf6bb4b60,16); - ROUND3(BX,CX,DX,AX,13,0xbebfbc70,23); - ROUND3(AX,BX,CX,DX, 0,0x289b7ec6, 4); - ROUND3(DX,AX,BX,CX, 3,0xeaa127fa,11); - ROUND3(CX,DX,AX,BX, 6,0xd4ef3085,16); - ROUND3(BX,CX,DX,AX, 9, 0x4881d05,23); - ROUND3(AX,BX,CX,DX,12,0xd9d4d039, 4); - ROUND3(DX,AX,BX,CX,15,0xe6db99e5,11); - ROUND3(CX,DX,AX,BX, 2,0x1fa27cf8,16); - ROUND3(BX,CX,DX,AX, 0,0xc4ac5665,23); - - MOVL (0*4)(SI), R8 - MOVL $0xffffffff, R9 - XORL DX, R9 - -#define ROUND4(a, b, c, d, index, const, shift) \ - LEAL const(a)(R8*1),a; \ - ORL b, R9; \ - XORL c, R9; \ - ADDL R9, a; \ - MOVL (index*4)(SI),R8; \ - MOVL $0xffffffff, R9; \ - ROLL $shift, a; \ - XORL c, R9; \ - ADDL b, a - - ROUND4(AX,BX,CX,DX, 7,0xf4292244, 6); - ROUND4(DX,AX,BX,CX,14,0x432aff97,10); - ROUND4(CX,DX,AX,BX, 5,0xab9423a7,15); - ROUND4(BX,CX,DX,AX,12,0xfc93a039,21); - ROUND4(AX,BX,CX,DX, 3,0x655b59c3, 6); - ROUND4(DX,AX,BX,CX,10,0x8f0ccc92,10); - ROUND4(CX,DX,AX,BX, 1,0xffeff47d,15); - ROUND4(BX,CX,DX,AX, 8,0x85845dd1,21); - ROUND4(AX,BX,CX,DX,15,0x6fa87e4f, 6); - ROUND4(DX,AX,BX,CX, 6,0xfe2ce6e0,10); - ROUND4(CX,DX,AX,BX,13,0xa3014314,15); - ROUND4(BX,CX,DX,AX, 4,0x4e0811a1,21); - ROUND4(AX,BX,CX,DX,11,0xf7537e82, 6); - ROUND4(DX,AX,BX,CX, 2,0xbd3af235,10); - ROUND4(CX,DX,AX,BX, 9,0x2ad7d2bb,15); - ROUND4(BX,CX,DX,AX, 0,0xeb86d391,21); - - ADDL R12, AX - ADDL R13, BX - ADDL R14, CX - ADDL R11, DX - - ADDQ $64, SI - CMPQ SI, DI - JB loop - -end: - MOVL dig+0(FP), R11 - MOVL AX, (0*4)(R11) - MOVL BX, (1*4)(R11) - MOVL CX, (2*4)(R11) - MOVL DX, (3*4)(R11) - RET diff --git a/src/pkg/crypto/md5/md5block_arm.s b/src/pkg/crypto/md5/md5block_arm.s deleted file mode 100644 index 3b26e549b..000000000 --- a/src/pkg/crypto/md5/md5block_arm.s +++ /dev/null @@ -1,299 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// -// ARM version of md5block.go - -#include "textflag.h" - -// Register definitions -table = 0 // Pointer to MD5 constants table -data = 1 // Pointer to data to hash -a = 2 // MD5 accumulator -b = 3 // MD5 accumulator -c = 4 // MD5 accumulator -d = 5 // MD5 accumulator -c0 = 6 // MD5 constant -c1 = 7 // MD5 constant -c2 = 8 // MD5 constant -// r9, r10 are forbidden -// r11 is OK provided you check the assembler that no synthetic instructions use it -c3 = 11 // MD5 constant -t0 = 12 // temporary -t1 = 14 // temporary - -// func block(dig *digest, p []byte) -// 0(FP) is *digest -// 4(FP) is p.array (struct Slice) -// 8(FP) is p.len -//12(FP) is p.cap -// -// Stack frame -p_end = -4 // -4(SP) pointer to the end of data -p_data = -8 // -8(SP) current data pointer -buf = -8-4*16 //-72(SP) 16 words temporary buffer - // 3 words at 4..12(R13) for called routine parameters - -TEXT ·block(SB), NOSPLIT, $84-16 - MOVW p+4(FP), R(data) // pointer to the data - MOVW p_len+8(FP), R(t0) // number of bytes - ADD R(data), R(t0) - MOVW R(t0), p_end(SP) // pointer to end of data - -loop: - MOVW R(data), p_data(SP) // Save R(data) - AND.S $3, R(data), R(t0) // TST $3, R(data) not working see issue 5921 - BEQ aligned // aligned detected - skip copy - - // Copy the unaligned source data into the aligned temporary buffer - // memove(to=4(R13), from=8(R13), n=12(R13)) - Corrupts all registers - MOVW $buf(SP), R(table) // to - MOVW $64, R(c0) // n - MOVM.IB [R(table),R(data),R(c0)], (R13) - BL runtime·memmove(SB) - - // Point to the local aligned copy of the data - MOVW $buf(SP), R(data) - -aligned: - // Point to the table of constants - // A PC relative add would be cheaper than this - MOVW $·table(SB), R(table) - - // Load up initial MD5 accumulator - MOVW dig+0(FP), R(c0) - MOVM.IA (R(c0)), [R(a),R(b),R(c),R(d)] - -// a += (((c^d)&b)^d) + X[index] + const -// a = a<>(32-shift) + b -#define ROUND1(a, b, c, d, index, shift, const) \ - EOR R(c), R(d), R(t0) ; \ - AND R(b), R(t0) ; \ - EOR R(d), R(t0) ; \ - MOVW (index<<2)(R(data)), R(t1) ; \ - ADD R(t1), R(t0) ; \ - ADD R(const), R(t0) ; \ - ADD R(t0), R(a) ; \ - ADD R(a)@>(32-shift), R(b), R(a) ; - - MOVM.IA.W (R(table)), [R(c0),R(c1),R(c2),R(c3)] - ROUND1(a, b, c, d, 0, 7, c0) - ROUND1(d, a, b, c, 1, 12, c1) - ROUND1(c, d, a, b, 2, 17, c2) - ROUND1(b, c, d, a, 3, 22, c3) - - MOVM.IA.W (R(table)), [R(c0),R(c1),R(c2),R(c3)] - ROUND1(a, b, c, d, 4, 7, c0) - ROUND1(d, a, b, c, 5, 12, c1) - ROUND1(c, d, a, b, 6, 17, c2) - ROUND1(b, c, d, a, 7, 22, c3) - - MOVM.IA.W (R(table)), [R(c0),R(c1),R(c2),R(c3)] - ROUND1(a, b, c, d, 8, 7, c0) - ROUND1(d, a, b, c, 9, 12, c1) - ROUND1(c, d, a, b, 10, 17, c2) - ROUND1(b, c, d, a, 11, 22, c3) - - MOVM.IA.W (R(table)), [R(c0),R(c1),R(c2),R(c3)] - ROUND1(a, b, c, d, 12, 7, c0) - ROUND1(d, a, b, c, 13, 12, c1) - ROUND1(c, d, a, b, 14, 17, c2) - ROUND1(b, c, d, a, 15, 22, c3) - -// a += (((b^c)&d)^c) + X[index] + const -// a = a<>(32-shift) + b -#define ROUND2(a, b, c, d, index, shift, const) \ - EOR R(b), R(c), R(t0) ; \ - AND R(d), R(t0) ; \ - EOR R(c), R(t0) ; \ - MOVW (index<<2)(R(data)), R(t1) ; \ - ADD R(t1), R(t0) ; \ - ADD R(const), R(t0) ; \ - ADD R(t0), R(a) ; \ - ADD R(a)@>(32-shift), R(b), R(a) ; - - MOVM.IA.W (R(table)), [R(c0),R(c1),R(c2),R(c3)] - ROUND2(a, b, c, d, 1, 5, c0) - ROUND2(d, a, b, c, 6, 9, c1) - ROUND2(c, d, a, b, 11, 14, c2) - ROUND2(b, c, d, a, 0, 20, c3) - - MOVM.IA.W (R(table)), [R(c0),R(c1),R(c2),R(c3)] - ROUND2(a, b, c, d, 5, 5, c0) - ROUND2(d, a, b, c, 10, 9, c1) - ROUND2(c, d, a, b, 15, 14, c2) - ROUND2(b, c, d, a, 4, 20, c3) - - MOVM.IA.W (R(table)), [R(c0),R(c1),R(c2),R(c3)] - ROUND2(a, b, c, d, 9, 5, c0) - ROUND2(d, a, b, c, 14, 9, c1) - ROUND2(c, d, a, b, 3, 14, c2) - ROUND2(b, c, d, a, 8, 20, c3) - - MOVM.IA.W (R(table)), [R(c0),R(c1),R(c2),R(c3)] - ROUND2(a, b, c, d, 13, 5, c0) - ROUND2(d, a, b, c, 2, 9, c1) - ROUND2(c, d, a, b, 7, 14, c2) - ROUND2(b, c, d, a, 12, 20, c3) - -// a += (b^c^d) + X[index] + const -// a = a<>(32-shift) + b -#define ROUND3(a, b, c, d, index, shift, const) \ - EOR R(b), R(c), R(t0) ; \ - EOR R(d), R(t0) ; \ - MOVW (index<<2)(R(data)), R(t1) ; \ - ADD R(t1), R(t0) ; \ - ADD R(const), R(t0) ; \ - ADD R(t0), R(a) ; \ - ADD R(a)@>(32-shift), R(b), R(a) ; - - MOVM.IA.W (R(table)), [R(c0),R(c1),R(c2),R(c3)] - ROUND3(a, b, c, d, 5, 4, c0) - ROUND3(d, a, b, c, 8, 11, c1) - ROUND3(c, d, a, b, 11, 16, c2) - ROUND3(b, c, d, a, 14, 23, c3) - - MOVM.IA.W (R(table)), [R(c0),R(c1),R(c2),R(c3)] - ROUND3(a, b, c, d, 1, 4, c0) - ROUND3(d, a, b, c, 4, 11, c1) - ROUND3(c, d, a, b, 7, 16, c2) - ROUND3(b, c, d, a, 10, 23, c3) - - MOVM.IA.W (R(table)), [R(c0),R(c1),R(c2),R(c3)] - ROUND3(a, b, c, d, 13, 4, c0) - ROUND3(d, a, b, c, 0, 11, c1) - ROUND3(c, d, a, b, 3, 16, c2) - ROUND3(b, c, d, a, 6, 23, c3) - - MOVM.IA.W (R(table)), [R(c0),R(c1),R(c2),R(c3)] - ROUND3(a, b, c, d, 9, 4, c0) - ROUND3(d, a, b, c, 12, 11, c1) - ROUND3(c, d, a, b, 15, 16, c2) - ROUND3(b, c, d, a, 2, 23, c3) - -// a += (c^(b|^d)) + X[index] + const -// a = a<>(32-shift) + b -#define ROUND4(a, b, c, d, index, shift, const) \ - MVN R(d), R(t0) ; \ - ORR R(b), R(t0) ; \ - EOR R(c), R(t0) ; \ - MOVW (index<<2)(R(data)), R(t1) ; \ - ADD R(t1), R(t0) ; \ - ADD R(const), R(t0) ; \ - ADD R(t0), R(a) ; \ - ADD R(a)@>(32-shift), R(b), R(a) ; - - MOVM.IA.W (R(table)), [R(c0),R(c1),R(c2),R(c3)] - ROUND4(a, b, c, d, 0, 6, c0) - ROUND4(d, a, b, c, 7, 10, c1) - ROUND4(c, d, a, b, 14, 15, c2) - ROUND4(b, c, d, a, 5, 21, c3) - - MOVM.IA.W (R(table)), [R(c0),R(c1),R(c2),R(c3)] - ROUND4(a, b, c, d, 12, 6, c0) - ROUND4(d, a, b, c, 3, 10, c1) - ROUND4(c, d, a, b, 10, 15, c2) - ROUND4(b, c, d, a, 1, 21, c3) - - MOVM.IA.W (R(table)), [R(c0),R(c1),R(c2),R(c3)] - ROUND4(a, b, c, d, 8, 6, c0) - ROUND4(d, a, b, c, 15, 10, c1) - ROUND4(c, d, a, b, 6, 15, c2) - ROUND4(b, c, d, a, 13, 21, c3) - - MOVM.IA.W (R(table)), [R(c0),R(c1),R(c2),R(c3)] - ROUND4(a, b, c, d, 4, 6, c0) - ROUND4(d, a, b, c, 11, 10, c1) - ROUND4(c, d, a, b, 2, 15, c2) - ROUND4(b, c, d, a, 9, 21, c3) - - MOVW dig+0(FP), R(t0) - MOVM.IA (R(t0)), [R(c0),R(c1),R(c2),R(c3)] - - ADD R(c0), R(a) - ADD R(c1), R(b) - ADD R(c2), R(c) - ADD R(c3), R(d) - - MOVM.IA [R(a),R(b),R(c),R(d)], (R(t0)) - - MOVW p_data(SP), R(data) - MOVW p_end(SP), R(t0) - ADD $64, R(data) - CMP R(t0), R(data) - BLO loop - - RET - -// MD5 constants table - - // Round 1 - DATA ·table+0x00(SB)/4, $0xd76aa478 - DATA ·table+0x04(SB)/4, $0xe8c7b756 - DATA ·table+0x08(SB)/4, $0x242070db - DATA ·table+0x0c(SB)/4, $0xc1bdceee - DATA ·table+0x10(SB)/4, $0xf57c0faf - DATA ·table+0x14(SB)/4, $0x4787c62a - DATA ·table+0x18(SB)/4, $0xa8304613 - DATA ·table+0x1c(SB)/4, $0xfd469501 - DATA ·table+0x20(SB)/4, $0x698098d8 - DATA ·table+0x24(SB)/4, $0x8b44f7af - DATA ·table+0x28(SB)/4, $0xffff5bb1 - DATA ·table+0x2c(SB)/4, $0x895cd7be - DATA ·table+0x30(SB)/4, $0x6b901122 - DATA ·table+0x34(SB)/4, $0xfd987193 - DATA ·table+0x38(SB)/4, $0xa679438e - DATA ·table+0x3c(SB)/4, $0x49b40821 - // Round 2 - DATA ·table+0x40(SB)/4, $0xf61e2562 - DATA ·table+0x44(SB)/4, $0xc040b340 - DATA ·table+0x48(SB)/4, $0x265e5a51 - DATA ·table+0x4c(SB)/4, $0xe9b6c7aa - DATA ·table+0x50(SB)/4, $0xd62f105d - DATA ·table+0x54(SB)/4, $0x02441453 - DATA ·table+0x58(SB)/4, $0xd8a1e681 - DATA ·table+0x5c(SB)/4, $0xe7d3fbc8 - DATA ·table+0x60(SB)/4, $0x21e1cde6 - DATA ·table+0x64(SB)/4, $0xc33707d6 - DATA ·table+0x68(SB)/4, $0xf4d50d87 - DATA ·table+0x6c(SB)/4, $0x455a14ed - DATA ·table+0x70(SB)/4, $0xa9e3e905 - DATA ·table+0x74(SB)/4, $0xfcefa3f8 - DATA ·table+0x78(SB)/4, $0x676f02d9 - DATA ·table+0x7c(SB)/4, $0x8d2a4c8a - // Round 3 - DATA ·table+0x80(SB)/4, $0xfffa3942 - DATA ·table+0x84(SB)/4, $0x8771f681 - DATA ·table+0x88(SB)/4, $0x6d9d6122 - DATA ·table+0x8c(SB)/4, $0xfde5380c - DATA ·table+0x90(SB)/4, $0xa4beea44 - DATA ·table+0x94(SB)/4, $0x4bdecfa9 - DATA ·table+0x98(SB)/4, $0xf6bb4b60 - DATA ·table+0x9c(SB)/4, $0xbebfbc70 - DATA ·table+0xa0(SB)/4, $0x289b7ec6 - DATA ·table+0xa4(SB)/4, $0xeaa127fa - DATA ·table+0xa8(SB)/4, $0xd4ef3085 - DATA ·table+0xac(SB)/4, $0x04881d05 - DATA ·table+0xb0(SB)/4, $0xd9d4d039 - DATA ·table+0xb4(SB)/4, $0xe6db99e5 - DATA ·table+0xb8(SB)/4, $0x1fa27cf8 - DATA ·table+0xbc(SB)/4, $0xc4ac5665 - // Round 4 - DATA ·table+0xc0(SB)/4, $0xf4292244 - DATA ·table+0xc4(SB)/4, $0x432aff97 - DATA ·table+0xc8(SB)/4, $0xab9423a7 - DATA ·table+0xcc(SB)/4, $0xfc93a039 - DATA ·table+0xd0(SB)/4, $0x655b59c3 - DATA ·table+0xd4(SB)/4, $0x8f0ccc92 - DATA ·table+0xd8(SB)/4, $0xffeff47d - DATA ·table+0xdc(SB)/4, $0x85845dd1 - DATA ·table+0xe0(SB)/4, $0x6fa87e4f - DATA ·table+0xe4(SB)/4, $0xfe2ce6e0 - DATA ·table+0xe8(SB)/4, $0xa3014314 - DATA ·table+0xec(SB)/4, $0x4e0811a1 - DATA ·table+0xf0(SB)/4, $0xf7537e82 - DATA ·table+0xf4(SB)/4, $0xbd3af235 - DATA ·table+0xf8(SB)/4, $0x2ad7d2bb - DATA ·table+0xfc(SB)/4, $0xeb86d391 - // Global definition - GLOBL ·table(SB),8,$256 diff --git a/src/pkg/crypto/md5/md5block_decl.go b/src/pkg/crypto/md5/md5block_decl.go deleted file mode 100644 index d7956a6d2..000000000 --- a/src/pkg/crypto/md5/md5block_decl.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build amd64 amd64p32 386 arm - -package md5 - -//go:noescape - -func block(dig *digest, p []byte) diff --git a/src/pkg/crypto/md5/md5block_generic.go b/src/pkg/crypto/md5/md5block_generic.go deleted file mode 100644 index 263463e51..000000000 --- a/src/pkg/crypto/md5/md5block_generic.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !amd64,!amd64p32,!386,!arm - -package md5 - -var block = blockGeneric diff --git a/src/pkg/crypto/rand/example_test.go b/src/pkg/crypto/rand/example_test.go deleted file mode 100644 index 8a2717300..000000000 --- a/src/pkg/crypto/rand/example_test.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package rand_test - -import ( - "bytes" - "crypto/rand" - "fmt" -) - -// This example reads 10 cryptographically secure pseudorandom numbers from -// rand.Reader and writes them to a byte slice. -func ExampleRead() { - c := 10 - b := make([]byte, c) - _, err := rand.Read(b) - if err != nil { - fmt.Println("error:", err) - return - } - // The slice should now contain random bytes instead of only zeroes. - fmt.Println(bytes.Equal(b, make([]byte, c))) - - // Output: - // false -} diff --git a/src/pkg/crypto/rand/rand.go b/src/pkg/crypto/rand/rand.go deleted file mode 100644 index 4da3adb70..000000000 --- a/src/pkg/crypto/rand/rand.go +++ /dev/null @@ -1,21 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package rand implements a cryptographically secure -// pseudorandom number generator. -package rand - -import "io" - -// Reader is a global, shared instance of a cryptographically -// strong pseudo-random generator. -// On Unix-like systems, Reader reads from /dev/urandom. -// On Windows systems, Reader uses the CryptGenRandom API. -var Reader io.Reader - -// Read is a helper function that calls Reader.Read using io.ReadFull. -// On return, n == len(b) if and only if err == nil. -func Read(b []byte) (n int, err error) { - return io.ReadFull(Reader, b) -} diff --git a/src/pkg/crypto/rand/rand_linux.go b/src/pkg/crypto/rand/rand_linux.go deleted file mode 100644 index 8cb59c75d..000000000 --- a/src/pkg/crypto/rand/rand_linux.go +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package rand - -import ( - "internal/syscall" - "sync" -) - -func init() { - altGetRandom = getRandomLinux -} - -var ( - once sync.Once - useSyscall bool -) - -func pickStrategy() { - // Test whether we should use the system call or /dev/urandom. - // We'll fall back to urandom if: - // - the kernel is too old (before 3.17) - // - the machine has no entropy available (early boot + no hardware - // entropy source?) and we want to avoid blocking later. - var buf [1]byte - n, err := syscall.GetRandom(buf[:], syscall.GRND_NONBLOCK) - useSyscall = n == 1 && err == nil -} - -func getRandomLinux(p []byte) (ok bool) { - once.Do(pickStrategy) - if !useSyscall { - return false - } - n, err := syscall.GetRandom(p, 0) - return n == len(p) && err == nil -} diff --git a/src/pkg/crypto/rand/rand_test.go b/src/pkg/crypto/rand/rand_test.go deleted file mode 100644 index e46e61d37..000000000 --- a/src/pkg/crypto/rand/rand_test.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package rand - -import ( - "bytes" - "compress/flate" - "io" - "testing" -) - -func TestRead(t *testing.T) { - var n int = 4e6 - if testing.Short() { - n = 1e5 - } - b := make([]byte, n) - n, err := io.ReadFull(Reader, b) - if n != len(b) || err != nil { - t.Fatalf("ReadFull(buf) = %d, %s", n, err) - } - - var z bytes.Buffer - f, _ := flate.NewWriter(&z, 5) - f.Write(b) - f.Close() - if z.Len() < len(b)*99/100 { - t.Fatalf("Compressed %d -> %d", len(b), z.Len()) - } -} - -func TestReadEmpty(t *testing.T) { - n, err := Reader.Read(make([]byte, 0)) - if n != 0 || err != nil { - t.Fatalf("Read(make([]byte, 0)) = %d, %v", n, err) - } - n, err = Reader.Read(nil) - if n != 0 || err != nil { - t.Fatalf("Read(nil) = %d, %v", n, err) - } -} diff --git a/src/pkg/crypto/rand/rand_unix.go b/src/pkg/crypto/rand/rand_unix.go deleted file mode 100644 index 62d0fbdb3..000000000 --- a/src/pkg/crypto/rand/rand_unix.go +++ /dev/null @@ -1,147 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build darwin dragonfly freebsd linux nacl netbsd openbsd plan9 solaris - -// Unix cryptographically secure pseudorandom number -// generator. - -package rand - -import ( - "bufio" - "crypto/aes" - "crypto/cipher" - "io" - "os" - "runtime" - "sync" - "time" -) - -const urandomDevice = "/dev/urandom" - -// Easy implementation: read from /dev/urandom. -// This is sufficient on Linux, OS X, and FreeBSD. - -func init() { - if runtime.GOOS == "plan9" { - Reader = newReader(nil) - } else { - Reader = &devReader{name: urandomDevice} - } -} - -// A devReader satisfies reads by reading the file named name. -type devReader struct { - name string - f io.Reader - mu sync.Mutex -} - -// altGetRandom if non-nil specifies an OS-specific function to get -// urandom-style randomness. -var altGetRandom func([]byte) (ok bool) - -func (r *devReader) Read(b []byte) (n int, err error) { - if altGetRandom != nil && r.name == urandomDevice && altGetRandom(b) { - return len(b), nil - } - r.mu.Lock() - defer r.mu.Unlock() - if r.f == nil { - f, err := os.Open(r.name) - if f == nil { - return 0, err - } - if runtime.GOOS == "plan9" { - r.f = f - } else { - r.f = bufio.NewReader(f) - } - } - return r.f.Read(b) -} - -// Alternate pseudo-random implementation for use on -// systems without a reliable /dev/urandom. - -// newReader returns a new pseudorandom generator that -// seeds itself by reading from entropy. If entropy == nil, -// the generator seeds itself by reading from the system's -// random number generator, typically /dev/random. -// The Read method on the returned reader always returns -// the full amount asked for, or else it returns an error. -// -// The generator uses the X9.31 algorithm with AES-128, -// reseeding after every 1 MB of generated data. -func newReader(entropy io.Reader) io.Reader { - if entropy == nil { - entropy = &devReader{name: "/dev/random"} - } - return &reader{entropy: entropy} -} - -type reader struct { - mu sync.Mutex - budget int // number of bytes that can be generated - cipher cipher.Block - entropy io.Reader - time, seed, dst, key [aes.BlockSize]byte -} - -func (r *reader) Read(b []byte) (n int, err error) { - r.mu.Lock() - defer r.mu.Unlock() - n = len(b) - - for len(b) > 0 { - if r.budget == 0 { - _, err := io.ReadFull(r.entropy, r.seed[0:]) - if err != nil { - return n - len(b), err - } - _, err = io.ReadFull(r.entropy, r.key[0:]) - if err != nil { - return n - len(b), err - } - r.cipher, err = aes.NewCipher(r.key[0:]) - if err != nil { - return n - len(b), err - } - r.budget = 1 << 20 // reseed after generating 1MB - } - r.budget -= aes.BlockSize - - // ANSI X9.31 (== X9.17) algorithm, but using AES in place of 3DES. - // - // single block: - // t = encrypt(time) - // dst = encrypt(t^seed) - // seed = encrypt(t^dst) - ns := time.Now().UnixNano() - r.time[0] = byte(ns >> 56) - r.time[1] = byte(ns >> 48) - r.time[2] = byte(ns >> 40) - r.time[3] = byte(ns >> 32) - r.time[4] = byte(ns >> 24) - r.time[5] = byte(ns >> 16) - r.time[6] = byte(ns >> 8) - r.time[7] = byte(ns) - r.cipher.Encrypt(r.time[0:], r.time[0:]) - for i := 0; i < aes.BlockSize; i++ { - r.dst[i] = r.time[i] ^ r.seed[i] - } - r.cipher.Encrypt(r.dst[0:], r.dst[0:]) - for i := 0; i < aes.BlockSize; i++ { - r.seed[i] = r.time[i] ^ r.dst[i] - } - r.cipher.Encrypt(r.seed[0:], r.seed[0:]) - - m := copy(b, r.dst[0:]) - b = b[m:] - } - - return n, nil -} diff --git a/src/pkg/crypto/rand/rand_windows.go b/src/pkg/crypto/rand/rand_windows.go deleted file mode 100644 index 82b39b64a..000000000 --- a/src/pkg/crypto/rand/rand_windows.go +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Windows cryptographically secure pseudorandom number -// generator. - -package rand - -import ( - "os" - "sync" - "syscall" -) - -// Implemented by using Windows CryptoAPI 2.0. - -func init() { Reader = &rngReader{} } - -// A rngReader satisfies reads by reading from the Windows CryptGenRandom API. -type rngReader struct { - prov syscall.Handle - mu sync.Mutex -} - -func (r *rngReader) Read(b []byte) (n int, err error) { - r.mu.Lock() - if r.prov == 0 { - const provType = syscall.PROV_RSA_FULL - const flags = syscall.CRYPT_VERIFYCONTEXT | syscall.CRYPT_SILENT - err := syscall.CryptAcquireContext(&r.prov, nil, nil, provType, flags) - if err != nil { - r.mu.Unlock() - return 0, os.NewSyscallError("CryptAcquireContext", err) - } - } - r.mu.Unlock() - - if len(b) == 0 { - return 0, nil - } - err = syscall.CryptGenRandom(r.prov, uint32(len(b)), &b[0]) - if err != nil { - return 0, os.NewSyscallError("CryptGenRandom", err) - } - return len(b), nil -} diff --git a/src/pkg/crypto/rand/util.go b/src/pkg/crypto/rand/util.go deleted file mode 100644 index 5f7440785..000000000 --- a/src/pkg/crypto/rand/util.go +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package rand - -import ( - "errors" - "io" - "math/big" -) - -// smallPrimes is a list of small, prime numbers that allows us to rapidly -// exclude some fraction of composite candidates when searching for a random -// prime. This list is truncated at the point where smallPrimesProduct exceeds -// a uint64. It does not include two because we ensure that the candidates are -// odd by construction. -var smallPrimes = []uint8{ - 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, -} - -// smallPrimesProduct is the product of the values in smallPrimes and allows us -// to reduce a candidate prime by this number and then determine whether it's -// coprime to all the elements of smallPrimes without further big.Int -// operations. -var smallPrimesProduct = new(big.Int).SetUint64(16294579238595022365) - -// Prime returns a number, p, of the given size, such that p is prime -// with high probability. -// Prime will return error for any error returned by rand.Read or if bits < 2. -func Prime(rand io.Reader, bits int) (p *big.Int, err error) { - if bits < 2 { - err = errors.New("crypto/rand: prime size must be at least 2-bit") - return - } - - b := uint(bits % 8) - if b == 0 { - b = 8 - } - - bytes := make([]byte, (bits+7)/8) - p = new(big.Int) - - bigMod := new(big.Int) - - for { - _, err = io.ReadFull(rand, bytes) - if err != nil { - return nil, err - } - - // Clear bits in the first byte to make sure the candidate has a size <= bits. - bytes[0] &= uint8(int(1<= 2 { - bytes[0] |= 3 << (b - 2) - } else { - // Here b==1, because b cannot be zero. - bytes[0] |= 1 - if len(bytes) > 1 { - bytes[1] |= 0x80 - } - } - // Make the value odd since an even number this large certainly isn't prime. - bytes[len(bytes)-1] |= 1 - - p.SetBytes(bytes) - - // Calculate the value mod the product of smallPrimes. If it's - // a multiple of any of these primes we add two until it isn't. - // The probability of overflowing is minimal and can be ignored - // because we still perform Miller-Rabin tests on the result. - bigMod.Mod(p, smallPrimesProduct) - mod := bigMod.Uint64() - - NextDelta: - for delta := uint64(0); delta < 1<<20; delta += 2 { - m := mod + delta - for _, prime := range smallPrimes { - if m%uint64(prime) == 0 && (bits > 6 || m != uint64(prime)) { - continue NextDelta - } - } - - if delta > 0 { - bigMod.SetUint64(delta) - p.Add(p, bigMod) - } - break - } - - // There is a tiny possibility that, by adding delta, we caused - // the number to be one bit too long. Thus we check BitLen - // here. - if p.ProbablyPrime(20) && p.BitLen() == bits { - return - } - } -} - -// Int returns a uniform random value in [0, max). It panics if max <= 0. -func Int(rand io.Reader, max *big.Int) (n *big.Int, err error) { - if max.Sign() <= 0 { - panic("crypto/rand: argument to Int is <= 0") - } - k := (max.BitLen() + 7) / 8 - - // b is the number of bits in the most significant byte of max. - b := uint(max.BitLen() % 8) - if b == 0 { - b = 8 - } - - bytes := make([]byte, k) - n = new(big.Int) - - for { - _, err = io.ReadFull(rand, bytes) - if err != nil { - return nil, err - } - - // Clear bits in the first byte to increase the probability - // that the candidate is < max. - bytes[0] &= uint8(int(1< 256 { - return nil, KeySizeError(k) - } - var c Cipher - for i := 0; i < 256; i++ { - c.s[i] = uint32(i) - } - var j uint8 = 0 - for i := 0; i < 256; i++ { - j += uint8(c.s[i]) + key[i%k] - c.s[i], c.s[j] = c.s[j], c.s[i] - } - return &c, nil -} - -// Reset zeros the key data so that it will no longer appear in the -// process's memory. -func (c *Cipher) Reset() { - for i := range c.s { - c.s[i] = 0 - } - c.i, c.j = 0, 0 -} - -// xorKeyStreamGeneric sets dst to the result of XORing src with the -// key stream. Dst and src may be the same slice but otherwise should -// not overlap. -// -// This is the pure Go version. rc4_{amd64,386,arm}* contain assembly -// implementations. This is here for tests and to prevent bitrot. -func (c *Cipher) xorKeyStreamGeneric(dst, src []byte) { - i, j := c.i, c.j - for k, v := range src { - i += 1 - j += uint8(c.s[i]) - c.s[i], c.s[j] = c.s[j], c.s[i] - dst[k] = v ^ uint8(c.s[uint8(c.s[i]+c.s[j])]) - } - c.i, c.j = i, j -} diff --git a/src/pkg/crypto/rc4/rc4_386.s b/src/pkg/crypto/rc4/rc4_386.s deleted file mode 100644 index 54221036b..000000000 --- a/src/pkg/crypto/rc4/rc4_386.s +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "textflag.h" - -// func xorKeyStream(dst, src *byte, n int, state *[256]byte, i, j *uint8) -TEXT ·xorKeyStream(SB),NOSPLIT,$0 - MOVL dst+0(FP), DI - MOVL src+4(FP), SI - MOVL state+12(FP), BP - - MOVL i+16(FP), AX - MOVBLZX (AX), AX - MOVL j+20(FP), BX - MOVBLZX (BX), BX - CMPL n+8(FP), $0 - JEQ done - -loop: - // i += 1 - INCB AX - - // j += c.s[i] - MOVBLZX (BP)(AX*4), DX - ADDB DX, BX - MOVBLZX BX, BX - - // c.s[i], c.s[j] = c.s[j], c.s[i] - MOVBLZX (BP)(BX*4), CX - MOVB CX, (BP)(AX*4) - MOVB DX, (BP)(BX*4) - - // *dst = *src ^ c.s[c.s[i]+c.s[j]] - ADDB DX, CX - MOVBLZX CX, CX - MOVB (BP)(CX*4), CX - XORB (SI), CX - MOVBLZX CX, CX - MOVB CX, (DI) - - INCL SI - INCL DI - DECL n+8(FP) - JNE loop - -done: - MOVL i+16(FP), CX - MOVB AX, (CX) - MOVL j+20(FP), CX - MOVB BX, (CX) - - RET diff --git a/src/pkg/crypto/rc4/rc4_amd64.s b/src/pkg/crypto/rc4/rc4_amd64.s deleted file mode 100644 index 57d941c8f..000000000 --- a/src/pkg/crypto/rc4/rc4_amd64.s +++ /dev/null @@ -1,179 +0,0 @@ -// Original source: -// http://www.zorinaq.com/papers/rc4-amd64.html -// http://www.zorinaq.com/papers/rc4-amd64.tar.bz2 - -#include "textflag.h" - -// Local modifications: -// -// Transliterated from GNU to 6a assembly syntax by the Go authors. -// The comments and spacing are from the original. -// -// The new EXTEND macros avoid a bad stall on some systems after 8-bit math. -// -// The original code accumulated 64 bits of key stream in an integer -// register and then XOR'ed the key stream into the data 8 bytes at a time. -// Modified to accumulate 128 bits of key stream into an XMM register -// and then XOR the key stream into the data 16 bytes at a time. -// Approximately doubles throughput. - -// NOTE: Changing EXTEND to a no-op makes the code run 1.2x faster on Core i5 -// but makes the code run 2.0x slower on Xeon. -#define EXTEND(r) MOVBLZX r, r - -/* -** RC4 implementation optimized for AMD64. -** -** Author: Marc Bevand -** Licence: I hereby disclaim the copyright on this code and place it -** in the public domain. -** -** The code has been designed to be easily integrated into openssl: -** the exported RC4() function can replace the actual implementations -** openssl already contains. Please note that when linking with openssl, -** it requires that sizeof(RC4_INT) == 8. So openssl must be compiled -** with -DRC4_INT='unsigned long'. -** -** The throughput achieved by this code is about 320 MBytes/sec, on -** a 1.8 GHz AMD Opteron (rev C0) processor. -*/ - -TEXT ·xorKeyStream(SB),NOSPLIT,$0 - MOVQ n+16(FP), BX // rbx = ARG(len) - MOVQ src+8(FP), SI // in = ARG(in) - MOVQ dst+0(FP), DI // out = ARG(out) - MOVQ state+24(FP), BP // d = ARG(data) - MOVQ i+32(FP), AX - MOVBQZX 0(AX), CX // x = *xp - MOVQ j+40(FP), AX - MOVBQZX 0(AX), DX // y = *yp - - LEAQ (SI)(BX*1), R9 // limit = in+len - -l1: CMPQ SI, R9 // cmp in with in+len - JGE finished // jump if (in >= in+len) - - INCB CX - EXTEND(CX) - TESTL $15, CX - JZ wordloop - - MOVBLZX (BP)(CX*4), AX - - ADDB AX, DX // y += tx - EXTEND(DX) - MOVBLZX (BP)(DX*4), BX // ty = d[y] - MOVB BX, (BP)(CX*4) // d[x] = ty - ADDB AX, BX // val = ty+tx - EXTEND(BX) - MOVB AX, (BP)(DX*4) // d[y] = tx - MOVBLZX (BP)(BX*4), R8 // val = d[val] - XORB (SI), R8 // xor 1 byte - MOVB R8, (DI) - INCQ SI // in++ - INCQ DI // out++ - JMP l1 - -wordloop: - SUBQ $16, R9 - CMPQ SI, R9 - JGT end - -start: - ADDQ $16, SI // increment in - ADDQ $16, DI // increment out - - // Each KEYROUND generates one byte of key and - // inserts it into an XMM register at the given 16-bit index. - // The key state array is uint32 words only using the bottom - // byte of each word, so the 16-bit OR only copies 8 useful bits. - // We accumulate alternating bytes into X0 and X1, and then at - // the end we OR X1<<8 into X0 to produce the actual key. - // - // At the beginning of the loop, CX%16 == 0, so the 16 loads - // at state[CX], state[CX+1], ..., state[CX+15] can precompute - // (state+CX) as R12 and then become R12[0], R12[1], ... R12[15], - // without fear of the byte computation CX+15 wrapping around. - // - // The first round needs R12[0], the second needs R12[1], and so on. - // We can avoid memory stalls by starting the load for round n+1 - // before the end of round n, using the LOAD macro. - LEAQ (BP)(CX*4), R12 - -#define KEYROUND(xmm, load, off, r1, r2, index) \ - MOVBLZX (BP)(DX*4), R8; \ - MOVB r1, (BP)(DX*4); \ - load((off+1), r2); \ - MOVB R8, (off*4)(R12); \ - ADDB r1, R8; \ - EXTEND(R8); \ - PINSRW $index, (BP)(R8*4), xmm - -#define LOAD(off, reg) \ - MOVBLZX (off*4)(R12), reg; \ - ADDB reg, DX; \ - EXTEND(DX) - -#define SKIP(off, reg) - - LOAD(0, AX) - KEYROUND(X0, LOAD, 0, AX, BX, 0) - KEYROUND(X1, LOAD, 1, BX, AX, 0) - KEYROUND(X0, LOAD, 2, AX, BX, 1) - KEYROUND(X1, LOAD, 3, BX, AX, 1) - KEYROUND(X0, LOAD, 4, AX, BX, 2) - KEYROUND(X1, LOAD, 5, BX, AX, 2) - KEYROUND(X0, LOAD, 6, AX, BX, 3) - KEYROUND(X1, LOAD, 7, BX, AX, 3) - KEYROUND(X0, LOAD, 8, AX, BX, 4) - KEYROUND(X1, LOAD, 9, BX, AX, 4) - KEYROUND(X0, LOAD, 10, AX, BX, 5) - KEYROUND(X1, LOAD, 11, BX, AX, 5) - KEYROUND(X0, LOAD, 12, AX, BX, 6) - KEYROUND(X1, LOAD, 13, BX, AX, 6) - KEYROUND(X0, LOAD, 14, AX, BX, 7) - KEYROUND(X1, SKIP, 15, BX, AX, 7) - - ADDB $16, CX - - PSLLQ $8, X1 - PXOR X1, X0 - MOVOU -16(SI), X2 - PXOR X0, X2 - MOVOU X2, -16(DI) - - CMPQ SI, R9 // cmp in with in+len-16 - JLE start // jump if (in <= in+len-16) - -end: - DECB CX - ADDQ $16, R9 // tmp = in+len - - // handle the last bytes, one by one -l2: CMPQ SI, R9 // cmp in with in+len - JGE finished // jump if (in >= in+len) - - INCB CX - EXTEND(CX) - MOVBLZX (BP)(CX*4), AX - - ADDB AX, DX // y += tx - EXTEND(DX) - MOVBLZX (BP)(DX*4), BX // ty = d[y] - MOVB BX, (BP)(CX*4) // d[x] = ty - ADDB AX, BX // val = ty+tx - EXTEND(BX) - MOVB AX, (BP)(DX*4) // d[y] = tx - MOVBLZX (BP)(BX*4), R8 // val = d[val] - XORB (SI), R8 // xor 1 byte - MOVB R8, (DI) - INCQ SI // in++ - INCQ DI // out++ - JMP l2 - -finished: - MOVQ j+40(FP), BX - MOVB DX, 0(BX) - MOVQ i+32(FP), AX - MOVB CX, 0(AX) - RET diff --git a/src/pkg/crypto/rc4/rc4_amd64p32.s b/src/pkg/crypto/rc4/rc4_amd64p32.s deleted file mode 100644 index 970b34e08..000000000 --- a/src/pkg/crypto/rc4/rc4_amd64p32.s +++ /dev/null @@ -1,192 +0,0 @@ -// Original source: -// http://www.zorinaq.com/papers/rc4-amd64.html -// http://www.zorinaq.com/papers/rc4-amd64.tar.bz2 - -#include "textflag.h" - -// Local modifications: -// -// Transliterated from GNU to 6a assembly syntax by the Go authors. -// The comments and spacing are from the original. -// -// The new EXTEND macros avoid a bad stall on some systems after 8-bit math. -// -// The original code accumulated 64 bits of key stream in an integer -// register and then XOR'ed the key stream into the data 8 bytes at a time. -// Modified to accumulate 128 bits of key stream into an XMM register -// and then XOR the key stream into the data 16 bytes at a time. -// Approximately doubles throughput. -// -// Converted to amd64p32. -// -// To make safe for Native Client, avoid use of BP, R15, -// and two-register addressing modes. - -// NOTE: Changing EXTEND to a no-op makes the code run 1.2x faster on Core i5 -// but makes the code run 2.0x slower on Xeon. -#define EXTEND(r) MOVBLZX r, r - -/* -** RC4 implementation optimized for AMD64. -** -** Author: Marc Bevand -** Licence: I hereby disclaim the copyright on this code and place it -** in the public domain. -** -** The code has been designed to be easily integrated into openssl: -** the exported RC4() function can replace the actual implementations -** openssl already contains. Please note that when linking with openssl, -** it requires that sizeof(RC4_INT) == 8. So openssl must be compiled -** with -DRC4_INT='unsigned long'. -** -** The throughput achieved by this code is about 320 MBytes/sec, on -** a 1.8 GHz AMD Opteron (rev C0) processor. -*/ - -TEXT ·xorKeyStream(SB),NOSPLIT,$0 - MOVL n+8(FP), BX // rbx = ARG(len) - MOVL src+4(FP), SI // in = ARG(in) - MOVL dst+0(FP), DI // out = ARG(out) - MOVL state+12(FP), R10 // d = ARG(data) - MOVL i+16(FP), AX - MOVBQZX 0(AX), CX // x = *xp - MOVL j+20(FP), AX - MOVBQZX 0(AX), DX // y = *yp - - LEAQ (SI)(BX*1), R9 // limit = in+len - -l1: CMPQ SI, R9 // cmp in with in+len - JGE finished // jump if (in >= in+len) - - INCB CX - EXTEND(CX) - TESTL $15, CX - JZ wordloop - LEAL (R10)(CX*4), R12 - - MOVBLZX (R12), AX - - ADDB AX, DX // y += tx - EXTEND(DX) - LEAL (R10)(DX*4), R11 - MOVBLZX (R11), BX // ty = d[y] - MOVB BX, (R12) // d[x] = ty - ADDB AX, BX // val = ty+tx - EXTEND(BX) - LEAL (R10)(BX*4), R13 - MOVB AX, (R11) // d[y] = tx - MOVBLZX (R13), R8 // val = d[val] - XORB (SI), R8 // xor 1 byte - MOVB R8, (DI) - INCQ SI // in++ - INCQ DI // out++ - JMP l1 - -wordloop: - SUBQ $16, R9 - CMPQ SI, R9 - JGT end - -start: - ADDQ $16, SI // increment in - ADDQ $16, DI // increment out - - // Each KEYROUND generates one byte of key and - // inserts it into an XMM register at the given 16-bit index. - // The key state array is uint32 words only using the bottom - // byte of each word, so the 16-bit OR only copies 8 useful bits. - // We accumulate alternating bytes into X0 and X1, and then at - // the end we OR X1<<8 into X0 to produce the actual key. - // - // At the beginning of the loop, CX%16 == 0, so the 16 loads - // at state[CX], state[CX+1], ..., state[CX+15] can precompute - // (state+CX) as R12 and then become R12[0], R12[1], ... R12[15], - // without fear of the byte computation CX+15 wrapping around. - // - // The first round needs R12[0], the second needs R12[1], and so on. - // We can avoid memory stalls by starting the load for round n+1 - // before the end of round n, using the LOAD macro. - LEAQ (R10)(CX*4), R12 - -#define KEYROUND(xmm, load, off, r1, r2, index) \ - LEAL (R10)(DX*4), R11; \ - MOVBLZX (R11), R8; \ - MOVB r1, (R11); \ - load((off+1), r2); \ - MOVB R8, (off*4)(R12); \ - ADDB r1, R8; \ - EXTEND(R8); \ - LEAL (R10)(R8*4), R14; \ - PINSRW $index, (R14), xmm - -#define LOAD(off, reg) \ - MOVBLZX (off*4)(R12), reg; \ - ADDB reg, DX; \ - EXTEND(DX) - -#define SKIP(off, reg) - - LOAD(0, AX) - KEYROUND(X0, LOAD, 0, AX, BX, 0) - KEYROUND(X1, LOAD, 1, BX, AX, 0) - KEYROUND(X0, LOAD, 2, AX, BX, 1) - KEYROUND(X1, LOAD, 3, BX, AX, 1) - KEYROUND(X0, LOAD, 4, AX, BX, 2) - KEYROUND(X1, LOAD, 5, BX, AX, 2) - KEYROUND(X0, LOAD, 6, AX, BX, 3) - KEYROUND(X1, LOAD, 7, BX, AX, 3) - KEYROUND(X0, LOAD, 8, AX, BX, 4) - KEYROUND(X1, LOAD, 9, BX, AX, 4) - KEYROUND(X0, LOAD, 10, AX, BX, 5) - KEYROUND(X1, LOAD, 11, BX, AX, 5) - KEYROUND(X0, LOAD, 12, AX, BX, 6) - KEYROUND(X1, LOAD, 13, BX, AX, 6) - KEYROUND(X0, LOAD, 14, AX, BX, 7) - KEYROUND(X1, SKIP, 15, BX, AX, 7) - - ADDB $16, CX - - PSLLQ $8, X1 - PXOR X1, X0 - MOVOU -16(SI), X2 - PXOR X0, X2 - MOVOU X2, -16(DI) - - CMPQ SI, R9 // cmp in with in+len-16 - JLE start // jump if (in <= in+len-16) - -end: - DECB CX - ADDQ $16, R9 // tmp = in+len - - // handle the last bytes, one by one -l2: CMPQ SI, R9 // cmp in with in+len - JGE finished // jump if (in >= in+len) - - INCB CX - EXTEND(CX) - LEAL (R10)(CX*4), R12 - MOVBLZX (R12), AX - - ADDB AX, DX // y += tx - EXTEND(DX) - LEAL (R10)(DX*4), R11 - MOVBLZX (R11), BX // ty = d[y] - MOVB BX, (R12) // d[x] = ty - ADDB AX, BX // val = ty+tx - EXTEND(BX) - LEAL (R10)(BX*4), R13 - MOVB AX, (R11) // d[y] = tx - MOVBLZX (R13), R8 // val = d[val] - XORB (SI), R8 // xor 1 byte - MOVB R8, (DI) - INCQ SI // in++ - INCQ DI // out++ - JMP l2 - -finished: - MOVL j+20(FP), BX - MOVB DX, 0(BX) - MOVL i+16(FP), AX - MOVB CX, 0(AX) - RET diff --git a/src/pkg/crypto/rc4/rc4_arm.s b/src/pkg/crypto/rc4/rc4_arm.s deleted file mode 100644 index 51be3bf95..000000000 --- a/src/pkg/crypto/rc4/rc4_arm.s +++ /dev/null @@ -1,62 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !nacl - -#include "textflag.h" - -// Registers -dst = 0 -src = 1 -n = 2 -state = 3 -pi = 4 -pj = 5 -i = 6 -j = 7 -k = 8 -t = 11 -t2 = 12 - -// func xorKeyStream(dst, src *byte, n int, state *[256]byte, i, j *uint8) -TEXT ·xorKeyStream(SB),NOSPLIT,$0 - MOVW 0(FP), R(dst) - MOVW 4(FP), R(src) - MOVW 8(FP), R(n) - MOVW 12(FP), R(state) - MOVW 16(FP), R(pi) - MOVW 20(FP), R(pj) - MOVBU (R(pi)), R(i) - MOVBU (R(pj)), R(j) - MOVW $0, R(k) - -loop: - // i += 1; j += state[i] - ADD $1, R(i) - AND $0xff, R(i) - MOVBU R(i)<<2(R(state)), R(t) - ADD R(t), R(j) - AND $0xff, R(j) - - // swap state[i] <-> state[j] - MOVBU R(j)<<2(R(state)), R(t2) - MOVB R(t2), R(i)<<2(R(state)) - MOVB R(t), R(j)<<2(R(state)) - - // dst[k] = src[k] ^ state[state[i] + state[j]] - ADD R(t2), R(t) - AND $0xff, R(t) - MOVBU R(t)<<2(R(state)), R(t) - MOVBU R(k)<<0(R(src)), R(t2) - EOR R(t), R(t2) - MOVB R(t2), R(k)<<0(R(dst)) - - ADD $1, R(k) - CMP R(k), R(n) - BNE loop - -done: - MOVB R(i), (R(pi)) - MOVB R(j), (R(pj)) - RET diff --git a/src/pkg/crypto/rc4/rc4_asm.go b/src/pkg/crypto/rc4/rc4_asm.go deleted file mode 100644 index 02e5b67d5..000000000 --- a/src/pkg/crypto/rc4/rc4_asm.go +++ /dev/null @@ -1,18 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build amd64 amd64p32 arm,!nacl 386 - -package rc4 - -func xorKeyStream(dst, src *byte, n int, state *[256]uint32, i, j *uint8) - -// XORKeyStream sets dst to the result of XORing src with the key stream. -// Dst and src may be the same slice but otherwise should not overlap. -func (c *Cipher) XORKeyStream(dst, src []byte) { - if len(src) == 0 { - return - } - xorKeyStream(&dst[0], &src[0], len(src), &c.s, &c.i, &c.j) -} diff --git a/src/pkg/crypto/rc4/rc4_ref.go b/src/pkg/crypto/rc4/rc4_ref.go deleted file mode 100644 index e34bd34cf..000000000 --- a/src/pkg/crypto/rc4/rc4_ref.go +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !amd64,!amd64p32,!arm,!386 arm,nacl - -package rc4 - -// XORKeyStream sets dst to the result of XORing src with the key stream. -// Dst and src may be the same slice but otherwise should not overlap. -func (c *Cipher) XORKeyStream(dst, src []byte) { - c.xorKeyStreamGeneric(dst, src) -} diff --git a/src/pkg/crypto/rc4/rc4_test.go b/src/pkg/crypto/rc4/rc4_test.go deleted file mode 100644 index af7988246..000000000 --- a/src/pkg/crypto/rc4/rc4_test.go +++ /dev/null @@ -1,173 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package rc4 - -import ( - "bytes" - "fmt" - "testing" -) - -type rc4Test struct { - key, keystream []byte -} - -var golden = []rc4Test{ - // Test vectors from the original cypherpunk posting of ARC4: - // http://groups.google.com/group/sci.crypt/msg/10a300c9d21afca0?pli=1 - { - []byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef}, - []byte{0x74, 0x94, 0xc2, 0xe7, 0x10, 0x4b, 0x08, 0x79}, - }, - { - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{0xde, 0x18, 0x89, 0x41, 0xa3, 0x37, 0x5d, 0x3a}, - }, - { - []byte{0xef, 0x01, 0x23, 0x45}, - []byte{0xd6, 0xa1, 0x41, 0xa7, 0xec, 0x3c, 0x38, 0xdf, 0xbd, 0x61}, - }, - - // Test vectors from the Wikipedia page: http://en.wikipedia.org/wiki/RC4 - { - []byte{0x4b, 0x65, 0x79}, - []byte{0xeb, 0x9f, 0x77, 0x81, 0xb7, 0x34, 0xca, 0x72, 0xa7, 0x19}, - }, - { - []byte{0x57, 0x69, 0x6b, 0x69}, - []byte{0x60, 0x44, 0xdb, 0x6d, 0x41, 0xb7}, - }, - { - []byte{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, - []byte{ - 0xde, 0x18, 0x89, 0x41, 0xa3, 0x37, 0x5d, 0x3a, - 0x8a, 0x06, 0x1e, 0x67, 0x57, 0x6e, 0x92, 0x6d, - 0xc7, 0x1a, 0x7f, 0xa3, 0xf0, 0xcc, 0xeb, 0x97, - 0x45, 0x2b, 0x4d, 0x32, 0x27, 0x96, 0x5f, 0x9e, - 0xa8, 0xcc, 0x75, 0x07, 0x6d, 0x9f, 0xb9, 0xc5, - 0x41, 0x7a, 0xa5, 0xcb, 0x30, 0xfc, 0x22, 0x19, - 0x8b, 0x34, 0x98, 0x2d, 0xbb, 0x62, 0x9e, 0xc0, - 0x4b, 0x4f, 0x8b, 0x05, 0xa0, 0x71, 0x08, 0x50, - 0x92, 0xa0, 0xc3, 0x58, 0x4a, 0x48, 0xe4, 0xa3, - 0x0a, 0x39, 0x7b, 0x8a, 0xcd, 0x1d, 0x00, 0x9e, - 0xc8, 0x7d, 0x68, 0x11, 0xf2, 0x2c, 0xf4, 0x9c, - 0xa3, 0xe5, 0x93, 0x54, 0xb9, 0x45, 0x15, 0x35, - 0xa2, 0x18, 0x7a, 0x86, 0x42, 0x6c, 0xca, 0x7d, - 0x5e, 0x82, 0x3e, 0xba, 0x00, 0x44, 0x12, 0x67, - 0x12, 0x57, 0xb8, 0xd8, 0x60, 0xae, 0x4c, 0xbd, - 0x4c, 0x49, 0x06, 0xbb, 0xc5, 0x35, 0xef, 0xe1, - 0x58, 0x7f, 0x08, 0xdb, 0x33, 0x95, 0x5c, 0xdb, - 0xcb, 0xad, 0x9b, 0x10, 0xf5, 0x3f, 0xc4, 0xe5, - 0x2c, 0x59, 0x15, 0x65, 0x51, 0x84, 0x87, 0xfe, - 0x08, 0x4d, 0x0e, 0x3f, 0x03, 0xde, 0xbc, 0xc9, - 0xda, 0x1c, 0xe9, 0x0d, 0x08, 0x5c, 0x2d, 0x8a, - 0x19, 0xd8, 0x37, 0x30, 0x86, 0x16, 0x36, 0x92, - 0x14, 0x2b, 0xd8, 0xfc, 0x5d, 0x7a, 0x73, 0x49, - 0x6a, 0x8e, 0x59, 0xee, 0x7e, 0xcf, 0x6b, 0x94, - 0x06, 0x63, 0xf4, 0xa6, 0xbe, 0xe6, 0x5b, 0xd2, - 0xc8, 0x5c, 0x46, 0x98, 0x6c, 0x1b, 0xef, 0x34, - 0x90, 0xd3, 0x7b, 0x38, 0xda, 0x85, 0xd3, 0x2e, - 0x97, 0x39, 0xcb, 0x23, 0x4a, 0x2b, 0xe7, 0x40, - }, - }, -} - -func testEncrypt(t *testing.T, desc string, c *Cipher, src, expect []byte) { - dst := make([]byte, len(src)) - c.XORKeyStream(dst, src) - for i, v := range dst { - if v != expect[i] { - t.Fatalf("%s: mismatch at byte %d:\nhave %x\nwant %x", desc, i, dst, expect) - } - } -} - -func TestGolden(t *testing.T) { - for gi, g := range golden { - data := make([]byte, len(g.keystream)) - for i := range data { - data[i] = byte(i) - } - - expect := make([]byte, len(g.keystream)) - for i := range expect { - expect[i] = byte(i) ^ g.keystream[i] - } - - for size := 1; size <= len(g.keystream); size++ { - c, err := NewCipher(g.key) - if err != nil { - t.Fatalf("#%d: NewCipher: %v", gi, err) - } - - off := 0 - for off < len(g.keystream) { - n := len(g.keystream) - off - if n > size { - n = size - } - desc := fmt.Sprintf("#%d@[%d:%d]", gi, off, off+n) - testEncrypt(t, desc, c, data[off:off+n], expect[off:off+n]) - off += n - } - } - } -} - -func TestBlock(t *testing.T) { - testBlock(t, (*Cipher).XORKeyStream) -} - -// Test the pure Go version. -// Because we have assembly for amd64, 386, and arm, this prevents -// bitrot of the reference implementations. -func TestBlockGeneric(t *testing.T) { - testBlock(t, (*Cipher).xorKeyStreamGeneric) -} - -func testBlock(t *testing.T, xor func(c *Cipher, dst, src []byte)) { - c1a, _ := NewCipher(golden[0].key) - c1b, _ := NewCipher(golden[1].key) - data1 := make([]byte, 1<<20) - for i := range data1 { - xor(c1a, data1[i:i+1], data1[i:i+1]) - xor(c1b, data1[i:i+1], data1[i:i+1]) - } - - c2a, _ := NewCipher(golden[0].key) - c2b, _ := NewCipher(golden[1].key) - data2 := make([]byte, 1<<20) - xor(c2a, data2, data2) - xor(c2b, data2, data2) - - if !bytes.Equal(data1, data2) { - t.Fatalf("bad block") - } -} - -func benchmark(b *testing.B, size int64) { - buf := make([]byte, size) - c, err := NewCipher(golden[0].key) - if err != nil { - panic(err) - } - b.SetBytes(size) - - for i := 0; i < b.N; i++ { - c.XORKeyStream(buf, buf) - } -} - -func BenchmarkRC4_128(b *testing.B) { - benchmark(b, 128) -} - -func BenchmarkRC4_1K(b *testing.B) { - benchmark(b, 1024) -} - -func BenchmarkRC4_8K(b *testing.B) { - benchmark(b, 8096) -} diff --git a/src/pkg/crypto/rsa/pkcs1v15.go b/src/pkg/crypto/rsa/pkcs1v15.go deleted file mode 100644 index 59e8bb5b7..000000000 --- a/src/pkg/crypto/rsa/pkcs1v15.go +++ /dev/null @@ -1,292 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package rsa - -import ( - "crypto" - "crypto/subtle" - "errors" - "io" - "math/big" -) - -// This file implements encryption and decryption using PKCS#1 v1.5 padding. - -// EncryptPKCS1v15 encrypts the given message with RSA and the padding scheme from PKCS#1 v1.5. -// The message must be no longer than the length of the public modulus minus 11 bytes. -// WARNING: use of this function to encrypt plaintexts other than session keys -// is dangerous. Use RSA OAEP in new protocols. -func EncryptPKCS1v15(rand io.Reader, pub *PublicKey, msg []byte) (out []byte, err error) { - if err := checkPub(pub); err != nil { - return nil, err - } - k := (pub.N.BitLen() + 7) / 8 - if len(msg) > k-11 { - err = ErrMessageTooLong - return - } - - // EM = 0x00 || 0x02 || PS || 0x00 || M - em := make([]byte, k) - em[1] = 2 - ps, mm := em[2:len(em)-len(msg)-1], em[len(em)-len(msg):] - err = nonZeroRandomBytes(ps, rand) - if err != nil { - return - } - em[len(em)-len(msg)-1] = 0 - copy(mm, msg) - - m := new(big.Int).SetBytes(em) - c := encrypt(new(big.Int), pub, m) - - copyWithLeftPad(em, c.Bytes()) - out = em - return -} - -// DecryptPKCS1v15 decrypts a plaintext using RSA and the padding scheme from PKCS#1 v1.5. -// If rand != nil, it uses RSA blinding to avoid timing side-channel attacks. -func DecryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (out []byte, err error) { - if err := checkPub(&priv.PublicKey); err != nil { - return nil, err - } - valid, out, index, err := decryptPKCS1v15(rand, priv, ciphertext) - if err != nil { - return - } - if valid == 0 { - return nil, ErrDecryption - } - out = out[index:] - return -} - -// DecryptPKCS1v15SessionKey decrypts a session key using RSA and the padding scheme from PKCS#1 v1.5. -// If rand != nil, it uses RSA blinding to avoid timing side-channel attacks. -// It returns an error if the ciphertext is the wrong length or if the -// ciphertext is greater than the public modulus. Otherwise, no error is -// returned. If the padding is valid, the resulting plaintext message is copied -// into key. Otherwise, key is unchanged. These alternatives occur in constant -// time. It is intended that the user of this function generate a random -// session key beforehand and continue the protocol with the resulting value. -// This will remove any possibility that an attacker can learn any information -// about the plaintext. -// See ``Chosen Ciphertext Attacks Against Protocols Based on the RSA -// Encryption Standard PKCS #1'', Daniel Bleichenbacher, Advances in Cryptology -// (Crypto '98). -func DecryptPKCS1v15SessionKey(rand io.Reader, priv *PrivateKey, ciphertext []byte, key []byte) (err error) { - if err := checkPub(&priv.PublicKey); err != nil { - return err - } - k := (priv.N.BitLen() + 7) / 8 - if k-(len(key)+3+8) < 0 { - return ErrDecryption - } - - valid, em, index, err := decryptPKCS1v15(rand, priv, ciphertext) - if err != nil { - return - } - - if len(em) != k { - // This should be impossible because decryptPKCS1v15 always - // returns the full slice. - return ErrDecryption - } - - valid &= subtle.ConstantTimeEq(int32(len(em)-index), int32(len(key))) - subtle.ConstantTimeCopy(valid, key, em[len(em)-len(key):]) - return -} - -// decryptPKCS1v15 decrypts ciphertext using priv and blinds the operation if -// rand is not nil. It returns one or zero in valid that indicates whether the -// plaintext was correctly structured. In either case, the plaintext is -// returned in em so that it may be read independently of whether it was valid -// in order to maintain constant memory access patterns. If the plaintext was -// valid then index contains the index of the original message in em. -func decryptPKCS1v15(rand io.Reader, priv *PrivateKey, ciphertext []byte) (valid int, em []byte, index int, err error) { - k := (priv.N.BitLen() + 7) / 8 - if k < 11 { - err = ErrDecryption - return - } - - c := new(big.Int).SetBytes(ciphertext) - m, err := decrypt(rand, priv, c) - if err != nil { - return - } - - em = leftPad(m.Bytes(), k) - firstByteIsZero := subtle.ConstantTimeByteEq(em[0], 0) - secondByteIsTwo := subtle.ConstantTimeByteEq(em[1], 2) - - // The remainder of the plaintext must be a string of non-zero random - // octets, followed by a 0, followed by the message. - // lookingForIndex: 1 iff we are still looking for the zero. - // index: the offset of the first zero byte. - lookingForIndex := 1 - - for i := 2; i < len(em); i++ { - equals0 := subtle.ConstantTimeByteEq(em[i], 0) - index = subtle.ConstantTimeSelect(lookingForIndex&equals0, i, index) - lookingForIndex = subtle.ConstantTimeSelect(equals0, 0, lookingForIndex) - } - - // The PS padding must be at least 8 bytes long, and it starts two - // bytes into em. - validPS := subtle.ConstantTimeLessOrEq(2+8, index) - - valid = firstByteIsZero & secondByteIsTwo & (^lookingForIndex & 1) & validPS - index = subtle.ConstantTimeSelect(valid, index+1, 0) - return valid, em, index, nil -} - -// nonZeroRandomBytes fills the given slice with non-zero random octets. -func nonZeroRandomBytes(s []byte, rand io.Reader) (err error) { - _, err = io.ReadFull(rand, s) - if err != nil { - return - } - - for i := 0; i < len(s); i++ { - for s[i] == 0 { - _, err = io.ReadFull(rand, s[i:i+1]) - if err != nil { - return - } - // In tests, the PRNG may return all zeros so we do - // this to break the loop. - s[i] ^= 0x42 - } - } - - return -} - -// These are ASN1 DER structures: -// DigestInfo ::= SEQUENCE { -// digestAlgorithm AlgorithmIdentifier, -// digest OCTET STRING -// } -// For performance, we don't use the generic ASN1 encoder. Rather, we -// precompute a prefix of the digest value that makes a valid ASN1 DER string -// with the correct contents. -var hashPrefixes = map[crypto.Hash][]byte{ - crypto.MD5: {0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10}, - crypto.SHA1: {0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a, 0x05, 0x00, 0x04, 0x14}, - crypto.SHA224: {0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c}, - crypto.SHA256: {0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20}, - crypto.SHA384: {0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30}, - crypto.SHA512: {0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40}, - crypto.MD5SHA1: {}, // A special TLS case which doesn't use an ASN1 prefix. - crypto.RIPEMD160: {0x30, 0x20, 0x30, 0x08, 0x06, 0x06, 0x28, 0xcf, 0x06, 0x03, 0x00, 0x31, 0x04, 0x14}, -} - -// SignPKCS1v15 calculates the signature of hashed using RSASSA-PKCS1-V1_5-SIGN from RSA PKCS#1 v1.5. -// Note that hashed must be the result of hashing the input message using the -// given hash function. If hash is zero, hashed is signed directly. This isn't -// advisable except for interoperability. -func SignPKCS1v15(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte) (s []byte, err error) { - hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed)) - if err != nil { - return - } - - tLen := len(prefix) + hashLen - k := (priv.N.BitLen() + 7) / 8 - if k < tLen+11 { - return nil, ErrMessageTooLong - } - - // EM = 0x00 || 0x01 || PS || 0x00 || T - em := make([]byte, k) - em[1] = 1 - for i := 2; i < k-tLen-1; i++ { - em[i] = 0xff - } - copy(em[k-tLen:k-hashLen], prefix) - copy(em[k-hashLen:k], hashed) - - m := new(big.Int).SetBytes(em) - c, err := decrypt(rand, priv, m) - if err != nil { - return - } - - copyWithLeftPad(em, c.Bytes()) - s = em - return -} - -// VerifyPKCS1v15 verifies an RSA PKCS#1 v1.5 signature. -// hashed is the result of hashing the input message using the given hash -// function and sig is the signature. A valid signature is indicated by -// returning a nil error. If hash is zero then hashed is used directly. This -// isn't advisable except for interoperability. -func VerifyPKCS1v15(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte) (err error) { - hashLen, prefix, err := pkcs1v15HashInfo(hash, len(hashed)) - if err != nil { - return - } - - tLen := len(prefix) + hashLen - k := (pub.N.BitLen() + 7) / 8 - if k < tLen+11 { - err = ErrVerification - return - } - - c := new(big.Int).SetBytes(sig) - m := encrypt(new(big.Int), pub, c) - em := leftPad(m.Bytes(), k) - // EM = 0x00 || 0x01 || PS || 0x00 || T - - ok := subtle.ConstantTimeByteEq(em[0], 0) - ok &= subtle.ConstantTimeByteEq(em[1], 1) - ok &= subtle.ConstantTimeCompare(em[k-hashLen:k], hashed) - ok &= subtle.ConstantTimeCompare(em[k-tLen:k-hashLen], prefix) - ok &= subtle.ConstantTimeByteEq(em[k-tLen-1], 0) - - for i := 2; i < k-tLen-1; i++ { - ok &= subtle.ConstantTimeByteEq(em[i], 0xff) - } - - if ok != 1 { - return ErrVerification - } - - return nil -} - -func pkcs1v15HashInfo(hash crypto.Hash, inLen int) (hashLen int, prefix []byte, err error) { - // Special case: crypto.Hash(0) is used to indicate that the data is - // signed directly. - if hash == 0 { - return inLen, nil, nil - } - - hashLen = hash.Size() - if inLen != hashLen { - return 0, nil, errors.New("crypto/rsa: input must be hashed message") - } - prefix, ok := hashPrefixes[hash] - if !ok { - return 0, nil, errors.New("crypto/rsa: unsupported hash function") - } - return -} - -// copyWithLeftPad copies src to the end of dest, padding with zero bytes as -// needed. -func copyWithLeftPad(dest, src []byte) { - numPaddingBytes := len(dest) - len(src) - for i := 0; i < numPaddingBytes; i++ { - dest[i] = 0 - } - copy(dest[numPaddingBytes:], src) -} diff --git a/src/pkg/crypto/rsa/pkcs1v15_test.go b/src/pkg/crypto/rsa/pkcs1v15_test.go deleted file mode 100644 index 2dc5dbc2c..000000000 --- a/src/pkg/crypto/rsa/pkcs1v15_test.go +++ /dev/null @@ -1,271 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package rsa - -import ( - "bytes" - "crypto" - "crypto/rand" - "crypto/sha1" - "encoding/base64" - "encoding/hex" - "io" - "math/big" - "testing" - "testing/quick" -) - -func decodeBase64(in string) []byte { - out := make([]byte, base64.StdEncoding.DecodedLen(len(in))) - n, err := base64.StdEncoding.Decode(out, []byte(in)) - if err != nil { - return nil - } - return out[0:n] -} - -type DecryptPKCS1v15Test struct { - in, out string -} - -// These test vectors were generated with `openssl rsautl -pkcs -encrypt` -var decryptPKCS1v15Tests = []DecryptPKCS1v15Test{ - { - "gIcUIoVkD6ATMBk/u/nlCZCCWRKdkfjCgFdo35VpRXLduiKXhNz1XupLLzTXAybEq15juc+EgY5o0DHv/nt3yg==", - "x", - }, - { - "Y7TOCSqofGhkRb+jaVRLzK8xw2cSo1IVES19utzv6hwvx+M8kFsoWQm5DzBeJCZTCVDPkTpavUuEbgp8hnUGDw==", - "testing.", - }, - { - "arReP9DJtEVyV2Dg3dDp4c/PSk1O6lxkoJ8HcFupoRorBZG+7+1fDAwT1olNddFnQMjmkb8vxwmNMoTAT/BFjQ==", - "testing.\n", - }, - { - "WtaBXIoGC54+vH0NH0CHHE+dRDOsMc/6BrfFu2lEqcKL9+uDuWaf+Xj9mrbQCjjZcpQuX733zyok/jsnqe/Ftw==", - "01234567890123456789012345678901234567890123456789012", - }, -} - -func TestDecryptPKCS1v15(t *testing.T) { - for i, test := range decryptPKCS1v15Tests { - out, err := DecryptPKCS1v15(nil, rsaPrivateKey, decodeBase64(test.in)) - if err != nil { - t.Errorf("#%d error decrypting", i) - } - want := []byte(test.out) - if !bytes.Equal(out, want) { - t.Errorf("#%d got:%#v want:%#v", i, out, want) - } - } -} - -func TestEncryptPKCS1v15(t *testing.T) { - random := rand.Reader - k := (rsaPrivateKey.N.BitLen() + 7) / 8 - - tryEncryptDecrypt := func(in []byte, blind bool) bool { - if len(in) > k-11 { - in = in[0 : k-11] - } - - ciphertext, err := EncryptPKCS1v15(random, &rsaPrivateKey.PublicKey, in) - if err != nil { - t.Errorf("error encrypting: %s", err) - return false - } - - var rand io.Reader - if !blind { - rand = nil - } else { - rand = random - } - plaintext, err := DecryptPKCS1v15(rand, rsaPrivateKey, ciphertext) - if err != nil { - t.Errorf("error decrypting: %s", err) - return false - } - - if !bytes.Equal(plaintext, in) { - t.Errorf("output mismatch: %#v %#v", plaintext, in) - return false - } - return true - } - - config := new(quick.Config) - if testing.Short() { - config.MaxCount = 10 - } - quick.Check(tryEncryptDecrypt, config) -} - -// These test vectors were generated with `openssl rsautl -pkcs -encrypt` -var decryptPKCS1v15SessionKeyTests = []DecryptPKCS1v15Test{ - { - "e6ukkae6Gykq0fKzYwULpZehX+UPXYzMoB5mHQUDEiclRbOTqas4Y0E6nwns1BBpdvEJcilhl5zsox/6DtGsYg==", - "1234", - }, - { - "Dtis4uk/q/LQGGqGk97P59K03hkCIVFMEFZRgVWOAAhxgYpCRG0MX2adptt92l67IqMki6iVQyyt0TtX3IdtEw==", - "FAIL", - }, - { - "LIyFyCYCptPxrvTxpol8F3M7ZivlMsf53zs0vHRAv+rDIh2YsHS69ePMoPMe3TkOMZ3NupiL3takPxIs1sK+dw==", - "abcd", - }, - { - "bafnobel46bKy76JzqU/RIVOH0uAYvzUtauKmIidKgM0sMlvobYVAVQPeUQ/oTGjbIZ1v/6Gyi5AO4DtHruGdw==", - "FAIL", - }, -} - -func TestEncryptPKCS1v15SessionKey(t *testing.T) { - for i, test := range decryptPKCS1v15SessionKeyTests { - key := []byte("FAIL") - err := DecryptPKCS1v15SessionKey(nil, rsaPrivateKey, decodeBase64(test.in), key) - if err != nil { - t.Errorf("#%d error decrypting", i) - } - want := []byte(test.out) - if !bytes.Equal(key, want) { - t.Errorf("#%d got:%#v want:%#v", i, key, want) - } - } -} - -func TestNonZeroRandomBytes(t *testing.T) { - random := rand.Reader - - b := make([]byte, 512) - err := nonZeroRandomBytes(b, random) - if err != nil { - t.Errorf("returned error: %s", err) - } - for _, b := range b { - if b == 0 { - t.Errorf("Zero octet found") - return - } - } -} - -type signPKCS1v15Test struct { - in, out string -} - -// These vectors have been tested with -// `openssl rsautl -verify -inkey pk -in signature | hexdump -C` -var signPKCS1v15Tests = []signPKCS1v15Test{ - {"Test.\n", "a4f3fa6ea93bcdd0c57be020c1193ecbfd6f200a3d95c409769b029578fa0e336ad9a347600e40d3ae823b8c7e6bad88cc07c1d54c3a1523cbbb6d58efc362ae"}, -} - -func TestSignPKCS1v15(t *testing.T) { - for i, test := range signPKCS1v15Tests { - h := sha1.New() - h.Write([]byte(test.in)) - digest := h.Sum(nil) - - s, err := SignPKCS1v15(nil, rsaPrivateKey, crypto.SHA1, digest) - if err != nil { - t.Errorf("#%d %s", i, err) - } - - expected, _ := hex.DecodeString(test.out) - if !bytes.Equal(s, expected) { - t.Errorf("#%d got: %x want: %x", i, s, expected) - } - } -} - -func TestVerifyPKCS1v15(t *testing.T) { - for i, test := range signPKCS1v15Tests { - h := sha1.New() - h.Write([]byte(test.in)) - digest := h.Sum(nil) - - sig, _ := hex.DecodeString(test.out) - - err := VerifyPKCS1v15(&rsaPrivateKey.PublicKey, crypto.SHA1, digest, sig) - if err != nil { - t.Errorf("#%d %s", i, err) - } - } -} - -func TestOverlongMessagePKCS1v15(t *testing.T) { - ciphertext := decodeBase64("fjOVdirUzFoLlukv80dBllMLjXythIf22feqPrNo0YoIjzyzyoMFiLjAc/Y4krkeZ11XFThIrEvw\nkRiZcCq5ng==") - _, err := DecryptPKCS1v15(nil, rsaPrivateKey, ciphertext) - if err == nil { - t.Error("RSA decrypted a message that was too long.") - } -} - -func TestUnpaddedSignature(t *testing.T) { - msg := []byte("Thu Dec 19 18:06:16 EST 2013\n") - // This base64 value was generated with: - // % echo Thu Dec 19 18:06:16 EST 2013 > /tmp/msg - // % openssl rsautl -sign -inkey key -out /tmp/sig -in /tmp/msg - // - // Where "key" contains the RSA private key given at the bottom of this - // file. - expectedSig := decodeBase64("pX4DR8azytjdQ1rtUiC040FjkepuQut5q2ZFX1pTjBrOVKNjgsCDyiJDGZTCNoh9qpXYbhl7iEym30BWWwuiZg==") - - sig, err := SignPKCS1v15(nil, rsaPrivateKey, crypto.Hash(0), msg) - if err != nil { - t.Fatalf("SignPKCS1v15 failed: %s", err) - } - if !bytes.Equal(sig, expectedSig) { - t.Fatalf("signature is not expected value: got %x, want %x", sig, expectedSig) - } - if err := VerifyPKCS1v15(&rsaPrivateKey.PublicKey, crypto.Hash(0), msg, sig); err != nil { - t.Fatalf("signature failed to verify: %s", err) - } -} - -func TestShortSessionKey(t *testing.T) { - // This tests that attempting to decrypt a session key where the - // ciphertext is too small doesn't run outside the array bounds. - ciphertext, err := EncryptPKCS1v15(rand.Reader, &rsaPrivateKey.PublicKey, []byte{1}) - if err != nil { - t.Fatalf("Failed to encrypt short message: %s", err) - } - - var key [32]byte - if err := DecryptPKCS1v15SessionKey(nil, rsaPrivateKey, ciphertext, key[:]); err != nil { - t.Fatalf("Failed to decrypt short message: %s", err) - } - - for _, v := range key { - if v != 0 { - t.Fatal("key was modified when ciphertext was invalid") - } - } -} - -// In order to generate new test vectors you'll need the PEM form of this key: -// -----BEGIN RSA PRIVATE KEY----- -// MIIBOgIBAAJBALKZD0nEffqM1ACuak0bijtqE2QrI/KLADv7l3kK3ppMyCuLKoF0 -// fd7Ai2KW5ToIwzFofvJcS/STa6HA5gQenRUCAwEAAQJBAIq9amn00aS0h/CrjXqu -// /ThglAXJmZhOMPVn4eiu7/ROixi9sex436MaVeMqSNf7Ex9a8fRNfWss7Sqd9eWu -// RTUCIQDasvGASLqmjeffBNLTXV2A5g4t+kLVCpsEIZAycV5GswIhANEPLmax0ME/ -// EO+ZJ79TJKN5yiGBRsv5yvx5UiHxajEXAiAhAol5N4EUyq6I9w1rYdhPMGpLfk7A -// IU2snfRJ6Nq2CQIgFrPsWRCkV+gOYcajD17rEqmuLrdIRexpg8N1DOSXoJ8CIGlS -// tAboUGBxTDq3ZroNism3DaMIbKPyYrAqhKov1h5V -// -----END RSA PRIVATE KEY----- - -var rsaPrivateKey = &PrivateKey{ - PublicKey: PublicKey{ - N: fromBase10("9353930466774385905609975137998169297361893554149986716853295022578535724979677252958524466350471210367835187480748268864277464700638583474144061408845077"), - E: 65537, - }, - D: fromBase10("7266398431328116344057699379749222532279343923819063639497049039389899328538543087657733766554155839834519529439851673014800261285757759040931985506583861"), - Primes: []*big.Int{ - fromBase10("98920366548084643601728869055592650835572950932266967461790948584315647051443"), - fromBase10("94560208308847015747498523884063394671606671904944666360068158221458669711639"), - }, -} diff --git a/src/pkg/crypto/rsa/pss.go b/src/pkg/crypto/rsa/pss.go deleted file mode 100644 index e9f290825..000000000 --- a/src/pkg/crypto/rsa/pss.go +++ /dev/null @@ -1,297 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package rsa - -// This file implements the PSS signature scheme [1]. -// -// [1] http://www.rsa.com/rsalabs/pkcs/files/h11300-wp-pkcs-1v2-2-rsa-cryptography-standard.pdf - -import ( - "bytes" - "crypto" - "errors" - "hash" - "io" - "math/big" -) - -func emsaPSSEncode(mHash []byte, emBits int, salt []byte, hash hash.Hash) ([]byte, error) { - // See [1], section 9.1.1 - hLen := hash.Size() - sLen := len(salt) - emLen := (emBits + 7) / 8 - - // 1. If the length of M is greater than the input limitation for the - // hash function (2^61 - 1 octets for SHA-1), output "message too - // long" and stop. - // - // 2. Let mHash = Hash(M), an octet string of length hLen. - - if len(mHash) != hLen { - return nil, errors.New("crypto/rsa: input must be hashed message") - } - - // 3. If emLen < hLen + sLen + 2, output "encoding error" and stop. - - if emLen < hLen+sLen+2 { - return nil, errors.New("crypto/rsa: encoding error") - } - - em := make([]byte, emLen) - db := em[:emLen-sLen-hLen-2+1+sLen] - h := em[emLen-sLen-hLen-2+1+sLen : emLen-1] - - // 4. Generate a random octet string salt of length sLen; if sLen = 0, - // then salt is the empty string. - // - // 5. Let - // M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt; - // - // M' is an octet string of length 8 + hLen + sLen with eight - // initial zero octets. - // - // 6. Let H = Hash(M'), an octet string of length hLen. - - var prefix [8]byte - - hash.Write(prefix[:]) - hash.Write(mHash) - hash.Write(salt) - - h = hash.Sum(h[:0]) - hash.Reset() - - // 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2 - // zero octets. The length of PS may be 0. - // - // 8. Let DB = PS || 0x01 || salt; DB is an octet string of length - // emLen - hLen - 1. - - db[emLen-sLen-hLen-2] = 0x01 - copy(db[emLen-sLen-hLen-1:], salt) - - // 9. Let dbMask = MGF(H, emLen - hLen - 1). - // - // 10. Let maskedDB = DB \xor dbMask. - - mgf1XOR(db, hash, h) - - // 11. Set the leftmost 8 * emLen - emBits bits of the leftmost octet in - // maskedDB to zero. - - db[0] &= (0xFF >> uint(8*emLen-emBits)) - - // 12. Let EM = maskedDB || H || 0xbc. - em[emLen-1] = 0xBC - - // 13. Output EM. - return em, nil -} - -func emsaPSSVerify(mHash, em []byte, emBits, sLen int, hash hash.Hash) error { - // 1. If the length of M is greater than the input limitation for the - // hash function (2^61 - 1 octets for SHA-1), output "inconsistent" - // and stop. - // - // 2. Let mHash = Hash(M), an octet string of length hLen. - hLen := hash.Size() - if hLen != len(mHash) { - return ErrVerification - } - - // 3. If emLen < hLen + sLen + 2, output "inconsistent" and stop. - emLen := (emBits + 7) / 8 - if emLen < hLen+sLen+2 { - return ErrVerification - } - - // 4. If the rightmost octet of EM does not have hexadecimal value - // 0xbc, output "inconsistent" and stop. - if em[len(em)-1] != 0xBC { - return ErrVerification - } - - // 5. Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and - // let H be the next hLen octets. - db := em[:emLen-hLen-1] - h := em[emLen-hLen-1 : len(em)-1] - - // 6. If the leftmost 8 * emLen - emBits bits of the leftmost octet in - // maskedDB are not all equal to zero, output "inconsistent" and - // stop. - if em[0]&(0xFF<> uint(8*emLen-emBits)) - - if sLen == PSSSaltLengthAuto { - FindSaltLength: - for sLen = emLen - (hLen + 2); sLen >= 0; sLen-- { - switch db[emLen-hLen-sLen-2] { - case 1: - break FindSaltLength - case 0: - continue - default: - return ErrVerification - } - } - if sLen < 0 { - return ErrVerification - } - } else { - // 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero - // or if the octet at position emLen - hLen - sLen - 1 (the leftmost - // position is "position 1") does not have hexadecimal value 0x01, - // output "inconsistent" and stop. - for _, e := range db[:emLen-hLen-sLen-2] { - if e != 0x00 { - return ErrVerification - } - } - if db[emLen-hLen-sLen-2] != 0x01 { - return ErrVerification - } - } - - // 11. Let salt be the last sLen octets of DB. - salt := db[len(db)-sLen:] - - // 12. Let - // M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt ; - // M' is an octet string of length 8 + hLen + sLen with eight - // initial zero octets. - // - // 13. Let H' = Hash(M'), an octet string of length hLen. - var prefix [8]byte - hash.Write(prefix[:]) - hash.Write(mHash) - hash.Write(salt) - - h0 := hash.Sum(nil) - - // 14. If H = H', output "consistent." Otherwise, output "inconsistent." - if !bytes.Equal(h0, h) { - return ErrVerification - } - return nil -} - -// signPSSWithSalt calculates the signature of hashed using PSS [1] with specified salt. -// Note that hashed must be the result of hashing the input message using the -// given hash function. salt is a random sequence of bytes whose length will be -// later used to verify the signature. -func signPSSWithSalt(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed, salt []byte) (s []byte, err error) { - nBits := priv.N.BitLen() - em, err := emsaPSSEncode(hashed, nBits-1, salt, hash.New()) - if err != nil { - return - } - m := new(big.Int).SetBytes(em) - c, err := decrypt(rand, priv, m) - if err != nil { - return - } - s = make([]byte, (nBits+7)/8) - copyWithLeftPad(s, c.Bytes()) - return -} - -const ( - // PSSSaltLengthAuto causes the salt in a PSS signature to be as large - // as possible when signing, and to be auto-detected when verifying. - PSSSaltLengthAuto = 0 - // PSSSaltLengthEqualsHash causes the salt length to equal the length - // of the hash used in the signature. - PSSSaltLengthEqualsHash = -1 -) - -// PSSOptions contains options for creating and verifying PSS signatures. -type PSSOptions struct { - // SaltLength controls the length of the salt used in the PSS - // signature. It can either be a number of bytes, or one of the special - // PSSSaltLength constants. - SaltLength int - - // Hash, if not zero, overrides the hash function passed to SignPSS. - // This is the only way to specify the hash function when using the - // crypto.Signer interface. - Hash crypto.Hash -} - -// HashFunc returns pssOpts.Hash so that PSSOptions implements -// crypto.SignerOpts. -func (pssOpts *PSSOptions) HashFunc() crypto.Hash { - return pssOpts.Hash -} - -func (opts *PSSOptions) saltLength() int { - if opts == nil { - return PSSSaltLengthAuto - } - return opts.SaltLength -} - -// SignPSS calculates the signature of hashed using RSASSA-PSS [1]. -// Note that hashed must be the result of hashing the input message using the -// given hash function. The opts argument may be nil, in which case sensible -// defaults are used. -func SignPSS(rand io.Reader, priv *PrivateKey, hash crypto.Hash, hashed []byte, opts *PSSOptions) (s []byte, err error) { - saltLength := opts.saltLength() - switch saltLength { - case PSSSaltLengthAuto: - saltLength = (priv.N.BitLen()+7)/8 - 2 - hash.Size() - case PSSSaltLengthEqualsHash: - saltLength = hash.Size() - } - - if opts.Hash != 0 { - hash = opts.Hash - } - - salt := make([]byte, saltLength) - if _, err = io.ReadFull(rand, salt); err != nil { - return - } - return signPSSWithSalt(rand, priv, hash, hashed, salt) -} - -// VerifyPSS verifies a PSS signature. -// hashed is the result of hashing the input message using the given hash -// function and sig is the signature. A valid signature is indicated by -// returning a nil error. The opts argument may be nil, in which case sensible -// defaults are used. -func VerifyPSS(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte, opts *PSSOptions) error { - return verifyPSS(pub, hash, hashed, sig, opts.saltLength()) -} - -// verifyPSS verifies a PSS signature with the given salt length. -func verifyPSS(pub *PublicKey, hash crypto.Hash, hashed []byte, sig []byte, saltLen int) error { - nBits := pub.N.BitLen() - if len(sig) != (nBits+7)/8 { - return ErrVerification - } - s := new(big.Int).SetBytes(sig) - m := encrypt(new(big.Int), pub, s) - emBits := nBits - 1 - emLen := (emBits + 7) / 8 - if emLen < len(m.Bytes()) { - return ErrVerification - } - em := make([]byte, emLen) - copyWithLeftPad(em, m.Bytes()) - if saltLen == PSSSaltLengthEqualsHash { - saltLen = hash.Size() - } - return emsaPSSVerify(hashed, em, emBits, saltLen, hash.New()) -} diff --git a/src/pkg/crypto/rsa/pss_test.go b/src/pkg/crypto/rsa/pss_test.go deleted file mode 100644 index 32e6fc39d..000000000 --- a/src/pkg/crypto/rsa/pss_test.go +++ /dev/null @@ -1,249 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package rsa - -import ( - "bufio" - "bytes" - "compress/bzip2" - "crypto" - _ "crypto/md5" - "crypto/rand" - "crypto/sha1" - _ "crypto/sha256" - "encoding/hex" - "math/big" - "os" - "strconv" - "strings" - "testing" -) - -func TestEMSAPSS(t *testing.T) { - // Test vector in file pss-int.txt from: ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip - msg := []byte{ - 0x85, 0x9e, 0xef, 0x2f, 0xd7, 0x8a, 0xca, 0x00, 0x30, 0x8b, - 0xdc, 0x47, 0x11, 0x93, 0xbf, 0x55, 0xbf, 0x9d, 0x78, 0xdb, - 0x8f, 0x8a, 0x67, 0x2b, 0x48, 0x46, 0x34, 0xf3, 0xc9, 0xc2, - 0x6e, 0x64, 0x78, 0xae, 0x10, 0x26, 0x0f, 0xe0, 0xdd, 0x8c, - 0x08, 0x2e, 0x53, 0xa5, 0x29, 0x3a, 0xf2, 0x17, 0x3c, 0xd5, - 0x0c, 0x6d, 0x5d, 0x35, 0x4f, 0xeb, 0xf7, 0x8b, 0x26, 0x02, - 0x1c, 0x25, 0xc0, 0x27, 0x12, 0xe7, 0x8c, 0xd4, 0x69, 0x4c, - 0x9f, 0x46, 0x97, 0x77, 0xe4, 0x51, 0xe7, 0xf8, 0xe9, 0xe0, - 0x4c, 0xd3, 0x73, 0x9c, 0x6b, 0xbf, 0xed, 0xae, 0x48, 0x7f, - 0xb5, 0x56, 0x44, 0xe9, 0xca, 0x74, 0xff, 0x77, 0xa5, 0x3c, - 0xb7, 0x29, 0x80, 0x2f, 0x6e, 0xd4, 0xa5, 0xff, 0xa8, 0xba, - 0x15, 0x98, 0x90, 0xfc, - } - salt := []byte{ - 0xe3, 0xb5, 0xd5, 0xd0, 0x02, 0xc1, 0xbc, 0xe5, 0x0c, 0x2b, - 0x65, 0xef, 0x88, 0xa1, 0x88, 0xd8, 0x3b, 0xce, 0x7e, 0x61, - } - expected := []byte{ - 0x66, 0xe4, 0x67, 0x2e, 0x83, 0x6a, 0xd1, 0x21, 0xba, 0x24, - 0x4b, 0xed, 0x65, 0x76, 0xb8, 0x67, 0xd9, 0xa4, 0x47, 0xc2, - 0x8a, 0x6e, 0x66, 0xa5, 0xb8, 0x7d, 0xee, 0x7f, 0xbc, 0x7e, - 0x65, 0xaf, 0x50, 0x57, 0xf8, 0x6f, 0xae, 0x89, 0x84, 0xd9, - 0xba, 0x7f, 0x96, 0x9a, 0xd6, 0xfe, 0x02, 0xa4, 0xd7, 0x5f, - 0x74, 0x45, 0xfe, 0xfd, 0xd8, 0x5b, 0x6d, 0x3a, 0x47, 0x7c, - 0x28, 0xd2, 0x4b, 0xa1, 0xe3, 0x75, 0x6f, 0x79, 0x2d, 0xd1, - 0xdc, 0xe8, 0xca, 0x94, 0x44, 0x0e, 0xcb, 0x52, 0x79, 0xec, - 0xd3, 0x18, 0x3a, 0x31, 0x1f, 0xc8, 0x96, 0xda, 0x1c, 0xb3, - 0x93, 0x11, 0xaf, 0x37, 0xea, 0x4a, 0x75, 0xe2, 0x4b, 0xdb, - 0xfd, 0x5c, 0x1d, 0xa0, 0xde, 0x7c, 0xec, 0xdf, 0x1a, 0x89, - 0x6f, 0x9d, 0x8b, 0xc8, 0x16, 0xd9, 0x7c, 0xd7, 0xa2, 0xc4, - 0x3b, 0xad, 0x54, 0x6f, 0xbe, 0x8c, 0xfe, 0xbc, - } - - hash := sha1.New() - hash.Write(msg) - hashed := hash.Sum(nil) - - encoded, err := emsaPSSEncode(hashed, 1023, salt, sha1.New()) - if err != nil { - t.Errorf("Error from emsaPSSEncode: %s\n", err) - } - if !bytes.Equal(encoded, expected) { - t.Errorf("Bad encoding. got %x, want %x", encoded, expected) - } - - if err = emsaPSSVerify(hashed, encoded, 1023, len(salt), sha1.New()); err != nil { - t.Errorf("Bad verification: %s", err) - } -} - -// TestPSSGolden tests all the test vectors in pss-vect.txt from -// ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-1/pkcs-1v2-1-vec.zip -func TestPSSGolden(t *testing.T) { - inFile, err := os.Open("testdata/pss-vect.txt.bz2") - if err != nil { - t.Fatalf("Failed to open input file: %s", err) - } - defer inFile.Close() - - // The pss-vect.txt file contains RSA keys and then a series of - // signatures. A goroutine is used to preprocess the input by merging - // lines, removing spaces in hex values and identifying the start of - // new keys and signature blocks. - const newKeyMarker = "START NEW KEY" - const newSignatureMarker = "START NEW SIGNATURE" - - values := make(chan string) - - go func() { - defer close(values) - scanner := bufio.NewScanner(bzip2.NewReader(inFile)) - var partialValue string - lastWasValue := true - - for scanner.Scan() { - line := scanner.Text() - switch { - case len(line) == 0: - if len(partialValue) > 0 { - values <- strings.Replace(partialValue, " ", "", -1) - partialValue = "" - lastWasValue = true - } - continue - case strings.HasPrefix(line, "# ======") && lastWasValue: - values <- newKeyMarker - lastWasValue = false - case strings.HasPrefix(line, "# ------") && lastWasValue: - values <- newSignatureMarker - lastWasValue = false - case strings.HasPrefix(line, "#"): - continue - default: - partialValue += line - } - } - if err := scanner.Err(); err != nil { - panic(err) - } - }() - - var key *PublicKey - var hashed []byte - hash := crypto.SHA1 - h := hash.New() - opts := &PSSOptions{ - SaltLength: PSSSaltLengthEqualsHash, - } - - for marker := range values { - switch marker { - case newKeyMarker: - key = new(PublicKey) - nHex, ok := <-values - if !ok { - continue - } - key.N = bigFromHex(nHex) - key.E = intFromHex(<-values) - // We don't care for d, p, q, dP, dQ or qInv. - for i := 0; i < 6; i++ { - <-values - } - case newSignatureMarker: - msg := fromHex(<-values) - <-values // skip salt - sig := fromHex(<-values) - - h.Reset() - h.Write(msg) - hashed = h.Sum(hashed[:0]) - - if err := VerifyPSS(key, hash, hashed, sig, opts); err != nil { - t.Error(err) - } - default: - t.Fatalf("unknown marker: " + marker) - } - } -} - -// TestPSSOpenSSL ensures that we can verify a PSS signature from OpenSSL with -// the default options. OpenSSL sets the salt length to be maximal. -func TestPSSOpenSSL(t *testing.T) { - hash := crypto.SHA256 - h := hash.New() - h.Write([]byte("testing")) - hashed := h.Sum(nil) - - // Generated with `echo -n testing | openssl dgst -sign key.pem -sigopt rsa_padding_mode:pss -sha256 > sig` - sig := []byte{ - 0x95, 0x59, 0x6f, 0xd3, 0x10, 0xa2, 0xe7, 0xa2, 0x92, 0x9d, - 0x4a, 0x07, 0x2e, 0x2b, 0x27, 0xcc, 0x06, 0xc2, 0x87, 0x2c, - 0x52, 0xf0, 0x4a, 0xcc, 0x05, 0x94, 0xf2, 0xc3, 0x2e, 0x20, - 0xd7, 0x3e, 0x66, 0x62, 0xb5, 0x95, 0x2b, 0xa3, 0x93, 0x9a, - 0x66, 0x64, 0x25, 0xe0, 0x74, 0x66, 0x8c, 0x3e, 0x92, 0xeb, - 0xc6, 0xe6, 0xc0, 0x44, 0xf3, 0xb4, 0xb4, 0x2e, 0x8c, 0x66, - 0x0a, 0x37, 0x9c, 0x69, - } - - if err := VerifyPSS(&rsaPrivateKey.PublicKey, hash, hashed, sig, nil); err != nil { - t.Error(err) - } -} - -func TestPSSSigning(t *testing.T) { - var saltLengthCombinations = []struct { - signSaltLength, verifySaltLength int - good bool - }{ - {PSSSaltLengthAuto, PSSSaltLengthAuto, true}, - {PSSSaltLengthEqualsHash, PSSSaltLengthAuto, true}, - {PSSSaltLengthEqualsHash, PSSSaltLengthEqualsHash, true}, - {PSSSaltLengthEqualsHash, 8, false}, - {PSSSaltLengthAuto, PSSSaltLengthEqualsHash, false}, - {8, 8, true}, - } - - hash := crypto.MD5 - h := hash.New() - h.Write([]byte("testing")) - hashed := h.Sum(nil) - var opts PSSOptions - - for i, test := range saltLengthCombinations { - opts.SaltLength = test.signSaltLength - sig, err := SignPSS(rand.Reader, rsaPrivateKey, hash, hashed, &opts) - if err != nil { - t.Errorf("#%d: error while signing: %s", i, err) - continue - } - - opts.SaltLength = test.verifySaltLength - err = VerifyPSS(&rsaPrivateKey.PublicKey, hash, hashed, sig, &opts) - if (err == nil) != test.good { - t.Errorf("#%d: bad result, wanted: %t, got: %s", i, test.good, err) - } - } -} - -func bigFromHex(hex string) *big.Int { - n, ok := new(big.Int).SetString(hex, 16) - if !ok { - panic("bad hex: " + hex) - } - return n -} - -func intFromHex(hex string) int { - i, err := strconv.ParseInt(hex, 16, 32) - if err != nil { - panic(err) - } - return int(i) -} - -func fromHex(hexStr string) []byte { - s, err := hex.DecodeString(hexStr) - if err != nil { - panic(err) - } - return s -} diff --git a/src/pkg/crypto/rsa/rsa.go b/src/pkg/crypto/rsa/rsa.go deleted file mode 100644 index 270231128..000000000 --- a/src/pkg/crypto/rsa/rsa.go +++ /dev/null @@ -1,557 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package rsa implements RSA encryption as specified in PKCS#1. -package rsa - -import ( - "crypto" - "crypto/rand" - "crypto/subtle" - "errors" - "hash" - "io" - "math/big" -) - -var bigZero = big.NewInt(0) -var bigOne = big.NewInt(1) - -// A PublicKey represents the public part of an RSA key. -type PublicKey struct { - N *big.Int // modulus - E int // public exponent -} - -var ( - errPublicModulus = errors.New("crypto/rsa: missing public modulus") - errPublicExponentSmall = errors.New("crypto/rsa: public exponent too small") - errPublicExponentLarge = errors.New("crypto/rsa: public exponent too large") -) - -// checkPub sanity checks the public key before we use it. -// We require pub.E to fit into a 32-bit integer so that we -// do not have different behavior depending on whether -// int is 32 or 64 bits. See also -// http://www.imperialviolet.org/2012/03/16/rsae.html. -func checkPub(pub *PublicKey) error { - if pub.N == nil { - return errPublicModulus - } - if pub.E < 2 { - return errPublicExponentSmall - } - if pub.E > 1<<31-1 { - return errPublicExponentLarge - } - return nil -} - -// A PrivateKey represents an RSA key -type PrivateKey struct { - PublicKey // public part. - D *big.Int // private exponent - Primes []*big.Int // prime factors of N, has >= 2 elements. - - // Precomputed contains precomputed values that speed up private - // operations, if available. - Precomputed PrecomputedValues -} - -// Public returns the public key corresponding to priv. -func (priv *PrivateKey) Public() crypto.PublicKey { - return &priv.PublicKey -} - -// Sign signs msg with priv, reading randomness from rand. If opts is a -// *PSSOptions then the PSS algorithm will be used, otherwise PKCS#1 v1.5 will -// be used. This method is intended to support keys where the private part is -// kept in, for example, a hardware module. Common uses should use the Sign* -// functions in this package. -func (priv *PrivateKey) Sign(rand io.Reader, msg []byte, opts crypto.SignerOpts) ([]byte, error) { - if pssOpts, ok := opts.(*PSSOptions); ok { - return SignPSS(rand, priv, pssOpts.Hash, msg, pssOpts) - } - - return SignPKCS1v15(rand, priv, opts.HashFunc(), msg) -} - -type PrecomputedValues struct { - Dp, Dq *big.Int // D mod (P-1) (or mod Q-1) - Qinv *big.Int // Q^-1 mod P - - // CRTValues is used for the 3rd and subsequent primes. Due to a - // historical accident, the CRT for the first two primes is handled - // differently in PKCS#1 and interoperability is sufficiently - // important that we mirror this. - CRTValues []CRTValue -} - -// CRTValue contains the precomputed chinese remainder theorem values. -type CRTValue struct { - Exp *big.Int // D mod (prime-1). - Coeff *big.Int // R·Coeff ≡ 1 mod Prime. - R *big.Int // product of primes prior to this (inc p and q). -} - -// Validate performs basic sanity checks on the key. -// It returns nil if the key is valid, or else an error describing a problem. -func (priv *PrivateKey) Validate() error { - if err := checkPub(&priv.PublicKey); err != nil { - return err - } - - // Check that the prime factors are actually prime. Note that this is - // just a sanity check. Since the random witnesses chosen by - // ProbablyPrime are deterministic, given the candidate number, it's - // easy for an attack to generate composites that pass this test. - for _, prime := range priv.Primes { - if !prime.ProbablyPrime(20) { - return errors.New("crypto/rsa: prime factor is composite") - } - } - - // Check that Πprimes == n. - modulus := new(big.Int).Set(bigOne) - for _, prime := range priv.Primes { - modulus.Mul(modulus, prime) - } - if modulus.Cmp(priv.N) != 0 { - return errors.New("crypto/rsa: invalid modulus") - } - - // Check that de ≡ 1 mod p-1, for each prime. - // This implies that e is coprime to each p-1 as e has a multiplicative - // inverse. Therefore e is coprime to lcm(p-1,q-1,r-1,...) = - // exponent(ℤ/nℤ). It also implies that a^de ≡ a mod p as a^(p-1) ≡ 1 - // mod p. Thus a^de ≡ a mod n for all a coprime to n, as required. - congruence := new(big.Int) - de := new(big.Int).SetInt64(int64(priv.E)) - de.Mul(de, priv.D) - for _, prime := range priv.Primes { - pminus1 := new(big.Int).Sub(prime, bigOne) - congruence.Mod(de, pminus1) - if congruence.Cmp(bigOne) != 0 { - return errors.New("crypto/rsa: invalid exponents") - } - } - return nil -} - -// GenerateKey generates an RSA keypair of the given bit size using the -// random source random (for example, crypto/rand.Reader). -func GenerateKey(random io.Reader, bits int) (priv *PrivateKey, err error) { - return GenerateMultiPrimeKey(random, 2, bits) -} - -// GenerateMultiPrimeKey generates a multi-prime RSA keypair of the given bit -// size and the given random source, as suggested in [1]. Although the public -// keys are compatible (actually, indistinguishable) from the 2-prime case, -// the private keys are not. Thus it may not be possible to export multi-prime -// private keys in certain formats or to subsequently import them into other -// code. -// -// Table 1 in [2] suggests maximum numbers of primes for a given size. -// -// [1] US patent 4405829 (1972, expired) -// [2] http://www.cacr.math.uwaterloo.ca/techreports/2006/cacr2006-16.pdf -func GenerateMultiPrimeKey(random io.Reader, nprimes int, bits int) (priv *PrivateKey, err error) { - priv = new(PrivateKey) - priv.E = 65537 - - if nprimes < 2 { - return nil, errors.New("crypto/rsa: GenerateMultiPrimeKey: nprimes must be >= 2") - } - - primes := make([]*big.Int, nprimes) - -NextSetOfPrimes: - for { - todo := bits - // crypto/rand should set the top two bits in each prime. - // Thus each prime has the form - // p_i = 2^bitlen(p_i) × 0.11... (in base 2). - // And the product is: - // P = 2^todo × α - // where α is the product of nprimes numbers of the form 0.11... - // - // If α < 1/2 (which can happen for nprimes > 2), we need to - // shift todo to compensate for lost bits: the mean value of 0.11... - // is 7/8, so todo + shift - nprimes * log2(7/8) ~= bits - 1/2 - // will give good results. - if nprimes >= 7 { - todo += (nprimes - 2) / 5 - } - for i := 0; i < nprimes; i++ { - primes[i], err = rand.Prime(random, todo/(nprimes-i)) - if err != nil { - return nil, err - } - todo -= primes[i].BitLen() - } - - // Make sure that primes is pairwise unequal. - for i, prime := range primes { - for j := 0; j < i; j++ { - if prime.Cmp(primes[j]) == 0 { - continue NextSetOfPrimes - } - } - } - - n := new(big.Int).Set(bigOne) - totient := new(big.Int).Set(bigOne) - pminus1 := new(big.Int) - for _, prime := range primes { - n.Mul(n, prime) - pminus1.Sub(prime, bigOne) - totient.Mul(totient, pminus1) - } - if n.BitLen() != bits { - // This should never happen for nprimes == 2 because - // crypto/rand should set the top two bits in each prime. - // For nprimes > 2 we hope it does not happen often. - continue NextSetOfPrimes - } - - g := new(big.Int) - priv.D = new(big.Int) - y := new(big.Int) - e := big.NewInt(int64(priv.E)) - g.GCD(priv.D, y, e, totient) - - if g.Cmp(bigOne) == 0 { - if priv.D.Sign() < 0 { - priv.D.Add(priv.D, totient) - } - priv.Primes = primes - priv.N = n - - break - } - } - - priv.Precompute() - return -} - -// incCounter increments a four byte, big-endian counter. -func incCounter(c *[4]byte) { - if c[3]++; c[3] != 0 { - return - } - if c[2]++; c[2] != 0 { - return - } - if c[1]++; c[1] != 0 { - return - } - c[0]++ -} - -// mgf1XOR XORs the bytes in out with a mask generated using the MGF1 function -// specified in PKCS#1 v2.1. -func mgf1XOR(out []byte, hash hash.Hash, seed []byte) { - var counter [4]byte - var digest []byte - - done := 0 - for done < len(out) { - hash.Write(seed) - hash.Write(counter[0:4]) - digest = hash.Sum(digest[:0]) - hash.Reset() - - for i := 0; i < len(digest) && done < len(out); i++ { - out[done] ^= digest[i] - done++ - } - incCounter(&counter) - } -} - -// ErrMessageTooLong is returned when attempting to encrypt a message which is -// too large for the size of the public key. -var ErrMessageTooLong = errors.New("crypto/rsa: message too long for RSA public key size") - -func encrypt(c *big.Int, pub *PublicKey, m *big.Int) *big.Int { - e := big.NewInt(int64(pub.E)) - c.Exp(m, e, pub.N) - return c -} - -// EncryptOAEP encrypts the given message with RSA-OAEP. -// The message must be no longer than the length of the public modulus less -// twice the hash length plus 2. -func EncryptOAEP(hash hash.Hash, random io.Reader, pub *PublicKey, msg []byte, label []byte) (out []byte, err error) { - if err := checkPub(pub); err != nil { - return nil, err - } - hash.Reset() - k := (pub.N.BitLen() + 7) / 8 - if len(msg) > k-2*hash.Size()-2 { - err = ErrMessageTooLong - return - } - - hash.Write(label) - lHash := hash.Sum(nil) - hash.Reset() - - em := make([]byte, k) - seed := em[1 : 1+hash.Size()] - db := em[1+hash.Size():] - - copy(db[0:hash.Size()], lHash) - db[len(db)-len(msg)-1] = 1 - copy(db[len(db)-len(msg):], msg) - - _, err = io.ReadFull(random, seed) - if err != nil { - return - } - - mgf1XOR(db, hash, seed) - mgf1XOR(seed, hash, db) - - m := new(big.Int) - m.SetBytes(em) - c := encrypt(new(big.Int), pub, m) - out = c.Bytes() - - if len(out) < k { - // If the output is too small, we need to left-pad with zeros. - t := make([]byte, k) - copy(t[k-len(out):], out) - out = t - } - - return -} - -// ErrDecryption represents a failure to decrypt a message. -// It is deliberately vague to avoid adaptive attacks. -var ErrDecryption = errors.New("crypto/rsa: decryption error") - -// ErrVerification represents a failure to verify a signature. -// It is deliberately vague to avoid adaptive attacks. -var ErrVerification = errors.New("crypto/rsa: verification error") - -// modInverse returns ia, the inverse of a in the multiplicative group of prime -// order n. It requires that a be a member of the group (i.e. less than n). -func modInverse(a, n *big.Int) (ia *big.Int, ok bool) { - g := new(big.Int) - x := new(big.Int) - y := new(big.Int) - g.GCD(x, y, a, n) - if g.Cmp(bigOne) != 0 { - // In this case, a and n aren't coprime and we cannot calculate - // the inverse. This happens because the values of n are nearly - // prime (being the product of two primes) rather than truly - // prime. - return - } - - if x.Cmp(bigOne) < 0 { - // 0 is not the multiplicative inverse of any element so, if x - // < 1, then x is negative. - x.Add(x, n) - } - - return x, true -} - -// Precompute performs some calculations that speed up private key operations -// in the future. -func (priv *PrivateKey) Precompute() { - if priv.Precomputed.Dp != nil { - return - } - - priv.Precomputed.Dp = new(big.Int).Sub(priv.Primes[0], bigOne) - priv.Precomputed.Dp.Mod(priv.D, priv.Precomputed.Dp) - - priv.Precomputed.Dq = new(big.Int).Sub(priv.Primes[1], bigOne) - priv.Precomputed.Dq.Mod(priv.D, priv.Precomputed.Dq) - - priv.Precomputed.Qinv = new(big.Int).ModInverse(priv.Primes[1], priv.Primes[0]) - - r := new(big.Int).Mul(priv.Primes[0], priv.Primes[1]) - priv.Precomputed.CRTValues = make([]CRTValue, len(priv.Primes)-2) - for i := 2; i < len(priv.Primes); i++ { - prime := priv.Primes[i] - values := &priv.Precomputed.CRTValues[i-2] - - values.Exp = new(big.Int).Sub(prime, bigOne) - values.Exp.Mod(priv.D, values.Exp) - - values.R = new(big.Int).Set(r) - values.Coeff = new(big.Int).ModInverse(r, prime) - - r.Mul(r, prime) - } -} - -// decrypt performs an RSA decryption, resulting in a plaintext integer. If a -// random source is given, RSA blinding is used. -func decrypt(random io.Reader, priv *PrivateKey, c *big.Int) (m *big.Int, err error) { - // TODO(agl): can we get away with reusing blinds? - if c.Cmp(priv.N) > 0 { - err = ErrDecryption - return - } - - var ir *big.Int - if random != nil { - // Blinding enabled. Blinding involves multiplying c by r^e. - // Then the decryption operation performs (m^e * r^e)^d mod n - // which equals mr mod n. The factor of r can then be removed - // by multiplying by the multiplicative inverse of r. - - var r *big.Int - - for { - r, err = rand.Int(random, priv.N) - if err != nil { - return - } - if r.Cmp(bigZero) == 0 { - r = bigOne - } - var ok bool - ir, ok = modInverse(r, priv.N) - if ok { - break - } - } - bigE := big.NewInt(int64(priv.E)) - rpowe := new(big.Int).Exp(r, bigE, priv.N) - cCopy := new(big.Int).Set(c) - cCopy.Mul(cCopy, rpowe) - cCopy.Mod(cCopy, priv.N) - c = cCopy - } - - if priv.Precomputed.Dp == nil { - m = new(big.Int).Exp(c, priv.D, priv.N) - } else { - // We have the precalculated values needed for the CRT. - m = new(big.Int).Exp(c, priv.Precomputed.Dp, priv.Primes[0]) - m2 := new(big.Int).Exp(c, priv.Precomputed.Dq, priv.Primes[1]) - m.Sub(m, m2) - if m.Sign() < 0 { - m.Add(m, priv.Primes[0]) - } - m.Mul(m, priv.Precomputed.Qinv) - m.Mod(m, priv.Primes[0]) - m.Mul(m, priv.Primes[1]) - m.Add(m, m2) - - for i, values := range priv.Precomputed.CRTValues { - prime := priv.Primes[2+i] - m2.Exp(c, values.Exp, prime) - m2.Sub(m2, m) - m2.Mul(m2, values.Coeff) - m2.Mod(m2, prime) - if m2.Sign() < 0 { - m2.Add(m2, prime) - } - m2.Mul(m2, values.R) - m.Add(m, m2) - } - } - - if ir != nil { - // Unblind. - m.Mul(m, ir) - m.Mod(m, priv.N) - } - - return -} - -// DecryptOAEP decrypts ciphertext using RSA-OAEP. -// If random != nil, DecryptOAEP uses RSA blinding to avoid timing side-channel attacks. -func DecryptOAEP(hash hash.Hash, random io.Reader, priv *PrivateKey, ciphertext []byte, label []byte) (msg []byte, err error) { - if err := checkPub(&priv.PublicKey); err != nil { - return nil, err - } - k := (priv.N.BitLen() + 7) / 8 - if len(ciphertext) > k || - k < hash.Size()*2+2 { - err = ErrDecryption - return - } - - c := new(big.Int).SetBytes(ciphertext) - - m, err := decrypt(random, priv, c) - if err != nil { - return - } - - hash.Write(label) - lHash := hash.Sum(nil) - hash.Reset() - - // Converting the plaintext number to bytes will strip any - // leading zeros so we may have to left pad. We do this unconditionally - // to avoid leaking timing information. (Although we still probably - // leak the number of leading zeros. It's not clear that we can do - // anything about this.) - em := leftPad(m.Bytes(), k) - - firstByteIsZero := subtle.ConstantTimeByteEq(em[0], 0) - - seed := em[1 : hash.Size()+1] - db := em[hash.Size()+1:] - - mgf1XOR(seed, hash, db) - mgf1XOR(db, hash, seed) - - lHash2 := db[0:hash.Size()] - - // We have to validate the plaintext in constant time in order to avoid - // attacks like: J. Manger. A Chosen Ciphertext Attack on RSA Optimal - // Asymmetric Encryption Padding (OAEP) as Standardized in PKCS #1 - // v2.0. In J. Kilian, editor, Advances in Cryptology. - lHash2Good := subtle.ConstantTimeCompare(lHash, lHash2) - - // The remainder of the plaintext must be zero or more 0x00, followed - // by 0x01, followed by the message. - // lookingForIndex: 1 iff we are still looking for the 0x01 - // index: the offset of the first 0x01 byte - // invalid: 1 iff we saw a non-zero byte before the 0x01. - var lookingForIndex, index, invalid int - lookingForIndex = 1 - rest := db[hash.Size():] - - for i := 0; i < len(rest); i++ { - equals0 := subtle.ConstantTimeByteEq(rest[i], 0) - equals1 := subtle.ConstantTimeByteEq(rest[i], 1) - index = subtle.ConstantTimeSelect(lookingForIndex&equals1, i, index) - lookingForIndex = subtle.ConstantTimeSelect(equals1, 0, lookingForIndex) - invalid = subtle.ConstantTimeSelect(lookingForIndex&^equals0, 1, invalid) - } - - if firstByteIsZero&lHash2Good&^invalid&^lookingForIndex != 1 { - err = ErrDecryption - return - } - - msg = rest[index+1:] - return -} - -// leftPad returns a new slice of length size. The contents of input are right -// aligned in the new slice. -func leftPad(input []byte, size int) (out []byte) { - n := len(input) - if n > size { - n = size - } - out = make([]byte, size) - copy(out[len(out)-n:], input) - return -} diff --git a/src/pkg/crypto/rsa/rsa_test.go b/src/pkg/crypto/rsa/rsa_test.go deleted file mode 100644 index 4ee1c3a8b..000000000 --- a/src/pkg/crypto/rsa/rsa_test.go +++ /dev/null @@ -1,392 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package rsa - -import ( - "bytes" - "crypto/rand" - "crypto/sha1" - "math/big" - "testing" -) - -func TestKeyGeneration(t *testing.T) { - size := 1024 - if testing.Short() { - size = 128 - } - priv, err := GenerateKey(rand.Reader, size) - if err != nil { - t.Errorf("failed to generate key") - } - if bits := priv.N.BitLen(); bits != size { - t.Errorf("key too short (%d vs %d)", bits, size) - } - testKeyBasics(t, priv) -} - -func Test3PrimeKeyGeneration(t *testing.T) { - size := 768 - if testing.Short() { - size = 256 - } - - priv, err := GenerateMultiPrimeKey(rand.Reader, 3, size) - if err != nil { - t.Errorf("failed to generate key") - } - testKeyBasics(t, priv) -} - -func Test4PrimeKeyGeneration(t *testing.T) { - size := 768 - if testing.Short() { - size = 256 - } - - priv, err := GenerateMultiPrimeKey(rand.Reader, 4, size) - if err != nil { - t.Errorf("failed to generate key") - } - testKeyBasics(t, priv) -} - -func TestNPrimeKeyGeneration(t *testing.T) { - primeSize := 64 - maxN := 24 - if testing.Short() { - primeSize = 16 - maxN = 16 - } - // Test that generation of N-prime keys works for N > 4. - for n := 5; n < maxN; n++ { - priv, err := GenerateMultiPrimeKey(rand.Reader, n, 64+n*primeSize) - if err == nil { - testKeyBasics(t, priv) - } else { - t.Errorf("failed to generate %d-prime key", n) - } - } -} - -func TestGnuTLSKey(t *testing.T) { - // This is a key generated by `certtool --generate-privkey --bits 128`. - // It's such that de ≢ 1 mod φ(n), but is congruent mod the order of - // the group. - priv := &PrivateKey{ - PublicKey: PublicKey{ - N: fromBase10("290684273230919398108010081414538931343"), - E: 65537, - }, - D: fromBase10("31877380284581499213530787347443987241"), - Primes: []*big.Int{ - fromBase10("16775196964030542637"), - fromBase10("17328218193455850539"), - }, - } - testKeyBasics(t, priv) -} - -func testKeyBasics(t *testing.T, priv *PrivateKey) { - if err := priv.Validate(); err != nil { - t.Errorf("Validate() failed: %s", err) - } - if priv.D.Cmp(priv.N) > 0 { - t.Errorf("private exponent too large") - } - - pub := &priv.PublicKey - m := big.NewInt(42) - c := encrypt(new(big.Int), pub, m) - - m2, err := decrypt(nil, priv, c) - if err != nil { - t.Errorf("error while decrypting: %s", err) - return - } - if m.Cmp(m2) != 0 { - t.Errorf("got:%v, want:%v (%+v)", m2, m, priv) - } - - m3, err := decrypt(rand.Reader, priv, c) - if err != nil { - t.Errorf("error while decrypting (blind): %s", err) - } - if m.Cmp(m3) != 0 { - t.Errorf("(blind) got:%v, want:%v (%#v)", m3, m, priv) - } -} - -func fromBase10(base10 string) *big.Int { - i, ok := new(big.Int).SetString(base10, 10) - if !ok { - panic("bad number: " + base10) - } - return i -} - -func BenchmarkRSA2048Decrypt(b *testing.B) { - b.StopTimer() - priv := &PrivateKey{ - PublicKey: PublicKey{ - N: fromBase10("14314132931241006650998084889274020608918049032671858325988396851334124245188214251956198731333464217832226406088020736932173064754214329009979944037640912127943488972644697423190955557435910767690712778463524983667852819010259499695177313115447116110358524558307947613422897787329221478860907963827160223559690523660574329011927531289655711860504630573766609239332569210831325633840174683944553667352219670930408593321661375473885147973879086994006440025257225431977751512374815915392249179976902953721486040787792801849818254465486633791826766873076617116727073077821584676715609985777563958286637185868165868520557"), - E: 3, - }, - D: fromBase10("9542755287494004433998723259516013739278699355114572217325597900889416163458809501304132487555642811888150937392013824621448709836142886006653296025093941418628992648429798282127303704957273845127141852309016655778568546006839666463451542076964744073572349705538631742281931858219480985907271975884773482372966847639853897890615456605598071088189838676728836833012254065983259638538107719766738032720239892094196108713378822882383694456030043492571063441943847195939549773271694647657549658603365629458610273821292232646334717612674519997533901052790334279661754176490593041941863932308687197618671528035670452762731"), - Primes: []*big.Int{ - fromBase10("130903255182996722426771613606077755295583329135067340152947172868415809027537376306193179624298874215608270802054347609836776473930072411958753044562214537013874103802006369634761074377213995983876788718033850153719421695468704276694983032644416930879093914927146648402139231293035971427838068945045019075433"), - fromBase10("109348945610485453577574767652527472924289229538286649661240938988020367005475727988253438647560958573506159449538793540472829815903949343191091817779240101054552748665267574271163617694640513549693841337820602726596756351006149518830932261246698766355347898158548465400674856021497190430791824869615170301029"), - }, - } - priv.Precompute() - - c := fromBase10("8472002792838218989464636159316973636630013835787202418124758118372358261975764365740026024610403138425986214991379012696600761514742817632790916315594342398720903716529235119816755589383377471752116975374952783629225022962092351886861518911824745188989071172097120352727368980275252089141512321893536744324822590480751098257559766328893767334861211872318961900897793874075248286439689249972315699410830094164386544311554704755110361048571142336148077772023880664786019636334369759624917224888206329520528064315309519262325023881707530002540634660750469137117568199824615333883758410040459705787022909848740188613313") - - b.StartTimer() - - for i := 0; i < b.N; i++ { - decrypt(nil, priv, c) - } -} - -func Benchmark3PrimeRSA2048Decrypt(b *testing.B) { - b.StopTimer() - priv := &PrivateKey{ - PublicKey: PublicKey{ - N: fromBase10("16346378922382193400538269749936049106320265317511766357599732575277382844051791096569333808598921852351577762718529818072849191122419410612033592401403764925096136759934497687765453905884149505175426053037420486697072448609022753683683718057795566811401938833367954642951433473337066311978821180526439641496973296037000052546108507805269279414789035461158073156772151892452251106173507240488993608650881929629163465099476849643165682709047462010581308719577053905787496296934240246311806555924593059995202856826239801816771116902778517096212527979497399966526283516447337775509777558018145573127308919204297111496233"), - E: 3, - }, - D: fromBase10("10897585948254795600358846499957366070880176878341177571733155050184921896034527397712889205732614568234385175145686545381899460748279607074689061600935843283397424506622998458510302603922766336783617368686090042765718290914099334449154829375179958369993407724946186243249568928237086215759259909861748642124071874879861299389874230489928271621259294894142840428407196932444474088857746123104978617098858619445675532587787023228852383149557470077802718705420275739737958953794088728369933811184572620857678792001136676902250566845618813972833750098806496641114644760255910789397593428910198080271317419213080834885003"), - Primes: []*big.Int{ - fromBase10("1025363189502892836833747188838978207017355117492483312747347695538428729137306368764177201532277413433182799108299960196606011786562992097313508180436744488171474690412562218914213688661311117337381958560443"), - fromBase10("3467903426626310123395340254094941045497208049900750380025518552334536945536837294961497712862519984786362199788654739924501424784631315081391467293694361474867825728031147665777546570788493758372218019373"), - fromBase10("4597024781409332673052708605078359346966325141767460991205742124888960305710298765592730135879076084498363772408626791576005136245060321874472727132746643162385746062759369754202494417496879741537284589047"), - }, - } - priv.Precompute() - - c := fromBase10("8472002792838218989464636159316973636630013835787202418124758118372358261975764365740026024610403138425986214991379012696600761514742817632790916315594342398720903716529235119816755589383377471752116975374952783629225022962092351886861518911824745188989071172097120352727368980275252089141512321893536744324822590480751098257559766328893767334861211872318961900897793874075248286439689249972315699410830094164386544311554704755110361048571142336148077772023880664786019636334369759624917224888206329520528064315309519262325023881707530002540634660750469137117568199824615333883758410040459705787022909848740188613313") - - b.StartTimer() - - for i := 0; i < b.N; i++ { - decrypt(nil, priv, c) - } -} - -type testEncryptOAEPMessage struct { - in []byte - seed []byte - out []byte -} - -type testEncryptOAEPStruct struct { - modulus string - e int - d string - msgs []testEncryptOAEPMessage -} - -func TestEncryptOAEP(t *testing.T) { - sha1 := sha1.New() - n := new(big.Int) - for i, test := range testEncryptOAEPData { - n.SetString(test.modulus, 16) - public := PublicKey{n, test.e} - - for j, message := range test.msgs { - randomSource := bytes.NewReader(message.seed) - out, err := EncryptOAEP(sha1, randomSource, &public, message.in, nil) - if err != nil { - t.Errorf("#%d,%d error: %s", i, j, err) - } - if !bytes.Equal(out, message.out) { - t.Errorf("#%d,%d bad result: %x (want %x)", i, j, out, message.out) - } - } - } -} - -func TestDecryptOAEP(t *testing.T) { - random := rand.Reader - - sha1 := sha1.New() - n := new(big.Int) - d := new(big.Int) - for i, test := range testEncryptOAEPData { - n.SetString(test.modulus, 16) - d.SetString(test.d, 16) - private := new(PrivateKey) - private.PublicKey = PublicKey{n, test.e} - private.D = d - - for j, message := range test.msgs { - out, err := DecryptOAEP(sha1, nil, private, message.out, nil) - if err != nil { - t.Errorf("#%d,%d error: %s", i, j, err) - } else if !bytes.Equal(out, message.in) { - t.Errorf("#%d,%d bad result: %#v (want %#v)", i, j, out, message.in) - } - - // Decrypt with blinding. - out, err = DecryptOAEP(sha1, random, private, message.out, nil) - if err != nil { - t.Errorf("#%d,%d (blind) error: %s", i, j, err) - } else if !bytes.Equal(out, message.in) { - t.Errorf("#%d,%d (blind) bad result: %#v (want %#v)", i, j, out, message.in) - } - } - if testing.Short() { - break - } - } -} - -// testEncryptOAEPData contains a subset of the vectors from RSA's "Test vectors for RSA-OAEP". -var testEncryptOAEPData = []testEncryptOAEPStruct{ - // Key 1 - {"a8b3b284af8eb50b387034a860f146c4919f318763cd6c5598c8ae4811a1e0abc4c7e0b082d693a5e7fced675cf4668512772c0cbc64a742c6c630f533c8cc72f62ae833c40bf25842e984bb78bdbf97c0107d55bdb662f5c4e0fab9845cb5148ef7392dd3aaff93ae1e6b667bb3d4247616d4f5ba10d4cfd226de88d39f16fb", - 65537, - "53339cfdb79fc8466a655c7316aca85c55fd8f6dd898fdaf119517ef4f52e8fd8e258df93fee180fa0e4ab29693cd83b152a553d4ac4d1812b8b9fa5af0e7f55fe7304df41570926f3311f15c4d65a732c483116ee3d3d2d0af3549ad9bf7cbfb78ad884f84d5beb04724dc7369b31def37d0cf539e9cfcdd3de653729ead5d1", - []testEncryptOAEPMessage{ - // Example 1.1 - { - []byte{0x66, 0x28, 0x19, 0x4e, 0x12, 0x07, 0x3d, 0xb0, - 0x3b, 0xa9, 0x4c, 0xda, 0x9e, 0xf9, 0x53, 0x23, 0x97, - 0xd5, 0x0d, 0xba, 0x79, 0xb9, 0x87, 0x00, 0x4a, 0xfe, - 0xfe, 0x34, - }, - []byte{0x18, 0xb7, 0x76, 0xea, 0x21, 0x06, 0x9d, 0x69, - 0x77, 0x6a, 0x33, 0xe9, 0x6b, 0xad, 0x48, 0xe1, 0xdd, - 0xa0, 0xa5, 0xef, - }, - []byte{0x35, 0x4f, 0xe6, 0x7b, 0x4a, 0x12, 0x6d, 0x5d, - 0x35, 0xfe, 0x36, 0xc7, 0x77, 0x79, 0x1a, 0x3f, 0x7b, - 0xa1, 0x3d, 0xef, 0x48, 0x4e, 0x2d, 0x39, 0x08, 0xaf, - 0xf7, 0x22, 0xfa, 0xd4, 0x68, 0xfb, 0x21, 0x69, 0x6d, - 0xe9, 0x5d, 0x0b, 0xe9, 0x11, 0xc2, 0xd3, 0x17, 0x4f, - 0x8a, 0xfc, 0xc2, 0x01, 0x03, 0x5f, 0x7b, 0x6d, 0x8e, - 0x69, 0x40, 0x2d, 0xe5, 0x45, 0x16, 0x18, 0xc2, 0x1a, - 0x53, 0x5f, 0xa9, 0xd7, 0xbf, 0xc5, 0xb8, 0xdd, 0x9f, - 0xc2, 0x43, 0xf8, 0xcf, 0x92, 0x7d, 0xb3, 0x13, 0x22, - 0xd6, 0xe8, 0x81, 0xea, 0xa9, 0x1a, 0x99, 0x61, 0x70, - 0xe6, 0x57, 0xa0, 0x5a, 0x26, 0x64, 0x26, 0xd9, 0x8c, - 0x88, 0x00, 0x3f, 0x84, 0x77, 0xc1, 0x22, 0x70, 0x94, - 0xa0, 0xd9, 0xfa, 0x1e, 0x8c, 0x40, 0x24, 0x30, 0x9c, - 0xe1, 0xec, 0xcc, 0xb5, 0x21, 0x00, 0x35, 0xd4, 0x7a, - 0xc7, 0x2e, 0x8a, - }, - }, - // Example 1.2 - { - []byte{0x75, 0x0c, 0x40, 0x47, 0xf5, 0x47, 0xe8, 0xe4, - 0x14, 0x11, 0x85, 0x65, 0x23, 0x29, 0x8a, 0xc9, 0xba, - 0xe2, 0x45, 0xef, 0xaf, 0x13, 0x97, 0xfb, 0xe5, 0x6f, - 0x9d, 0xd5, - }, - []byte{0x0c, 0xc7, 0x42, 0xce, 0x4a, 0x9b, 0x7f, 0x32, - 0xf9, 0x51, 0xbc, 0xb2, 0x51, 0xef, 0xd9, 0x25, 0xfe, - 0x4f, 0xe3, 0x5f, - }, - []byte{0x64, 0x0d, 0xb1, 0xac, 0xc5, 0x8e, 0x05, 0x68, - 0xfe, 0x54, 0x07, 0xe5, 0xf9, 0xb7, 0x01, 0xdf, 0xf8, - 0xc3, 0xc9, 0x1e, 0x71, 0x6c, 0x53, 0x6f, 0xc7, 0xfc, - 0xec, 0x6c, 0xb5, 0xb7, 0x1c, 0x11, 0x65, 0x98, 0x8d, - 0x4a, 0x27, 0x9e, 0x15, 0x77, 0xd7, 0x30, 0xfc, 0x7a, - 0x29, 0x93, 0x2e, 0x3f, 0x00, 0xc8, 0x15, 0x15, 0x23, - 0x6d, 0x8d, 0x8e, 0x31, 0x01, 0x7a, 0x7a, 0x09, 0xdf, - 0x43, 0x52, 0xd9, 0x04, 0xcd, 0xeb, 0x79, 0xaa, 0x58, - 0x3a, 0xdc, 0xc3, 0x1e, 0xa6, 0x98, 0xa4, 0xc0, 0x52, - 0x83, 0xda, 0xba, 0x90, 0x89, 0xbe, 0x54, 0x91, 0xf6, - 0x7c, 0x1a, 0x4e, 0xe4, 0x8d, 0xc7, 0x4b, 0xbb, 0xe6, - 0x64, 0x3a, 0xef, 0x84, 0x66, 0x79, 0xb4, 0xcb, 0x39, - 0x5a, 0x35, 0x2d, 0x5e, 0xd1, 0x15, 0x91, 0x2d, 0xf6, - 0x96, 0xff, 0xe0, 0x70, 0x29, 0x32, 0x94, 0x6d, 0x71, - 0x49, 0x2b, 0x44, - }, - }, - // Example 1.3 - { - []byte{0xd9, 0x4a, 0xe0, 0x83, 0x2e, 0x64, 0x45, 0xce, - 0x42, 0x33, 0x1c, 0xb0, 0x6d, 0x53, 0x1a, 0x82, 0xb1, - 0xdb, 0x4b, 0xaa, 0xd3, 0x0f, 0x74, 0x6d, 0xc9, 0x16, - 0xdf, 0x24, 0xd4, 0xe3, 0xc2, 0x45, 0x1f, 0xff, 0x59, - 0xa6, 0x42, 0x3e, 0xb0, 0xe1, 0xd0, 0x2d, 0x4f, 0xe6, - 0x46, 0xcf, 0x69, 0x9d, 0xfd, 0x81, 0x8c, 0x6e, 0x97, - 0xb0, 0x51, - }, - []byte{0x25, 0x14, 0xdf, 0x46, 0x95, 0x75, 0x5a, 0x67, - 0xb2, 0x88, 0xea, 0xf4, 0x90, 0x5c, 0x36, 0xee, 0xc6, - 0x6f, 0xd2, 0xfd, - }, - []byte{0x42, 0x37, 0x36, 0xed, 0x03, 0x5f, 0x60, 0x26, - 0xaf, 0x27, 0x6c, 0x35, 0xc0, 0xb3, 0x74, 0x1b, 0x36, - 0x5e, 0x5f, 0x76, 0xca, 0x09, 0x1b, 0x4e, 0x8c, 0x29, - 0xe2, 0xf0, 0xbe, 0xfe, 0xe6, 0x03, 0x59, 0x5a, 0xa8, - 0x32, 0x2d, 0x60, 0x2d, 0x2e, 0x62, 0x5e, 0x95, 0xeb, - 0x81, 0xb2, 0xf1, 0xc9, 0x72, 0x4e, 0x82, 0x2e, 0xca, - 0x76, 0xdb, 0x86, 0x18, 0xcf, 0x09, 0xc5, 0x34, 0x35, - 0x03, 0xa4, 0x36, 0x08, 0x35, 0xb5, 0x90, 0x3b, 0xc6, - 0x37, 0xe3, 0x87, 0x9f, 0xb0, 0x5e, 0x0e, 0xf3, 0x26, - 0x85, 0xd5, 0xae, 0xc5, 0x06, 0x7c, 0xd7, 0xcc, 0x96, - 0xfe, 0x4b, 0x26, 0x70, 0xb6, 0xea, 0xc3, 0x06, 0x6b, - 0x1f, 0xcf, 0x56, 0x86, 0xb6, 0x85, 0x89, 0xaa, 0xfb, - 0x7d, 0x62, 0x9b, 0x02, 0xd8, 0xf8, 0x62, 0x5c, 0xa3, - 0x83, 0x36, 0x24, 0xd4, 0x80, 0x0f, 0xb0, 0x81, 0xb1, - 0xcf, 0x94, 0xeb, - }, - }, - }, - }, - // Key 10 - {"ae45ed5601cec6b8cc05f803935c674ddbe0d75c4c09fd7951fc6b0caec313a8df39970c518bffba5ed68f3f0d7f22a4029d413f1ae07e4ebe9e4177ce23e7f5404b569e4ee1bdcf3c1fb03ef113802d4f855eb9b5134b5a7c8085adcae6fa2fa1417ec3763be171b0c62b760ede23c12ad92b980884c641f5a8fac26bdad4a03381a22fe1b754885094c82506d4019a535a286afeb271bb9ba592de18dcf600c2aeeae56e02f7cf79fc14cf3bdc7cd84febbbf950ca90304b2219a7aa063aefa2c3c1980e560cd64afe779585b6107657b957857efde6010988ab7de417fc88d8f384c4e6e72c3f943e0c31c0c4a5cc36f879d8a3ac9d7d59860eaada6b83bb", - 65537, - "056b04216fe5f354ac77250a4b6b0c8525a85c59b0bd80c56450a22d5f438e596a333aa875e291dd43f48cb88b9d5fc0d499f9fcd1c397f9afc070cd9e398c8d19e61db7c7410a6b2675dfbf5d345b804d201add502d5ce2dfcb091ce9997bbebe57306f383e4d588103f036f7e85d1934d152a323e4a8db451d6f4a5b1b0f102cc150e02feee2b88dea4ad4c1baccb24d84072d14e1d24a6771f7408ee30564fb86d4393a34bcf0b788501d193303f13a2284b001f0f649eaf79328d4ac5c430ab4414920a9460ed1b7bc40ec653e876d09abc509ae45b525190116a0c26101848298509c1c3bf3a483e7274054e15e97075036e989f60932807b5257751e79", - []testEncryptOAEPMessage{ - // Example 10.1 - { - []byte{0x8b, 0xba, 0x6b, 0xf8, 0x2a, 0x6c, 0x0f, 0x86, - 0xd5, 0xf1, 0x75, 0x6e, 0x97, 0x95, 0x68, 0x70, 0xb0, - 0x89, 0x53, 0xb0, 0x6b, 0x4e, 0xb2, 0x05, 0xbc, 0x16, - 0x94, 0xee, - }, - []byte{0x47, 0xe1, 0xab, 0x71, 0x19, 0xfe, 0xe5, 0x6c, - 0x95, 0xee, 0x5e, 0xaa, 0xd8, 0x6f, 0x40, 0xd0, 0xaa, - 0x63, 0xbd, 0x33, - }, - []byte{0x53, 0xea, 0x5d, 0xc0, 0x8c, 0xd2, 0x60, 0xfb, - 0x3b, 0x85, 0x85, 0x67, 0x28, 0x7f, 0xa9, 0x15, 0x52, - 0xc3, 0x0b, 0x2f, 0xeb, 0xfb, 0xa2, 0x13, 0xf0, 0xae, - 0x87, 0x70, 0x2d, 0x06, 0x8d, 0x19, 0xba, 0xb0, 0x7f, - 0xe5, 0x74, 0x52, 0x3d, 0xfb, 0x42, 0x13, 0x9d, 0x68, - 0xc3, 0xc5, 0xaf, 0xee, 0xe0, 0xbf, 0xe4, 0xcb, 0x79, - 0x69, 0xcb, 0xf3, 0x82, 0xb8, 0x04, 0xd6, 0xe6, 0x13, - 0x96, 0x14, 0x4e, 0x2d, 0x0e, 0x60, 0x74, 0x1f, 0x89, - 0x93, 0xc3, 0x01, 0x4b, 0x58, 0xb9, 0xb1, 0x95, 0x7a, - 0x8b, 0xab, 0xcd, 0x23, 0xaf, 0x85, 0x4f, 0x4c, 0x35, - 0x6f, 0xb1, 0x66, 0x2a, 0xa7, 0x2b, 0xfc, 0xc7, 0xe5, - 0x86, 0x55, 0x9d, 0xc4, 0x28, 0x0d, 0x16, 0x0c, 0x12, - 0x67, 0x85, 0xa7, 0x23, 0xeb, 0xee, 0xbe, 0xff, 0x71, - 0xf1, 0x15, 0x94, 0x44, 0x0a, 0xae, 0xf8, 0x7d, 0x10, - 0x79, 0x3a, 0x87, 0x74, 0xa2, 0x39, 0xd4, 0xa0, 0x4c, - 0x87, 0xfe, 0x14, 0x67, 0xb9, 0xda, 0xf8, 0x52, 0x08, - 0xec, 0x6c, 0x72, 0x55, 0x79, 0x4a, 0x96, 0xcc, 0x29, - 0x14, 0x2f, 0x9a, 0x8b, 0xd4, 0x18, 0xe3, 0xc1, 0xfd, - 0x67, 0x34, 0x4b, 0x0c, 0xd0, 0x82, 0x9d, 0xf3, 0xb2, - 0xbe, 0xc6, 0x02, 0x53, 0x19, 0x62, 0x93, 0xc6, 0xb3, - 0x4d, 0x3f, 0x75, 0xd3, 0x2f, 0x21, 0x3d, 0xd4, 0x5c, - 0x62, 0x73, 0xd5, 0x05, 0xad, 0xf4, 0xcc, 0xed, 0x10, - 0x57, 0xcb, 0x75, 0x8f, 0xc2, 0x6a, 0xee, 0xfa, 0x44, - 0x12, 0x55, 0xed, 0x4e, 0x64, 0xc1, 0x99, 0xee, 0x07, - 0x5e, 0x7f, 0x16, 0x64, 0x61, 0x82, 0xfd, 0xb4, 0x64, - 0x73, 0x9b, 0x68, 0xab, 0x5d, 0xaf, 0xf0, 0xe6, 0x3e, - 0x95, 0x52, 0x01, 0x68, 0x24, 0xf0, 0x54, 0xbf, 0x4d, - 0x3c, 0x8c, 0x90, 0xa9, 0x7b, 0xb6, 0xb6, 0x55, 0x32, - 0x84, 0xeb, 0x42, 0x9f, 0xcc, - }, - }, - }, - }, -} diff --git a/src/pkg/crypto/rsa/testdata/pss-vect.txt.bz2 b/src/pkg/crypto/rsa/testdata/pss-vect.txt.bz2 deleted file mode 100644 index ad3da1ac4..000000000 Binary files a/src/pkg/crypto/rsa/testdata/pss-vect.txt.bz2 and /dev/null differ diff --git a/src/pkg/crypto/sha1/example_test.go b/src/pkg/crypto/sha1/example_test.go deleted file mode 100644 index 42aec8afa..000000000 --- a/src/pkg/crypto/sha1/example_test.go +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package sha1_test - -import ( - "crypto/sha1" - "fmt" - "io" -) - -func ExampleNew() { - h := sha1.New() - io.WriteString(h, "His money is twice tainted:") - io.WriteString(h, " 'taint yours and 'taint mine.") - fmt.Printf("% x", h.Sum(nil)) - // Output: 59 7f 6a 54 00 10 f9 4c 15 d7 18 06 a9 9a 2c 87 10 e7 47 bd -} - -func ExampleSum() { - data := []byte("This page intentionally left blank.") - fmt.Printf("% x", sha1.Sum(data)) - // Output: af 06 49 23 bb f2 30 15 96 aa c4 c2 73 ba 32 17 8e bc 4a 96 -} diff --git a/src/pkg/crypto/sha1/sha1.go b/src/pkg/crypto/sha1/sha1.go deleted file mode 100644 index 9f1a96e36..000000000 --- a/src/pkg/crypto/sha1/sha1.go +++ /dev/null @@ -1,130 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package sha1 implements the SHA1 hash algorithm as defined in RFC 3174. -package sha1 - -import ( - "crypto" - "hash" -) - -func init() { - crypto.RegisterHash(crypto.SHA1, New) -} - -// The size of a SHA1 checksum in bytes. -const Size = 20 - -// The blocksize of SHA1 in bytes. -const BlockSize = 64 - -const ( - chunk = 64 - init0 = 0x67452301 - init1 = 0xEFCDAB89 - init2 = 0x98BADCFE - init3 = 0x10325476 - init4 = 0xC3D2E1F0 -) - -// digest represents the partial evaluation of a checksum. -type digest struct { - h [5]uint32 - x [chunk]byte - nx int - len uint64 -} - -func (d *digest) Reset() { - d.h[0] = init0 - d.h[1] = init1 - d.h[2] = init2 - d.h[3] = init3 - d.h[4] = init4 - d.nx = 0 - d.len = 0 -} - -// New returns a new hash.Hash computing the SHA1 checksum. -func New() hash.Hash { - d := new(digest) - d.Reset() - return d -} - -func (d *digest) Size() int { return Size } - -func (d *digest) BlockSize() int { return BlockSize } - -func (d *digest) Write(p []byte) (nn int, err error) { - nn = len(p) - d.len += uint64(nn) - if d.nx > 0 { - n := copy(d.x[d.nx:], p) - d.nx += n - if d.nx == chunk { - block(d, d.x[:]) - d.nx = 0 - } - p = p[n:] - } - if len(p) >= chunk { - n := len(p) &^ (chunk - 1) - block(d, p[:n]) - p = p[n:] - } - if len(p) > 0 { - d.nx = copy(d.x[:], p) - } - return -} - -func (d0 *digest) Sum(in []byte) []byte { - // Make a copy of d0 so that caller can keep writing and summing. - d := *d0 - hash := d.checkSum() - return append(in, hash[:]...) -} - -func (d *digest) checkSum() [Size]byte { - len := d.len - // Padding. Add a 1 bit and 0 bits until 56 bytes mod 64. - var tmp [64]byte - tmp[0] = 0x80 - if len%64 < 56 { - d.Write(tmp[0 : 56-len%64]) - } else { - d.Write(tmp[0 : 64+56-len%64]) - } - - // Length in bits. - len <<= 3 - for i := uint(0); i < 8; i++ { - tmp[i] = byte(len >> (56 - 8*i)) - } - d.Write(tmp[0:8]) - - if d.nx != 0 { - panic("d.nx != 0") - } - - var digest [Size]byte - for i, s := range d.h { - digest[i*4] = byte(s >> 24) - digest[i*4+1] = byte(s >> 16) - digest[i*4+2] = byte(s >> 8) - digest[i*4+3] = byte(s) - } - - return digest -} - -// Sum returns the SHA1 checksum of the data. -func Sum(data []byte) [Size]byte { - var d digest - d.Reset() - d.Write(data) - return d.checkSum() -} diff --git a/src/pkg/crypto/sha1/sha1_test.go b/src/pkg/crypto/sha1/sha1_test.go deleted file mode 100644 index 4a629518b..000000000 --- a/src/pkg/crypto/sha1/sha1_test.go +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// SHA1 hash algorithm. See RFC 3174. - -package sha1 - -import ( - "crypto/rand" - "fmt" - "io" - "testing" -) - -type sha1Test struct { - out string - in string -} - -var golden = []sha1Test{ - {"da39a3ee5e6b4b0d3255bfef95601890afd80709", ""}, - {"86f7e437faa5a7fce15d1ddcb9eaeaea377667b8", "a"}, - {"da23614e02469a0d7c7bd1bdab5c9c474b1904dc", "ab"}, - {"a9993e364706816aba3e25717850c26c9cd0d89d", "abc"}, - {"81fe8bfe87576c3ecb22426f8e57847382917acf", "abcd"}, - {"03de6c570bfe24bfc328ccd7ca46b76eadaf4334", "abcde"}, - {"1f8ac10f23c5b5bc1167bda84b833e5c057a77d2", "abcdef"}, - {"2fb5e13419fc89246865e7a324f476ec624e8740", "abcdefg"}, - {"425af12a0743502b322e93a015bcf868e324d56a", "abcdefgh"}, - {"c63b19f1e4c8b5f76b25c49b8b87f57d8e4872a1", "abcdefghi"}, - {"d68c19a0a345b7eab78d5e11e991c026ec60db63", "abcdefghij"}, - {"ebf81ddcbe5bf13aaabdc4d65354fdf2044f38a7", "Discard medicine more than two years old."}, - {"e5dea09392dd886ca63531aaa00571dc07554bb6", "He who has a shady past knows that nice guys finish last."}, - {"45988f7234467b94e3e9494434c96ee3609d8f8f", "I wouldn't marry him with a ten foot pole."}, - {"55dee037eb7460d5a692d1ce11330b260e40c988", "Free! Free!/A trip/to Mars/for 900/empty jars/Burma Shave"}, - {"b7bc5fb91080c7de6b582ea281f8a396d7c0aee8", "The days of the digital watch are numbered. -Tom Stoppard"}, - {"c3aed9358f7c77f523afe86135f06b95b3999797", "Nepal premier won't resign."}, - {"6e29d302bf6e3a5e4305ff318d983197d6906bb9", "For every action there is an equal and opposite government program."}, - {"597f6a540010f94c15d71806a99a2c8710e747bd", "His money is twice tainted: 'taint yours and 'taint mine."}, - {"6859733b2590a8a091cecf50086febc5ceef1e80", "There is no reason for any individual to have a computer in their home. -Ken Olsen, 1977"}, - {"514b2630ec089b8aee18795fc0cf1f4860cdacad", "It's a tiny change to the code and not completely disgusting. - Bob Manchek"}, - {"c5ca0d4a7b6676fc7aa72caa41cc3d5df567ed69", "size: a.out: bad magic"}, - {"74c51fa9a04eadc8c1bbeaa7fc442f834b90a00a", "The major problem is with sendmail. -Mark Horton"}, - {"0b4c4ce5f52c3ad2821852a8dc00217fa18b8b66", "Give me a rock, paper and scissors and I will move the world. CCFestoon"}, - {"3ae7937dd790315beb0f48330e8642237c61550a", "If the enemy is within range, then so are you."}, - {"410a2b296df92b9a47412b13281df8f830a9f44b", "It's well we cannot hear the screams/That we create in others' dreams."}, - {"841e7c85ca1adcddbdd0187f1289acb5c642f7f5", "You remind me of a TV show, but that's all right: I watch it anyway."}, - {"163173b825d03b952601376b25212df66763e1db", "C is as portable as Stonehedge!!"}, - {"32b0377f2687eb88e22106f133c586ab314d5279", "Even if I could be Shakespeare, I think I should still choose to be Faraday. - A. Huxley"}, - {"0885aaf99b569542fd165fa44e322718f4a984e0", "The fugacity of a constituent in a mixture of gases at a given temperature is proportional to its mole fraction. Lewis-Randall Rule"}, - {"6627d6904d71420b0bf3886ab629623538689f45", "How can you write a big system without C++? -Paul Glick"}, -} - -func TestGolden(t *testing.T) { - for i := 0; i < len(golden); i++ { - g := golden[i] - s := fmt.Sprintf("%x", Sum([]byte(g.in))) - if s != g.out { - t.Fatalf("Sum function: sha1(%s) = %s want %s", g.in, s, g.out) - } - c := New() - for j := 0; j < 3; j++ { - if j < 2 { - io.WriteString(c, g.in) - } else { - io.WriteString(c, g.in[0:len(g.in)/2]) - c.Sum(nil) - io.WriteString(c, g.in[len(g.in)/2:]) - } - s := fmt.Sprintf("%x", c.Sum(nil)) - if s != g.out { - t.Fatalf("sha1[%d](%s) = %s want %s", j, g.in, s, g.out) - } - c.Reset() - } - } -} - -func TestSize(t *testing.T) { - c := New() - if got := c.Size(); got != Size { - t.Errorf("Size = %d; want %d", got, Size) - } -} - -func TestBlockSize(t *testing.T) { - c := New() - if got := c.BlockSize(); got != BlockSize { - t.Errorf("BlockSize = %d; want %d", got, BlockSize) - } -} - -// Tests that blockGeneric (pure Go) and block (in assembly for amd64, 386, arm) match. -func TestBlockGeneric(t *testing.T) { - gen, asm := New().(*digest), New().(*digest) - buf := make([]byte, BlockSize*20) // arbitrary factor - rand.Read(buf) - blockGeneric(gen, buf) - block(asm, buf) - if *gen != *asm { - t.Error("block and blockGeneric resulted in different states") - } -} - -var bench = New() -var buf = make([]byte, 8192) - -func benchmarkSize(b *testing.B, size int) { - b.SetBytes(int64(size)) - sum := make([]byte, bench.Size()) - for i := 0; i < b.N; i++ { - bench.Reset() - bench.Write(buf[:size]) - bench.Sum(sum[:0]) - } -} - -func BenchmarkHash8Bytes(b *testing.B) { - benchmarkSize(b, 8) -} - -func BenchmarkHash1K(b *testing.B) { - benchmarkSize(b, 1024) -} - -func BenchmarkHash8K(b *testing.B) { - benchmarkSize(b, 8192) -} diff --git a/src/pkg/crypto/sha1/sha1block.go b/src/pkg/crypto/sha1/sha1block.go deleted file mode 100644 index fde3c981c..000000000 --- a/src/pkg/crypto/sha1/sha1block.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package sha1 - -const ( - _K0 = 0x5A827999 - _K1 = 0x6ED9EBA1 - _K2 = 0x8F1BBCDC - _K3 = 0xCA62C1D6 -) - -// blockGeneric is a portable, pure Go version of the SHA1 block step. -// It's used by sha1block_generic.go and tests. -func blockGeneric(dig *digest, p []byte) { - var w [16]uint32 - - h0, h1, h2, h3, h4 := dig.h[0], dig.h[1], dig.h[2], dig.h[3], dig.h[4] - for len(p) >= chunk { - // Can interlace the computation of w with the - // rounds below if needed for speed. - for i := 0; i < 16; i++ { - j := i * 4 - w[i] = uint32(p[j])<<24 | uint32(p[j+1])<<16 | uint32(p[j+2])<<8 | uint32(p[j+3]) - } - - a, b, c, d, e := h0, h1, h2, h3, h4 - - // Each of the four 20-iteration rounds - // differs only in the computation of f and - // the choice of K (_K0, _K1, etc). - i := 0 - for ; i < 16; i++ { - f := b&c | (^b)&d - a5 := a<<5 | a>>(32-5) - b30 := b<<30 | b>>(32-30) - t := a5 + f + e + w[i&0xf] + _K0 - a, b, c, d, e = t, a, b30, c, d - } - for ; i < 20; i++ { - tmp := w[(i-3)&0xf] ^ w[(i-8)&0xf] ^ w[(i-14)&0xf] ^ w[(i)&0xf] - w[i&0xf] = tmp<<1 | tmp>>(32-1) - - f := b&c | (^b)&d - a5 := a<<5 | a>>(32-5) - b30 := b<<30 | b>>(32-30) - t := a5 + f + e + w[i&0xf] + _K0 - a, b, c, d, e = t, a, b30, c, d - } - for ; i < 40; i++ { - tmp := w[(i-3)&0xf] ^ w[(i-8)&0xf] ^ w[(i-14)&0xf] ^ w[(i)&0xf] - w[i&0xf] = tmp<<1 | tmp>>(32-1) - f := b ^ c ^ d - a5 := a<<5 | a>>(32-5) - b30 := b<<30 | b>>(32-30) - t := a5 + f + e + w[i&0xf] + _K1 - a, b, c, d, e = t, a, b30, c, d - } - for ; i < 60; i++ { - tmp := w[(i-3)&0xf] ^ w[(i-8)&0xf] ^ w[(i-14)&0xf] ^ w[(i)&0xf] - w[i&0xf] = tmp<<1 | tmp>>(32-1) - f := ((b | c) & d) | (b & c) - - a5 := a<<5 | a>>(32-5) - b30 := b<<30 | b>>(32-30) - t := a5 + f + e + w[i&0xf] + _K2 - a, b, c, d, e = t, a, b30, c, d - } - for ; i < 80; i++ { - tmp := w[(i-3)&0xf] ^ w[(i-8)&0xf] ^ w[(i-14)&0xf] ^ w[(i)&0xf] - w[i&0xf] = tmp<<1 | tmp>>(32-1) - f := b ^ c ^ d - a5 := a<<5 | a>>(32-5) - b30 := b<<30 | b>>(32-30) - t := a5 + f + e + w[i&0xf] + _K3 - a, b, c, d, e = t, a, b30, c, d - } - - h0 += a - h1 += b - h2 += c - h3 += d - h4 += e - - p = p[chunk:] - } - - dig.h[0], dig.h[1], dig.h[2], dig.h[3], dig.h[4] = h0, h1, h2, h3, h4 -} diff --git a/src/pkg/crypto/sha1/sha1block_386.s b/src/pkg/crypto/sha1/sha1block_386.s deleted file mode 100644 index a0adabc3c..000000000 --- a/src/pkg/crypto/sha1/sha1block_386.s +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "textflag.h" - -// SHA1 block routine. See sha1block.go for Go equivalent. -// -// There are 80 rounds of 4 types: -// - rounds 0-15 are type 1 and load data (ROUND1 macro). -// - rounds 16-19 are type 1 and do not load data (ROUND1x macro). -// - rounds 20-39 are type 2 and do not load data (ROUND2 macro). -// - rounds 40-59 are type 3 and do not load data (ROUND3 macro). -// - rounds 60-79 are type 4 and do not load data (ROUND4 macro). -// -// Each round loads or shuffles the data, then computes a per-round -// function of b, c, d, and then mixes the result into and rotates the -// five registers a, b, c, d, e holding the intermediate results. -// -// The register rotation is implemented by rotating the arguments to -// the round macros instead of by explicit move instructions. - -// Like sha1block_amd64.s, but we keep the data and limit pointers on the stack. -// To free up the word pointer (R10 on amd64, DI here), we add it to e during -// LOAD/SHUFFLE instead of during MIX. -// -// The stack holds the intermediate word array - 16 uint32s - at 0(SP) up to 64(SP). -// The saved a, b, c, d, e (R11 through R15 on amd64) are at 64(SP) up to 84(SP). -// The saved limit pointer (DI on amd64) is at 84(SP). -// The saved data pointer (SI on amd64) is at 88(SP). - -#define LOAD(index, e) \ - MOVL 88(SP), SI; \ - MOVL (index*4)(SI), DI; \ - BSWAPL DI; \ - MOVL DI, (index*4)(SP); \ - ADDL DI, e - -#define SHUFFLE(index, e) \ - MOVL (((index)&0xf)*4)(SP), DI; \ - XORL (((index-3)&0xf)*4)(SP), DI; \ - XORL (((index-8)&0xf)*4)(SP), DI; \ - XORL (((index-14)&0xf)*4)(SP), DI; \ - ROLL $1, DI; \ - MOVL DI, (((index)&0xf)*4)(SP); \ - ADDL DI, e - -#define FUNC1(a, b, c, d, e) \ - MOVL d, DI; \ - XORL c, DI; \ - ANDL b, DI; \ - XORL d, DI - -#define FUNC2(a, b, c, d, e) \ - MOVL b, DI; \ - XORL c, DI; \ - XORL d, DI - -#define FUNC3(a, b, c, d, e) \ - MOVL b, SI; \ - ORL c, SI; \ - ANDL d, SI; \ - MOVL b, DI; \ - ANDL c, DI; \ - ORL SI, DI - -#define FUNC4 FUNC2 - -#define MIX(a, b, c, d, e, const) \ - ROLL $30, b; \ - ADDL DI, e; \ - MOVL a, SI; \ - ROLL $5, SI; \ - LEAL const(e)(SI*1), e - -#define ROUND1(a, b, c, d, e, index) \ - LOAD(index, e); \ - FUNC1(a, b, c, d, e); \ - MIX(a, b, c, d, e, 0x5A827999) - -#define ROUND1x(a, b, c, d, e, index) \ - SHUFFLE(index, e); \ - FUNC1(a, b, c, d, e); \ - MIX(a, b, c, d, e, 0x5A827999) - -#define ROUND2(a, b, c, d, e, index) \ - SHUFFLE(index, e); \ - FUNC2(a, b, c, d, e); \ - MIX(a, b, c, d, e, 0x6ED9EBA1) - -#define ROUND3(a, b, c, d, e, index) \ - SHUFFLE(index, e); \ - FUNC3(a, b, c, d, e); \ - MIX(a, b, c, d, e, 0x8F1BBCDC) - -#define ROUND4(a, b, c, d, e, index) \ - SHUFFLE(index, e); \ - FUNC4(a, b, c, d, e); \ - MIX(a, b, c, d, e, 0xCA62C1D6) - -// func block(dig *digest, p []byte) -TEXT ·block(SB),NOSPLIT,$92-16 - MOVL dig+0(FP), BP - MOVL p+4(FP), SI - MOVL p_len+8(FP), DX - SHRL $6, DX - SHLL $6, DX - - LEAL (SI)(DX*1), DI - MOVL (0*4)(BP), AX - MOVL (1*4)(BP), BX - MOVL (2*4)(BP), CX - MOVL (3*4)(BP), DX - MOVL (4*4)(BP), BP - - CMPL SI, DI - JEQ end - - MOVL DI, 84(SP) - -loop: - MOVL SI, 88(SP) - - MOVL AX, 64(SP) - MOVL BX, 68(SP) - MOVL CX, 72(SP) - MOVL DX, 76(SP) - MOVL BP, 80(SP) - - ROUND1(AX, BX, CX, DX, BP, 0) - ROUND1(BP, AX, BX, CX, DX, 1) - ROUND1(DX, BP, AX, BX, CX, 2) - ROUND1(CX, DX, BP, AX, BX, 3) - ROUND1(BX, CX, DX, BP, AX, 4) - ROUND1(AX, BX, CX, DX, BP, 5) - ROUND1(BP, AX, BX, CX, DX, 6) - ROUND1(DX, BP, AX, BX, CX, 7) - ROUND1(CX, DX, BP, AX, BX, 8) - ROUND1(BX, CX, DX, BP, AX, 9) - ROUND1(AX, BX, CX, DX, BP, 10) - ROUND1(BP, AX, BX, CX, DX, 11) - ROUND1(DX, BP, AX, BX, CX, 12) - ROUND1(CX, DX, BP, AX, BX, 13) - ROUND1(BX, CX, DX, BP, AX, 14) - ROUND1(AX, BX, CX, DX, BP, 15) - - ROUND1x(BP, AX, BX, CX, DX, 16) - ROUND1x(DX, BP, AX, BX, CX, 17) - ROUND1x(CX, DX, BP, AX, BX, 18) - ROUND1x(BX, CX, DX, BP, AX, 19) - - ROUND2(AX, BX, CX, DX, BP, 20) - ROUND2(BP, AX, BX, CX, DX, 21) - ROUND2(DX, BP, AX, BX, CX, 22) - ROUND2(CX, DX, BP, AX, BX, 23) - ROUND2(BX, CX, DX, BP, AX, 24) - ROUND2(AX, BX, CX, DX, BP, 25) - ROUND2(BP, AX, BX, CX, DX, 26) - ROUND2(DX, BP, AX, BX, CX, 27) - ROUND2(CX, DX, BP, AX, BX, 28) - ROUND2(BX, CX, DX, BP, AX, 29) - ROUND2(AX, BX, CX, DX, BP, 30) - ROUND2(BP, AX, BX, CX, DX, 31) - ROUND2(DX, BP, AX, BX, CX, 32) - ROUND2(CX, DX, BP, AX, BX, 33) - ROUND2(BX, CX, DX, BP, AX, 34) - ROUND2(AX, BX, CX, DX, BP, 35) - ROUND2(BP, AX, BX, CX, DX, 36) - ROUND2(DX, BP, AX, BX, CX, 37) - ROUND2(CX, DX, BP, AX, BX, 38) - ROUND2(BX, CX, DX, BP, AX, 39) - - ROUND3(AX, BX, CX, DX, BP, 40) - ROUND3(BP, AX, BX, CX, DX, 41) - ROUND3(DX, BP, AX, BX, CX, 42) - ROUND3(CX, DX, BP, AX, BX, 43) - ROUND3(BX, CX, DX, BP, AX, 44) - ROUND3(AX, BX, CX, DX, BP, 45) - ROUND3(BP, AX, BX, CX, DX, 46) - ROUND3(DX, BP, AX, BX, CX, 47) - ROUND3(CX, DX, BP, AX, BX, 48) - ROUND3(BX, CX, DX, BP, AX, 49) - ROUND3(AX, BX, CX, DX, BP, 50) - ROUND3(BP, AX, BX, CX, DX, 51) - ROUND3(DX, BP, AX, BX, CX, 52) - ROUND3(CX, DX, BP, AX, BX, 53) - ROUND3(BX, CX, DX, BP, AX, 54) - ROUND3(AX, BX, CX, DX, BP, 55) - ROUND3(BP, AX, BX, CX, DX, 56) - ROUND3(DX, BP, AX, BX, CX, 57) - ROUND3(CX, DX, BP, AX, BX, 58) - ROUND3(BX, CX, DX, BP, AX, 59) - - ROUND4(AX, BX, CX, DX, BP, 60) - ROUND4(BP, AX, BX, CX, DX, 61) - ROUND4(DX, BP, AX, BX, CX, 62) - ROUND4(CX, DX, BP, AX, BX, 63) - ROUND4(BX, CX, DX, BP, AX, 64) - ROUND4(AX, BX, CX, DX, BP, 65) - ROUND4(BP, AX, BX, CX, DX, 66) - ROUND4(DX, BP, AX, BX, CX, 67) - ROUND4(CX, DX, BP, AX, BX, 68) - ROUND4(BX, CX, DX, BP, AX, 69) - ROUND4(AX, BX, CX, DX, BP, 70) - ROUND4(BP, AX, BX, CX, DX, 71) - ROUND4(DX, BP, AX, BX, CX, 72) - ROUND4(CX, DX, BP, AX, BX, 73) - ROUND4(BX, CX, DX, BP, AX, 74) - ROUND4(AX, BX, CX, DX, BP, 75) - ROUND4(BP, AX, BX, CX, DX, 76) - ROUND4(DX, BP, AX, BX, CX, 77) - ROUND4(CX, DX, BP, AX, BX, 78) - ROUND4(BX, CX, DX, BP, AX, 79) - - ADDL 64(SP), AX - ADDL 68(SP), BX - ADDL 72(SP), CX - ADDL 76(SP), DX - ADDL 80(SP), BP - - MOVL 88(SP), SI - ADDL $64, SI - CMPL SI, 84(SP) - JB loop - -end: - MOVL dig+0(FP), DI - MOVL AX, (0*4)(DI) - MOVL BX, (1*4)(DI) - MOVL CX, (2*4)(DI) - MOVL DX, (3*4)(DI) - MOVL BP, (4*4)(DI) - RET diff --git a/src/pkg/crypto/sha1/sha1block_amd64.s b/src/pkg/crypto/sha1/sha1block_amd64.s deleted file mode 100644 index 4319df63e..000000000 --- a/src/pkg/crypto/sha1/sha1block_amd64.s +++ /dev/null @@ -1,216 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "textflag.h" - -// SHA1 block routine. See sha1block.go for Go equivalent. -// -// There are 80 rounds of 4 types: -// - rounds 0-15 are type 1 and load data (ROUND1 macro). -// - rounds 16-19 are type 1 and do not load data (ROUND1x macro). -// - rounds 20-39 are type 2 and do not load data (ROUND2 macro). -// - rounds 40-59 are type 3 and do not load data (ROUND3 macro). -// - rounds 60-79 are type 4 and do not load data (ROUND4 macro). -// -// Each round loads or shuffles the data, then computes a per-round -// function of b, c, d, and then mixes the result into and rotates the -// five registers a, b, c, d, e holding the intermediate results. -// -// The register rotation is implemented by rotating the arguments to -// the round macros instead of by explicit move instructions. - -#define LOAD(index) \ - MOVL (index*4)(SI), R10; \ - BSWAPL R10; \ - MOVL R10, (index*4)(SP) - -#define SHUFFLE(index) \ - MOVL (((index)&0xf)*4)(SP), R10; \ - XORL (((index-3)&0xf)*4)(SP), R10; \ - XORL (((index-8)&0xf)*4)(SP), R10; \ - XORL (((index-14)&0xf)*4)(SP), R10; \ - ROLL $1, R10; \ - MOVL R10, (((index)&0xf)*4)(SP) - -#define FUNC1(a, b, c, d, e) \ - MOVL d, R9; \ - XORL c, R9; \ - ANDL b, R9; \ - XORL d, R9 - -#define FUNC2(a, b, c, d, e) \ - MOVL b, R9; \ - XORL c, R9; \ - XORL d, R9 - -#define FUNC3(a, b, c, d, e) \ - MOVL b, R8; \ - ORL c, R8; \ - ANDL d, R8; \ - MOVL b, R9; \ - ANDL c, R9; \ - ORL R8, R9 - -#define FUNC4 FUNC2 - -#define MIX(a, b, c, d, e, const) \ - ROLL $30, b; \ - ADDL R9, e; \ - MOVL a, R8; \ - ROLL $5, R8; \ - LEAL const(e)(R10*1), e; \ - ADDL R8, e - -#define ROUND1(a, b, c, d, e, index) \ - LOAD(index); \ - FUNC1(a, b, c, d, e); \ - MIX(a, b, c, d, e, 0x5A827999) - -#define ROUND1x(a, b, c, d, e, index) \ - SHUFFLE(index); \ - FUNC1(a, b, c, d, e); \ - MIX(a, b, c, d, e, 0x5A827999) - -#define ROUND2(a, b, c, d, e, index) \ - SHUFFLE(index); \ - FUNC2(a, b, c, d, e); \ - MIX(a, b, c, d, e, 0x6ED9EBA1) - -#define ROUND3(a, b, c, d, e, index) \ - SHUFFLE(index); \ - FUNC3(a, b, c, d, e); \ - MIX(a, b, c, d, e, 0x8F1BBCDC) - -#define ROUND4(a, b, c, d, e, index) \ - SHUFFLE(index); \ - FUNC4(a, b, c, d, e); \ - MIX(a, b, c, d, e, 0xCA62C1D6) - -TEXT ·block(SB),NOSPLIT,$64-32 - MOVQ dig+0(FP), BP - MOVQ p_base+8(FP), SI - MOVQ p_len+16(FP), DX - SHRQ $6, DX - SHLQ $6, DX - - LEAQ (SI)(DX*1), DI - MOVL (0*4)(BP), AX - MOVL (1*4)(BP), BX - MOVL (2*4)(BP), CX - MOVL (3*4)(BP), DX - MOVL (4*4)(BP), BP - - CMPQ SI, DI - JEQ end - -loop: - MOVL AX, R11 - MOVL BX, R12 - MOVL CX, R13 - MOVL DX, R14 - MOVL BP, R15 - - ROUND1(AX, BX, CX, DX, BP, 0) - ROUND1(BP, AX, BX, CX, DX, 1) - ROUND1(DX, BP, AX, BX, CX, 2) - ROUND1(CX, DX, BP, AX, BX, 3) - ROUND1(BX, CX, DX, BP, AX, 4) - ROUND1(AX, BX, CX, DX, BP, 5) - ROUND1(BP, AX, BX, CX, DX, 6) - ROUND1(DX, BP, AX, BX, CX, 7) - ROUND1(CX, DX, BP, AX, BX, 8) - ROUND1(BX, CX, DX, BP, AX, 9) - ROUND1(AX, BX, CX, DX, BP, 10) - ROUND1(BP, AX, BX, CX, DX, 11) - ROUND1(DX, BP, AX, BX, CX, 12) - ROUND1(CX, DX, BP, AX, BX, 13) - ROUND1(BX, CX, DX, BP, AX, 14) - ROUND1(AX, BX, CX, DX, BP, 15) - - ROUND1x(BP, AX, BX, CX, DX, 16) - ROUND1x(DX, BP, AX, BX, CX, 17) - ROUND1x(CX, DX, BP, AX, BX, 18) - ROUND1x(BX, CX, DX, BP, AX, 19) - - ROUND2(AX, BX, CX, DX, BP, 20) - ROUND2(BP, AX, BX, CX, DX, 21) - ROUND2(DX, BP, AX, BX, CX, 22) - ROUND2(CX, DX, BP, AX, BX, 23) - ROUND2(BX, CX, DX, BP, AX, 24) - ROUND2(AX, BX, CX, DX, BP, 25) - ROUND2(BP, AX, BX, CX, DX, 26) - ROUND2(DX, BP, AX, BX, CX, 27) - ROUND2(CX, DX, BP, AX, BX, 28) - ROUND2(BX, CX, DX, BP, AX, 29) - ROUND2(AX, BX, CX, DX, BP, 30) - ROUND2(BP, AX, BX, CX, DX, 31) - ROUND2(DX, BP, AX, BX, CX, 32) - ROUND2(CX, DX, BP, AX, BX, 33) - ROUND2(BX, CX, DX, BP, AX, 34) - ROUND2(AX, BX, CX, DX, BP, 35) - ROUND2(BP, AX, BX, CX, DX, 36) - ROUND2(DX, BP, AX, BX, CX, 37) - ROUND2(CX, DX, BP, AX, BX, 38) - ROUND2(BX, CX, DX, BP, AX, 39) - - ROUND3(AX, BX, CX, DX, BP, 40) - ROUND3(BP, AX, BX, CX, DX, 41) - ROUND3(DX, BP, AX, BX, CX, 42) - ROUND3(CX, DX, BP, AX, BX, 43) - ROUND3(BX, CX, DX, BP, AX, 44) - ROUND3(AX, BX, CX, DX, BP, 45) - ROUND3(BP, AX, BX, CX, DX, 46) - ROUND3(DX, BP, AX, BX, CX, 47) - ROUND3(CX, DX, BP, AX, BX, 48) - ROUND3(BX, CX, DX, BP, AX, 49) - ROUND3(AX, BX, CX, DX, BP, 50) - ROUND3(BP, AX, BX, CX, DX, 51) - ROUND3(DX, BP, AX, BX, CX, 52) - ROUND3(CX, DX, BP, AX, BX, 53) - ROUND3(BX, CX, DX, BP, AX, 54) - ROUND3(AX, BX, CX, DX, BP, 55) - ROUND3(BP, AX, BX, CX, DX, 56) - ROUND3(DX, BP, AX, BX, CX, 57) - ROUND3(CX, DX, BP, AX, BX, 58) - ROUND3(BX, CX, DX, BP, AX, 59) - - ROUND4(AX, BX, CX, DX, BP, 60) - ROUND4(BP, AX, BX, CX, DX, 61) - ROUND4(DX, BP, AX, BX, CX, 62) - ROUND4(CX, DX, BP, AX, BX, 63) - ROUND4(BX, CX, DX, BP, AX, 64) - ROUND4(AX, BX, CX, DX, BP, 65) - ROUND4(BP, AX, BX, CX, DX, 66) - ROUND4(DX, BP, AX, BX, CX, 67) - ROUND4(CX, DX, BP, AX, BX, 68) - ROUND4(BX, CX, DX, BP, AX, 69) - ROUND4(AX, BX, CX, DX, BP, 70) - ROUND4(BP, AX, BX, CX, DX, 71) - ROUND4(DX, BP, AX, BX, CX, 72) - ROUND4(CX, DX, BP, AX, BX, 73) - ROUND4(BX, CX, DX, BP, AX, 74) - ROUND4(AX, BX, CX, DX, BP, 75) - ROUND4(BP, AX, BX, CX, DX, 76) - ROUND4(DX, BP, AX, BX, CX, 77) - ROUND4(CX, DX, BP, AX, BX, 78) - ROUND4(BX, CX, DX, BP, AX, 79) - - ADDL R11, AX - ADDL R12, BX - ADDL R13, CX - ADDL R14, DX - ADDL R15, BP - - ADDQ $64, SI - CMPQ SI, DI - JB loop - -end: - MOVQ dig+0(FP), DI - MOVL AX, (0*4)(DI) - MOVL BX, (1*4)(DI) - MOVL CX, (2*4)(DI) - MOVL DX, (3*4)(DI) - MOVL BP, (4*4)(DI) - RET diff --git a/src/pkg/crypto/sha1/sha1block_amd64p32.s b/src/pkg/crypto/sha1/sha1block_amd64p32.s deleted file mode 100644 index d93fbf1ed..000000000 --- a/src/pkg/crypto/sha1/sha1block_amd64p32.s +++ /dev/null @@ -1,216 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "textflag.h" - -// SHA1 block routine. See sha1block.go for Go equivalent. -// -// There are 80 rounds of 4 types: -// - rounds 0-15 are type 1 and load data (ROUND1 macro). -// - rounds 16-19 are type 1 and do not load data (ROUND1x macro). -// - rounds 20-39 are type 2 and do not load data (ROUND2 macro). -// - rounds 40-59 are type 3 and do not load data (ROUND3 macro). -// - rounds 60-79 are type 4 and do not load data (ROUND4 macro). -// -// Each round loads or shuffles the data, then computes a per-round -// function of b, c, d, and then mixes the result into and rotates the -// five registers a, b, c, d, e holding the intermediate results. -// -// The register rotation is implemented by rotating the arguments to -// the round macros instead of by explicit move instructions. -// -// amd64p32 version. -// To ensure safety for Native Client, avoids use of BP and R15 -// as well as two-register addressing modes. - -#define LOAD(index) \ - MOVL (index*4)(SI), R10; \ - BSWAPL R10; \ - MOVL R10, (index*4)(SP) - -#define SHUFFLE(index) \ - MOVL (((index)&0xf)*4)(SP), R10; \ - XORL (((index-3)&0xf)*4)(SP), R10; \ - XORL (((index-8)&0xf)*4)(SP), R10; \ - XORL (((index-14)&0xf)*4)(SP), R10; \ - ROLL $1, R10; \ - MOVL R10, (((index)&0xf)*4)(SP) - -#define FUNC1(a, b, c, d, e) \ - MOVL d, R9; \ - XORL c, R9; \ - ANDL b, R9; \ - XORL d, R9 - -#define FUNC2(a, b, c, d, e) \ - MOVL b, R9; \ - XORL c, R9; \ - XORL d, R9 - -#define FUNC3(a, b, c, d, e) \ - MOVL b, R8; \ - ORL c, R8; \ - ANDL d, R8; \ - MOVL b, R9; \ - ANDL c, R9; \ - ORL R8, R9 - -#define FUNC4 FUNC2 - -#define MIX(a, b, c, d, e, const) \ - ROLL $30, b; \ - ADDL R9, e; \ - MOVL a, R8; \ - ROLL $5, R8; \ - LEAL const(e)(R10*1), e; \ - ADDL R8, e - -#define ROUND1(a, b, c, d, e, index) \ - LOAD(index); \ - FUNC1(a, b, c, d, e); \ - MIX(a, b, c, d, e, 0x5A827999) - -#define ROUND1x(a, b, c, d, e, index) \ - SHUFFLE(index); \ - FUNC1(a, b, c, d, e); \ - MIX(a, b, c, d, e, 0x5A827999) - -#define ROUND2(a, b, c, d, e, index) \ - SHUFFLE(index); \ - FUNC2(a, b, c, d, e); \ - MIX(a, b, c, d, e, 0x6ED9EBA1) - -#define ROUND3(a, b, c, d, e, index) \ - SHUFFLE(index); \ - FUNC3(a, b, c, d, e); \ - MIX(a, b, c, d, e, 0x8F1BBCDC) - -#define ROUND4(a, b, c, d, e, index) \ - SHUFFLE(index); \ - FUNC4(a, b, c, d, e); \ - MIX(a, b, c, d, e, 0xCA62C1D6) - -TEXT ·block(SB),NOSPLIT,$64-32 - MOVL dig+0(FP), R14 - MOVL p_base+4(FP), SI - MOVL p_len+8(FP), DX - SHRQ $6, DX - SHLQ $6, DX - - LEAQ (SI)(DX*1), DI - MOVL (0*4)(R14), AX - MOVL (1*4)(R14), BX - MOVL (2*4)(R14), CX - MOVL (3*4)(R14), DX - MOVL (4*4)(R14), R13 - - CMPQ SI, DI - JEQ end - -loop: -#define BP R13 /* keep diff from sha1block_amd64.s small */ - ROUND1(AX, BX, CX, DX, BP, 0) - ROUND1(BP, AX, BX, CX, DX, 1) - ROUND1(DX, BP, AX, BX, CX, 2) - ROUND1(CX, DX, BP, AX, BX, 3) - ROUND1(BX, CX, DX, BP, AX, 4) - ROUND1(AX, BX, CX, DX, BP, 5) - ROUND1(BP, AX, BX, CX, DX, 6) - ROUND1(DX, BP, AX, BX, CX, 7) - ROUND1(CX, DX, BP, AX, BX, 8) - ROUND1(BX, CX, DX, BP, AX, 9) - ROUND1(AX, BX, CX, DX, BP, 10) - ROUND1(BP, AX, BX, CX, DX, 11) - ROUND1(DX, BP, AX, BX, CX, 12) - ROUND1(CX, DX, BP, AX, BX, 13) - ROUND1(BX, CX, DX, BP, AX, 14) - ROUND1(AX, BX, CX, DX, BP, 15) - - ROUND1x(BP, AX, BX, CX, DX, 16) - ROUND1x(DX, BP, AX, BX, CX, 17) - ROUND1x(CX, DX, BP, AX, BX, 18) - ROUND1x(BX, CX, DX, BP, AX, 19) - - ROUND2(AX, BX, CX, DX, BP, 20) - ROUND2(BP, AX, BX, CX, DX, 21) - ROUND2(DX, BP, AX, BX, CX, 22) - ROUND2(CX, DX, BP, AX, BX, 23) - ROUND2(BX, CX, DX, BP, AX, 24) - ROUND2(AX, BX, CX, DX, BP, 25) - ROUND2(BP, AX, BX, CX, DX, 26) - ROUND2(DX, BP, AX, BX, CX, 27) - ROUND2(CX, DX, BP, AX, BX, 28) - ROUND2(BX, CX, DX, BP, AX, 29) - ROUND2(AX, BX, CX, DX, BP, 30) - ROUND2(BP, AX, BX, CX, DX, 31) - ROUND2(DX, BP, AX, BX, CX, 32) - ROUND2(CX, DX, BP, AX, BX, 33) - ROUND2(BX, CX, DX, BP, AX, 34) - ROUND2(AX, BX, CX, DX, BP, 35) - ROUND2(BP, AX, BX, CX, DX, 36) - ROUND2(DX, BP, AX, BX, CX, 37) - ROUND2(CX, DX, BP, AX, BX, 38) - ROUND2(BX, CX, DX, BP, AX, 39) - - ROUND3(AX, BX, CX, DX, BP, 40) - ROUND3(BP, AX, BX, CX, DX, 41) - ROUND3(DX, BP, AX, BX, CX, 42) - ROUND3(CX, DX, BP, AX, BX, 43) - ROUND3(BX, CX, DX, BP, AX, 44) - ROUND3(AX, BX, CX, DX, BP, 45) - ROUND3(BP, AX, BX, CX, DX, 46) - ROUND3(DX, BP, AX, BX, CX, 47) - ROUND3(CX, DX, BP, AX, BX, 48) - ROUND3(BX, CX, DX, BP, AX, 49) - ROUND3(AX, BX, CX, DX, BP, 50) - ROUND3(BP, AX, BX, CX, DX, 51) - ROUND3(DX, BP, AX, BX, CX, 52) - ROUND3(CX, DX, BP, AX, BX, 53) - ROUND3(BX, CX, DX, BP, AX, 54) - ROUND3(AX, BX, CX, DX, BP, 55) - ROUND3(BP, AX, BX, CX, DX, 56) - ROUND3(DX, BP, AX, BX, CX, 57) - ROUND3(CX, DX, BP, AX, BX, 58) - ROUND3(BX, CX, DX, BP, AX, 59) - - ROUND4(AX, BX, CX, DX, BP, 60) - ROUND4(BP, AX, BX, CX, DX, 61) - ROUND4(DX, BP, AX, BX, CX, 62) - ROUND4(CX, DX, BP, AX, BX, 63) - ROUND4(BX, CX, DX, BP, AX, 64) - ROUND4(AX, BX, CX, DX, BP, 65) - ROUND4(BP, AX, BX, CX, DX, 66) - ROUND4(DX, BP, AX, BX, CX, 67) - ROUND4(CX, DX, BP, AX, BX, 68) - ROUND4(BX, CX, DX, BP, AX, 69) - ROUND4(AX, BX, CX, DX, BP, 70) - ROUND4(BP, AX, BX, CX, DX, 71) - ROUND4(DX, BP, AX, BX, CX, 72) - ROUND4(CX, DX, BP, AX, BX, 73) - ROUND4(BX, CX, DX, BP, AX, 74) - ROUND4(AX, BX, CX, DX, BP, 75) - ROUND4(BP, AX, BX, CX, DX, 76) - ROUND4(DX, BP, AX, BX, CX, 77) - ROUND4(CX, DX, BP, AX, BX, 78) - ROUND4(BX, CX, DX, BP, AX, 79) -#undef BP - - ADDL (0*4)(R14), AX - ADDL (1*4)(R14), BX - ADDL (2*4)(R14), CX - ADDL (3*4)(R14), DX - ADDL (4*4)(R14), R13 - - MOVL AX, (0*4)(R14) - MOVL BX, (1*4)(R14) - MOVL CX, (2*4)(R14) - MOVL DX, (3*4)(R14) - MOVL R13, (4*4)(R14) - - ADDQ $64, SI - CMPQ SI, DI - JB loop - -end: - RET diff --git a/src/pkg/crypto/sha1/sha1block_arm.s b/src/pkg/crypto/sha1/sha1block_arm.s deleted file mode 100644 index f11f33dc3..000000000 --- a/src/pkg/crypto/sha1/sha1block_arm.s +++ /dev/null @@ -1,217 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. -// -// ARM version of md5block.go - -#include "textflag.h" - -// SHA1 block routine. See sha1block.go for Go equivalent. -// -// There are 80 rounds of 4 types: -// - rounds 0-15 are type 1 and load data (ROUND1 macro). -// - rounds 16-19 are type 1 and do not load data (ROUND1x macro). -// - rounds 20-39 are type 2 and do not load data (ROUND2 macro). -// - rounds 40-59 are type 3 and do not load data (ROUND3 macro). -// - rounds 60-79 are type 4 and do not load data (ROUND4 macro). -// -// Each round loads or shuffles the data, then computes a per-round -// function of b, c, d, and then mixes the result into and rotates the -// five registers a, b, c, d, e holding the intermediate results. -// -// The register rotation is implemented by rotating the arguments to -// the round macros instead of by explicit move instructions. - -// Register definitions -data = 0 // Pointer to incoming data -const = 1 // Current constant for SHA round -a = 2 // SHA1 accumulator -b = 3 // SHA1 accumulator -c = 4 // SHA1 accumulator -d = 5 // SHA1 accumulator -e = 6 // SHA1 accumulator -t0 = 7 // Temporary -t1 = 8 // Temporary -// r9, r10 are forbidden -// r11 is OK provided you check the assembler that no synthetic instructions use it -t2 = 11 // Temporary -ctr = 12 // loop counter -w = 14 // point to w buffer - -// func block(dig *digest, p []byte) -// 0(FP) is *digest -// 4(FP) is p.array (struct Slice) -// 8(FP) is p.len -//12(FP) is p.cap -// -// Stack frame -p_end = -4 // -4(SP) pointer to the end of data -p_data = p_end - 4 // -8(SP) current data pointer -w_buf = p_data - 4*80 // -328(SP) 80 words temporary buffer w uint32[80] -saved = w_buf - 4*5 // -348(SP) saved sha1 registers a,b,c,d,e - these must be last -// Total size +4 for saved LR is 352 - - // w[i] = p[j]<<24 | p[j+1]<<16 | p[j+2]<<8 | p[j+3] - // e += w[i] -#define LOAD(e) \ - MOVBU 2(R(data)), R(t0) ; \ - MOVBU 3(R(data)), R(t1) ; \ - MOVBU 1(R(data)), R(t2) ; \ - ORR R(t0)<<8, R(t1), R(t0) ; \ - MOVBU.P 4(R(data)), R(t1) ; \ - ORR R(t2)<<16, R(t0), R(t0) ; \ - ORR R(t1)<<24, R(t0), R(t0) ; \ - MOVW.P R(t0), 4(R(w)) ; \ - ADD R(t0), R(e), R(e) - - // tmp := w[(i-3)&0xf] ^ w[(i-8)&0xf] ^ w[(i-14)&0xf] ^ w[(i)&0xf] - // w[i&0xf] = tmp<<1 | tmp>>(32-1) - // e += w[i&0xf] -#define SHUFFLE(e) \ - MOVW (-16*4)(R(w)), R(t0) ; \ - MOVW (-14*4)(R(w)), R(t1) ; \ - MOVW (-8*4)(R(w)), R(t2) ; \ - EOR R(t0), R(t1), R(t0) ; \ - MOVW (-3*4)(R(w)), R(t1) ; \ - EOR R(t2), R(t0), R(t0) ; \ - EOR R(t0), R(t1), R(t0) ; \ - MOVW R(t0)@>(32-1), R(t0) ; \ - MOVW.P R(t0), 4(R(w)) ; \ - ADD R(t0), R(e), R(e) - - // t1 = (b & c) | ((~b) & d) -#define FUNC1(a, b, c, d, e) \ - MVN R(b), R(t1) ; \ - AND R(b), R(c), R(t0) ; \ - AND R(d), R(t1), R(t1) ; \ - ORR R(t0), R(t1), R(t1) - - // t1 = b ^ c ^ d -#define FUNC2(a, b, c, d, e) \ - EOR R(b), R(c), R(t1) ; \ - EOR R(d), R(t1), R(t1) - - // t1 = (b & c) | (b & d) | (c & d) = - // t1 = (b & c) | ((b | c) & d) -#define FUNC3(a, b, c, d, e) \ - ORR R(b), R(c), R(t0) ; \ - AND R(b), R(c), R(t1) ; \ - AND R(d), R(t0), R(t0) ; \ - ORR R(t0), R(t1), R(t1) - -#define FUNC4 FUNC2 - - // a5 := a<<5 | a>>(32-5) - // b = b<<30 | b>>(32-30) - // e = a5 + t1 + e + const -#define MIX(a, b, c, d, e) \ - ADD R(t1), R(e), R(e) ; \ - MOVW R(b)@>(32-30), R(b) ; \ - ADD R(a)@>(32-5), R(e), R(e) ; \ - ADD R(const), R(e), R(e) - -#define ROUND1(a, b, c, d, e) \ - LOAD(e) ; \ - FUNC1(a, b, c, d, e) ; \ - MIX(a, b, c, d, e) - -#define ROUND1x(a, b, c, d, e) \ - SHUFFLE(e) ; \ - FUNC1(a, b, c, d, e) ; \ - MIX(a, b, c, d, e) - -#define ROUND2(a, b, c, d, e) \ - SHUFFLE(e) ; \ - FUNC2(a, b, c, d, e) ; \ - MIX(a, b, c, d, e) - -#define ROUND3(a, b, c, d, e) \ - SHUFFLE(e) ; \ - FUNC3(a, b, c, d, e) ; \ - MIX(a, b, c, d, e) - -#define ROUND4(a, b, c, d, e) \ - SHUFFLE(e) ; \ - FUNC4(a, b, c, d, e) ; \ - MIX(a, b, c, d, e) - - -// func block(dig *digest, p []byte) -TEXT ·block(SB), 0, $352-16 - MOVW p+4(FP), R(data) // pointer to the data - MOVW p_len+8(FP), R(t0) // number of bytes - ADD R(data), R(t0) - MOVW R(t0), p_end(SP) // pointer to end of data - - // Load up initial SHA1 accumulator - MOVW dig+0(FP), R(t0) - MOVM.IA (R(t0)), [R(a),R(b),R(c),R(d),R(e)] - -loop: - // Save registers at SP+4 onwards - MOVM.IB [R(a),R(b),R(c),R(d),R(e)], (R13) - - MOVW $w_buf(SP), R(w) - MOVW $0x5A827999, R(const) - MOVW $3, R(ctr) -loop1: ROUND1(a, b, c, d, e) - ROUND1(e, a, b, c, d) - ROUND1(d, e, a, b, c) - ROUND1(c, d, e, a, b) - ROUND1(b, c, d, e, a) - SUB.S $1, R(ctr) - BNE loop1 - - ROUND1(a, b, c, d, e) - ROUND1x(e, a, b, c, d) - ROUND1x(d, e, a, b, c) - ROUND1x(c, d, e, a, b) - ROUND1x(b, c, d, e, a) - - MOVW $0x6ED9EBA1, R(const) - MOVW $4, R(ctr) -loop2: ROUND2(a, b, c, d, e) - ROUND2(e, a, b, c, d) - ROUND2(d, e, a, b, c) - ROUND2(c, d, e, a, b) - ROUND2(b, c, d, e, a) - SUB.S $1, R(ctr) - BNE loop2 - - MOVW $0x8F1BBCDC, R(const) - MOVW $4, R(ctr) -loop3: ROUND3(a, b, c, d, e) - ROUND3(e, a, b, c, d) - ROUND3(d, e, a, b, c) - ROUND3(c, d, e, a, b) - ROUND3(b, c, d, e, a) - SUB.S $1, R(ctr) - BNE loop3 - - MOVW $0xCA62C1D6, R(const) - MOVW $4, R(ctr) -loop4: ROUND4(a, b, c, d, e) - ROUND4(e, a, b, c, d) - ROUND4(d, e, a, b, c) - ROUND4(c, d, e, a, b) - ROUND4(b, c, d, e, a) - SUB.S $1, R(ctr) - BNE loop4 - - // Accumulate - restoring registers from SP+4 - MOVM.IB (R13), [R(t0),R(t1),R(t2),R(ctr),R(w)] - ADD R(t0), R(a) - ADD R(t1), R(b) - ADD R(t2), R(c) - ADD R(ctr), R(d) - ADD R(w), R(e) - - MOVW p_end(SP), R(t0) - CMP R(t0), R(data) - BLO loop - - // Save final SHA1 accumulator - MOVW dig+0(FP), R(t0) - MOVM.IA [R(a),R(b),R(c),R(d),R(e)], (R(t0)) - - RET diff --git a/src/pkg/crypto/sha1/sha1block_decl.go b/src/pkg/crypto/sha1/sha1block_decl.go deleted file mode 100644 index 24e521af1..000000000 --- a/src/pkg/crypto/sha1/sha1block_decl.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build amd64 amd64p32 arm 386 - -package sha1 - -//go:noescape - -func block(dig *digest, p []byte) diff --git a/src/pkg/crypto/sha1/sha1block_generic.go b/src/pkg/crypto/sha1/sha1block_generic.go deleted file mode 100644 index 696e26b62..000000000 --- a/src/pkg/crypto/sha1/sha1block_generic.go +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !amd64,!amd64p32,!386,!arm - -package sha1 - -var block = blockGeneric diff --git a/src/pkg/crypto/sha256/sha256.go b/src/pkg/crypto/sha256/sha256.go deleted file mode 100644 index d84cebf2f..000000000 --- a/src/pkg/crypto/sha256/sha256.go +++ /dev/null @@ -1,193 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package sha256 implements the SHA224 and SHA256 hash algorithms as defined -// in FIPS 180-4. -package sha256 - -import ( - "crypto" - "hash" -) - -func init() { - crypto.RegisterHash(crypto.SHA224, New224) - crypto.RegisterHash(crypto.SHA256, New) -} - -// The size of a SHA256 checksum in bytes. -const Size = 32 - -// The size of a SHA224 checksum in bytes. -const Size224 = 28 - -// The blocksize of SHA256 and SHA224 in bytes. -const BlockSize = 64 - -const ( - chunk = 64 - init0 = 0x6A09E667 - init1 = 0xBB67AE85 - init2 = 0x3C6EF372 - init3 = 0xA54FF53A - init4 = 0x510E527F - init5 = 0x9B05688C - init6 = 0x1F83D9AB - init7 = 0x5BE0CD19 - init0_224 = 0xC1059ED8 - init1_224 = 0x367CD507 - init2_224 = 0x3070DD17 - init3_224 = 0xF70E5939 - init4_224 = 0xFFC00B31 - init5_224 = 0x68581511 - init6_224 = 0x64F98FA7 - init7_224 = 0xBEFA4FA4 -) - -// digest represents the partial evaluation of a checksum. -type digest struct { - h [8]uint32 - x [chunk]byte - nx int - len uint64 - is224 bool // mark if this digest is SHA-224 -} - -func (d *digest) Reset() { - if !d.is224 { - d.h[0] = init0 - d.h[1] = init1 - d.h[2] = init2 - d.h[3] = init3 - d.h[4] = init4 - d.h[5] = init5 - d.h[6] = init6 - d.h[7] = init7 - } else { - d.h[0] = init0_224 - d.h[1] = init1_224 - d.h[2] = init2_224 - d.h[3] = init3_224 - d.h[4] = init4_224 - d.h[5] = init5_224 - d.h[6] = init6_224 - d.h[7] = init7_224 - } - d.nx = 0 - d.len = 0 -} - -// New returns a new hash.Hash computing the SHA256 checksum. -func New() hash.Hash { - d := new(digest) - d.Reset() - return d -} - -// New224 returns a new hash.Hash computing the SHA224 checksum. -func New224() hash.Hash { - d := new(digest) - d.is224 = true - d.Reset() - return d -} - -func (d *digest) Size() int { - if !d.is224 { - return Size - } - return Size224 -} - -func (d *digest) BlockSize() int { return BlockSize } - -func (d *digest) Write(p []byte) (nn int, err error) { - nn = len(p) - d.len += uint64(nn) - if d.nx > 0 { - n := copy(d.x[d.nx:], p) - d.nx += n - if d.nx == chunk { - block(d, d.x[:]) - d.nx = 0 - } - p = p[n:] - } - if len(p) >= chunk { - n := len(p) &^ (chunk - 1) - block(d, p[:n]) - p = p[n:] - } - if len(p) > 0 { - d.nx = copy(d.x[:], p) - } - return -} - -func (d0 *digest) Sum(in []byte) []byte { - // Make a copy of d0 so that caller can keep writing and summing. - d := *d0 - hash := d.checkSum() - if d.is224 { - return append(in, hash[:Size224]...) - } - return append(in, hash[:]...) -} - -func (d *digest) checkSum() [Size]byte { - len := d.len - // Padding. Add a 1 bit and 0 bits until 56 bytes mod 64. - var tmp [64]byte - tmp[0] = 0x80 - if len%64 < 56 { - d.Write(tmp[0 : 56-len%64]) - } else { - d.Write(tmp[0 : 64+56-len%64]) - } - - // Length in bits. - len <<= 3 - for i := uint(0); i < 8; i++ { - tmp[i] = byte(len >> (56 - 8*i)) - } - d.Write(tmp[0:8]) - - if d.nx != 0 { - panic("d.nx != 0") - } - - h := d.h[:] - if d.is224 { - h = d.h[:7] - } - - var digest [Size]byte - for i, s := range h { - digest[i*4] = byte(s >> 24) - digest[i*4+1] = byte(s >> 16) - digest[i*4+2] = byte(s >> 8) - digest[i*4+3] = byte(s) - } - - return digest -} - -// Sum256 returns the SHA256 checksum of the data. -func Sum256(data []byte) [Size]byte { - var d digest - d.Reset() - d.Write(data) - return d.checkSum() -} - -// Sum224 returns the SHA224 checksum of the data. -func Sum224(data []byte) (sum224 [Size224]byte) { - var d digest - d.is224 = true - d.Reset() - d.Write(data) - sum := d.checkSum() - copy(sum224[:], sum[:Size224]) - return -} diff --git a/src/pkg/crypto/sha256/sha256_test.go b/src/pkg/crypto/sha256/sha256_test.go deleted file mode 100644 index 1d883d390..000000000 --- a/src/pkg/crypto/sha256/sha256_test.go +++ /dev/null @@ -1,176 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// SHA256 hash algorithm. See FIPS 180-2. - -package sha256 - -import ( - "fmt" - "io" - "testing" -) - -type sha256Test struct { - out string - in string -} - -var golden = []sha256Test{ - {"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", ""}, - {"ca978112ca1bbdcafac231b39a23dc4da786eff8147c4e72b9807785afee48bb", "a"}, - {"fb8e20fc2e4c3f248c60c39bd652f3c1347298bb977b8b4d5903b85055620603", "ab"}, - {"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad", "abc"}, - {"88d4266fd4e6338d13b845fcf289579d209c897823b9217da3e161936f031589", "abcd"}, - {"36bbe50ed96841d10443bcb670d6554f0a34b761be67ec9c4a8ad2c0c44ca42c", "abcde"}, - {"bef57ec7f53a6d40beb640a780a639c83bc29ac8a9816f1fc6c5c6dcd93c4721", "abcdef"}, - {"7d1a54127b222502f5b79b5fb0803061152a44f92b37e23c6527baf665d4da9a", "abcdefg"}, - {"9c56cc51b374c3ba189210d5b6d4bf57790d351c96c47c02190ecf1e430635ab", "abcdefgh"}, - {"19cc02f26df43cc571bc9ed7b0c4d29224a3ec229529221725ef76d021c8326f", "abcdefghi"}, - {"72399361da6a7754fec986dca5b7cbaf1c810a28ded4abaf56b2106d06cb78b0", "abcdefghij"}, - {"a144061c271f152da4d151034508fed1c138b8c976339de229c3bb6d4bbb4fce", "Discard medicine more than two years old."}, - {"6dae5caa713a10ad04b46028bf6dad68837c581616a1589a265a11288d4bb5c4", "He who has a shady past knows that nice guys finish last."}, - {"ae7a702a9509039ddbf29f0765e70d0001177914b86459284dab8b348c2dce3f", "I wouldn't marry him with a ten foot pole."}, - {"6748450b01c568586715291dfa3ee018da07d36bb7ea6f180c1af6270215c64f", "Free! Free!/A trip/to Mars/for 900/empty jars/Burma Shave"}, - {"14b82014ad2b11f661b5ae6a99b75105c2ffac278cd071cd6c05832793635774", "The days of the digital watch are numbered. -Tom Stoppard"}, - {"7102cfd76e2e324889eece5d6c41921b1e142a4ac5a2692be78803097f6a48d8", "Nepal premier won't resign."}, - {"23b1018cd81db1d67983c5f7417c44da9deb582459e378d7a068552ea649dc9f", "For every action there is an equal and opposite government program."}, - {"8001f190dfb527261c4cfcab70c98e8097a7a1922129bc4096950e57c7999a5a", "His money is twice tainted: 'taint yours and 'taint mine."}, - {"8c87deb65505c3993eb24b7a150c4155e82eee6960cf0c3a8114ff736d69cad5", "There is no reason for any individual to have a computer in their home. -Ken Olsen, 1977"}, - {"bfb0a67a19cdec3646498b2e0f751bddc41bba4b7f30081b0b932aad214d16d7", "It's a tiny change to the code and not completely disgusting. - Bob Manchek"}, - {"7f9a0b9bf56332e19f5a0ec1ad9c1425a153da1c624868fda44561d6b74daf36", "size: a.out: bad magic"}, - {"b13f81b8aad9e3666879af19886140904f7f429ef083286195982a7588858cfc", "The major problem is with sendmail. -Mark Horton"}, - {"b26c38d61519e894480c70c8374ea35aa0ad05b2ae3d6674eec5f52a69305ed4", "Give me a rock, paper and scissors and I will move the world. CCFestoon"}, - {"049d5e26d4f10222cd841a119e38bd8d2e0d1129728688449575d4ff42b842c1", "If the enemy is within range, then so are you."}, - {"0e116838e3cc1c1a14cd045397e29b4d087aa11b0853fc69ec82e90330d60949", "It's well we cannot hear the screams/That we create in others' dreams."}, - {"4f7d8eb5bcf11de2a56b971021a444aa4eafd6ecd0f307b5109e4e776cd0fe46", "You remind me of a TV show, but that's all right: I watch it anyway."}, - {"61c0cc4c4bd8406d5120b3fb4ebc31ce87667c162f29468b3c779675a85aebce", "C is as portable as Stonehedge!!"}, - {"1fb2eb3688093c4a3f80cd87a5547e2ce940a4f923243a79a2a1e242220693ac", "Even if I could be Shakespeare, I think I should still choose to be Faraday. - A. Huxley"}, - {"395585ce30617b62c80b93e8208ce866d4edc811a177fdb4b82d3911d8696423", "The fugacity of a constituent in a mixture of gases at a given temperature is proportional to its mole fraction. Lewis-Randall Rule"}, - {"4f9b189a13d030838269dce846b16a1ce9ce81fe63e65de2f636863336a98fe6", "How can you write a big system without C++? -Paul Glick"}, -} - -var golden224 = []sha256Test{ - {"d14a028c2a3a2bc9476102bb288234c415a2b01f828ea62ac5b3e42f", ""}, - {"abd37534c7d9a2efb9465de931cd7055ffdb8879563ae98078d6d6d5", "a"}, - {"db3cda86d4429a1d39c148989566b38f7bda0156296bd364ba2f878b", "ab"}, - {"23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7", "abc"}, - {"a76654d8e3550e9a2d67a0eeb6c67b220e5885eddd3fde135806e601", "abcd"}, - {"bdd03d560993e675516ba5a50638b6531ac2ac3d5847c61916cfced6", "abcde"}, - {"7043631cb415556a275a4ebecb802c74ee9f6153908e1792a90b6a98", "abcdef"}, - {"d1884e711701ad81abe0c77a3b0ea12e19ba9af64077286c72fc602d", "abcdefg"}, - {"17eb7d40f0356f8598e89eafad5f6c759b1f822975d9c9b737c8a517", "abcdefgh"}, - {"aeb35915346c584db820d2de7af3929ffafef9222a9bcb26516c7334", "abcdefghi"}, - {"d35e1e5af29ddb0d7e154357df4ad9842afee527c689ee547f753188", "abcdefghij"}, - {"19297f1cef7ddc8a7e947f5c5a341e10f7245045e425db67043988d7", "Discard medicine more than two years old."}, - {"0f10c2eb436251f777fbbd125e260d36aecf180411726c7c885f599a", "He who has a shady past knows that nice guys finish last."}, - {"4d1842104919f314cad8a3cd20b3cba7e8ed3e7abed62b57441358f6", "I wouldn't marry him with a ten foot pole."}, - {"a8ba85c6fe0c48fbffc72bbb2f03fcdbc87ae2dc7a56804d1590fb3b", "Free! Free!/A trip/to Mars/for 900/empty jars/Burma Shave"}, - {"5543fbab26e67e8885b1a852d567d1cb8b9bfe42e0899584c50449a9", "The days of the digital watch are numbered. -Tom Stoppard"}, - {"65ca107390f5da9efa05d28e57b221657edc7e43a9a18fb15b053ddb", "Nepal premier won't resign."}, - {"84953962be366305a9cc9b5cd16ed019edc37ac96c0deb3e12cca116", "For every action there is an equal and opposite government program."}, - {"35a189ce987151dfd00b3577583cc6a74b9869eecf894459cb52038d", "His money is twice tainted: 'taint yours and 'taint mine."}, - {"2fc333713983edfd4ef2c0da6fb6d6415afb94987c91e4069eb063e6", "There is no reason for any individual to have a computer in their home. -Ken Olsen, 1977"}, - {"cbe32d38d577a1b355960a4bc3c659c2dc4670859a19777a875842c4", "It's a tiny change to the code and not completely disgusting. - Bob Manchek"}, - {"a2dc118ce959e027576413a7b440c875cdc8d40df9141d6ef78a57e1", "size: a.out: bad magic"}, - {"d10787e24052bcff26dc484787a54ed819e4e4511c54890ee977bf81", "The major problem is with sendmail. -Mark Horton"}, - {"62efcf16ab8a893acdf2f348aaf06b63039ff1bf55508c830532c9fb", "Give me a rock, paper and scissors and I will move the world. CCFestoon"}, - {"3e9b7e4613c59f58665104c5fa86c272db5d3a2ff30df5bb194a5c99", "If the enemy is within range, then so are you."}, - {"5999c208b8bdf6d471bb7c359ac5b829e73a8211dff686143a4e7f18", "It's well we cannot hear the screams/That we create in others' dreams."}, - {"3b2d67ff54eabc4ef737b14edf87c64280ef582bcdf2a6d56908b405", "You remind me of a TV show, but that's all right: I watch it anyway."}, - {"d0733595d20e4d3d6b5c565a445814d1bbb2fd08b9a3b8ffb97930c6", "C is as portable as Stonehedge!!"}, - {"43fb8aeed8a833175c9295c1165415f98c866ef08a4922959d673507", "Even if I could be Shakespeare, I think I should still choose to be Faraday. - A. Huxley"}, - {"ec18e66e93afc4fb1604bc2baedbfd20b44c43d76e65c0996d7851c6", "The fugacity of a constituent in a mixture of gases at a given temperature is proportional to its mole fraction. Lewis-Randall Rule"}, - {"86ed2eaa9c75ba98396e5c9fb2f679ecf0ea2ed1e0ee9ceecb4a9332", "How can you write a big system without C++? -Paul Glick"}, -} - -func TestGolden(t *testing.T) { - for i := 0; i < len(golden); i++ { - g := golden[i] - s := fmt.Sprintf("%x", Sum256([]byte(g.in))) - if s != g.out { - t.Fatalf("Sum256 function: sha256(%s) = %s want %s", g.in, s, g.out) - } - c := New() - for j := 0; j < 3; j++ { - if j < 2 { - io.WriteString(c, g.in) - } else { - io.WriteString(c, g.in[0:len(g.in)/2]) - c.Sum(nil) - io.WriteString(c, g.in[len(g.in)/2:]) - } - s := fmt.Sprintf("%x", c.Sum(nil)) - if s != g.out { - t.Fatalf("sha256[%d](%s) = %s want %s", j, g.in, s, g.out) - } - c.Reset() - } - } - for i := 0; i < len(golden224); i++ { - g := golden224[i] - s := fmt.Sprintf("%x", Sum224([]byte(g.in))) - if s != g.out { - t.Fatalf("Sum224 function: sha224(%s) = %s want %s", g.in, s, g.out) - } - c := New224() - for j := 0; j < 3; j++ { - if j < 2 { - io.WriteString(c, g.in) - } else { - io.WriteString(c, g.in[0:len(g.in)/2]) - c.Sum(nil) - io.WriteString(c, g.in[len(g.in)/2:]) - } - s := fmt.Sprintf("%x", c.Sum(nil)) - if s != g.out { - t.Fatalf("sha224[%d](%s) = %s want %s", j, g.in, s, g.out) - } - c.Reset() - } - } -} - -func TestSize(t *testing.T) { - c := New() - if got := c.Size(); got != Size { - t.Errorf("Size = %d; want %d", got, Size) - } - c = New224() - if got := c.Size(); got != Size224 { - t.Errorf("New224.Size = %d; want %d", got, Size224) - } -} - -func TestBlockSize(t *testing.T) { - c := New() - if got := c.BlockSize(); got != BlockSize { - t.Errorf("BlockSize = %d want %d", got, BlockSize) - } -} - -var bench = New() -var buf = make([]byte, 8192) - -func benchmarkSize(b *testing.B, size int) { - b.SetBytes(int64(size)) - sum := make([]byte, bench.Size()) - for i := 0; i < b.N; i++ { - bench.Reset() - bench.Write(buf[:size]) - bench.Sum(sum[:0]) - } -} - -func BenchmarkHash8Bytes(b *testing.B) { - benchmarkSize(b, 8) -} - -func BenchmarkHash1K(b *testing.B) { - benchmarkSize(b, 1024) -} - -func BenchmarkHash8K(b *testing.B) { - benchmarkSize(b, 8192) -} diff --git a/src/pkg/crypto/sha256/sha256block.go b/src/pkg/crypto/sha256/sha256block.go deleted file mode 100644 index ca5efd156..000000000 --- a/src/pkg/crypto/sha256/sha256block.go +++ /dev/null @@ -1,128 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !386,!amd64 - -// SHA256 block step. -// In its own file so that a faster assembly or C version -// can be substituted easily. - -package sha256 - -var _K = []uint32{ - 0x428a2f98, - 0x71374491, - 0xb5c0fbcf, - 0xe9b5dba5, - 0x3956c25b, - 0x59f111f1, - 0x923f82a4, - 0xab1c5ed5, - 0xd807aa98, - 0x12835b01, - 0x243185be, - 0x550c7dc3, - 0x72be5d74, - 0x80deb1fe, - 0x9bdc06a7, - 0xc19bf174, - 0xe49b69c1, - 0xefbe4786, - 0x0fc19dc6, - 0x240ca1cc, - 0x2de92c6f, - 0x4a7484aa, - 0x5cb0a9dc, - 0x76f988da, - 0x983e5152, - 0xa831c66d, - 0xb00327c8, - 0xbf597fc7, - 0xc6e00bf3, - 0xd5a79147, - 0x06ca6351, - 0x14292967, - 0x27b70a85, - 0x2e1b2138, - 0x4d2c6dfc, - 0x53380d13, - 0x650a7354, - 0x766a0abb, - 0x81c2c92e, - 0x92722c85, - 0xa2bfe8a1, - 0xa81a664b, - 0xc24b8b70, - 0xc76c51a3, - 0xd192e819, - 0xd6990624, - 0xf40e3585, - 0x106aa070, - 0x19a4c116, - 0x1e376c08, - 0x2748774c, - 0x34b0bcb5, - 0x391c0cb3, - 0x4ed8aa4a, - 0x5b9cca4f, - 0x682e6ff3, - 0x748f82ee, - 0x78a5636f, - 0x84c87814, - 0x8cc70208, - 0x90befffa, - 0xa4506ceb, - 0xbef9a3f7, - 0xc67178f2, -} - -func block(dig *digest, p []byte) { - var w [64]uint32 - h0, h1, h2, h3, h4, h5, h6, h7 := dig.h[0], dig.h[1], dig.h[2], dig.h[3], dig.h[4], dig.h[5], dig.h[6], dig.h[7] - for len(p) >= chunk { - // Can interlace the computation of w with the - // rounds below if needed for speed. - for i := 0; i < 16; i++ { - j := i * 4 - w[i] = uint32(p[j])<<24 | uint32(p[j+1])<<16 | uint32(p[j+2])<<8 | uint32(p[j+3]) - } - for i := 16; i < 64; i++ { - v1 := w[i-2] - t1 := (v1>>17 | v1<<(32-17)) ^ (v1>>19 | v1<<(32-19)) ^ (v1 >> 10) - v2 := w[i-15] - t2 := (v2>>7 | v2<<(32-7)) ^ (v2>>18 | v2<<(32-18)) ^ (v2 >> 3) - w[i] = t1 + w[i-7] + t2 + w[i-16] - } - - a, b, c, d, e, f, g, h := h0, h1, h2, h3, h4, h5, h6, h7 - - for i := 0; i < 64; i++ { - t1 := h + ((e>>6 | e<<(32-6)) ^ (e>>11 | e<<(32-11)) ^ (e>>25 | e<<(32-25))) + ((e & f) ^ (^e & g)) + _K[i] + w[i] - - t2 := ((a>>2 | a<<(32-2)) ^ (a>>13 | a<<(32-13)) ^ (a>>22 | a<<(32-22))) + ((a & b) ^ (a & c) ^ (b & c)) - - h = g - g = f - f = e - e = d + t1 - d = c - c = b - b = a - a = t1 + t2 - } - - h0 += a - h1 += b - h2 += c - h3 += d - h4 += e - h5 += f - h6 += g - h7 += h - - p = p[chunk:] - } - - dig.h[0], dig.h[1], dig.h[2], dig.h[3], dig.h[4], dig.h[5], dig.h[6], dig.h[7] = h0, h1, h2, h3, h4, h5, h6, h7 -} diff --git a/src/pkg/crypto/sha256/sha256block_386.s b/src/pkg/crypto/sha256/sha256block_386.s deleted file mode 100644 index 73ae2bf30..000000000 --- a/src/pkg/crypto/sha256/sha256block_386.s +++ /dev/null @@ -1,283 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// SHA256 block routine. See sha256block.go for Go equivalent. -// -// The algorithm is detailed in FIPS 180-4: -// -// http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf -// -// Wt = Mt; for 0 <= t <= 15 -// Wt = SIGMA1(Wt-2) + SIGMA0(Wt-15) + Wt-16; for 16 <= t <= 63 -// -// a = H0 -// b = H1 -// c = H2 -// d = H3 -// e = H4 -// f = H5 -// g = H6 -// h = H7 -// -// for t = 0 to 63 { -// T1 = h + BIGSIGMA1(e) + Ch(e,f,g) + Kt + Wt -// T2 = BIGSIGMA0(a) + Maj(a,b,c) -// h = g -// g = f -// f = e -// e = d + T1 -// d = c -// c = b -// b = a -// a = T1 + T2 -// } -// -// H0 = a + H0 -// H1 = b + H1 -// H2 = c + H2 -// H3 = d + H3 -// H4 = e + H4 -// H5 = f + H5 -// H6 = g + H6 -// H7 = h + H7 - -// Wt = Mt; for 0 <= t <= 15 -#define MSGSCHEDULE0(index) \ - MOVL (index*4)(SI), AX; \ - BSWAPL AX; \ - MOVL AX, (index*4)(BP) - -// Wt = SIGMA1(Wt-2) + Wt-7 + SIGMA0(Wt-15) + Wt-16; for 16 <= t <= 63 -// SIGMA0(x) = ROTR(7,x) XOR ROTR(18,x) XOR SHR(3,x) -// SIGMA1(x) = ROTR(17,x) XOR ROTR(19,x) XOR SHR(10,x) -#define MSGSCHEDULE1(index) \ - MOVL ((index-2)*4)(BP), AX; \ - MOVL AX, CX; \ - RORL $17, AX; \ - MOVL CX, DX; \ - RORL $19, CX; \ - SHRL $10, DX; \ - MOVL ((index-15)*4)(BP), BX; \ - XORL CX, AX; \ - MOVL BX, CX; \ - XORL DX, AX; \ - RORL $7, BX; \ - MOVL CX, DX; \ - SHRL $3, DX; \ - RORL $18, CX; \ - ADDL ((index-7)*4)(BP), AX; \ - XORL CX, BX; \ - XORL DX, BX; \ - ADDL ((index-16)*4)(BP), BX; \ - ADDL BX, AX; \ - MOVL AX, ((index)*4)(BP) - -// Calculate T1 in AX - uses AX, BX, CX and DX registers. -// Wt is passed in AX. -// T1 = h + BIGSIGMA1(e) + Ch(e, f, g) + Kt + Wt -// BIGSIGMA1(x) = ROTR(6,x) XOR ROTR(11,x) XOR ROTR(25,x) -// Ch(x, y, z) = (x AND y) XOR (NOT x AND z) -#define SHA256T1(const, e, f, g, h) \ - MOVL (h*4)(DI), BX; \ - ADDL AX, BX; \ - MOVL (e*4)(DI), AX; \ - ADDL $const, BX; \ - MOVL (e*4)(DI), CX; \ - RORL $6, AX; \ - MOVL (e*4)(DI), DX; \ - RORL $11, CX; \ - XORL CX, AX; \ - MOVL (e*4)(DI), CX; \ - RORL $25, DX; \ - ANDL (f*4)(DI), CX; \ - XORL AX, DX; \ - MOVL (e*4)(DI), AX; \ - NOTL AX; \ - ADDL DX, BX; \ - ANDL (g*4)(DI), AX; \ - XORL CX, AX; \ - ADDL BX, AX - -// Calculate T2 in BX - uses AX, BX, CX and DX registers. -// T2 = BIGSIGMA0(a) + Maj(a, b, c) -// BIGSIGMA0(x) = ROTR(2,x) XOR ROTR(13,x) XOR ROTR(22,x) -// Maj(x, y, z) = (x AND y) XOR (x AND z) XOR (y AND z) -#define SHA256T2(a, b, c) \ - MOVL (a*4)(DI), AX; \ - MOVL (c*4)(DI), BX; \ - RORL $2, AX; \ - MOVL (a*4)(DI), DX; \ - ANDL (b*4)(DI), BX; \ - RORL $13, DX; \ - MOVL (a*4)(DI), CX; \ - ANDL (c*4)(DI), CX; \ - XORL DX, AX; \ - XORL CX, BX; \ - MOVL (a*4)(DI), DX; \ - MOVL (b*4)(DI), CX; \ - RORL $22, DX; \ - ANDL (a*4)(DI), CX; \ - XORL CX, BX; \ - XORL DX, AX; \ - ADDL AX, BX - -// Calculate T1 and T2, then e = d + T1 and a = T1 + T2. -// The values for e and a are stored in d and h, ready for rotation. -#define SHA256ROUND(index, const, a, b, c, d, e, f, g, h) \ - SHA256T1(const, e, f, g, h); \ - MOVL AX, 292(SP); \ - SHA256T2(a, b, c); \ - MOVL 292(SP), AX; \ - ADDL AX, BX; \ - ADDL AX, (d*4)(DI); \ - MOVL BX, (h*4)(DI) - -#define SHA256ROUND0(index, const, a, b, c, d, e, f, g, h) \ - MSGSCHEDULE0(index); \ - SHA256ROUND(index, const, a, b, c, d, e, f, g, h) - -#define SHA256ROUND1(index, const, a, b, c, d, e, f, g, h) \ - MSGSCHEDULE1(index); \ - SHA256ROUND(index, const, a, b, c, d, e, f, g, h) - -TEXT ·block(SB),0,$296-12 - MOVL p_base+4(FP), SI - MOVL p_len+8(FP), DX - SHRL $6, DX - SHLL $6, DX - - LEAL (SI)(DX*1), DI - MOVL DI, 288(SP) - CMPL SI, DI - JEQ end - - LEAL 256(SP), DI // variables - - MOVL dig+0(FP), BP - MOVL (0*4)(BP), AX // a = H0 - MOVL AX, (0*4)(DI) - MOVL (1*4)(BP), BX // b = H1 - MOVL BX, (1*4)(DI) - MOVL (2*4)(BP), CX // c = H2 - MOVL CX, (2*4)(DI) - MOVL (3*4)(BP), DX // d = H3 - MOVL DX, (3*4)(DI) - MOVL (4*4)(BP), AX // e = H4 - MOVL AX, (4*4)(DI) - MOVL (5*4)(BP), BX // f = H5 - MOVL BX, (5*4)(DI) - MOVL (6*4)(BP), CX // g = H6 - MOVL CX, (6*4)(DI) - MOVL (7*4)(BP), DX // h = H7 - MOVL DX, (7*4)(DI) - -loop: - MOVL SP, BP // message schedule - - SHA256ROUND0(0, 0x428a2f98, 0, 1, 2, 3, 4, 5, 6, 7) - SHA256ROUND0(1, 0x71374491, 7, 0, 1, 2, 3, 4, 5, 6) - SHA256ROUND0(2, 0xb5c0fbcf, 6, 7, 0, 1, 2, 3, 4, 5) - SHA256ROUND0(3, 0xe9b5dba5, 5, 6, 7, 0, 1, 2, 3, 4) - SHA256ROUND0(4, 0x3956c25b, 4, 5, 6, 7, 0, 1, 2, 3) - SHA256ROUND0(5, 0x59f111f1, 3, 4, 5, 6, 7, 0, 1, 2) - SHA256ROUND0(6, 0x923f82a4, 2, 3, 4, 5, 6, 7, 0, 1) - SHA256ROUND0(7, 0xab1c5ed5, 1, 2, 3, 4, 5, 6, 7, 0) - SHA256ROUND0(8, 0xd807aa98, 0, 1, 2, 3, 4, 5, 6, 7) - SHA256ROUND0(9, 0x12835b01, 7, 0, 1, 2, 3, 4, 5, 6) - SHA256ROUND0(10, 0x243185be, 6, 7, 0, 1, 2, 3, 4, 5) - SHA256ROUND0(11, 0x550c7dc3, 5, 6, 7, 0, 1, 2, 3, 4) - SHA256ROUND0(12, 0x72be5d74, 4, 5, 6, 7, 0, 1, 2, 3) - SHA256ROUND0(13, 0x80deb1fe, 3, 4, 5, 6, 7, 0, 1, 2) - SHA256ROUND0(14, 0x9bdc06a7, 2, 3, 4, 5, 6, 7, 0, 1) - SHA256ROUND0(15, 0xc19bf174, 1, 2, 3, 4, 5, 6, 7, 0) - - SHA256ROUND1(16, 0xe49b69c1, 0, 1, 2, 3, 4, 5, 6, 7) - SHA256ROUND1(17, 0xefbe4786, 7, 0, 1, 2, 3, 4, 5, 6) - SHA256ROUND1(18, 0x0fc19dc6, 6, 7, 0, 1, 2, 3, 4, 5) - SHA256ROUND1(19, 0x240ca1cc, 5, 6, 7, 0, 1, 2, 3, 4) - SHA256ROUND1(20, 0x2de92c6f, 4, 5, 6, 7, 0, 1, 2, 3) - SHA256ROUND1(21, 0x4a7484aa, 3, 4, 5, 6, 7, 0, 1, 2) - SHA256ROUND1(22, 0x5cb0a9dc, 2, 3, 4, 5, 6, 7, 0, 1) - SHA256ROUND1(23, 0x76f988da, 1, 2, 3, 4, 5, 6, 7, 0) - SHA256ROUND1(24, 0x983e5152, 0, 1, 2, 3, 4, 5, 6, 7) - SHA256ROUND1(25, 0xa831c66d, 7, 0, 1, 2, 3, 4, 5, 6) - SHA256ROUND1(26, 0xb00327c8, 6, 7, 0, 1, 2, 3, 4, 5) - SHA256ROUND1(27, 0xbf597fc7, 5, 6, 7, 0, 1, 2, 3, 4) - SHA256ROUND1(28, 0xc6e00bf3, 4, 5, 6, 7, 0, 1, 2, 3) - SHA256ROUND1(29, 0xd5a79147, 3, 4, 5, 6, 7, 0, 1, 2) - SHA256ROUND1(30, 0x06ca6351, 2, 3, 4, 5, 6, 7, 0, 1) - SHA256ROUND1(31, 0x14292967, 1, 2, 3, 4, 5, 6, 7, 0) - SHA256ROUND1(32, 0x27b70a85, 0, 1, 2, 3, 4, 5, 6, 7) - SHA256ROUND1(33, 0x2e1b2138, 7, 0, 1, 2, 3, 4, 5, 6) - SHA256ROUND1(34, 0x4d2c6dfc, 6, 7, 0, 1, 2, 3, 4, 5) - SHA256ROUND1(35, 0x53380d13, 5, 6, 7, 0, 1, 2, 3, 4) - SHA256ROUND1(36, 0x650a7354, 4, 5, 6, 7, 0, 1, 2, 3) - SHA256ROUND1(37, 0x766a0abb, 3, 4, 5, 6, 7, 0, 1, 2) - SHA256ROUND1(38, 0x81c2c92e, 2, 3, 4, 5, 6, 7, 0, 1) - SHA256ROUND1(39, 0x92722c85, 1, 2, 3, 4, 5, 6, 7, 0) - SHA256ROUND1(40, 0xa2bfe8a1, 0, 1, 2, 3, 4, 5, 6, 7) - SHA256ROUND1(41, 0xa81a664b, 7, 0, 1, 2, 3, 4, 5, 6) - SHA256ROUND1(42, 0xc24b8b70, 6, 7, 0, 1, 2, 3, 4, 5) - SHA256ROUND1(43, 0xc76c51a3, 5, 6, 7, 0, 1, 2, 3, 4) - SHA256ROUND1(44, 0xd192e819, 4, 5, 6, 7, 0, 1, 2, 3) - SHA256ROUND1(45, 0xd6990624, 3, 4, 5, 6, 7, 0, 1, 2) - SHA256ROUND1(46, 0xf40e3585, 2, 3, 4, 5, 6, 7, 0, 1) - SHA256ROUND1(47, 0x106aa070, 1, 2, 3, 4, 5, 6, 7, 0) - SHA256ROUND1(48, 0x19a4c116, 0, 1, 2, 3, 4, 5, 6, 7) - SHA256ROUND1(49, 0x1e376c08, 7, 0, 1, 2, 3, 4, 5, 6) - SHA256ROUND1(50, 0x2748774c, 6, 7, 0, 1, 2, 3, 4, 5) - SHA256ROUND1(51, 0x34b0bcb5, 5, 6, 7, 0, 1, 2, 3, 4) - SHA256ROUND1(52, 0x391c0cb3, 4, 5, 6, 7, 0, 1, 2, 3) - SHA256ROUND1(53, 0x4ed8aa4a, 3, 4, 5, 6, 7, 0, 1, 2) - SHA256ROUND1(54, 0x5b9cca4f, 2, 3, 4, 5, 6, 7, 0, 1) - SHA256ROUND1(55, 0x682e6ff3, 1, 2, 3, 4, 5, 6, 7, 0) - SHA256ROUND1(56, 0x748f82ee, 0, 1, 2, 3, 4, 5, 6, 7) - SHA256ROUND1(57, 0x78a5636f, 7, 0, 1, 2, 3, 4, 5, 6) - SHA256ROUND1(58, 0x84c87814, 6, 7, 0, 1, 2, 3, 4, 5) - SHA256ROUND1(59, 0x8cc70208, 5, 6, 7, 0, 1, 2, 3, 4) - SHA256ROUND1(60, 0x90befffa, 4, 5, 6, 7, 0, 1, 2, 3) - SHA256ROUND1(61, 0xa4506ceb, 3, 4, 5, 6, 7, 0, 1, 2) - SHA256ROUND1(62, 0xbef9a3f7, 2, 3, 4, 5, 6, 7, 0, 1) - SHA256ROUND1(63, 0xc67178f2, 1, 2, 3, 4, 5, 6, 7, 0) - - MOVL dig+0(FP), BP - MOVL (0*4)(BP), AX // H0 = a + H0 - ADDL (0*4)(DI), AX - MOVL AX, (0*4)(DI) - MOVL AX, (0*4)(BP) - MOVL (1*4)(BP), BX // H1 = b + H1 - ADDL (1*4)(DI), BX - MOVL BX, (1*4)(DI) - MOVL BX, (1*4)(BP) - MOVL (2*4)(BP), CX // H2 = c + H2 - ADDL (2*4)(DI), CX - MOVL CX, (2*4)(DI) - MOVL CX, (2*4)(BP) - MOVL (3*4)(BP), DX // H3 = d + H3 - ADDL (3*4)(DI), DX - MOVL DX, (3*4)(DI) - MOVL DX, (3*4)(BP) - MOVL (4*4)(BP), AX // H4 = e + H4 - ADDL (4*4)(DI), AX - MOVL AX, (4*4)(DI) - MOVL AX, (4*4)(BP) - MOVL (5*4)(BP), BX // H5 = f + H5 - ADDL (5*4)(DI), BX - MOVL BX, (5*4)(DI) - MOVL BX, (5*4)(BP) - MOVL (6*4)(BP), CX // H6 = g + H6 - ADDL (6*4)(DI), CX - MOVL CX, (6*4)(DI) - MOVL CX, (6*4)(BP) - MOVL (7*4)(BP), DX // H7 = h + H7 - ADDL (7*4)(DI), DX - MOVL DX, (7*4)(DI) - MOVL DX, (7*4)(BP) - - ADDL $64, SI - CMPL SI, 288(SP) - JB loop - -end: - RET diff --git a/src/pkg/crypto/sha256/sha256block_amd64.s b/src/pkg/crypto/sha256/sha256block_amd64.s deleted file mode 100644 index 868eaed48..000000000 --- a/src/pkg/crypto/sha256/sha256block_amd64.s +++ /dev/null @@ -1,256 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "textflag.h" - -// SHA256 block routine. See sha256block.go for Go equivalent. -// -// The algorithm is detailed in FIPS 180-4: -// -// http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf -// -// Wt = Mt; for 0 <= t <= 15 -// Wt = SIGMA1(Wt-2) + SIGMA0(Wt-15) + Wt-16; for 16 <= t <= 63 -// -// a = H0 -// b = H1 -// c = H2 -// d = H3 -// e = H4 -// f = H5 -// g = H6 -// h = H7 -// -// for t = 0 to 63 { -// T1 = h + BIGSIGMA1(e) + Ch(e,f,g) + Kt + Wt -// T2 = BIGSIGMA0(a) + Maj(a,b,c) -// h = g -// g = f -// f = e -// e = d + T1 -// d = c -// c = b -// b = a -// a = T1 + T2 -// } -// -// H0 = a + H0 -// H1 = b + H1 -// H2 = c + H2 -// H3 = d + H3 -// H4 = e + H4 -// H5 = f + H5 -// H6 = g + H6 -// H7 = h + H7 - -// Wt = Mt; for 0 <= t <= 15 -#define MSGSCHEDULE0(index) \ - MOVL (index*4)(SI), AX; \ - BSWAPL AX; \ - MOVL AX, (index*4)(BP) - -// Wt = SIGMA1(Wt-2) + Wt-7 + SIGMA0(Wt-15) + Wt-16; for 16 <= t <= 63 -// SIGMA0(x) = ROTR(7,x) XOR ROTR(18,x) XOR SHR(3,x) -// SIGMA1(x) = ROTR(17,x) XOR ROTR(19,x) XOR SHR(10,x) -#define MSGSCHEDULE1(index) \ - MOVL ((index-2)*4)(BP), AX; \ - MOVL AX, CX; \ - RORL $17, AX; \ - MOVL CX, DX; \ - RORL $19, CX; \ - SHRL $10, DX; \ - MOVL ((index-15)*4)(BP), BX; \ - XORL CX, AX; \ - MOVL BX, CX; \ - XORL DX, AX; \ - RORL $7, BX; \ - MOVL CX, DX; \ - SHRL $3, DX; \ - RORL $18, CX; \ - ADDL ((index-7)*4)(BP), AX; \ - XORL CX, BX; \ - XORL DX, BX; \ - ADDL ((index-16)*4)(BP), BX; \ - ADDL BX, AX; \ - MOVL AX, ((index)*4)(BP) - -// Calculate T1 in AX - uses AX, CX and DX registers. -// h is also used as an accumulator. Wt is passed in AX. -// T1 = h + BIGSIGMA1(e) + Ch(e, f, g) + Kt + Wt -// BIGSIGMA1(x) = ROTR(6,x) XOR ROTR(11,x) XOR ROTR(25,x) -// Ch(x, y, z) = (x AND y) XOR (NOT x AND z) -#define SHA256T1(const, e, f, g, h) \ - ADDL AX, h; \ - MOVL e, AX; \ - ADDL $const, h; \ - MOVL e, CX; \ - RORL $6, AX; \ - MOVL e, DX; \ - RORL $11, CX; \ - XORL CX, AX; \ - MOVL e, CX; \ - RORL $25, DX; \ - ANDL f, CX; \ - XORL AX, DX; \ - MOVL e, AX; \ - NOTL AX; \ - ADDL DX, h; \ - ANDL g, AX; \ - XORL CX, AX; \ - ADDL h, AX - -// Calculate T2 in BX - uses BX, CX, DX and DI registers. -// T2 = BIGSIGMA0(a) + Maj(a, b, c) -// BIGSIGMA0(x) = ROTR(2,x) XOR ROTR(13,x) XOR ROTR(22,x) -// Maj(x, y, z) = (x AND y) XOR (x AND z) XOR (y AND z) -#define SHA256T2(a, b, c) \ - MOVL a, DI; \ - MOVL c, BX; \ - RORL $2, DI; \ - MOVL a, DX; \ - ANDL b, BX; \ - RORL $13, DX; \ - MOVL a, CX; \ - ANDL c, CX; \ - XORL DX, DI; \ - XORL CX, BX; \ - MOVL a, DX; \ - MOVL b, CX; \ - RORL $22, DX; \ - ANDL a, CX; \ - XORL CX, BX; \ - XORL DX, DI; \ - ADDL DI, BX - -// Calculate T1 and T2, then e = d + T1 and a = T1 + T2. -// The values for e and a are stored in d and h, ready for rotation. -#define SHA256ROUND(index, const, a, b, c, d, e, f, g, h) \ - SHA256T1(const, e, f, g, h); \ - SHA256T2(a, b, c); \ - MOVL BX, h; \ - ADDL AX, d; \ - ADDL AX, h - -#define SHA256ROUND0(index, const, a, b, c, d, e, f, g, h) \ - MSGSCHEDULE0(index); \ - SHA256ROUND(index, const, a, b, c, d, e, f, g, h) - -#define SHA256ROUND1(index, const, a, b, c, d, e, f, g, h) \ - MSGSCHEDULE1(index); \ - SHA256ROUND(index, const, a, b, c, d, e, f, g, h) - -TEXT ·block(SB),0,$264-32 - MOVQ p_base+8(FP), SI - MOVQ p_len+16(FP), DX - SHRQ $6, DX - SHLQ $6, DX - - LEAQ (SI)(DX*1), DI - MOVQ DI, 256(SP) - CMPQ SI, DI - JEQ end - - MOVQ dig+0(FP), BP - MOVL (0*4)(BP), R8 // a = H0 - MOVL (1*4)(BP), R9 // b = H1 - MOVL (2*4)(BP), R10 // c = H2 - MOVL (3*4)(BP), R11 // d = H3 - MOVL (4*4)(BP), R12 // e = H4 - MOVL (5*4)(BP), R13 // f = H5 - MOVL (6*4)(BP), R14 // g = H6 - MOVL (7*4)(BP), R15 // h = H7 - -loop: - MOVQ SP, BP // message schedule - - SHA256ROUND0(0, 0x428a2f98, R8, R9, R10, R11, R12, R13, R14, R15) - SHA256ROUND0(1, 0x71374491, R15, R8, R9, R10, R11, R12, R13, R14) - SHA256ROUND0(2, 0xb5c0fbcf, R14, R15, R8, R9, R10, R11, R12, R13) - SHA256ROUND0(3, 0xe9b5dba5, R13, R14, R15, R8, R9, R10, R11, R12) - SHA256ROUND0(4, 0x3956c25b, R12, R13, R14, R15, R8, R9, R10, R11) - SHA256ROUND0(5, 0x59f111f1, R11, R12, R13, R14, R15, R8, R9, R10) - SHA256ROUND0(6, 0x923f82a4, R10, R11, R12, R13, R14, R15, R8, R9) - SHA256ROUND0(7, 0xab1c5ed5, R9, R10, R11, R12, R13, R14, R15, R8) - SHA256ROUND0(8, 0xd807aa98, R8, R9, R10, R11, R12, R13, R14, R15) - SHA256ROUND0(9, 0x12835b01, R15, R8, R9, R10, R11, R12, R13, R14) - SHA256ROUND0(10, 0x243185be, R14, R15, R8, R9, R10, R11, R12, R13) - SHA256ROUND0(11, 0x550c7dc3, R13, R14, R15, R8, R9, R10, R11, R12) - SHA256ROUND0(12, 0x72be5d74, R12, R13, R14, R15, R8, R9, R10, R11) - SHA256ROUND0(13, 0x80deb1fe, R11, R12, R13, R14, R15, R8, R9, R10) - SHA256ROUND0(14, 0x9bdc06a7, R10, R11, R12, R13, R14, R15, R8, R9) - SHA256ROUND0(15, 0xc19bf174, R9, R10, R11, R12, R13, R14, R15, R8) - - SHA256ROUND1(16, 0xe49b69c1, R8, R9, R10, R11, R12, R13, R14, R15) - SHA256ROUND1(17, 0xefbe4786, R15, R8, R9, R10, R11, R12, R13, R14) - SHA256ROUND1(18, 0x0fc19dc6, R14, R15, R8, R9, R10, R11, R12, R13) - SHA256ROUND1(19, 0x240ca1cc, R13, R14, R15, R8, R9, R10, R11, R12) - SHA256ROUND1(20, 0x2de92c6f, R12, R13, R14, R15, R8, R9, R10, R11) - SHA256ROUND1(21, 0x4a7484aa, R11, R12, R13, R14, R15, R8, R9, R10) - SHA256ROUND1(22, 0x5cb0a9dc, R10, R11, R12, R13, R14, R15, R8, R9) - SHA256ROUND1(23, 0x76f988da, R9, R10, R11, R12, R13, R14, R15, R8) - SHA256ROUND1(24, 0x983e5152, R8, R9, R10, R11, R12, R13, R14, R15) - SHA256ROUND1(25, 0xa831c66d, R15, R8, R9, R10, R11, R12, R13, R14) - SHA256ROUND1(26, 0xb00327c8, R14, R15, R8, R9, R10, R11, R12, R13) - SHA256ROUND1(27, 0xbf597fc7, R13, R14, R15, R8, R9, R10, R11, R12) - SHA256ROUND1(28, 0xc6e00bf3, R12, R13, R14, R15, R8, R9, R10, R11) - SHA256ROUND1(29, 0xd5a79147, R11, R12, R13, R14, R15, R8, R9, R10) - SHA256ROUND1(30, 0x06ca6351, R10, R11, R12, R13, R14, R15, R8, R9) - SHA256ROUND1(31, 0x14292967, R9, R10, R11, R12, R13, R14, R15, R8) - SHA256ROUND1(32, 0x27b70a85, R8, R9, R10, R11, R12, R13, R14, R15) - SHA256ROUND1(33, 0x2e1b2138, R15, R8, R9, R10, R11, R12, R13, R14) - SHA256ROUND1(34, 0x4d2c6dfc, R14, R15, R8, R9, R10, R11, R12, R13) - SHA256ROUND1(35, 0x53380d13, R13, R14, R15, R8, R9, R10, R11, R12) - SHA256ROUND1(36, 0x650a7354, R12, R13, R14, R15, R8, R9, R10, R11) - SHA256ROUND1(37, 0x766a0abb, R11, R12, R13, R14, R15, R8, R9, R10) - SHA256ROUND1(38, 0x81c2c92e, R10, R11, R12, R13, R14, R15, R8, R9) - SHA256ROUND1(39, 0x92722c85, R9, R10, R11, R12, R13, R14, R15, R8) - SHA256ROUND1(40, 0xa2bfe8a1, R8, R9, R10, R11, R12, R13, R14, R15) - SHA256ROUND1(41, 0xa81a664b, R15, R8, R9, R10, R11, R12, R13, R14) - SHA256ROUND1(42, 0xc24b8b70, R14, R15, R8, R9, R10, R11, R12, R13) - SHA256ROUND1(43, 0xc76c51a3, R13, R14, R15, R8, R9, R10, R11, R12) - SHA256ROUND1(44, 0xd192e819, R12, R13, R14, R15, R8, R9, R10, R11) - SHA256ROUND1(45, 0xd6990624, R11, R12, R13, R14, R15, R8, R9, R10) - SHA256ROUND1(46, 0xf40e3585, R10, R11, R12, R13, R14, R15, R8, R9) - SHA256ROUND1(47, 0x106aa070, R9, R10, R11, R12, R13, R14, R15, R8) - SHA256ROUND1(48, 0x19a4c116, R8, R9, R10, R11, R12, R13, R14, R15) - SHA256ROUND1(49, 0x1e376c08, R15, R8, R9, R10, R11, R12, R13, R14) - SHA256ROUND1(50, 0x2748774c, R14, R15, R8, R9, R10, R11, R12, R13) - SHA256ROUND1(51, 0x34b0bcb5, R13, R14, R15, R8, R9, R10, R11, R12) - SHA256ROUND1(52, 0x391c0cb3, R12, R13, R14, R15, R8, R9, R10, R11) - SHA256ROUND1(53, 0x4ed8aa4a, R11, R12, R13, R14, R15, R8, R9, R10) - SHA256ROUND1(54, 0x5b9cca4f, R10, R11, R12, R13, R14, R15, R8, R9) - SHA256ROUND1(55, 0x682e6ff3, R9, R10, R11, R12, R13, R14, R15, R8) - SHA256ROUND1(56, 0x748f82ee, R8, R9, R10, R11, R12, R13, R14, R15) - SHA256ROUND1(57, 0x78a5636f, R15, R8, R9, R10, R11, R12, R13, R14) - SHA256ROUND1(58, 0x84c87814, R14, R15, R8, R9, R10, R11, R12, R13) - SHA256ROUND1(59, 0x8cc70208, R13, R14, R15, R8, R9, R10, R11, R12) - SHA256ROUND1(60, 0x90befffa, R12, R13, R14, R15, R8, R9, R10, R11) - SHA256ROUND1(61, 0xa4506ceb, R11, R12, R13, R14, R15, R8, R9, R10) - SHA256ROUND1(62, 0xbef9a3f7, R10, R11, R12, R13, R14, R15, R8, R9) - SHA256ROUND1(63, 0xc67178f2, R9, R10, R11, R12, R13, R14, R15, R8) - - MOVQ dig+0(FP), BP - ADDL (0*4)(BP), R8 // H0 = a + H0 - MOVL R8, (0*4)(BP) - ADDL (1*4)(BP), R9 // H1 = b + H1 - MOVL R9, (1*4)(BP) - ADDL (2*4)(BP), R10 // H2 = c + H2 - MOVL R10, (2*4)(BP) - ADDL (3*4)(BP), R11 // H3 = d + H3 - MOVL R11, (3*4)(BP) - ADDL (4*4)(BP), R12 // H4 = e + H4 - MOVL R12, (4*4)(BP) - ADDL (5*4)(BP), R13 // H5 = f + H5 - MOVL R13, (5*4)(BP) - ADDL (6*4)(BP), R14 // H6 = g + H6 - MOVL R14, (6*4)(BP) - ADDL (7*4)(BP), R15 // H7 = h + H7 - MOVL R15, (7*4)(BP) - - ADDQ $64, SI - CMPQ SI, 256(SP) - JB loop - -end: - RET diff --git a/src/pkg/crypto/sha256/sha256block_decl.go b/src/pkg/crypto/sha256/sha256block_decl.go deleted file mode 100644 index a50c97871..000000000 --- a/src/pkg/crypto/sha256/sha256block_decl.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build 386 amd64 - -package sha256 - -//go:noescape - -func block(dig *digest, p []byte) diff --git a/src/pkg/crypto/sha512/sha512.go b/src/pkg/crypto/sha512/sha512.go deleted file mode 100644 index bca7a91e2..000000000 --- a/src/pkg/crypto/sha512/sha512.go +++ /dev/null @@ -1,198 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package sha512 implements the SHA384 and SHA512 hash algorithms as defined -// in FIPS 180-2. -package sha512 - -import ( - "crypto" - "hash" -) - -func init() { - crypto.RegisterHash(crypto.SHA384, New384) - crypto.RegisterHash(crypto.SHA512, New) -} - -// The size of a SHA512 checksum in bytes. -const Size = 64 - -// The size of a SHA384 checksum in bytes. -const Size384 = 48 - -// The blocksize of SHA512 and SHA384 in bytes. -const BlockSize = 128 - -const ( - chunk = 128 - init0 = 0x6a09e667f3bcc908 - init1 = 0xbb67ae8584caa73b - init2 = 0x3c6ef372fe94f82b - init3 = 0xa54ff53a5f1d36f1 - init4 = 0x510e527fade682d1 - init5 = 0x9b05688c2b3e6c1f - init6 = 0x1f83d9abfb41bd6b - init7 = 0x5be0cd19137e2179 - init0_384 = 0xcbbb9d5dc1059ed8 - init1_384 = 0x629a292a367cd507 - init2_384 = 0x9159015a3070dd17 - init3_384 = 0x152fecd8f70e5939 - init4_384 = 0x67332667ffc00b31 - init5_384 = 0x8eb44a8768581511 - init6_384 = 0xdb0c2e0d64f98fa7 - init7_384 = 0x47b5481dbefa4fa4 -) - -// digest represents the partial evaluation of a checksum. -type digest struct { - h [8]uint64 - x [chunk]byte - nx int - len uint64 - is384 bool // mark if this digest is SHA-384 -} - -func (d *digest) Reset() { - if !d.is384 { - d.h[0] = init0 - d.h[1] = init1 - d.h[2] = init2 - d.h[3] = init3 - d.h[4] = init4 - d.h[5] = init5 - d.h[6] = init6 - d.h[7] = init7 - } else { - d.h[0] = init0_384 - d.h[1] = init1_384 - d.h[2] = init2_384 - d.h[3] = init3_384 - d.h[4] = init4_384 - d.h[5] = init5_384 - d.h[6] = init6_384 - d.h[7] = init7_384 - } - d.nx = 0 - d.len = 0 -} - -// New returns a new hash.Hash computing the SHA512 checksum. -func New() hash.Hash { - d := new(digest) - d.Reset() - return d -} - -// New384 returns a new hash.Hash computing the SHA384 checksum. -func New384() hash.Hash { - d := new(digest) - d.is384 = true - d.Reset() - return d -} - -func (d *digest) Size() int { - if !d.is384 { - return Size - } - return Size384 -} - -func (d *digest) BlockSize() int { return BlockSize } - -func (d *digest) Write(p []byte) (nn int, err error) { - nn = len(p) - d.len += uint64(nn) - if d.nx > 0 { - n := copy(d.x[d.nx:], p) - d.nx += n - if d.nx == chunk { - block(d, d.x[:]) - d.nx = 0 - } - p = p[n:] - } - if len(p) >= chunk { - n := len(p) &^ (chunk - 1) - block(d, p[:n]) - p = p[n:] - } - if len(p) > 0 { - d.nx = copy(d.x[:], p) - } - return -} - -func (d0 *digest) Sum(in []byte) []byte { - // Make a copy of d0 so that caller can keep writing and summing. - d := new(digest) - *d = *d0 - hash := d.checkSum() - if d.is384 { - return append(in, hash[:Size384]...) - } - return append(in, hash[:]...) -} - -func (d *digest) checkSum() [Size]byte { - // Padding. Add a 1 bit and 0 bits until 112 bytes mod 128. - len := d.len - var tmp [128]byte - tmp[0] = 0x80 - if len%128 < 112 { - d.Write(tmp[0 : 112-len%128]) - } else { - d.Write(tmp[0 : 128+112-len%128]) - } - - // Length in bits. - len <<= 3 - for i := uint(0); i < 16; i++ { - tmp[i] = byte(len >> (120 - 8*i)) - } - d.Write(tmp[0:16]) - - if d.nx != 0 { - panic("d.nx != 0") - } - - h := d.h[:] - if d.is384 { - h = d.h[:6] - } - - var digest [Size]byte - for i, s := range h { - digest[i*8] = byte(s >> 56) - digest[i*8+1] = byte(s >> 48) - digest[i*8+2] = byte(s >> 40) - digest[i*8+3] = byte(s >> 32) - digest[i*8+4] = byte(s >> 24) - digest[i*8+5] = byte(s >> 16) - digest[i*8+6] = byte(s >> 8) - digest[i*8+7] = byte(s) - } - - return digest -} - -// Sum512 returns the SHA512 checksum of the data. -func Sum512(data []byte) [Size]byte { - var d digest - d.Reset() - d.Write(data) - return d.checkSum() -} - -// Sum384 returns the SHA384 checksum of the data. -func Sum384(data []byte) (sum384 [Size384]byte) { - var d digest - d.is384 = true - d.Reset() - d.Write(data) - sum := d.checkSum() - copy(sum384[:], sum[:Size384]) - return -} diff --git a/src/pkg/crypto/sha512/sha512_test.go b/src/pkg/crypto/sha512/sha512_test.go deleted file mode 100644 index 541860f70..000000000 --- a/src/pkg/crypto/sha512/sha512_test.go +++ /dev/null @@ -1,176 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// SHA512 hash algorithm. See FIPS 180-2. - -package sha512 - -import ( - "fmt" - "io" - "testing" -) - -type sha512Test struct { - out string - in string -} - -var golden = []sha512Test{ - {"cf83e1357eefb8bdf1542850d66d8007d620e4050b5715dc83f4a921d36ce9ce47d0d13c5d85f2b0ff8318d2877eec2f63b931bd47417a81a538327af927da3e", ""}, - {"1f40fc92da241694750979ee6cf582f2d5d7d28e18335de05abc54d0560e0f5302860c652bf08d560252aa5e74210546f369fbbbce8c12cfc7957b2652fe9a75", "a"}, - {"2d408a0717ec188158278a796c689044361dc6fdde28d6f04973b80896e1823975cdbf12eb63f9e0591328ee235d80e9b5bf1aa6a44f4617ff3caf6400eb172d", "ab"}, - {"ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f", "abc"}, - {"d8022f2060ad6efd297ab73dcc5355c9b214054b0d1776a136a669d26a7d3b14f73aa0d0ebff19ee333368f0164b6419a96da49e3e481753e7e96b716bdccb6f", "abcd"}, - {"878ae65a92e86cac011a570d4c30a7eaec442b85ce8eca0c2952b5e3cc0628c2e79d889ad4d5c7c626986d452dd86374b6ffaa7cd8b67665bef2289a5c70b0a1", "abcde"}, - {"e32ef19623e8ed9d267f657a81944b3d07adbb768518068e88435745564e8d4150a0a703be2a7d88b61e3d390c2bb97e2d4c311fdc69d6b1267f05f59aa920e7", "abcdef"}, - {"d716a4188569b68ab1b6dfac178e570114cdf0ea3a1cc0e31486c3e41241bc6a76424e8c37ab26f096fc85ef9886c8cb634187f4fddff645fb099f1ff54c6b8c", "abcdefg"}, - {"a3a8c81bc97c2560010d7389bc88aac974a104e0e2381220c6e084c4dccd1d2d17d4f86db31c2a851dc80e6681d74733c55dcd03dd96f6062cdda12a291ae6ce", "abcdefgh"}, - {"f22d51d25292ca1d0f68f69aedc7897019308cc9db46efb75a03dd494fc7f126c010e8ade6a00a0c1a5f1b75d81e0ed5a93ce98dc9b833db7839247b1d9c24fe", "abcdefghi"}, - {"ef6b97321f34b1fea2169a7db9e1960b471aa13302a988087357c520be957ca119c3ba68e6b4982c019ec89de3865ccf6a3cda1fe11e59f98d99f1502c8b9745", "abcdefghij"}, - {"2210d99af9c8bdecda1b4beff822136753d8342505ddce37f1314e2cdbb488c6016bdaa9bd2ffa513dd5de2e4b50f031393d8ab61f773b0e0130d7381e0f8a1d", "Discard medicine more than two years old."}, - {"a687a8985b4d8d0a24f115fe272255c6afaf3909225838546159c1ed685c211a203796ae8ecc4c81a5b6315919b3a64f10713da07e341fcdbb08541bf03066ce", "He who has a shady past knows that nice guys finish last."}, - {"8ddb0392e818b7d585ab22769a50df660d9f6d559cca3afc5691b8ca91b8451374e42bcdabd64589ed7c91d85f626596228a5c8572677eb98bc6b624befb7af8", "I wouldn't marry him with a ten foot pole."}, - {"26ed8f6ca7f8d44b6a8a54ae39640fa8ad5c673f70ee9ce074ba4ef0d483eea00bab2f61d8695d6b34df9c6c48ae36246362200ed820448bdc03a720366a87c6", "Free! Free!/A trip/to Mars/for 900/empty jars/Burma Shave"}, - {"e5a14bf044be69615aade89afcf1ab0389d5fc302a884d403579d1386a2400c089b0dbb387ed0f463f9ee342f8244d5a38cfbc0e819da9529fbff78368c9a982", "The days of the digital watch are numbered. -Tom Stoppard"}, - {"420a1faa48919e14651bed45725abe0f7a58e0f099424c4e5a49194946e38b46c1f8034b18ef169b2e31050d1648e0b982386595f7df47da4b6fd18e55333015", "Nepal premier won't resign."}, - {"d926a863beadb20134db07683535c72007b0e695045876254f341ddcccde132a908c5af57baa6a6a9c63e6649bba0c213dc05fadcf9abccea09f23dcfb637fbe", "For every action there is an equal and opposite government program."}, - {"9a98dd9bb67d0da7bf83da5313dff4fd60a4bac0094f1b05633690ffa7f6d61de9a1d4f8617937d560833a9aaa9ccafe3fd24db418d0e728833545cadd3ad92d", "His money is twice tainted: 'taint yours and 'taint mine."}, - {"d7fde2d2351efade52f4211d3746a0780a26eec3df9b2ed575368a8a1c09ec452402293a8ea4eceb5a4f60064ea29b13cdd86918cd7a4faf366160b009804107", "There is no reason for any individual to have a computer in their home. -Ken Olsen, 1977"}, - {"b0f35ffa2697359c33a56f5c0cf715c7aeed96da9905ca2698acadb08fbc9e669bf566b6bd5d61a3e86dc22999bcc9f2224e33d1d4f32a228cf9d0349e2db518", "It's a tiny change to the code and not completely disgusting. - Bob Manchek"}, - {"3d2e5f91778c9e66f7e061293aaa8a8fc742dd3b2e4f483772464b1144189b49273e610e5cccd7a81a19ca1fa70f16b10f1a100a4d8c1372336be8484c64b311", "size: a.out: bad magic"}, - {"b2f68ff58ac015efb1c94c908b0d8c2bf06f491e4de8e6302c49016f7f8a33eac3e959856c7fddbc464de618701338a4b46f76dbfaf9a1e5262b5f40639771c7", "The major problem is with sendmail. -Mark Horton"}, - {"d8c92db5fdf52cf8215e4df3b4909d29203ff4d00e9ad0b64a6a4e04dec5e74f62e7c35c7fb881bd5de95442123df8f57a489b0ae616bd326f84d10021121c57", "Give me a rock, paper and scissors and I will move the world. CCFestoon"}, - {"19a9f8dc0a233e464e8566ad3ca9b91e459a7b8c4780985b015776e1bf239a19bc233d0556343e2b0a9bc220900b4ebf4f8bdf89ff8efeaf79602d6849e6f72e", "If the enemy is within range, then so are you."}, - {"00b4c41f307bde87301cdc5b5ab1ae9a592e8ecbb2021dd7bc4b34e2ace60741cc362560bec566ba35178595a91932b8d5357e2c9cec92d393b0fa7831852476", "It's well we cannot hear the screams/That we create in others' dreams."}, - {"91eccc3d5375fd026e4d6787874b1dce201cecd8a27dbded5065728cb2d09c58a3d467bb1faf353bf7ba567e005245d5321b55bc344f7c07b91cb6f26c959be7", "You remind me of a TV show, but that's all right: I watch it anyway."}, - {"fabbbe22180f1f137cfdc9556d2570e775d1ae02a597ded43a72a40f9b485d500043b7be128fb9fcd982b83159a0d99aa855a9e7cc4240c00dc01a9bdf8218d7", "C is as portable as Stonehedge!!"}, - {"2ecdec235c1fa4fc2a154d8fba1dddb8a72a1ad73838b51d792331d143f8b96a9f6fcb0f34d7caa351fe6d88771c4f105040e0392f06e0621689d33b2f3ba92e", "Even if I could be Shakespeare, I think I should still choose to be Faraday. - A. Huxley"}, - {"7ad681f6f96f82f7abfa7ecc0334e8fa16d3dc1cdc45b60b7af43fe4075d2357c0c1d60e98350f1afb1f2fe7a4d7cd2ad55b88e458e06b73c40b437331f5dab4", "The fugacity of a constituent in a mixture of gases at a given temperature is proportional to its mole fraction. Lewis-Randall Rule"}, - {"833f9248ab4a3b9e5131f745fda1ffd2dd435b30e965957e78291c7ab73605fd1912b0794e5c233ab0a12d205a39778d19b83515d6a47003f19cdee51d98c7e0", "How can you write a big system without C++? -Paul Glick"}, -} - -var golden384 = []sha512Test{ - {"38b060a751ac96384cd9327eb1b1e36a21fdb71114be07434c0cc7bf63f6e1da274edebfe76f65fbd51ad2f14898b95b", ""}, - {"54a59b9f22b0b80880d8427e548b7c23abd873486e1f035dce9cd697e85175033caa88e6d57bc35efae0b5afd3145f31", "a"}, - {"c7be03ba5bcaa384727076db0018e99248e1a6e8bd1b9ef58a9ec9dd4eeebb3f48b836201221175befa74ddc3d35afdd", "ab"}, - {"cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed8086072ba1e7cc2358baeca134c825a7", "abc"}, - {"1165b3406ff0b52a3d24721f785462ca2276c9f454a116c2b2ba20171a7905ea5a026682eb659c4d5f115c363aa3c79b", "abcd"}, - {"4c525cbeac729eaf4b4665815bc5db0c84fe6300068a727cf74e2813521565abc0ec57a37ee4d8be89d097c0d2ad52f0", "abcde"}, - {"c6a4c65b227e7387b9c3e839d44869c4cfca3ef583dea64117859b808c1e3d8ae689e1e314eeef52a6ffe22681aa11f5", "abcdef"}, - {"9f11fc131123f844c1226f429b6a0a6af0525d9f40f056c7fc16cdf1b06bda08e302554417a59fa7dcf6247421959d22", "abcdefg"}, - {"9000cd7cada59d1d2eb82912f7f24e5e69cc5517f68283b005fa27c285b61e05edf1ad1a8a9bded6fd29eb87d75ad806", "abcdefgh"}, - {"ef54915b60cf062b8dd0c29ae3cad69abe6310de63ac081f46ef019c5c90897caefd79b796cfa81139788a260ded52df", "abcdefghi"}, - {"a12070030a02d86b0ddacd0d3a5b598344513d0a051e7355053e556a0055489c1555399b03342845c4adde2dc44ff66c", "abcdefghij"}, - {"86f58ec2d74d1b7f8eb0c2ff0967316699639e8d4eb129de54bdf34c96cdbabe200d052149f2dd787f43571ba74670d4", "Discard medicine more than two years old."}, - {"ae4a2b639ca9bfa04b1855d5a05fe7f230994f790891c6979103e2605f660c4c1262a48142dcbeb57a1914ba5f7c3fa7", "He who has a shady past knows that nice guys finish last."}, - {"40ae213df6436eca952aa6841886fcdb82908ef1576a99c8f49bb9dd5023169f7c53035abdda0b54c302f4974e2105e7", "I wouldn't marry him with a ten foot pole."}, - {"e7cf8b873c9bc950f06259aa54309f349cefa72c00d597aebf903e6519a50011dfe355afff064a10701c705693848df9", "Free! Free!/A trip/to Mars/for 900/empty jars/Burma Shave"}, - {"c3d4f0f4047181c7d39d34703365f7bf70207183caf2c2f6145f04da895ef69124d9cdeb635da636c3a474e61024e29b", "The days of the digital watch are numbered. -Tom Stoppard"}, - {"a097aab567e167d5cf93676ed73252a69f9687cb3179bb2d27c9878119e94bf7b7c4b58dc90582edfaf66e11388ed714", "Nepal premier won't resign."}, - {"5026ca45c41fc64712eb65065da92f6467541c78f8966d3fe2c8e3fb769a3ec14215f819654b47bd64f7f0eac17184f3", "For every action there is an equal and opposite government program."}, - {"ac1cc0f5ac8d5f5514a7b738ac322b7fb52a161b449c3672e9b6a6ad1a5e4b26b001cf3bad24c56598676ca17d4b445a", "His money is twice tainted: 'taint yours and 'taint mine."}, - {"722d10c5de371ec0c8c4b5247ac8a5f1d240d68c73f8da13d8b25f0166d6f309bf9561979a111a0049405771d201941a", "There is no reason for any individual to have a computer in their home. -Ken Olsen, 1977"}, - {"dc2d3ea18bfa10549c63bf2b75b39b5167a80c12aff0e05443168ea87ff149fb0eda5e0bd234eb5d48c7d02ffc5807f1", "It's a tiny change to the code and not completely disgusting. - Bob Manchek"}, - {"1d67c969e2a945ae5346d2139760261504d4ba164c522443afe19ef3e29b152a4c52445489cfc9d7215e5a450e8e1e4e", "size: a.out: bad magic"}, - {"5ff8e075e465646e7b73ef36d812c6e9f7d60fa6ea0e533e5569b4f73cde53cdd2cc787f33540af57cca3fe467d32fe0", "The major problem is with sendmail. -Mark Horton"}, - {"5bd0a997a67c9ae1979a894eb0cde403dde003c9b6f2c03cf21925c42ff4e1176e6df1ca005381612ef18457b9b7ec3b", "Give me a rock, paper and scissors and I will move the world. CCFestoon"}, - {"1eee6da33e7e54fc5be52ae23b94b16ba4d2a947ae4505c6a3edfc7401151ea5205ac01b669b56f27d8ef7f175ed7762", "If the enemy is within range, then so are you."}, - {"76b06e9dea66bfbb1a96029426dc0dfd7830bd297eb447ff5358d94a87cd00c88b59df2493fef56ecbb5231073892ea9", "It's well we cannot hear the screams/That we create in others' dreams."}, - {"12acaf21452cff586143e3f5db0bfdf7802c057e1adf2a619031c4e1b0ccc4208cf6cef8fe722bbaa2fb46a30d9135d8", "You remind me of a TV show, but that's all right: I watch it anyway."}, - {"0fc23d7f4183efd186f0bc4fc5db867e026e2146b06cb3d52f4bdbd57d1740122caa853b41868b197b2ac759db39df88", "C is as portable as Stonehedge!!"}, - {"bc805578a7f85d34a86a32976e1c34fe65cf815186fbef76f46ef99cda10723f971f3f1464d488243f5e29db7488598d", "Even if I could be Shakespeare, I think I should still choose to be Faraday. - A. Huxley"}, - {"b23918399a12ebf4431559eec3813eaf7412e875fd7464f16d581e473330842d2e96c6be49a7ce3f9bb0b8bc0fcbe0fe", "The fugacity of a constituent in a mixture of gases at a given temperature is proportional to its mole fraction. Lewis-Randall Rule"}, - {"1764b700eb1ead52a2fc33cc28975c2180f1b8faa5038d94cffa8d78154aab16e91dd787e7b0303948ebed62561542c8", "How can you write a big system without C++? -Paul Glick"}, -} - -func TestGolden(t *testing.T) { - for i := 0; i < len(golden); i++ { - g := golden[i] - s := fmt.Sprintf("%x", Sum512([]byte(g.in))) - if s != g.out { - t.Fatalf("Sum512 function: sha512(%s) = %s want %s", g.in, s, g.out) - } - c := New() - for j := 0; j < 3; j++ { - if j < 2 { - io.WriteString(c, g.in) - } else { - io.WriteString(c, g.in[0:len(g.in)/2]) - c.Sum(nil) - io.WriteString(c, g.in[len(g.in)/2:]) - } - s := fmt.Sprintf("%x", c.Sum(nil)) - if s != g.out { - t.Fatalf("sha512[%d](%s) = %s want %s", j, g.in, s, g.out) - } - c.Reset() - } - } - for i := 0; i < len(golden384); i++ { - g := golden384[i] - s := fmt.Sprintf("%x", Sum384([]byte(g.in))) - if s != g.out { - t.Fatalf("Sum384 function: sha384(%s) = %s want %s", g.in, s, g.out) - } - c := New384() - for j := 0; j < 3; j++ { - if j < 2 { - io.WriteString(c, g.in) - } else { - io.WriteString(c, g.in[0:len(g.in)/2]) - c.Sum(nil) - io.WriteString(c, g.in[len(g.in)/2:]) - } - s := fmt.Sprintf("%x", c.Sum(nil)) - if s != g.out { - t.Fatalf("sha384[%d](%s) = %s want %s", j, g.in, s, g.out) - } - c.Reset() - } - } -} - -func TestSize(t *testing.T) { - c := New() - if got := c.Size(); got != Size { - t.Errorf("Size = %d; want %d", got, Size) - } - c = New384() - if got := c.Size(); got != Size384 { - t.Errorf("New384.Size = %d; want %d", got, Size384) - } -} - -func TestBlockSize(t *testing.T) { - c := New() - if got := c.BlockSize(); got != BlockSize { - t.Errorf("BlockSize = %d; want %d", got, BlockSize) - } -} - -var bench = New() -var buf = make([]byte, 8192) - -func benchmarkSize(b *testing.B, size int) { - b.SetBytes(int64(size)) - sum := make([]byte, bench.Size()) - for i := 0; i < b.N; i++ { - bench.Reset() - bench.Write(buf[:size]) - bench.Sum(sum[:0]) - } -} - -func BenchmarkHash8Bytes(b *testing.B) { - benchmarkSize(b, 8) -} - -func BenchmarkHash1K(b *testing.B) { - benchmarkSize(b, 1024) -} - -func BenchmarkHash8K(b *testing.B) { - benchmarkSize(b, 8192) -} diff --git a/src/pkg/crypto/sha512/sha512block.go b/src/pkg/crypto/sha512/sha512block.go deleted file mode 100644 index 648ae8f7e..000000000 --- a/src/pkg/crypto/sha512/sha512block.go +++ /dev/null @@ -1,144 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !amd64 - -// SHA512 block step. -// In its own file so that a faster assembly or C version -// can be substituted easily. - -package sha512 - -var _K = []uint64{ - 0x428a2f98d728ae22, - 0x7137449123ef65cd, - 0xb5c0fbcfec4d3b2f, - 0xe9b5dba58189dbbc, - 0x3956c25bf348b538, - 0x59f111f1b605d019, - 0x923f82a4af194f9b, - 0xab1c5ed5da6d8118, - 0xd807aa98a3030242, - 0x12835b0145706fbe, - 0x243185be4ee4b28c, - 0x550c7dc3d5ffb4e2, - 0x72be5d74f27b896f, - 0x80deb1fe3b1696b1, - 0x9bdc06a725c71235, - 0xc19bf174cf692694, - 0xe49b69c19ef14ad2, - 0xefbe4786384f25e3, - 0x0fc19dc68b8cd5b5, - 0x240ca1cc77ac9c65, - 0x2de92c6f592b0275, - 0x4a7484aa6ea6e483, - 0x5cb0a9dcbd41fbd4, - 0x76f988da831153b5, - 0x983e5152ee66dfab, - 0xa831c66d2db43210, - 0xb00327c898fb213f, - 0xbf597fc7beef0ee4, - 0xc6e00bf33da88fc2, - 0xd5a79147930aa725, - 0x06ca6351e003826f, - 0x142929670a0e6e70, - 0x27b70a8546d22ffc, - 0x2e1b21385c26c926, - 0x4d2c6dfc5ac42aed, - 0x53380d139d95b3df, - 0x650a73548baf63de, - 0x766a0abb3c77b2a8, - 0x81c2c92e47edaee6, - 0x92722c851482353b, - 0xa2bfe8a14cf10364, - 0xa81a664bbc423001, - 0xc24b8b70d0f89791, - 0xc76c51a30654be30, - 0xd192e819d6ef5218, - 0xd69906245565a910, - 0xf40e35855771202a, - 0x106aa07032bbd1b8, - 0x19a4c116b8d2d0c8, - 0x1e376c085141ab53, - 0x2748774cdf8eeb99, - 0x34b0bcb5e19b48a8, - 0x391c0cb3c5c95a63, - 0x4ed8aa4ae3418acb, - 0x5b9cca4f7763e373, - 0x682e6ff3d6b2b8a3, - 0x748f82ee5defb2fc, - 0x78a5636f43172f60, - 0x84c87814a1f0ab72, - 0x8cc702081a6439ec, - 0x90befffa23631e28, - 0xa4506cebde82bde9, - 0xbef9a3f7b2c67915, - 0xc67178f2e372532b, - 0xca273eceea26619c, - 0xd186b8c721c0c207, - 0xeada7dd6cde0eb1e, - 0xf57d4f7fee6ed178, - 0x06f067aa72176fba, - 0x0a637dc5a2c898a6, - 0x113f9804bef90dae, - 0x1b710b35131c471b, - 0x28db77f523047d84, - 0x32caab7b40c72493, - 0x3c9ebe0a15c9bebc, - 0x431d67c49c100d4c, - 0x4cc5d4becb3e42b6, - 0x597f299cfc657e2a, - 0x5fcb6fab3ad6faec, - 0x6c44198c4a475817, -} - -func block(dig *digest, p []byte) { - var w [80]uint64 - h0, h1, h2, h3, h4, h5, h6, h7 := dig.h[0], dig.h[1], dig.h[2], dig.h[3], dig.h[4], dig.h[5], dig.h[6], dig.h[7] - for len(p) >= chunk { - for i := 0; i < 16; i++ { - j := i * 8 - w[i] = uint64(p[j])<<56 | uint64(p[j+1])<<48 | uint64(p[j+2])<<40 | uint64(p[j+3])<<32 | - uint64(p[j+4])<<24 | uint64(p[j+5])<<16 | uint64(p[j+6])<<8 | uint64(p[j+7]) - } - for i := 16; i < 80; i++ { - v1 := w[i-2] - t1 := (v1>>19 | v1<<(64-19)) ^ (v1>>61 | v1<<(64-61)) ^ (v1 >> 6) - v2 := w[i-15] - t2 := (v2>>1 | v2<<(64-1)) ^ (v2>>8 | v2<<(64-8)) ^ (v2 >> 7) - - w[i] = t1 + w[i-7] + t2 + w[i-16] - } - - a, b, c, d, e, f, g, h := h0, h1, h2, h3, h4, h5, h6, h7 - - for i := 0; i < 80; i++ { - t1 := h + ((e>>14 | e<<(64-14)) ^ (e>>18 | e<<(64-18)) ^ (e>>41 | e<<(64-41))) + ((e & f) ^ (^e & g)) + _K[i] + w[i] - - t2 := ((a>>28 | a<<(64-28)) ^ (a>>34 | a<<(64-34)) ^ (a>>39 | a<<(64-39))) + ((a & b) ^ (a & c) ^ (b & c)) - - h = g - g = f - f = e - e = d + t1 - d = c - c = b - b = a - a = t1 + t2 - } - - h0 += a - h1 += b - h2 += c - h3 += d - h4 += e - h5 += f - h6 += g - h7 += h - - p = p[chunk:] - } - - dig.h[0], dig.h[1], dig.h[2], dig.h[3], dig.h[4], dig.h[5], dig.h[6], dig.h[7] = h0, h1, h2, h3, h4, h5, h6, h7 -} diff --git a/src/pkg/crypto/sha512/sha512block_amd64.s b/src/pkg/crypto/sha512/sha512block_amd64.s deleted file mode 100644 index 2e10233de..000000000 --- a/src/pkg/crypto/sha512/sha512block_amd64.s +++ /dev/null @@ -1,273 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -#include "textflag.h" - -// SHA512 block routine. See sha512block.go for Go equivalent. -// -// The algorithm is detailed in FIPS 180-4: -// -// http://csrc.nist.gov/publications/fips/fips180-4/fips-180-4.pdf -// -// Wt = Mt; for 0 <= t <= 15 -// Wt = SIGMA1(Wt-2) + SIGMA0(Wt-15) + Wt-16; for 16 <= t <= 79 -// -// a = H0 -// b = H1 -// c = H2 -// d = H3 -// e = H4 -// f = H5 -// g = H6 -// h = H7 -// -// for t = 0 to 79 { -// T1 = h + BIGSIGMA1(e) + Ch(e,f,g) + Kt + Wt -// T2 = BIGSIGMA0(a) + Maj(a,b,c) -// h = g -// g = f -// f = e -// e = d + T1 -// d = c -// c = b -// b = a -// a = T1 + T2 -// } -// -// H0 = a + H0 -// H1 = b + H1 -// H2 = c + H2 -// H3 = d + H3 -// H4 = e + H4 -// H5 = f + H5 -// H6 = g + H6 -// H7 = h + H7 - -// Wt = Mt; for 0 <= t <= 15 -#define MSGSCHEDULE0(index) \ - MOVQ (index*8)(SI), AX; \ - BSWAPQ AX; \ - MOVQ AX, (index*8)(BP) - -// Wt = SIGMA1(Wt-2) + Wt-7 + SIGMA0(Wt-15) + Wt-16; for 16 <= t <= 79 -// SIGMA0(x) = ROTR(1,x) XOR ROTR(8,x) XOR SHR(7,x) -// SIGMA1(x) = ROTR(19,x) XOR ROTR(61,x) XOR SHR(6,x) -#define MSGSCHEDULE1(index) \ - MOVQ ((index-2)*8)(BP), AX; \ - MOVQ AX, CX; \ - RORQ $19, AX; \ - MOVQ CX, DX; \ - RORQ $61, CX; \ - SHRQ $6, DX; \ - MOVQ ((index-15)*8)(BP), BX; \ - XORQ CX, AX; \ - MOVQ BX, CX; \ - XORQ DX, AX; \ - RORQ $1, BX; \ - MOVQ CX, DX; \ - SHRQ $7, DX; \ - RORQ $8, CX; \ - ADDQ ((index-7)*8)(BP), AX; \ - XORQ CX, BX; \ - XORQ DX, BX; \ - ADDQ ((index-16)*8)(BP), BX; \ - ADDQ BX, AX; \ - MOVQ AX, ((index)*8)(BP) - -// Calculate T1 in AX - uses AX, CX and DX registers. -// h is also used as an accumulator. Wt is passed in AX. -// T1 = h + BIGSIGMA1(e) + Ch(e, f, g) + Kt + Wt -// BIGSIGMA1(x) = ROTR(14,x) XOR ROTR(18,x) XOR ROTR(41,x) -// Ch(x, y, z) = (x AND y) XOR (NOT x AND z) -#define SHA512T1(const, e, f, g, h) \ - MOVQ $const, DX; \ - ADDQ AX, h; \ - MOVQ e, AX; \ - ADDQ DX, h; \ - MOVQ e, CX; \ - RORQ $14, AX; \ - MOVQ e, DX; \ - RORQ $18, CX; \ - XORQ CX, AX; \ - MOVQ e, CX; \ - RORQ $41, DX; \ - ANDQ f, CX; \ - XORQ AX, DX; \ - MOVQ e, AX; \ - NOTQ AX; \ - ADDQ DX, h; \ - ANDQ g, AX; \ - XORQ CX, AX; \ - ADDQ h, AX - -// Calculate T2 in BX - uses BX, CX, DX and DI registers. -// T2 = BIGSIGMA0(a) + Maj(a, b, c) -// BIGSIGMA0(x) = ROTR(28,x) XOR ROTR(34,x) XOR ROTR(39,x) -// Maj(x, y, z) = (x AND y) XOR (x AND z) XOR (y AND z) -#define SHA512T2(a, b, c) \ - MOVQ a, DI; \ - MOVQ c, BX; \ - RORQ $28, DI; \ - MOVQ a, DX; \ - ANDQ b, BX; \ - RORQ $34, DX; \ - MOVQ a, CX; \ - ANDQ c, CX; \ - XORQ DX, DI; \ - XORQ CX, BX; \ - MOVQ a, DX; \ - MOVQ b, CX; \ - RORQ $39, DX; \ - ANDQ a, CX; \ - XORQ CX, BX; \ - XORQ DX, DI; \ - ADDQ DI, BX - -// Calculate T1 and T2, then e = d + T1 and a = T1 + T2. -// The values for e and a are stored in d and h, ready for rotation. -#define SHA512ROUND(index, const, a, b, c, d, e, f, g, h) \ - SHA512T1(const, e, f, g, h); \ - SHA512T2(a, b, c); \ - MOVQ BX, h; \ - ADDQ AX, d; \ - ADDQ AX, h - -#define SHA512ROUND0(index, const, a, b, c, d, e, f, g, h) \ - MSGSCHEDULE0(index); \ - SHA512ROUND(index, const, a, b, c, d, e, f, g, h) - -#define SHA512ROUND1(index, const, a, b, c, d, e, f, g, h) \ - MSGSCHEDULE1(index); \ - SHA512ROUND(index, const, a, b, c, d, e, f, g, h) - -TEXT ·block(SB),0,$648-32 - MOVQ p_base+8(FP), SI - MOVQ p_len+16(FP), DX - SHRQ $7, DX - SHLQ $7, DX - - LEAQ (SI)(DX*1), DI - MOVQ DI, 640(SP) - CMPQ SI, DI - JEQ end - - MOVQ dig+0(FP), BP - MOVQ (0*8)(BP), R8 // a = H0 - MOVQ (1*8)(BP), R9 // b = H1 - MOVQ (2*8)(BP), R10 // c = H2 - MOVQ (3*8)(BP), R11 // d = H3 - MOVQ (4*8)(BP), R12 // e = H4 - MOVQ (5*8)(BP), R13 // f = H5 - MOVQ (6*8)(BP), R14 // g = H6 - MOVQ (7*8)(BP), R15 // h = H7 - -loop: - MOVQ SP, BP // message schedule - - SHA512ROUND0(0, 0x428a2f98d728ae22, R8, R9, R10, R11, R12, R13, R14, R15) - SHA512ROUND0(1, 0x7137449123ef65cd, R15, R8, R9, R10, R11, R12, R13, R14) - SHA512ROUND0(2, 0xb5c0fbcfec4d3b2f, R14, R15, R8, R9, R10, R11, R12, R13) - SHA512ROUND0(3, 0xe9b5dba58189dbbc, R13, R14, R15, R8, R9, R10, R11, R12) - SHA512ROUND0(4, 0x3956c25bf348b538, R12, R13, R14, R15, R8, R9, R10, R11) - SHA512ROUND0(5, 0x59f111f1b605d019, R11, R12, R13, R14, R15, R8, R9, R10) - SHA512ROUND0(6, 0x923f82a4af194f9b, R10, R11, R12, R13, R14, R15, R8, R9) - SHA512ROUND0(7, 0xab1c5ed5da6d8118, R9, R10, R11, R12, R13, R14, R15, R8) - SHA512ROUND0(8, 0xd807aa98a3030242, R8, R9, R10, R11, R12, R13, R14, R15) - SHA512ROUND0(9, 0x12835b0145706fbe, R15, R8, R9, R10, R11, R12, R13, R14) - SHA512ROUND0(10, 0x243185be4ee4b28c, R14, R15, R8, R9, R10, R11, R12, R13) - SHA512ROUND0(11, 0x550c7dc3d5ffb4e2, R13, R14, R15, R8, R9, R10, R11, R12) - SHA512ROUND0(12, 0x72be5d74f27b896f, R12, R13, R14, R15, R8, R9, R10, R11) - SHA512ROUND0(13, 0x80deb1fe3b1696b1, R11, R12, R13, R14, R15, R8, R9, R10) - SHA512ROUND0(14, 0x9bdc06a725c71235, R10, R11, R12, R13, R14, R15, R8, R9) - SHA512ROUND0(15, 0xc19bf174cf692694, R9, R10, R11, R12, R13, R14, R15, R8) - - SHA512ROUND1(16, 0xe49b69c19ef14ad2, R8, R9, R10, R11, R12, R13, R14, R15) - SHA512ROUND1(17, 0xefbe4786384f25e3, R15, R8, R9, R10, R11, R12, R13, R14) - SHA512ROUND1(18, 0x0fc19dc68b8cd5b5, R14, R15, R8, R9, R10, R11, R12, R13) - SHA512ROUND1(19, 0x240ca1cc77ac9c65, R13, R14, R15, R8, R9, R10, R11, R12) - SHA512ROUND1(20, 0x2de92c6f592b0275, R12, R13, R14, R15, R8, R9, R10, R11) - SHA512ROUND1(21, 0x4a7484aa6ea6e483, R11, R12, R13, R14, R15, R8, R9, R10) - SHA512ROUND1(22, 0x5cb0a9dcbd41fbd4, R10, R11, R12, R13, R14, R15, R8, R9) - SHA512ROUND1(23, 0x76f988da831153b5, R9, R10, R11, R12, R13, R14, R15, R8) - SHA512ROUND1(24, 0x983e5152ee66dfab, R8, R9, R10, R11, R12, R13, R14, R15) - SHA512ROUND1(25, 0xa831c66d2db43210, R15, R8, R9, R10, R11, R12, R13, R14) - SHA512ROUND1(26, 0xb00327c898fb213f, R14, R15, R8, R9, R10, R11, R12, R13) - SHA512ROUND1(27, 0xbf597fc7beef0ee4, R13, R14, R15, R8, R9, R10, R11, R12) - SHA512ROUND1(28, 0xc6e00bf33da88fc2, R12, R13, R14, R15, R8, R9, R10, R11) - SHA512ROUND1(29, 0xd5a79147930aa725, R11, R12, R13, R14, R15, R8, R9, R10) - SHA512ROUND1(30, 0x06ca6351e003826f, R10, R11, R12, R13, R14, R15, R8, R9) - SHA512ROUND1(31, 0x142929670a0e6e70, R9, R10, R11, R12, R13, R14, R15, R8) - SHA512ROUND1(32, 0x27b70a8546d22ffc, R8, R9, R10, R11, R12, R13, R14, R15) - SHA512ROUND1(33, 0x2e1b21385c26c926, R15, R8, R9, R10, R11, R12, R13, R14) - SHA512ROUND1(34, 0x4d2c6dfc5ac42aed, R14, R15, R8, R9, R10, R11, R12, R13) - SHA512ROUND1(35, 0x53380d139d95b3df, R13, R14, R15, R8, R9, R10, R11, R12) - SHA512ROUND1(36, 0x650a73548baf63de, R12, R13, R14, R15, R8, R9, R10, R11) - SHA512ROUND1(37, 0x766a0abb3c77b2a8, R11, R12, R13, R14, R15, R8, R9, R10) - SHA512ROUND1(38, 0x81c2c92e47edaee6, R10, R11, R12, R13, R14, R15, R8, R9) - SHA512ROUND1(39, 0x92722c851482353b, R9, R10, R11, R12, R13, R14, R15, R8) - SHA512ROUND1(40, 0xa2bfe8a14cf10364, R8, R9, R10, R11, R12, R13, R14, R15) - SHA512ROUND1(41, 0xa81a664bbc423001, R15, R8, R9, R10, R11, R12, R13, R14) - SHA512ROUND1(42, 0xc24b8b70d0f89791, R14, R15, R8, R9, R10, R11, R12, R13) - SHA512ROUND1(43, 0xc76c51a30654be30, R13, R14, R15, R8, R9, R10, R11, R12) - SHA512ROUND1(44, 0xd192e819d6ef5218, R12, R13, R14, R15, R8, R9, R10, R11) - SHA512ROUND1(45, 0xd69906245565a910, R11, R12, R13, R14, R15, R8, R9, R10) - SHA512ROUND1(46, 0xf40e35855771202a, R10, R11, R12, R13, R14, R15, R8, R9) - SHA512ROUND1(47, 0x106aa07032bbd1b8, R9, R10, R11, R12, R13, R14, R15, R8) - SHA512ROUND1(48, 0x19a4c116b8d2d0c8, R8, R9, R10, R11, R12, R13, R14, R15) - SHA512ROUND1(49, 0x1e376c085141ab53, R15, R8, R9, R10, R11, R12, R13, R14) - SHA512ROUND1(50, 0x2748774cdf8eeb99, R14, R15, R8, R9, R10, R11, R12, R13) - SHA512ROUND1(51, 0x34b0bcb5e19b48a8, R13, R14, R15, R8, R9, R10, R11, R12) - SHA512ROUND1(52, 0x391c0cb3c5c95a63, R12, R13, R14, R15, R8, R9, R10, R11) - SHA512ROUND1(53, 0x4ed8aa4ae3418acb, R11, R12, R13, R14, R15, R8, R9, R10) - SHA512ROUND1(54, 0x5b9cca4f7763e373, R10, R11, R12, R13, R14, R15, R8, R9) - SHA512ROUND1(55, 0x682e6ff3d6b2b8a3, R9, R10, R11, R12, R13, R14, R15, R8) - SHA512ROUND1(56, 0x748f82ee5defb2fc, R8, R9, R10, R11, R12, R13, R14, R15) - SHA512ROUND1(57, 0x78a5636f43172f60, R15, R8, R9, R10, R11, R12, R13, R14) - SHA512ROUND1(58, 0x84c87814a1f0ab72, R14, R15, R8, R9, R10, R11, R12, R13) - SHA512ROUND1(59, 0x8cc702081a6439ec, R13, R14, R15, R8, R9, R10, R11, R12) - SHA512ROUND1(60, 0x90befffa23631e28, R12, R13, R14, R15, R8, R9, R10, R11) - SHA512ROUND1(61, 0xa4506cebde82bde9, R11, R12, R13, R14, R15, R8, R9, R10) - SHA512ROUND1(62, 0xbef9a3f7b2c67915, R10, R11, R12, R13, R14, R15, R8, R9) - SHA512ROUND1(63, 0xc67178f2e372532b, R9, R10, R11, R12, R13, R14, R15, R8) - SHA512ROUND1(64, 0xca273eceea26619c, R8, R9, R10, R11, R12, R13, R14, R15) - SHA512ROUND1(65, 0xd186b8c721c0c207, R15, R8, R9, R10, R11, R12, R13, R14) - SHA512ROUND1(66, 0xeada7dd6cde0eb1e, R14, R15, R8, R9, R10, R11, R12, R13) - SHA512ROUND1(67, 0xf57d4f7fee6ed178, R13, R14, R15, R8, R9, R10, R11, R12) - SHA512ROUND1(68, 0x06f067aa72176fba, R12, R13, R14, R15, R8, R9, R10, R11) - SHA512ROUND1(69, 0x0a637dc5a2c898a6, R11, R12, R13, R14, R15, R8, R9, R10) - SHA512ROUND1(70, 0x113f9804bef90dae, R10, R11, R12, R13, R14, R15, R8, R9) - SHA512ROUND1(71, 0x1b710b35131c471b, R9, R10, R11, R12, R13, R14, R15, R8) - SHA512ROUND1(72, 0x28db77f523047d84, R8, R9, R10, R11, R12, R13, R14, R15) - SHA512ROUND1(73, 0x32caab7b40c72493, R15, R8, R9, R10, R11, R12, R13, R14) - SHA512ROUND1(74, 0x3c9ebe0a15c9bebc, R14, R15, R8, R9, R10, R11, R12, R13) - SHA512ROUND1(75, 0x431d67c49c100d4c, R13, R14, R15, R8, R9, R10, R11, R12) - SHA512ROUND1(76, 0x4cc5d4becb3e42b6, R12, R13, R14, R15, R8, R9, R10, R11) - SHA512ROUND1(77, 0x597f299cfc657e2a, R11, R12, R13, R14, R15, R8, R9, R10) - SHA512ROUND1(78, 0x5fcb6fab3ad6faec, R10, R11, R12, R13, R14, R15, R8, R9) - SHA512ROUND1(79, 0x6c44198c4a475817, R9, R10, R11, R12, R13, R14, R15, R8) - - MOVQ dig+0(FP), BP - ADDQ (0*8)(BP), R8 // H0 = a + H0 - MOVQ R8, (0*8)(BP) - ADDQ (1*8)(BP), R9 // H1 = b + H1 - MOVQ R9, (1*8)(BP) - ADDQ (2*8)(BP), R10 // H2 = c + H2 - MOVQ R10, (2*8)(BP) - ADDQ (3*8)(BP), R11 // H3 = d + H3 - MOVQ R11, (3*8)(BP) - ADDQ (4*8)(BP), R12 // H4 = e + H4 - MOVQ R12, (4*8)(BP) - ADDQ (5*8)(BP), R13 // H5 = f + H5 - MOVQ R13, (5*8)(BP) - ADDQ (6*8)(BP), R14 // H6 = g + H6 - MOVQ R14, (6*8)(BP) - ADDQ (7*8)(BP), R15 // H7 = h + H7 - MOVQ R15, (7*8)(BP) - - ADDQ $128, SI - CMPQ SI, 640(SP) - JB loop - -end: - RET diff --git a/src/pkg/crypto/sha512/sha512block_decl.go b/src/pkg/crypto/sha512/sha512block_decl.go deleted file mode 100644 index bef99de2e..000000000 --- a/src/pkg/crypto/sha512/sha512block_decl.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build amd64 - -package sha512 - -//go:noescape - -func block(dig *digest, p []byte) diff --git a/src/pkg/crypto/subtle/constant_time.go b/src/pkg/crypto/subtle/constant_time.go deleted file mode 100644 index 6f80e7c58..000000000 --- a/src/pkg/crypto/subtle/constant_time.go +++ /dev/null @@ -1,73 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package subtle implements functions that are often useful in cryptographic -// code but require careful thought to use correctly. -package subtle - -// ConstantTimeCompare returns 1 iff the two slices, x -// and y, have equal contents. The time taken is a function of the length of -// the slices and is independent of the contents. -func ConstantTimeCompare(x, y []byte) int { - if len(x) != len(y) { - return 0 - } - - var v byte - - for i := 0; i < len(x); i++ { - v |= x[i] ^ y[i] - } - - return ConstantTimeByteEq(v, 0) -} - -// ConstantTimeSelect returns x if v is 1 and y if v is 0. -// Its behavior is undefined if v takes any other value. -func ConstantTimeSelect(v, x, y int) int { return ^(v-1)&x | (v-1)&y } - -// ConstantTimeByteEq returns 1 if x == y and 0 otherwise. -func ConstantTimeByteEq(x, y uint8) int { - z := ^(x ^ y) - z &= z >> 4 - z &= z >> 2 - z &= z >> 1 - - return int(z) -} - -// ConstantTimeEq returns 1 if x == y and 0 otherwise. -func ConstantTimeEq(x, y int32) int { - z := ^(x ^ y) - z &= z >> 16 - z &= z >> 8 - z &= z >> 4 - z &= z >> 2 - z &= z >> 1 - - return int(z & 1) -} - -// ConstantTimeCopy copies the contents of y into x (a slice of equal length) -// if v == 1. If v == 0, x is left unchanged. Its behavior is undefined if v -// takes any other value. -func ConstantTimeCopy(v int, x, y []byte) { - if len(x) != len(y) { - panic("subtle: slices have different lengths") - } - - xmask := byte(v - 1) - ymask := byte(^(v - 1)) - for i := 0; i < len(x); i++ { - x[i] = x[i]&xmask | y[i]&ymask - } -} - -// ConstantTimeLessOrEq returns 1 if x <= y and 0 otherwise. -// Its behavior is undefined if x or y are negative or > 2**31 - 1. -func ConstantTimeLessOrEq(x, y int) int { - x32 := int32(x) - y32 := int32(y) - return int(((x32 - y32 - 1) >> 31) & 1) -} diff --git a/src/pkg/crypto/subtle/constant_time_test.go b/src/pkg/crypto/subtle/constant_time_test.go deleted file mode 100644 index 619a45444..000000000 --- a/src/pkg/crypto/subtle/constant_time_test.go +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package subtle - -import ( - "testing" - "testing/quick" -) - -type TestConstantTimeCompareStruct struct { - a, b []byte - out int -} - -var testConstantTimeCompareData = []TestConstantTimeCompareStruct{ - {[]byte{}, []byte{}, 1}, - {[]byte{0x11}, []byte{0x11}, 1}, - {[]byte{0x12}, []byte{0x11}, 0}, - {[]byte{0x11}, []byte{0x11, 0x12}, 0}, - {[]byte{0x11, 0x12}, []byte{0x11}, 0}, -} - -func TestConstantTimeCompare(t *testing.T) { - for i, test := range testConstantTimeCompareData { - if r := ConstantTimeCompare(test.a, test.b); r != test.out { - t.Errorf("#%d bad result (got %x, want %x)", i, r, test.out) - } - } -} - -type TestConstantTimeByteEqStruct struct { - a, b uint8 - out int -} - -var testConstandTimeByteEqData = []TestConstantTimeByteEqStruct{ - {0, 0, 1}, - {0, 1, 0}, - {1, 0, 0}, - {0xff, 0xff, 1}, - {0xff, 0xfe, 0}, -} - -func byteEq(a, b uint8) int { - if a == b { - return 1 - } - return 0 -} - -func TestConstantTimeByteEq(t *testing.T) { - for i, test := range testConstandTimeByteEqData { - if r := ConstantTimeByteEq(test.a, test.b); r != test.out { - t.Errorf("#%d bad result (got %x, want %x)", i, r, test.out) - } - } - err := quick.CheckEqual(ConstantTimeByteEq, byteEq, nil) - if err != nil { - t.Error(err) - } -} - -func eq(a, b int32) int { - if a == b { - return 1 - } - return 0 -} - -func TestConstantTimeEq(t *testing.T) { - err := quick.CheckEqual(ConstantTimeEq, eq, nil) - if err != nil { - t.Error(err) - } -} - -func makeCopy(v int, x, y []byte) []byte { - if len(x) > len(y) { - x = x[0:len(y)] - } else { - y = y[0:len(x)] - } - if v == 1 { - copy(x, y) - } - return x -} - -func constantTimeCopyWrapper(v int, x, y []byte) []byte { - if len(x) > len(y) { - x = x[0:len(y)] - } else { - y = y[0:len(x)] - } - v &= 1 - ConstantTimeCopy(v, x, y) - return x -} - -func TestConstantTimeCopy(t *testing.T) { - err := quick.CheckEqual(constantTimeCopyWrapper, makeCopy, nil) - if err != nil { - t.Error(err) - } -} - -var lessOrEqTests = []struct { - x, y, result int -}{ - {0, 0, 1}, - {1, 0, 0}, - {0, 1, 1}, - {10, 20, 1}, - {20, 10, 0}, - {10, 10, 1}, -} - -func TestConstantTimeLessOrEq(t *testing.T) { - for i, test := range lessOrEqTests { - result := ConstantTimeLessOrEq(test.x, test.y) - if result != test.result { - t.Errorf("#%d: %d <= %d gave %d, expected %d", i, test.x, test.y, result, test.result) - } - } -} diff --git a/src/pkg/crypto/tls/alert.go b/src/pkg/crypto/tls/alert.go deleted file mode 100644 index 0856311e4..000000000 --- a/src/pkg/crypto/tls/alert.go +++ /dev/null @@ -1,77 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tls - -import "strconv" - -type alert uint8 - -const ( - // alert level - alertLevelWarning = 1 - alertLevelError = 2 -) - -const ( - alertCloseNotify alert = 0 - alertUnexpectedMessage alert = 10 - alertBadRecordMAC alert = 20 - alertDecryptionFailed alert = 21 - alertRecordOverflow alert = 22 - alertDecompressionFailure alert = 30 - alertHandshakeFailure alert = 40 - alertBadCertificate alert = 42 - alertUnsupportedCertificate alert = 43 - alertCertificateRevoked alert = 44 - alertCertificateExpired alert = 45 - alertCertificateUnknown alert = 46 - alertIllegalParameter alert = 47 - alertUnknownCA alert = 48 - alertAccessDenied alert = 49 - alertDecodeError alert = 50 - alertDecryptError alert = 51 - alertProtocolVersion alert = 70 - alertInsufficientSecurity alert = 71 - alertInternalError alert = 80 - alertUserCanceled alert = 90 - alertNoRenegotiation alert = 100 -) - -var alertText = map[alert]string{ - alertCloseNotify: "close notify", - alertUnexpectedMessage: "unexpected message", - alertBadRecordMAC: "bad record MAC", - alertDecryptionFailed: "decryption failed", - alertRecordOverflow: "record overflow", - alertDecompressionFailure: "decompression failure", - alertHandshakeFailure: "handshake failure", - alertBadCertificate: "bad certificate", - alertUnsupportedCertificate: "unsupported certificate", - alertCertificateRevoked: "revoked certificate", - alertCertificateExpired: "expired certificate", - alertCertificateUnknown: "unknown certificate", - alertIllegalParameter: "illegal parameter", - alertUnknownCA: "unknown certificate authority", - alertAccessDenied: "access denied", - alertDecodeError: "error decoding message", - alertDecryptError: "error decrypting message", - alertProtocolVersion: "protocol version not supported", - alertInsufficientSecurity: "insufficient security level", - alertInternalError: "internal error", - alertUserCanceled: "user canceled", - alertNoRenegotiation: "no renegotiation", -} - -func (e alert) String() string { - s, ok := alertText[e] - if ok { - return s - } - return "alert(" + strconv.Itoa(int(e)) + ")" -} - -func (e alert) Error() string { - return e.String() -} diff --git a/src/pkg/crypto/tls/cipher_suites.go b/src/pkg/crypto/tls/cipher_suites.go deleted file mode 100644 index 39a51459d..000000000 --- a/src/pkg/crypto/tls/cipher_suites.go +++ /dev/null @@ -1,270 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tls - -import ( - "crypto/aes" - "crypto/cipher" - "crypto/des" - "crypto/hmac" - "crypto/rc4" - "crypto/sha1" - "crypto/x509" - "hash" -) - -// a keyAgreement implements the client and server side of a TLS key agreement -// protocol by generating and processing key exchange messages. -type keyAgreement interface { - // On the server side, the first two methods are called in order. - - // In the case that the key agreement protocol doesn't use a - // ServerKeyExchange message, generateServerKeyExchange can return nil, - // nil. - generateServerKeyExchange(*Config, *Certificate, *clientHelloMsg, *serverHelloMsg) (*serverKeyExchangeMsg, error) - processClientKeyExchange(*Config, *Certificate, *clientKeyExchangeMsg, uint16) ([]byte, error) - - // On the client side, the next two methods are called in order. - - // This method may not be called if the server doesn't send a - // ServerKeyExchange message. - processServerKeyExchange(*Config, *clientHelloMsg, *serverHelloMsg, *x509.Certificate, *serverKeyExchangeMsg) error - generateClientKeyExchange(*Config, *clientHelloMsg, *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) -} - -const ( - // suiteECDH indicates that the cipher suite involves elliptic curve - // Diffie-Hellman. This means that it should only be selected when the - // client indicates that it supports ECC with a curve and point format - // that we're happy with. - suiteECDHE = 1 << iota - // suiteECDSA indicates that the cipher suite involves an ECDSA - // signature and therefore may only be selected when the server's - // certificate is ECDSA. If this is not set then the cipher suite is - // RSA based. - suiteECDSA - // suiteTLS12 indicates that the cipher suite should only be advertised - // and accepted when using TLS 1.2. - suiteTLS12 -) - -// A cipherSuite is a specific combination of key agreement, cipher and MAC -// function. All cipher suites currently assume RSA key agreement. -type cipherSuite struct { - id uint16 - // the lengths, in bytes, of the key material needed for each component. - keyLen int - macLen int - ivLen int - ka func(version uint16) keyAgreement - // flags is a bitmask of the suite* values, above. - flags int - cipher func(key, iv []byte, isRead bool) interface{} - mac func(version uint16, macKey []byte) macFunction - aead func(key, fixedNonce []byte) cipher.AEAD -} - -var cipherSuites = []*cipherSuite{ - // Ciphersuite order is chosen so that ECDHE comes before plain RSA - // and RC4 comes before AES (because of the Lucky13 attack). - {TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, ecdheRSAKA, suiteECDHE | suiteTLS12, nil, nil, aeadAESGCM}, - {TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256, 16, 0, 4, ecdheECDSAKA, suiteECDHE | suiteECDSA | suiteTLS12, nil, nil, aeadAESGCM}, - {TLS_ECDHE_RSA_WITH_RC4_128_SHA, 16, 20, 0, ecdheRSAKA, suiteECDHE, cipherRC4, macSHA1, nil}, - {TLS_ECDHE_ECDSA_WITH_RC4_128_SHA, 16, 20, 0, ecdheECDSAKA, suiteECDHE | suiteECDSA, cipherRC4, macSHA1, nil}, - {TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA, 16, 20, 16, ecdheRSAKA, suiteECDHE, cipherAES, macSHA1, nil}, - {TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA, 16, 20, 16, ecdheECDSAKA, suiteECDHE | suiteECDSA, cipherAES, macSHA1, nil}, - {TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, 32, 20, 16, ecdheRSAKA, suiteECDHE, cipherAES, macSHA1, nil}, - {TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, 32, 20, 16, ecdheECDSAKA, suiteECDHE | suiteECDSA, cipherAES, macSHA1, nil}, - {TLS_RSA_WITH_RC4_128_SHA, 16, 20, 0, rsaKA, 0, cipherRC4, macSHA1, nil}, - {TLS_RSA_WITH_AES_128_CBC_SHA, 16, 20, 16, rsaKA, 0, cipherAES, macSHA1, nil}, - {TLS_RSA_WITH_AES_256_CBC_SHA, 32, 20, 16, rsaKA, 0, cipherAES, macSHA1, nil}, - {TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, 8, ecdheRSAKA, suiteECDHE, cipher3DES, macSHA1, nil}, - {TLS_RSA_WITH_3DES_EDE_CBC_SHA, 24, 20, 8, rsaKA, 0, cipher3DES, macSHA1, nil}, -} - -func cipherRC4(key, iv []byte, isRead bool) interface{} { - cipher, _ := rc4.NewCipher(key) - return cipher -} - -func cipher3DES(key, iv []byte, isRead bool) interface{} { - block, _ := des.NewTripleDESCipher(key) - if isRead { - return cipher.NewCBCDecrypter(block, iv) - } - return cipher.NewCBCEncrypter(block, iv) -} - -func cipherAES(key, iv []byte, isRead bool) interface{} { - block, _ := aes.NewCipher(key) - if isRead { - return cipher.NewCBCDecrypter(block, iv) - } - return cipher.NewCBCEncrypter(block, iv) -} - -// macSHA1 returns a macFunction for the given protocol version. -func macSHA1(version uint16, key []byte) macFunction { - if version == VersionSSL30 { - mac := ssl30MAC{ - h: sha1.New(), - key: make([]byte, len(key)), - } - copy(mac.key, key) - return mac - } - return tls10MAC{hmac.New(sha1.New, key)} -} - -type macFunction interface { - Size() int - MAC(digestBuf, seq, header, data []byte) []byte -} - -// fixedNonceAEAD wraps an AEAD and prefixes a fixed portion of the nonce to -// each call. -type fixedNonceAEAD struct { - // sealNonce and openNonce are buffers where the larger nonce will be - // constructed. Since a seal and open operation may be running - // concurrently, there is a separate buffer for each. - sealNonce, openNonce []byte - aead cipher.AEAD -} - -func (f *fixedNonceAEAD) NonceSize() int { return 8 } -func (f *fixedNonceAEAD) Overhead() int { return f.aead.Overhead() } - -func (f *fixedNonceAEAD) Seal(out, nonce, plaintext, additionalData []byte) []byte { - copy(f.sealNonce[len(f.sealNonce)-8:], nonce) - return f.aead.Seal(out, f.sealNonce, plaintext, additionalData) -} - -func (f *fixedNonceAEAD) Open(out, nonce, plaintext, additionalData []byte) ([]byte, error) { - copy(f.openNonce[len(f.openNonce)-8:], nonce) - return f.aead.Open(out, f.openNonce, plaintext, additionalData) -} - -func aeadAESGCM(key, fixedNonce []byte) cipher.AEAD { - aes, err := aes.NewCipher(key) - if err != nil { - panic(err) - } - aead, err := cipher.NewGCM(aes) - if err != nil { - panic(err) - } - - nonce1, nonce2 := make([]byte, 12), make([]byte, 12) - copy(nonce1, fixedNonce) - copy(nonce2, fixedNonce) - - return &fixedNonceAEAD{nonce1, nonce2, aead} -} - -// ssl30MAC implements the SSLv3 MAC function, as defined in -// www.mozilla.org/projects/security/pki/nss/ssl/draft302.txt section 5.2.3.1 -type ssl30MAC struct { - h hash.Hash - key []byte -} - -func (s ssl30MAC) Size() int { - return s.h.Size() -} - -var ssl30Pad1 = [48]byte{0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36} - -var ssl30Pad2 = [48]byte{0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c} - -func (s ssl30MAC) MAC(digestBuf, seq, header, data []byte) []byte { - padLength := 48 - if s.h.Size() == 20 { - padLength = 40 - } - - s.h.Reset() - s.h.Write(s.key) - s.h.Write(ssl30Pad1[:padLength]) - s.h.Write(seq) - s.h.Write(header[:1]) - s.h.Write(header[3:5]) - s.h.Write(data) - digestBuf = s.h.Sum(digestBuf[:0]) - - s.h.Reset() - s.h.Write(s.key) - s.h.Write(ssl30Pad2[:padLength]) - s.h.Write(digestBuf) - return s.h.Sum(digestBuf[:0]) -} - -// tls10MAC implements the TLS 1.0 MAC function. RFC 2246, section 6.2.3. -type tls10MAC struct { - h hash.Hash -} - -func (s tls10MAC) Size() int { - return s.h.Size() -} - -func (s tls10MAC) MAC(digestBuf, seq, header, data []byte) []byte { - s.h.Reset() - s.h.Write(seq) - s.h.Write(header) - s.h.Write(data) - return s.h.Sum(digestBuf[:0]) -} - -func rsaKA(version uint16) keyAgreement { - return rsaKeyAgreement{} -} - -func ecdheECDSAKA(version uint16) keyAgreement { - return &ecdheKeyAgreement{ - sigType: signatureECDSA, - version: version, - } -} - -func ecdheRSAKA(version uint16) keyAgreement { - return &ecdheKeyAgreement{ - sigType: signatureRSA, - version: version, - } -} - -// mutualCipherSuite returns a cipherSuite given a list of supported -// ciphersuites and the id requested by the peer. -func mutualCipherSuite(have []uint16, want uint16) *cipherSuite { - for _, id := range have { - if id == want { - for _, suite := range cipherSuites { - if suite.id == want { - return suite - } - } - return nil - } - } - return nil -} - -// A list of the possible cipher suite ids. Taken from -// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml -const ( - TLS_RSA_WITH_RC4_128_SHA uint16 = 0x0005 - TLS_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0x000a - TLS_RSA_WITH_AES_128_CBC_SHA uint16 = 0x002f - TLS_RSA_WITH_AES_256_CBC_SHA uint16 = 0x0035 - TLS_ECDHE_ECDSA_WITH_RC4_128_SHA uint16 = 0xc007 - TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA uint16 = 0xc009 - TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA uint16 = 0xc00a - TLS_ECDHE_RSA_WITH_RC4_128_SHA uint16 = 0xc011 - TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA uint16 = 0xc012 - TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA uint16 = 0xc013 - TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA uint16 = 0xc014 - TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 uint16 = 0xc02f - TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 uint16 = 0xc02b -) diff --git a/src/pkg/crypto/tls/common.go b/src/pkg/crypto/tls/common.go deleted file mode 100644 index 776b70c93..000000000 --- a/src/pkg/crypto/tls/common.go +++ /dev/null @@ -1,621 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tls - -import ( - "container/list" - "crypto" - "crypto/rand" - "crypto/x509" - "fmt" - "io" - "math/big" - "strings" - "sync" - "time" -) - -const ( - VersionSSL30 = 0x0300 - VersionTLS10 = 0x0301 - VersionTLS11 = 0x0302 - VersionTLS12 = 0x0303 -) - -const ( - maxPlaintext = 16384 // maximum plaintext payload length - maxCiphertext = 16384 + 2048 // maximum ciphertext payload length - recordHeaderLen = 5 // record header length - maxHandshake = 65536 // maximum handshake we support (protocol max is 16 MB) - - minVersion = VersionSSL30 - maxVersion = VersionTLS12 -) - -// TLS record types. -type recordType uint8 - -const ( - recordTypeChangeCipherSpec recordType = 20 - recordTypeAlert recordType = 21 - recordTypeHandshake recordType = 22 - recordTypeApplicationData recordType = 23 -) - -// TLS handshake message types. -const ( - typeClientHello uint8 = 1 - typeServerHello uint8 = 2 - typeNewSessionTicket uint8 = 4 - typeCertificate uint8 = 11 - typeServerKeyExchange uint8 = 12 - typeCertificateRequest uint8 = 13 - typeServerHelloDone uint8 = 14 - typeCertificateVerify uint8 = 15 - typeClientKeyExchange uint8 = 16 - typeFinished uint8 = 20 - typeCertificateStatus uint8 = 22 - typeNextProtocol uint8 = 67 // Not IANA assigned -) - -// TLS compression types. -const ( - compressionNone uint8 = 0 -) - -// TLS extension numbers -const ( - extensionServerName uint16 = 0 - extensionStatusRequest uint16 = 5 - extensionSupportedCurves uint16 = 10 - extensionSupportedPoints uint16 = 11 - extensionSignatureAlgorithms uint16 = 13 - extensionALPN uint16 = 16 - extensionSessionTicket uint16 = 35 - extensionNextProtoNeg uint16 = 13172 // not IANA assigned - extensionRenegotiationInfo uint16 = 0xff01 -) - -// TLS signaling cipher suite values -const ( - scsvRenegotiation uint16 = 0x00ff -) - -// CurveID is the type of a TLS identifier for an elliptic curve. See -// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8 -type CurveID uint16 - -const ( - CurveP256 CurveID = 23 - CurveP384 CurveID = 24 - CurveP521 CurveID = 25 -) - -// TLS Elliptic Curve Point Formats -// http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-9 -const ( - pointFormatUncompressed uint8 = 0 -) - -// TLS CertificateStatusType (RFC 3546) -const ( - statusTypeOCSP uint8 = 1 -) - -// Certificate types (for certificateRequestMsg) -const ( - certTypeRSASign = 1 // A certificate containing an RSA key - certTypeDSSSign = 2 // A certificate containing a DSA key - certTypeRSAFixedDH = 3 // A certificate containing a static DH key - certTypeDSSFixedDH = 4 // A certificate containing a static DH key - - // See RFC4492 sections 3 and 5.5. - certTypeECDSASign = 64 // A certificate containing an ECDSA-capable public key, signed with ECDSA. - certTypeRSAFixedECDH = 65 // A certificate containing an ECDH-capable public key, signed with RSA. - certTypeECDSAFixedECDH = 66 // A certificate containing an ECDH-capable public key, signed with ECDSA. - - // Rest of these are reserved by the TLS spec -) - -// Hash functions for TLS 1.2 (See RFC 5246, section A.4.1) -const ( - hashSHA1 uint8 = 2 - hashSHA256 uint8 = 4 -) - -// Signature algorithms for TLS 1.2 (See RFC 5246, section A.4.1) -const ( - signatureRSA uint8 = 1 - signatureECDSA uint8 = 3 -) - -// signatureAndHash mirrors the TLS 1.2, SignatureAndHashAlgorithm struct. See -// RFC 5246, section A.4.1. -type signatureAndHash struct { - hash, signature uint8 -} - -// supportedSKXSignatureAlgorithms contains the signature and hash algorithms -// that the code advertises as supported in a TLS 1.2 ClientHello. -var supportedSKXSignatureAlgorithms = []signatureAndHash{ - {hashSHA256, signatureRSA}, - {hashSHA256, signatureECDSA}, - {hashSHA1, signatureRSA}, - {hashSHA1, signatureECDSA}, -} - -// supportedClientCertSignatureAlgorithms contains the signature and hash -// algorithms that the code advertises as supported in a TLS 1.2 -// CertificateRequest. -var supportedClientCertSignatureAlgorithms = []signatureAndHash{ - {hashSHA256, signatureRSA}, - {hashSHA256, signatureECDSA}, -} - -// ConnectionState records basic TLS details about the connection. -type ConnectionState struct { - Version uint16 // TLS version used by the connection (e.g. VersionTLS12) - HandshakeComplete bool // TLS handshake is complete - DidResume bool // connection resumes a previous TLS connection - CipherSuite uint16 // cipher suite in use (TLS_RSA_WITH_RC4_128_SHA, ...) - NegotiatedProtocol string // negotiated next protocol (from Config.NextProtos) - NegotiatedProtocolIsMutual bool // negotiated protocol was advertised by server - ServerName string // server name requested by client, if any (server side only) - PeerCertificates []*x509.Certificate // certificate chain presented by remote peer - VerifiedChains [][]*x509.Certificate // verified chains built from PeerCertificates - - // TLSUnique contains the "tls-unique" channel binding value (see RFC - // 5929, section 3). For resumed sessions this value will be nil - // because resumption does not include enough context (see - // https://secure-resumption.com/#channelbindings). This will change in - // future versions of Go once the TLS master-secret fix has been - // standardized and implemented. - TLSUnique []byte -} - -// ClientAuthType declares the policy the server will follow for -// TLS Client Authentication. -type ClientAuthType int - -const ( - NoClientCert ClientAuthType = iota - RequestClientCert - RequireAnyClientCert - VerifyClientCertIfGiven - RequireAndVerifyClientCert -) - -// ClientSessionState contains the state needed by clients to resume TLS -// sessions. -type ClientSessionState struct { - sessionTicket []uint8 // Encrypted ticket used for session resumption with server - vers uint16 // SSL/TLS version negotiated for the session - cipherSuite uint16 // Ciphersuite negotiated for the session - masterSecret []byte // MasterSecret generated by client on a full handshake - serverCertificates []*x509.Certificate // Certificate chain presented by the server -} - -// ClientSessionCache is a cache of ClientSessionState objects that can be used -// by a client to resume a TLS session with a given server. ClientSessionCache -// implementations should expect to be called concurrently from different -// goroutines. -type ClientSessionCache interface { - // Get searches for a ClientSessionState associated with the given key. - // On return, ok is true if one was found. - Get(sessionKey string) (session *ClientSessionState, ok bool) - - // Put adds the ClientSessionState to the cache with the given key. - Put(sessionKey string, cs *ClientSessionState) -} - -// ClientHelloInfo contains information from a ClientHello message in order to -// guide certificate selection in the GetCertificate callback. -type ClientHelloInfo struct { - // CipherSuites lists the CipherSuites supported by the client (e.g. - // TLS_RSA_WITH_RC4_128_SHA). - CipherSuites []uint16 - - // ServerName indicates the name of the server requested by the client - // in order to support virtual hosting. ServerName is only set if the - // client is using SNI (see - // http://tools.ietf.org/html/rfc4366#section-3.1). - ServerName string - - // SupportedCurves lists the elliptic curves supported by the client. - // SupportedCurves is set only if the Supported Elliptic Curves - // Extension is being used (see - // http://tools.ietf.org/html/rfc4492#section-5.1.1). - SupportedCurves []CurveID - - // SupportedPoints lists the point formats supported by the client. - // SupportedPoints is set only if the Supported Point Formats Extension - // is being used (see - // http://tools.ietf.org/html/rfc4492#section-5.1.2). - SupportedPoints []uint8 -} - -// A Config structure is used to configure a TLS client or server. -// After one has been passed to a TLS function it must not be -// modified. A Config may be reused; the tls package will also not -// modify it. -type Config struct { - // Rand provides the source of entropy for nonces and RSA blinding. - // If Rand is nil, TLS uses the cryptographic random reader in package - // crypto/rand. - // The Reader must be safe for use by multiple goroutines. - Rand io.Reader - - // Time returns the current time as the number of seconds since the epoch. - // If Time is nil, TLS uses time.Now. - Time func() time.Time - - // Certificates contains one or more certificate chains - // to present to the other side of the connection. - // Server configurations must include at least one certificate. - Certificates []Certificate - - // NameToCertificate maps from a certificate name to an element of - // Certificates. Note that a certificate name can be of the form - // '*.example.com' and so doesn't have to be a domain name as such. - // See Config.BuildNameToCertificate - // The nil value causes the first element of Certificates to be used - // for all connections. - NameToCertificate map[string]*Certificate - - // GetCertificate returns a Certificate based on the given - // ClientHelloInfo. If GetCertificate is nil or returns nil, then the - // certificate is retrieved from NameToCertificate. If - // NameToCertificate is nil, the first element of Certificates will be - // used. - GetCertificate func(clientHello *ClientHelloInfo) (*Certificate, error) - - // RootCAs defines the set of root certificate authorities - // that clients use when verifying server certificates. - // If RootCAs is nil, TLS uses the host's root CA set. - RootCAs *x509.CertPool - - // NextProtos is a list of supported, application level protocols. - NextProtos []string - - // ServerName is used to verify the hostname on the returned - // certificates unless InsecureSkipVerify is given. It is also included - // in the client's handshake to support virtual hosting. - ServerName string - - // ClientAuth determines the server's policy for - // TLS Client Authentication. The default is NoClientCert. - ClientAuth ClientAuthType - - // ClientCAs defines the set of root certificate authorities - // that servers use if required to verify a client certificate - // by the policy in ClientAuth. - ClientCAs *x509.CertPool - - // InsecureSkipVerify controls whether a client verifies the - // server's certificate chain and host name. - // If InsecureSkipVerify is true, TLS accepts any certificate - // presented by the server and any host name in that certificate. - // In this mode, TLS is susceptible to man-in-the-middle attacks. - // This should be used only for testing. - InsecureSkipVerify bool - - // CipherSuites is a list of supported cipher suites. If CipherSuites - // is nil, TLS uses a list of suites supported by the implementation. - CipherSuites []uint16 - - // PreferServerCipherSuites controls whether the server selects the - // client's most preferred ciphersuite, or the server's most preferred - // ciphersuite. If true then the server's preference, as expressed in - // the order of elements in CipherSuites, is used. - PreferServerCipherSuites bool - - // SessionTicketsDisabled may be set to true to disable session ticket - // (resumption) support. - SessionTicketsDisabled bool - - // SessionTicketKey is used by TLS servers to provide session - // resumption. See RFC 5077. If zero, it will be filled with - // random data before the first server handshake. - // - // If multiple servers are terminating connections for the same host - // they should all have the same SessionTicketKey. If the - // SessionTicketKey leaks, previously recorded and future TLS - // connections using that key are compromised. - SessionTicketKey [32]byte - - // SessionCache is a cache of ClientSessionState entries for TLS session - // resumption. - ClientSessionCache ClientSessionCache - - // MinVersion contains the minimum SSL/TLS version that is acceptable. - // If zero, then SSLv3 is taken as the minimum. - MinVersion uint16 - - // MaxVersion contains the maximum SSL/TLS version that is acceptable. - // If zero, then the maximum version supported by this package is used, - // which is currently TLS 1.2. - MaxVersion uint16 - - // CurvePreferences contains the elliptic curves that will be used in - // an ECDHE handshake, in preference order. If empty, the default will - // be used. - CurvePreferences []CurveID - - serverInitOnce sync.Once // guards calling (*Config).serverInit -} - -func (c *Config) serverInit() { - if c.SessionTicketsDisabled { - return - } - - // If the key has already been set then we have nothing to do. - for _, b := range c.SessionTicketKey { - if b != 0 { - return - } - } - - if _, err := io.ReadFull(c.rand(), c.SessionTicketKey[:]); err != nil { - c.SessionTicketsDisabled = true - } -} - -func (c *Config) rand() io.Reader { - r := c.Rand - if r == nil { - return rand.Reader - } - return r -} - -func (c *Config) time() time.Time { - t := c.Time - if t == nil { - t = time.Now - } - return t() -} - -func (c *Config) cipherSuites() []uint16 { - s := c.CipherSuites - if s == nil { - s = defaultCipherSuites() - } - return s -} - -func (c *Config) minVersion() uint16 { - if c == nil || c.MinVersion == 0 { - return minVersion - } - return c.MinVersion -} - -func (c *Config) maxVersion() uint16 { - if c == nil || c.MaxVersion == 0 { - return maxVersion - } - return c.MaxVersion -} - -var defaultCurvePreferences = []CurveID{CurveP256, CurveP384, CurveP521} - -func (c *Config) curvePreferences() []CurveID { - if c == nil || len(c.CurvePreferences) == 0 { - return defaultCurvePreferences - } - return c.CurvePreferences -} - -// mutualVersion returns the protocol version to use given the advertised -// version of the peer. -func (c *Config) mutualVersion(vers uint16) (uint16, bool) { - minVersion := c.minVersion() - maxVersion := c.maxVersion() - - if vers < minVersion { - return 0, false - } - if vers > maxVersion { - vers = maxVersion - } - return vers, true -} - -// getCertificate returns the best certificate for the given ClientHelloInfo, -// defaulting to the first element of c.Certificates. -func (c *Config) getCertificate(clientHello *ClientHelloInfo) (*Certificate, error) { - if c.GetCertificate != nil { - cert, err := c.GetCertificate(clientHello) - if cert != nil || err != nil { - return cert, err - } - } - - if len(c.Certificates) == 1 || c.NameToCertificate == nil { - // There's only one choice, so no point doing any work. - return &c.Certificates[0], nil - } - - name := strings.ToLower(clientHello.ServerName) - for len(name) > 0 && name[len(name)-1] == '.' { - name = name[:len(name)-1] - } - - if cert, ok := c.NameToCertificate[name]; ok { - return cert, nil - } - - // try replacing labels in the name with wildcards until we get a - // match. - labels := strings.Split(name, ".") - for i := range labels { - labels[i] = "*" - candidate := strings.Join(labels, ".") - if cert, ok := c.NameToCertificate[candidate]; ok { - return cert, nil - } - } - - // If nothing matches, return the first certificate. - return &c.Certificates[0], nil -} - -// BuildNameToCertificate parses c.Certificates and builds c.NameToCertificate -// from the CommonName and SubjectAlternateName fields of each of the leaf -// certificates. -func (c *Config) BuildNameToCertificate() { - c.NameToCertificate = make(map[string]*Certificate) - for i := range c.Certificates { - cert := &c.Certificates[i] - x509Cert, err := x509.ParseCertificate(cert.Certificate[0]) - if err != nil { - continue - } - if len(x509Cert.Subject.CommonName) > 0 { - c.NameToCertificate[x509Cert.Subject.CommonName] = cert - } - for _, san := range x509Cert.DNSNames { - c.NameToCertificate[san] = cert - } - } -} - -// A Certificate is a chain of one or more certificates, leaf first. -type Certificate struct { - Certificate [][]byte - // PrivateKey contains the private key corresponding to the public key - // in Leaf. For a server, this must be a *rsa.PrivateKey or - // *ecdsa.PrivateKey. For a client doing client authentication, this - // can be any type that implements crypto.Signer (which includes RSA - // and ECDSA private keys). - PrivateKey crypto.PrivateKey - // OCSPStaple contains an optional OCSP response which will be served - // to clients that request it. - OCSPStaple []byte - // Leaf is the parsed form of the leaf certificate, which may be - // initialized using x509.ParseCertificate to reduce per-handshake - // processing for TLS clients doing client authentication. If nil, the - // leaf certificate will be parsed as needed. - Leaf *x509.Certificate -} - -// A TLS record. -type record struct { - contentType recordType - major, minor uint8 - payload []byte -} - -type handshakeMessage interface { - marshal() []byte - unmarshal([]byte) bool -} - -// lruSessionCache is a ClientSessionCache implementation that uses an LRU -// caching strategy. -type lruSessionCache struct { - sync.Mutex - - m map[string]*list.Element - q *list.List - capacity int -} - -type lruSessionCacheEntry struct { - sessionKey string - state *ClientSessionState -} - -// NewLRUClientSessionCache returns a ClientSessionCache with the given -// capacity that uses an LRU strategy. If capacity is < 1, a default capacity -// is used instead. -func NewLRUClientSessionCache(capacity int) ClientSessionCache { - const defaultSessionCacheCapacity = 64 - - if capacity < 1 { - capacity = defaultSessionCacheCapacity - } - return &lruSessionCache{ - m: make(map[string]*list.Element), - q: list.New(), - capacity: capacity, - } -} - -// Put adds the provided (sessionKey, cs) pair to the cache. -func (c *lruSessionCache) Put(sessionKey string, cs *ClientSessionState) { - c.Lock() - defer c.Unlock() - - if elem, ok := c.m[sessionKey]; ok { - entry := elem.Value.(*lruSessionCacheEntry) - entry.state = cs - c.q.MoveToFront(elem) - return - } - - if c.q.Len() < c.capacity { - entry := &lruSessionCacheEntry{sessionKey, cs} - c.m[sessionKey] = c.q.PushFront(entry) - return - } - - elem := c.q.Back() - entry := elem.Value.(*lruSessionCacheEntry) - delete(c.m, entry.sessionKey) - entry.sessionKey = sessionKey - entry.state = cs - c.q.MoveToFront(elem) - c.m[sessionKey] = elem -} - -// Get returns the ClientSessionState value associated with a given key. It -// returns (nil, false) if no value is found. -func (c *lruSessionCache) Get(sessionKey string) (*ClientSessionState, bool) { - c.Lock() - defer c.Unlock() - - if elem, ok := c.m[sessionKey]; ok { - c.q.MoveToFront(elem) - return elem.Value.(*lruSessionCacheEntry).state, true - } - return nil, false -} - -// TODO(jsing): Make these available to both crypto/x509 and crypto/tls. -type dsaSignature struct { - R, S *big.Int -} - -type ecdsaSignature dsaSignature - -var emptyConfig Config - -func defaultConfig() *Config { - return &emptyConfig -} - -var ( - once sync.Once - varDefaultCipherSuites []uint16 -) - -func defaultCipherSuites() []uint16 { - once.Do(initDefaultCipherSuites) - return varDefaultCipherSuites -} - -func initDefaultCipherSuites() { - varDefaultCipherSuites = make([]uint16, len(cipherSuites)) - for i, suite := range cipherSuites { - varDefaultCipherSuites[i] = suite.id - } -} - -func unexpectedMessageError(wanted, got interface{}) error { - return fmt.Errorf("tls: received unexpected handshake message of type %T when waiting for %T", got, wanted) -} diff --git a/src/pkg/crypto/tls/conn.go b/src/pkg/crypto/tls/conn.go deleted file mode 100644 index ba8e4c22b..000000000 --- a/src/pkg/crypto/tls/conn.go +++ /dev/null @@ -1,1030 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// TLS low level connection and record layer - -package tls - -import ( - "bytes" - "crypto/cipher" - "crypto/subtle" - "crypto/x509" - "errors" - "fmt" - "io" - "net" - "sync" - "time" -) - -// A Conn represents a secured connection. -// It implements the net.Conn interface. -type Conn struct { - // constant - conn net.Conn - isClient bool - - // constant after handshake; protected by handshakeMutex - handshakeMutex sync.Mutex // handshakeMutex < in.Mutex, out.Mutex, errMutex - handshakeErr error // error resulting from handshake - vers uint16 // TLS version - haveVers bool // version has been negotiated - config *Config // configuration passed to constructor - handshakeComplete bool - didResume bool // whether this connection was a session resumption - cipherSuite uint16 - ocspResponse []byte // stapled OCSP response - peerCertificates []*x509.Certificate - // verifiedChains contains the certificate chains that we built, as - // opposed to the ones presented by the server. - verifiedChains [][]*x509.Certificate - // serverName contains the server name indicated by the client, if any. - serverName string - // firstFinished contains the first Finished hash sent during the - // handshake. This is the "tls-unique" channel binding value. - firstFinished [12]byte - - clientProtocol string - clientProtocolFallback bool - - // input/output - in, out halfConn // in.Mutex < out.Mutex - rawInput *block // raw input, right off the wire - input *block // application data waiting to be read - hand bytes.Buffer // handshake data waiting to be read - - tmp [16]byte -} - -// Access to net.Conn methods. -// Cannot just embed net.Conn because that would -// export the struct field too. - -// LocalAddr returns the local network address. -func (c *Conn) LocalAddr() net.Addr { - return c.conn.LocalAddr() -} - -// RemoteAddr returns the remote network address. -func (c *Conn) RemoteAddr() net.Addr { - return c.conn.RemoteAddr() -} - -// SetDeadline sets the read and write deadlines associated with the connection. -// A zero value for t means Read and Write will not time out. -// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error. -func (c *Conn) SetDeadline(t time.Time) error { - return c.conn.SetDeadline(t) -} - -// SetReadDeadline sets the read deadline on the underlying connection. -// A zero value for t means Read will not time out. -func (c *Conn) SetReadDeadline(t time.Time) error { - return c.conn.SetReadDeadline(t) -} - -// SetWriteDeadline sets the write deadline on the underlying connection. -// A zero value for t means Write will not time out. -// After a Write has timed out, the TLS state is corrupt and all future writes will return the same error. -func (c *Conn) SetWriteDeadline(t time.Time) error { - return c.conn.SetWriteDeadline(t) -} - -// A halfConn represents one direction of the record layer -// connection, either sending or receiving. -type halfConn struct { - sync.Mutex - - err error // first permanent error - version uint16 // protocol version - cipher interface{} // cipher algorithm - mac macFunction - seq [8]byte // 64-bit sequence number - bfree *block // list of free blocks - - nextCipher interface{} // next encryption state - nextMac macFunction // next MAC algorithm - - // used to save allocating a new buffer for each MAC. - inDigestBuf, outDigestBuf []byte -} - -func (hc *halfConn) setErrorLocked(err error) error { - hc.err = err - return err -} - -func (hc *halfConn) error() error { - hc.Lock() - err := hc.err - hc.Unlock() - return err -} - -// prepareCipherSpec sets the encryption and MAC states -// that a subsequent changeCipherSpec will use. -func (hc *halfConn) prepareCipherSpec(version uint16, cipher interface{}, mac macFunction) { - hc.version = version - hc.nextCipher = cipher - hc.nextMac = mac -} - -// changeCipherSpec changes the encryption and MAC states -// to the ones previously passed to prepareCipherSpec. -func (hc *halfConn) changeCipherSpec() error { - if hc.nextCipher == nil { - return alertInternalError - } - hc.cipher = hc.nextCipher - hc.mac = hc.nextMac - hc.nextCipher = nil - hc.nextMac = nil - for i := range hc.seq { - hc.seq[i] = 0 - } - return nil -} - -// incSeq increments the sequence number. -func (hc *halfConn) incSeq() { - for i := 7; i >= 0; i-- { - hc.seq[i]++ - if hc.seq[i] != 0 { - return - } - } - - // Not allowed to let sequence number wrap. - // Instead, must renegotiate before it does. - // Not likely enough to bother. - panic("TLS: sequence number wraparound") -} - -// resetSeq resets the sequence number to zero. -func (hc *halfConn) resetSeq() { - for i := range hc.seq { - hc.seq[i] = 0 - } -} - -// removePadding returns an unpadded slice, in constant time, which is a prefix -// of the input. It also returns a byte which is equal to 255 if the padding -// was valid and 0 otherwise. See RFC 2246, section 6.2.3.2 -func removePadding(payload []byte) ([]byte, byte) { - if len(payload) < 1 { - return payload, 0 - } - - paddingLen := payload[len(payload)-1] - t := uint(len(payload)-1) - uint(paddingLen) - // if len(payload) >= (paddingLen - 1) then the MSB of t is zero - good := byte(int32(^t) >> 31) - - toCheck := 255 // the maximum possible padding length - // The length of the padded data is public, so we can use an if here - if toCheck+1 > len(payload) { - toCheck = len(payload) - 1 - } - - for i := 0; i < toCheck; i++ { - t := uint(paddingLen) - uint(i) - // if i <= paddingLen then the MSB of t is zero - mask := byte(int32(^t) >> 31) - b := payload[len(payload)-1-i] - good &^= mask&paddingLen ^ mask&b - } - - // We AND together the bits of good and replicate the result across - // all the bits. - good &= good << 4 - good &= good << 2 - good &= good << 1 - good = uint8(int8(good) >> 7) - - toRemove := good&paddingLen + 1 - return payload[:len(payload)-int(toRemove)], good -} - -// removePaddingSSL30 is a replacement for removePadding in the case that the -// protocol version is SSLv3. In this version, the contents of the padding -// are random and cannot be checked. -func removePaddingSSL30(payload []byte) ([]byte, byte) { - if len(payload) < 1 { - return payload, 0 - } - - paddingLen := int(payload[len(payload)-1]) + 1 - if paddingLen > len(payload) { - return payload, 0 - } - - return payload[:len(payload)-paddingLen], 255 -} - -func roundUp(a, b int) int { - return a + (b-a%b)%b -} - -// cbcMode is an interface for block ciphers using cipher block chaining. -type cbcMode interface { - cipher.BlockMode - SetIV([]byte) -} - -// decrypt checks and strips the mac and decrypts the data in b. Returns a -// success boolean, the number of bytes to skip from the start of the record in -// order to get the application payload, and an optional alert value. -func (hc *halfConn) decrypt(b *block) (ok bool, prefixLen int, alertValue alert) { - // pull out payload - payload := b.data[recordHeaderLen:] - - macSize := 0 - if hc.mac != nil { - macSize = hc.mac.Size() - } - - paddingGood := byte(255) - explicitIVLen := 0 - - // decrypt - if hc.cipher != nil { - switch c := hc.cipher.(type) { - case cipher.Stream: - c.XORKeyStream(payload, payload) - case cipher.AEAD: - explicitIVLen = 8 - if len(payload) < explicitIVLen { - return false, 0, alertBadRecordMAC - } - nonce := payload[:8] - payload = payload[8:] - - var additionalData [13]byte - copy(additionalData[:], hc.seq[:]) - copy(additionalData[8:], b.data[:3]) - n := len(payload) - c.Overhead() - additionalData[11] = byte(n >> 8) - additionalData[12] = byte(n) - var err error - payload, err = c.Open(payload[:0], nonce, payload, additionalData[:]) - if err != nil { - return false, 0, alertBadRecordMAC - } - b.resize(recordHeaderLen + explicitIVLen + len(payload)) - case cbcMode: - blockSize := c.BlockSize() - if hc.version >= VersionTLS11 { - explicitIVLen = blockSize - } - - if len(payload)%blockSize != 0 || len(payload) < roundUp(explicitIVLen+macSize+1, blockSize) { - return false, 0, alertBadRecordMAC - } - - if explicitIVLen > 0 { - c.SetIV(payload[:explicitIVLen]) - payload = payload[explicitIVLen:] - } - c.CryptBlocks(payload, payload) - if hc.version == VersionSSL30 { - payload, paddingGood = removePaddingSSL30(payload) - } else { - payload, paddingGood = removePadding(payload) - } - b.resize(recordHeaderLen + explicitIVLen + len(payload)) - - // note that we still have a timing side-channel in the - // MAC check, below. An attacker can align the record - // so that a correct padding will cause one less hash - // block to be calculated. Then they can iteratively - // decrypt a record by breaking each byte. See - // "Password Interception in a SSL/TLS Channel", Brice - // Canvel et al. - // - // However, our behavior matches OpenSSL, so we leak - // only as much as they do. - default: - panic("unknown cipher type") - } - } - - // check, strip mac - if hc.mac != nil { - if len(payload) < macSize { - return false, 0, alertBadRecordMAC - } - - // strip mac off payload, b.data - n := len(payload) - macSize - b.data[3] = byte(n >> 8) - b.data[4] = byte(n) - b.resize(recordHeaderLen + explicitIVLen + n) - remoteMAC := payload[n:] - localMAC := hc.mac.MAC(hc.inDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], payload[:n]) - - if subtle.ConstantTimeCompare(localMAC, remoteMAC) != 1 || paddingGood != 255 { - return false, 0, alertBadRecordMAC - } - hc.inDigestBuf = localMAC - } - hc.incSeq() - - return true, recordHeaderLen + explicitIVLen, 0 -} - -// padToBlockSize calculates the needed padding block, if any, for a payload. -// On exit, prefix aliases payload and extends to the end of the last full -// block of payload. finalBlock is a fresh slice which contains the contents of -// any suffix of payload as well as the needed padding to make finalBlock a -// full block. -func padToBlockSize(payload []byte, blockSize int) (prefix, finalBlock []byte) { - overrun := len(payload) % blockSize - paddingLen := blockSize - overrun - prefix = payload[:len(payload)-overrun] - finalBlock = make([]byte, blockSize) - copy(finalBlock, payload[len(payload)-overrun:]) - for i := overrun; i < blockSize; i++ { - finalBlock[i] = byte(paddingLen - 1) - } - return -} - -// encrypt encrypts and macs the data in b. -func (hc *halfConn) encrypt(b *block, explicitIVLen int) (bool, alert) { - // mac - if hc.mac != nil { - mac := hc.mac.MAC(hc.outDigestBuf, hc.seq[0:], b.data[:recordHeaderLen], b.data[recordHeaderLen+explicitIVLen:]) - - n := len(b.data) - b.resize(n + len(mac)) - copy(b.data[n:], mac) - hc.outDigestBuf = mac - } - - payload := b.data[recordHeaderLen:] - - // encrypt - if hc.cipher != nil { - switch c := hc.cipher.(type) { - case cipher.Stream: - c.XORKeyStream(payload, payload) - case cipher.AEAD: - payloadLen := len(b.data) - recordHeaderLen - explicitIVLen - b.resize(len(b.data) + c.Overhead()) - nonce := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen] - payload := b.data[recordHeaderLen+explicitIVLen:] - payload = payload[:payloadLen] - - var additionalData [13]byte - copy(additionalData[:], hc.seq[:]) - copy(additionalData[8:], b.data[:3]) - additionalData[11] = byte(payloadLen >> 8) - additionalData[12] = byte(payloadLen) - - c.Seal(payload[:0], nonce, payload, additionalData[:]) - case cbcMode: - blockSize := c.BlockSize() - if explicitIVLen > 0 { - c.SetIV(payload[:explicitIVLen]) - payload = payload[explicitIVLen:] - } - prefix, finalBlock := padToBlockSize(payload, blockSize) - b.resize(recordHeaderLen + explicitIVLen + len(prefix) + len(finalBlock)) - c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen:], prefix) - c.CryptBlocks(b.data[recordHeaderLen+explicitIVLen+len(prefix):], finalBlock) - default: - panic("unknown cipher type") - } - } - - // update length to include MAC and any block padding needed. - n := len(b.data) - recordHeaderLen - b.data[3] = byte(n >> 8) - b.data[4] = byte(n) - hc.incSeq() - - return true, 0 -} - -// A block is a simple data buffer. -type block struct { - data []byte - off int // index for Read - link *block -} - -// resize resizes block to be n bytes, growing if necessary. -func (b *block) resize(n int) { - if n > cap(b.data) { - b.reserve(n) - } - b.data = b.data[0:n] -} - -// reserve makes sure that block contains a capacity of at least n bytes. -func (b *block) reserve(n int) { - if cap(b.data) >= n { - return - } - m := cap(b.data) - if m == 0 { - m = 1024 - } - for m < n { - m *= 2 - } - data := make([]byte, len(b.data), m) - copy(data, b.data) - b.data = data -} - -// readFromUntil reads from r into b until b contains at least n bytes -// or else returns an error. -func (b *block) readFromUntil(r io.Reader, n int) error { - // quick case - if len(b.data) >= n { - return nil - } - - // read until have enough. - b.reserve(n) - for { - m, err := r.Read(b.data[len(b.data):cap(b.data)]) - b.data = b.data[0 : len(b.data)+m] - if len(b.data) >= n { - // TODO(bradfitz,agl): slightly suspicious - // that we're throwing away r.Read's err here. - break - } - if err != nil { - return err - } - } - return nil -} - -func (b *block) Read(p []byte) (n int, err error) { - n = copy(p, b.data[b.off:]) - b.off += n - return -} - -// newBlock allocates a new block, from hc's free list if possible. -func (hc *halfConn) newBlock() *block { - b := hc.bfree - if b == nil { - return new(block) - } - hc.bfree = b.link - b.link = nil - b.resize(0) - return b -} - -// freeBlock returns a block to hc's free list. -// The protocol is such that each side only has a block or two on -// its free list at a time, so there's no need to worry about -// trimming the list, etc. -func (hc *halfConn) freeBlock(b *block) { - b.link = hc.bfree - hc.bfree = b -} - -// splitBlock splits a block after the first n bytes, -// returning a block with those n bytes and a -// block with the remainder. the latter may be nil. -func (hc *halfConn) splitBlock(b *block, n int) (*block, *block) { - if len(b.data) <= n { - return b, nil - } - bb := hc.newBlock() - bb.resize(len(b.data) - n) - copy(bb.data, b.data[n:]) - b.data = b.data[0:n] - return b, bb -} - -// readRecord reads the next TLS record from the connection -// and updates the record layer state. -// c.in.Mutex <= L; c.input == nil. -func (c *Conn) readRecord(want recordType) error { - // Caller must be in sync with connection: - // handshake data if handshake not yet completed, - // else application data. (We don't support renegotiation.) - switch want { - default: - c.sendAlert(alertInternalError) - return c.in.setErrorLocked(errors.New("tls: unknown record type requested")) - case recordTypeHandshake, recordTypeChangeCipherSpec: - if c.handshakeComplete { - c.sendAlert(alertInternalError) - return c.in.setErrorLocked(errors.New("tls: handshake or ChangeCipherSpec requested after handshake complete")) - } - case recordTypeApplicationData: - if !c.handshakeComplete { - c.sendAlert(alertInternalError) - return c.in.setErrorLocked(errors.New("tls: application data record requested before handshake complete")) - } - } - -Again: - if c.rawInput == nil { - c.rawInput = c.in.newBlock() - } - b := c.rawInput - - // Read header, payload. - if err := b.readFromUntil(c.conn, recordHeaderLen); err != nil { - // RFC suggests that EOF without an alertCloseNotify is - // an error, but popular web sites seem to do this, - // so we can't make it an error. - // if err == io.EOF { - // err = io.ErrUnexpectedEOF - // } - if e, ok := err.(net.Error); !ok || !e.Temporary() { - c.in.setErrorLocked(err) - } - return err - } - typ := recordType(b.data[0]) - - // No valid TLS record has a type of 0x80, however SSLv2 handshakes - // start with a uint16 length where the MSB is set and the first record - // is always < 256 bytes long. Therefore typ == 0x80 strongly suggests - // an SSLv2 client. - if want == recordTypeHandshake && typ == 0x80 { - c.sendAlert(alertProtocolVersion) - return c.in.setErrorLocked(errors.New("tls: unsupported SSLv2 handshake received")) - } - - vers := uint16(b.data[1])<<8 | uint16(b.data[2]) - n := int(b.data[3])<<8 | int(b.data[4]) - if c.haveVers && vers != c.vers { - c.sendAlert(alertProtocolVersion) - return c.in.setErrorLocked(fmt.Errorf("tls: received record with version %x when expecting version %x", vers, c.vers)) - } - if n > maxCiphertext { - c.sendAlert(alertRecordOverflow) - return c.in.setErrorLocked(fmt.Errorf("tls: oversized record received with length %d", n)) - } - if !c.haveVers { - // First message, be extra suspicious: - // this might not be a TLS client. - // Bail out before reading a full 'body', if possible. - // The current max version is 3.1. - // If the version is >= 16.0, it's probably not real. - // Similarly, a clientHello message encodes in - // well under a kilobyte. If the length is >= 12 kB, - // it's probably not real. - if (typ != recordTypeAlert && typ != want) || vers >= 0x1000 || n >= 0x3000 { - c.sendAlert(alertUnexpectedMessage) - return c.in.setErrorLocked(fmt.Errorf("tls: first record does not look like a TLS handshake")) - } - } - if err := b.readFromUntil(c.conn, recordHeaderLen+n); err != nil { - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - if e, ok := err.(net.Error); !ok || !e.Temporary() { - c.in.setErrorLocked(err) - } - return err - } - - // Process message. - b, c.rawInput = c.in.splitBlock(b, recordHeaderLen+n) - ok, off, err := c.in.decrypt(b) - if !ok { - c.in.setErrorLocked(c.sendAlert(err)) - } - b.off = off - data := b.data[b.off:] - if len(data) > maxPlaintext { - err := c.sendAlert(alertRecordOverflow) - c.in.freeBlock(b) - return c.in.setErrorLocked(err) - } - - switch typ { - default: - c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) - - case recordTypeAlert: - if len(data) != 2 { - c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) - break - } - if alert(data[1]) == alertCloseNotify { - c.in.setErrorLocked(io.EOF) - break - } - switch data[0] { - case alertLevelWarning: - // drop on the floor - c.in.freeBlock(b) - goto Again - case alertLevelError: - c.in.setErrorLocked(&net.OpError{Op: "remote error", Err: alert(data[1])}) - default: - c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) - } - - case recordTypeChangeCipherSpec: - if typ != want || len(data) != 1 || data[0] != 1 { - c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) - break - } - err := c.in.changeCipherSpec() - if err != nil { - c.in.setErrorLocked(c.sendAlert(err.(alert))) - } - - case recordTypeApplicationData: - if typ != want { - c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) - break - } - c.input = b - b = nil - - case recordTypeHandshake: - // TODO(rsc): Should at least pick off connection close. - if typ != want { - return c.in.setErrorLocked(c.sendAlert(alertNoRenegotiation)) - } - c.hand.Write(data) - } - - if b != nil { - c.in.freeBlock(b) - } - return c.in.err -} - -// sendAlert sends a TLS alert message. -// c.out.Mutex <= L. -func (c *Conn) sendAlertLocked(err alert) error { - switch err { - case alertNoRenegotiation, alertCloseNotify: - c.tmp[0] = alertLevelWarning - default: - c.tmp[0] = alertLevelError - } - c.tmp[1] = byte(err) - c.writeRecord(recordTypeAlert, c.tmp[0:2]) - // closeNotify is a special case in that it isn't an error: - if err != alertCloseNotify { - return c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err}) - } - return nil -} - -// sendAlert sends a TLS alert message. -// L < c.out.Mutex. -func (c *Conn) sendAlert(err alert) error { - c.out.Lock() - defer c.out.Unlock() - return c.sendAlertLocked(err) -} - -// writeRecord writes a TLS record with the given type and payload -// to the connection and updates the record layer state. -// c.out.Mutex <= L. -func (c *Conn) writeRecord(typ recordType, data []byte) (n int, err error) { - b := c.out.newBlock() - for len(data) > 0 { - m := len(data) - if m > maxPlaintext { - m = maxPlaintext - } - explicitIVLen := 0 - explicitIVIsSeq := false - - var cbc cbcMode - if c.out.version >= VersionTLS11 { - var ok bool - if cbc, ok = c.out.cipher.(cbcMode); ok { - explicitIVLen = cbc.BlockSize() - } - } - if explicitIVLen == 0 { - if _, ok := c.out.cipher.(cipher.AEAD); ok { - explicitIVLen = 8 - // The AES-GCM construction in TLS has an - // explicit nonce so that the nonce can be - // random. However, the nonce is only 8 bytes - // which is too small for a secure, random - // nonce. Therefore we use the sequence number - // as the nonce. - explicitIVIsSeq = true - } - } - b.resize(recordHeaderLen + explicitIVLen + m) - b.data[0] = byte(typ) - vers := c.vers - if vers == 0 { - // Some TLS servers fail if the record version is - // greater than TLS 1.0 for the initial ClientHello. - vers = VersionTLS10 - } - b.data[1] = byte(vers >> 8) - b.data[2] = byte(vers) - b.data[3] = byte(m >> 8) - b.data[4] = byte(m) - if explicitIVLen > 0 { - explicitIV := b.data[recordHeaderLen : recordHeaderLen+explicitIVLen] - if explicitIVIsSeq { - copy(explicitIV, c.out.seq[:]) - } else { - if _, err = io.ReadFull(c.config.rand(), explicitIV); err != nil { - break - } - } - } - copy(b.data[recordHeaderLen+explicitIVLen:], data) - c.out.encrypt(b, explicitIVLen) - _, err = c.conn.Write(b.data) - if err != nil { - break - } - n += m - data = data[m:] - } - c.out.freeBlock(b) - - if typ == recordTypeChangeCipherSpec { - err = c.out.changeCipherSpec() - if err != nil { - // Cannot call sendAlert directly, - // because we already hold c.out.Mutex. - c.tmp[0] = alertLevelError - c.tmp[1] = byte(err.(alert)) - c.writeRecord(recordTypeAlert, c.tmp[0:2]) - return n, c.out.setErrorLocked(&net.OpError{Op: "local error", Err: err}) - } - } - return -} - -// readHandshake reads the next handshake message from -// the record layer. -// c.in.Mutex < L; c.out.Mutex < L. -func (c *Conn) readHandshake() (interface{}, error) { - for c.hand.Len() < 4 { - if err := c.in.err; err != nil { - return nil, err - } - if err := c.readRecord(recordTypeHandshake); err != nil { - return nil, err - } - } - - data := c.hand.Bytes() - n := int(data[1])<<16 | int(data[2])<<8 | int(data[3]) - if n > maxHandshake { - return nil, c.in.setErrorLocked(c.sendAlert(alertInternalError)) - } - for c.hand.Len() < 4+n { - if err := c.in.err; err != nil { - return nil, err - } - if err := c.readRecord(recordTypeHandshake); err != nil { - return nil, err - } - } - data = c.hand.Next(4 + n) - var m handshakeMessage - switch data[0] { - case typeClientHello: - m = new(clientHelloMsg) - case typeServerHello: - m = new(serverHelloMsg) - case typeNewSessionTicket: - m = new(newSessionTicketMsg) - case typeCertificate: - m = new(certificateMsg) - case typeCertificateRequest: - m = &certificateRequestMsg{ - hasSignatureAndHash: c.vers >= VersionTLS12, - } - case typeCertificateStatus: - m = new(certificateStatusMsg) - case typeServerKeyExchange: - m = new(serverKeyExchangeMsg) - case typeServerHelloDone: - m = new(serverHelloDoneMsg) - case typeClientKeyExchange: - m = new(clientKeyExchangeMsg) - case typeCertificateVerify: - m = &certificateVerifyMsg{ - hasSignatureAndHash: c.vers >= VersionTLS12, - } - case typeNextProtocol: - m = new(nextProtoMsg) - case typeFinished: - m = new(finishedMsg) - default: - return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) - } - - // The handshake message unmarshallers - // expect to be able to keep references to data, - // so pass in a fresh copy that won't be overwritten. - data = append([]byte(nil), data...) - - if !m.unmarshal(data) { - return nil, c.in.setErrorLocked(c.sendAlert(alertUnexpectedMessage)) - } - return m, nil -} - -// Write writes data to the connection. -func (c *Conn) Write(b []byte) (int, error) { - if err := c.Handshake(); err != nil { - return 0, err - } - - c.out.Lock() - defer c.out.Unlock() - - if err := c.out.err; err != nil { - return 0, err - } - - if !c.handshakeComplete { - return 0, alertInternalError - } - - // SSL 3.0 and TLS 1.0 are susceptible to a chosen-plaintext - // attack when using block mode ciphers due to predictable IVs. - // This can be prevented by splitting each Application Data - // record into two records, effectively randomizing the IV. - // - // http://www.openssl.org/~bodo/tls-cbc.txt - // https://bugzilla.mozilla.org/show_bug.cgi?id=665814 - // http://www.imperialviolet.org/2012/01/15/beastfollowup.html - - var m int - if len(b) > 1 && c.vers <= VersionTLS10 { - if _, ok := c.out.cipher.(cipher.BlockMode); ok { - n, err := c.writeRecord(recordTypeApplicationData, b[:1]) - if err != nil { - return n, c.out.setErrorLocked(err) - } - m, b = 1, b[1:] - } - } - - n, err := c.writeRecord(recordTypeApplicationData, b) - return n + m, c.out.setErrorLocked(err) -} - -// Read can be made to time out and return a net.Error with Timeout() == true -// after a fixed time limit; see SetDeadline and SetReadDeadline. -func (c *Conn) Read(b []byte) (n int, err error) { - if err = c.Handshake(); err != nil { - return - } - if len(b) == 0 { - // Put this after Handshake, in case people were calling - // Read(nil) for the side effect of the Handshake. - return - } - - c.in.Lock() - defer c.in.Unlock() - - // Some OpenSSL servers send empty records in order to randomize the - // CBC IV. So this loop ignores a limited number of empty records. - const maxConsecutiveEmptyRecords = 100 - for emptyRecordCount := 0; emptyRecordCount <= maxConsecutiveEmptyRecords; emptyRecordCount++ { - for c.input == nil && c.in.err == nil { - if err := c.readRecord(recordTypeApplicationData); err != nil { - // Soft error, like EAGAIN - return 0, err - } - } - if err := c.in.err; err != nil { - return 0, err - } - - n, err = c.input.Read(b) - if c.input.off >= len(c.input.data) { - c.in.freeBlock(c.input) - c.input = nil - } - - // If a close-notify alert is waiting, read it so that - // we can return (n, EOF) instead of (n, nil), to signal - // to the HTTP response reading goroutine that the - // connection is now closed. This eliminates a race - // where the HTTP response reading goroutine would - // otherwise not observe the EOF until its next read, - // by which time a client goroutine might have already - // tried to reuse the HTTP connection for a new - // request. - // See https://codereview.appspot.com/76400046 - // and http://golang.org/issue/3514 - if ri := c.rawInput; ri != nil && - n != 0 && err == nil && - c.input == nil && len(ri.data) > 0 && recordType(ri.data[0]) == recordTypeAlert { - if recErr := c.readRecord(recordTypeApplicationData); recErr != nil { - err = recErr // will be io.EOF on closeNotify - } - } - - if n != 0 || err != nil { - return n, err - } - } - - return 0, io.ErrNoProgress -} - -// Close closes the connection. -func (c *Conn) Close() error { - var alertErr error - - c.handshakeMutex.Lock() - defer c.handshakeMutex.Unlock() - if c.handshakeComplete { - alertErr = c.sendAlert(alertCloseNotify) - } - - if err := c.conn.Close(); err != nil { - return err - } - return alertErr -} - -// Handshake runs the client or server handshake -// protocol if it has not yet been run. -// Most uses of this package need not call Handshake -// explicitly: the first Read or Write will call it automatically. -func (c *Conn) Handshake() error { - c.handshakeMutex.Lock() - defer c.handshakeMutex.Unlock() - if err := c.handshakeErr; err != nil { - return err - } - if c.handshakeComplete { - return nil - } - - if c.isClient { - c.handshakeErr = c.clientHandshake() - } else { - c.handshakeErr = c.serverHandshake() - } - return c.handshakeErr -} - -// ConnectionState returns basic TLS details about the connection. -func (c *Conn) ConnectionState() ConnectionState { - c.handshakeMutex.Lock() - defer c.handshakeMutex.Unlock() - - var state ConnectionState - state.HandshakeComplete = c.handshakeComplete - if c.handshakeComplete { - state.Version = c.vers - state.NegotiatedProtocol = c.clientProtocol - state.DidResume = c.didResume - state.NegotiatedProtocolIsMutual = !c.clientProtocolFallback - state.CipherSuite = c.cipherSuite - state.PeerCertificates = c.peerCertificates - state.VerifiedChains = c.verifiedChains - state.ServerName = c.serverName - if !c.didResume { - state.TLSUnique = c.firstFinished[:] - } - } - - return state -} - -// OCSPResponse returns the stapled OCSP response from the TLS server, if -// any. (Only valid for client connections.) -func (c *Conn) OCSPResponse() []byte { - c.handshakeMutex.Lock() - defer c.handshakeMutex.Unlock() - - return c.ocspResponse -} - -// VerifyHostname checks that the peer certificate chain is valid for -// connecting to host. If so, it returns nil; if not, it returns an error -// describing the problem. -func (c *Conn) VerifyHostname(host string) error { - c.handshakeMutex.Lock() - defer c.handshakeMutex.Unlock() - if !c.isClient { - return errors.New("tls: VerifyHostname called on TLS server connection") - } - if !c.handshakeComplete { - return errors.New("tls: handshake has not yet been performed") - } - return c.peerCertificates[0].VerifyHostname(host) -} diff --git a/src/pkg/crypto/tls/conn_test.go b/src/pkg/crypto/tls/conn_test.go deleted file mode 100644 index ec802cad7..000000000 --- a/src/pkg/crypto/tls/conn_test.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tls - -import ( - "testing" -) - -func TestRoundUp(t *testing.T) { - if roundUp(0, 16) != 0 || - roundUp(1, 16) != 16 || - roundUp(15, 16) != 16 || - roundUp(16, 16) != 16 || - roundUp(17, 16) != 32 { - t.Error("roundUp broken") - } -} - -var paddingTests = []struct { - in []byte - good bool - expectedLen int -}{ - {[]byte{1, 2, 3, 4, 0}, true, 4}, - {[]byte{1, 2, 3, 4, 0, 1}, false, 0}, - {[]byte{1, 2, 3, 4, 99, 99}, false, 0}, - {[]byte{1, 2, 3, 4, 1, 1}, true, 4}, - {[]byte{1, 2, 3, 2, 2, 2}, true, 3}, - {[]byte{1, 2, 3, 3, 3, 3}, true, 2}, - {[]byte{1, 2, 3, 4, 3, 3}, false, 0}, - {[]byte{1, 4, 4, 4, 4, 4}, true, 1}, - {[]byte{5, 5, 5, 5, 5, 5}, true, 0}, - {[]byte{6, 6, 6, 6, 6, 6}, false, 0}, -} - -func TestRemovePadding(t *testing.T) { - for i, test := range paddingTests { - payload, good := removePadding(test.in) - expectedGood := byte(255) - if !test.good { - expectedGood = 0 - } - if good != expectedGood { - t.Errorf("#%d: wrong validity, want:%d got:%d", i, expectedGood, good) - } - if good == 255 && len(payload) != test.expectedLen { - t.Errorf("#%d: got %d, want %d", i, len(payload), test.expectedLen) - } - } -} - -var certExampleCom = `308201403081eda003020102020101300b06092a864886f70d010105301e311c301a060355040a131354657374696e67204365727469666963617465301e170d3131313030313138353835325a170d3132303933303138353835325a301e311c301a060355040a131354657374696e67204365727469666963617465305a300b06092a864886f70d010101034b003048024100bced6e32368599eeddf18796bfd03958a154f87e5b084f96e85136a56b886733592f493f0fc68b0d6b3551781cb95e13c5de458b28d6fb60d20a9129313261410203010001a31a301830160603551d11040f300d820b6578616d706c652e636f6d300b06092a864886f70d0101050341001a0b419d2c74474c6450654e5f10b32bf426ffdf55cad1c52602e7a9151513a3424c70f5960dcd682db0c33769cc1daa3fcdd3db10809d2392ed4a1bf50ced18` - -var certWildcardExampleCom = `308201423081efa003020102020101300b06092a864886f70d010105301e311c301a060355040a131354657374696e67204365727469666963617465301e170d3131313030313139303034365a170d3132303933303139303034365a301e311c301a060355040a131354657374696e67204365727469666963617465305a300b06092a864886f70d010101034b003048024100bced6e32368599eeddf18796bfd03958a154f87e5b084f96e85136a56b886733592f493f0fc68b0d6b3551781cb95e13c5de458b28d6fb60d20a9129313261410203010001a31c301a30180603551d110411300f820d2a2e6578616d706c652e636f6d300b06092a864886f70d0101050341001676f0c9e7c33c1b656ed5a6476c4e2ee9ec8e62df7407accb1875272b2edd0a22096cb2c22598d11604104d604f810eb4b5987ca6bb319c7e6ce48725c54059` - -var certFooExampleCom = `308201443081f1a003020102020101300b06092a864886f70d010105301e311c301a060355040a131354657374696e67204365727469666963617465301e170d3131313030313139303131345a170d3132303933303139303131345a301e311c301a060355040a131354657374696e67204365727469666963617465305a300b06092a864886f70d010101034b003048024100bced6e32368599eeddf18796bfd03958a154f87e5b084f96e85136a56b886733592f493f0fc68b0d6b3551781cb95e13c5de458b28d6fb60d20a9129313261410203010001a31e301c301a0603551d1104133011820f666f6f2e6578616d706c652e636f6d300b06092a864886f70d010105034100646a2a51f2aa2477add854b462cf5207ba16d3213ffb5d3d0eed473fbf09935019192d1d5b8ca6a2407b424cf04d97c4cd9197c83ecf81f0eab9464a1109d09f` - -var certDoubleWildcardExampleCom = `308201443081f1a003020102020101300b06092a864886f70d010105301e311c301a060355040a131354657374696e67204365727469666963617465301e170d3131313030313139303134315a170d3132303933303139303134315a301e311c301a060355040a131354657374696e67204365727469666963617465305a300b06092a864886f70d010101034b003048024100bced6e32368599eeddf18796bfd03958a154f87e5b084f96e85136a56b886733592f493f0fc68b0d6b3551781cb95e13c5de458b28d6fb60d20a9129313261410203010001a31e301c301a0603551d1104133011820f2a2e2a2e6578616d706c652e636f6d300b06092a864886f70d0101050341001c3de267975f56ef57771c6218ef95ecc65102e57bd1defe6f7efea90d9b26cf40de5bd7ad75e46201c7f2a92aaa3e907451e9409f65e28ddb6db80d726290f6` - -func TestCertificateSelection(t *testing.T) { - config := Config{ - Certificates: []Certificate{ - { - Certificate: [][]byte{fromHex(certExampleCom)}, - }, - { - Certificate: [][]byte{fromHex(certWildcardExampleCom)}, - }, - { - Certificate: [][]byte{fromHex(certFooExampleCom)}, - }, - { - Certificate: [][]byte{fromHex(certDoubleWildcardExampleCom)}, - }, - }, - } - - config.BuildNameToCertificate() - - pointerToIndex := func(c *Certificate) int { - for i := range config.Certificates { - if c == &config.Certificates[i] { - return i - } - } - return -1 - } - - certificateForName := func(name string) *Certificate { - clientHello := &ClientHelloInfo{ - ServerName: name, - } - if cert, err := config.getCertificate(clientHello); err != nil { - t.Errorf("unable to get certificate for name '%s': %s", name, err) - return nil - } else { - return cert - } - } - - if n := pointerToIndex(certificateForName("example.com")); n != 0 { - t.Errorf("example.com returned certificate %d, not 0", n) - } - if n := pointerToIndex(certificateForName("bar.example.com")); n != 1 { - t.Errorf("bar.example.com returned certificate %d, not 1", n) - } - if n := pointerToIndex(certificateForName("foo.example.com")); n != 2 { - t.Errorf("foo.example.com returned certificate %d, not 2", n) - } - if n := pointerToIndex(certificateForName("foo.bar.example.com")); n != 3 { - t.Errorf("foo.bar.example.com returned certificate %d, not 3", n) - } - if n := pointerToIndex(certificateForName("foo.bar.baz.example.com")); n != 0 { - t.Errorf("foo.bar.baz.example.com returned certificate %d, not 0", n) - } -} diff --git a/src/pkg/crypto/tls/example_test.go b/src/pkg/crypto/tls/example_test.go deleted file mode 100644 index 7628e431b..000000000 --- a/src/pkg/crypto/tls/example_test.go +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tls_test - -import ( - "crypto/tls" - "crypto/x509" -) - -func ExampleDial() { - // Connecting with a custom root-certificate set. - - const rootPEM = ` ------BEGIN CERTIFICATE----- -MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT -MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i -YWwgQ0EwHhcNMTMwNDA1MTUxNTU1WhcNMTUwNDA0MTUxNTU1WjBJMQswCQYDVQQG -EwJVUzETMBEGA1UEChMKR29vZ2xlIEluYzElMCMGA1UEAxMcR29vZ2xlIEludGVy -bmV0IEF1dGhvcml0eSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB -AJwqBHdc2FCROgajguDYUEi8iT/xGXAaiEZ+4I/F8YnOIe5a/mENtzJEiaB0C1NP -VaTOgmKV7utZX8bhBYASxF6UP7xbSDj0U/ck5vuR6RXEz/RTDfRK/J9U3n2+oGtv -h8DQUB8oMANA2ghzUWx//zo8pzcGjr1LEQTrfSTe5vn8MXH7lNVg8y5Kr0LSy+rE -ahqyzFPdFUuLH8gZYR/Nnag+YyuENWllhMgZxUYi+FOVvuOAShDGKuy6lyARxzmZ -EASg8GF6lSWMTlJ14rbtCMoU/M4iarNOz0YDl5cDfsCx3nuvRTPPuj5xt970JSXC -DTWJnZ37DhF5iR43xa+OcmkCAwEAAaOB+zCB+DAfBgNVHSMEGDAWgBTAephojYn7 -qwVkDBF9qn1luMrMTjAdBgNVHQ4EFgQUSt0GFhu89mi1dvWBtrtiGrpagS8wEgYD -VR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAQYwOgYDVR0fBDMwMTAvoC2g -K4YpaHR0cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9ndGdsb2JhbC5jcmwwPQYI -KwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwOi8vZ3RnbG9iYWwtb2NzcC5n -ZW90cnVzdC5jb20wFwYDVR0gBBAwDjAMBgorBgEEAdZ5AgUBMA0GCSqGSIb3DQEB -BQUAA4IBAQA21waAESetKhSbOHezI6B1WLuxfoNCunLaHtiONgaX4PCVOzf9G0JY -/iLIa704XtE7JW4S615ndkZAkNoUyHgN7ZVm2o6Gb4ChulYylYbc3GrKBIxbf/a/ -zG+FA1jDaFETzf3I93k9mTXwVqO94FntT0QJo544evZG0R0SnU++0ED8Vf4GXjza -HFa9llF7b1cq26KqltyMdMKVvvBulRP/F/A8rLIQjcxz++iPAsbw+zOzlTvjwsto -WHPbqCRiOwY1nQ2pM714A5AuTHhdUDqB1O6gyHA43LL5Z/qHQF1hwFGPa4NrzQU6 -yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx ------END CERTIFICATE-----` - - // First, create the set of root certificates. For this example we only - // have one. It's also possible to omit this in order to use the - // default root set of the current operating system. - roots := x509.NewCertPool() - ok := roots.AppendCertsFromPEM([]byte(rootPEM)) - if !ok { - panic("failed to parse root certificate") - } - - conn, err := tls.Dial("tcp", "mail.google.com:443", &tls.Config{ - RootCAs: roots, - }) - if err != nil { - panic("failed to connect: " + err.Error()) - } - conn.Close() -} diff --git a/src/pkg/crypto/tls/generate_cert.go b/src/pkg/crypto/tls/generate_cert.go deleted file mode 100644 index 83f9916ff..000000000 --- a/src/pkg/crypto/tls/generate_cert.go +++ /dev/null @@ -1,161 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// Generate a self-signed X.509 certificate for a TLS server. Outputs to -// 'cert.pem' and 'key.pem' and will overwrite existing files. - -package main - -import ( - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/rsa" - "crypto/x509" - "crypto/x509/pkix" - "encoding/pem" - "flag" - "fmt" - "log" - "math/big" - "net" - "os" - "strings" - "time" -) - -var ( - host = flag.String("host", "", "Comma-separated hostnames and IPs to generate a certificate for") - validFrom = flag.String("start-date", "", "Creation date formatted as Jan 1 15:04:05 2011") - validFor = flag.Duration("duration", 365*24*time.Hour, "Duration that certificate is valid for") - isCA = flag.Bool("ca", false, "whether this cert should be its own Certificate Authority") - rsaBits = flag.Int("rsa-bits", 2048, "Size of RSA key to generate. Ignored if --ecdsa-curve is set") - ecdsaCurve = flag.String("ecdsa-curve", "", "ECDSA curve to use to generate a key. Valid values are P224, P256, P384, P521") -) - -func publicKey(priv interface{}) interface{} { - switch k := priv.(type) { - case *rsa.PrivateKey: - return &k.PublicKey - case *ecdsa.PrivateKey: - return &k.PublicKey - default: - return nil - } -} - -func pemBlockForKey(priv interface{}) *pem.Block { - switch k := priv.(type) { - case *rsa.PrivateKey: - return &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(k)} - case *ecdsa.PrivateKey: - b, err := x509.MarshalECPrivateKey(k) - if err != nil { - fmt.Fprintf(os.Stderr, "Unable to marshal ECDSA private key: %v", err) - os.Exit(2) - } - return &pem.Block{Type: "EC PRIVATE KEY", Bytes: b} - default: - return nil - } -} - -func main() { - flag.Parse() - - if len(*host) == 0 { - log.Fatalf("Missing required --host parameter") - } - - var priv interface{} - var err error - switch *ecdsaCurve { - case "": - priv, err = rsa.GenerateKey(rand.Reader, *rsaBits) - case "P224": - priv, err = ecdsa.GenerateKey(elliptic.P224(), rand.Reader) - case "P256": - priv, err = ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - case "P384": - priv, err = ecdsa.GenerateKey(elliptic.P384(), rand.Reader) - case "P521": - priv, err = ecdsa.GenerateKey(elliptic.P521(), rand.Reader) - default: - fmt.Fprintf(os.Stderr, "Unrecognized elliptic curve: %q", *ecdsaCurve) - os.Exit(1) - } - if err != nil { - log.Fatalf("failed to generate private key: %s", err) - } - - var notBefore time.Time - if len(*validFrom) == 0 { - notBefore = time.Now() - } else { - notBefore, err = time.Parse("Jan 2 15:04:05 2006", *validFrom) - if err != nil { - fmt.Fprintf(os.Stderr, "Failed to parse creation date: %s\n", err) - os.Exit(1) - } - } - - notAfter := notBefore.Add(*validFor) - - serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128) - serialNumber, err := rand.Int(rand.Reader, serialNumberLimit) - if err != nil { - log.Fatalf("failed to generate serial number: %s", err) - } - - template := x509.Certificate{ - SerialNumber: serialNumber, - Subject: pkix.Name{ - Organization: []string{"Acme Co"}, - }, - NotBefore: notBefore, - NotAfter: notAfter, - - KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, - ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, - BasicConstraintsValid: true, - } - - hosts := strings.Split(*host, ",") - for _, h := range hosts { - if ip := net.ParseIP(h); ip != nil { - template.IPAddresses = append(template.IPAddresses, ip) - } else { - template.DNSNames = append(template.DNSNames, h) - } - } - - if *isCA { - template.IsCA = true - template.KeyUsage |= x509.KeyUsageCertSign - } - - derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, publicKey(priv), priv) - if err != nil { - log.Fatalf("Failed to create certificate: %s", err) - } - - certOut, err := os.Create("cert.pem") - if err != nil { - log.Fatalf("failed to open cert.pem for writing: %s", err) - } - pem.Encode(certOut, &pem.Block{Type: "CERTIFICATE", Bytes: derBytes}) - certOut.Close() - log.Print("written cert.pem\n") - - keyOut, err := os.OpenFile("key.pem", os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) - if err != nil { - log.Print("failed to open key.pem for writing:", err) - return - } - pem.Encode(keyOut, pemBlockForKey(priv)) - keyOut.Close() - log.Print("written key.pem\n") -} diff --git a/src/pkg/crypto/tls/handshake_client.go b/src/pkg/crypto/tls/handshake_client.go deleted file mode 100644 index 7f662e9c9..000000000 --- a/src/pkg/crypto/tls/handshake_client.go +++ /dev/null @@ -1,638 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tls - -import ( - "bytes" - "crypto" - "crypto/ecdsa" - "crypto/rsa" - "crypto/subtle" - "crypto/x509" - "errors" - "fmt" - "io" - "net" - "strconv" -) - -type clientHandshakeState struct { - c *Conn - serverHello *serverHelloMsg - hello *clientHelloMsg - suite *cipherSuite - finishedHash finishedHash - masterSecret []byte - session *ClientSessionState -} - -func (c *Conn) clientHandshake() error { - if c.config == nil { - c.config = defaultConfig() - } - - if len(c.config.ServerName) == 0 && !c.config.InsecureSkipVerify { - return errors.New("tls: either ServerName or InsecureSkipVerify must be specified in the tls.Config") - } - - nextProtosLength := 0 - for _, proto := range c.config.NextProtos { - if l := len(proto); l == 0 || l > 255 { - return errors.New("tls: invalid NextProtos value") - } else { - nextProtosLength += 1 + l - } - } - if nextProtosLength > 0xffff { - return errors.New("tls: NextProtos values too large") - } - - hello := &clientHelloMsg{ - vers: c.config.maxVersion(), - compressionMethods: []uint8{compressionNone}, - random: make([]byte, 32), - ocspStapling: true, - serverName: c.config.ServerName, - supportedCurves: c.config.curvePreferences(), - supportedPoints: []uint8{pointFormatUncompressed}, - nextProtoNeg: len(c.config.NextProtos) > 0, - secureRenegotiation: true, - alpnProtocols: c.config.NextProtos, - } - - possibleCipherSuites := c.config.cipherSuites() - hello.cipherSuites = make([]uint16, 0, len(possibleCipherSuites)) - -NextCipherSuite: - for _, suiteId := range possibleCipherSuites { - for _, suite := range cipherSuites { - if suite.id != suiteId { - continue - } - // Don't advertise TLS 1.2-only cipher suites unless - // we're attempting TLS 1.2. - if hello.vers < VersionTLS12 && suite.flags&suiteTLS12 != 0 { - continue - } - hello.cipherSuites = append(hello.cipherSuites, suiteId) - continue NextCipherSuite - } - } - - _, err := io.ReadFull(c.config.rand(), hello.random) - if err != nil { - c.sendAlert(alertInternalError) - return errors.New("tls: short read from Rand: " + err.Error()) - } - - if hello.vers >= VersionTLS12 { - hello.signatureAndHashes = supportedSKXSignatureAlgorithms - } - - var session *ClientSessionState - var cacheKey string - sessionCache := c.config.ClientSessionCache - if c.config.SessionTicketsDisabled { - sessionCache = nil - } - - if sessionCache != nil { - hello.ticketSupported = true - - // Try to resume a previously negotiated TLS session, if - // available. - cacheKey = clientSessionCacheKey(c.conn.RemoteAddr(), c.config) - candidateSession, ok := sessionCache.Get(cacheKey) - if ok { - // Check that the ciphersuite/version used for the - // previous session are still valid. - cipherSuiteOk := false - for _, id := range hello.cipherSuites { - if id == candidateSession.cipherSuite { - cipherSuiteOk = true - break - } - } - - versOk := candidateSession.vers >= c.config.minVersion() && - candidateSession.vers <= c.config.maxVersion() - if versOk && cipherSuiteOk { - session = candidateSession - } - } - } - - if session != nil { - hello.sessionTicket = session.sessionTicket - // A random session ID is used to detect when the - // server accepted the ticket and is resuming a session - // (see RFC 5077). - hello.sessionId = make([]byte, 16) - if _, err := io.ReadFull(c.config.rand(), hello.sessionId); err != nil { - c.sendAlert(alertInternalError) - return errors.New("tls: short read from Rand: " + err.Error()) - } - } - - c.writeRecord(recordTypeHandshake, hello.marshal()) - - msg, err := c.readHandshake() - if err != nil { - return err - } - serverHello, ok := msg.(*serverHelloMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(serverHello, msg) - } - - vers, ok := c.config.mutualVersion(serverHello.vers) - if !ok || vers < VersionTLS10 { - // TLS 1.0 is the minimum version supported as a client. - c.sendAlert(alertProtocolVersion) - return fmt.Errorf("tls: server selected unsupported protocol version %x", serverHello.vers) - } - c.vers = vers - c.haveVers = true - - suite := mutualCipherSuite(c.config.cipherSuites(), serverHello.cipherSuite) - if suite == nil { - c.sendAlert(alertHandshakeFailure) - return fmt.Errorf("tls: server selected an unsupported cipher suite") - } - - hs := &clientHandshakeState{ - c: c, - serverHello: serverHello, - hello: hello, - suite: suite, - finishedHash: newFinishedHash(c.vers), - session: session, - } - - hs.finishedHash.Write(hs.hello.marshal()) - hs.finishedHash.Write(hs.serverHello.marshal()) - - isResume, err := hs.processServerHello() - if err != nil { - return err - } - - if isResume { - if err := hs.establishKeys(); err != nil { - return err - } - if err := hs.readSessionTicket(); err != nil { - return err - } - if err := hs.readFinished(c.firstFinished[:]); err != nil { - return err - } - if err := hs.sendFinished(nil); err != nil { - return err - } - } else { - if err := hs.doFullHandshake(); err != nil { - return err - } - if err := hs.establishKeys(); err != nil { - return err - } - if err := hs.sendFinished(c.firstFinished[:]); err != nil { - return err - } - if err := hs.readSessionTicket(); err != nil { - return err - } - if err := hs.readFinished(nil); err != nil { - return err - } - } - - if sessionCache != nil && hs.session != nil && session != hs.session { - sessionCache.Put(cacheKey, hs.session) - } - - c.didResume = isResume - c.handshakeComplete = true - c.cipherSuite = suite.id - return nil -} - -func (hs *clientHandshakeState) doFullHandshake() error { - c := hs.c - - msg, err := c.readHandshake() - if err != nil { - return err - } - certMsg, ok := msg.(*certificateMsg) - if !ok || len(certMsg.certificates) == 0 { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(certMsg, msg) - } - hs.finishedHash.Write(certMsg.marshal()) - - certs := make([]*x509.Certificate, len(certMsg.certificates)) - for i, asn1Data := range certMsg.certificates { - cert, err := x509.ParseCertificate(asn1Data) - if err != nil { - c.sendAlert(alertBadCertificate) - return errors.New("tls: failed to parse certificate from server: " + err.Error()) - } - certs[i] = cert - } - - if !c.config.InsecureSkipVerify { - opts := x509.VerifyOptions{ - Roots: c.config.RootCAs, - CurrentTime: c.config.time(), - DNSName: c.config.ServerName, - Intermediates: x509.NewCertPool(), - } - - for i, cert := range certs { - if i == 0 { - continue - } - opts.Intermediates.AddCert(cert) - } - c.verifiedChains, err = certs[0].Verify(opts) - if err != nil { - c.sendAlert(alertBadCertificate) - return err - } - } - - switch certs[0].PublicKey.(type) { - case *rsa.PublicKey, *ecdsa.PublicKey: - break - default: - c.sendAlert(alertUnsupportedCertificate) - return fmt.Errorf("tls: server's certificate contains an unsupported type of public key: %T", certs[0].PublicKey) - } - - c.peerCertificates = certs - - if hs.serverHello.ocspStapling { - msg, err = c.readHandshake() - if err != nil { - return err - } - cs, ok := msg.(*certificateStatusMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(cs, msg) - } - hs.finishedHash.Write(cs.marshal()) - - if cs.statusType == statusTypeOCSP { - c.ocspResponse = cs.response - } - } - - msg, err = c.readHandshake() - if err != nil { - return err - } - - keyAgreement := hs.suite.ka(c.vers) - - skx, ok := msg.(*serverKeyExchangeMsg) - if ok { - hs.finishedHash.Write(skx.marshal()) - err = keyAgreement.processServerKeyExchange(c.config, hs.hello, hs.serverHello, certs[0], skx) - if err != nil { - c.sendAlert(alertUnexpectedMessage) - return err - } - - msg, err = c.readHandshake() - if err != nil { - return err - } - } - - var chainToSend *Certificate - var certRequested bool - certReq, ok := msg.(*certificateRequestMsg) - if ok { - certRequested = true - - // RFC 4346 on the certificateAuthorities field: - // A list of the distinguished names of acceptable certificate - // authorities. These distinguished names may specify a desired - // distinguished name for a root CA or for a subordinate CA; - // thus, this message can be used to describe both known roots - // and a desired authorization space. If the - // certificate_authorities list is empty then the client MAY - // send any certificate of the appropriate - // ClientCertificateType, unless there is some external - // arrangement to the contrary. - - hs.finishedHash.Write(certReq.marshal()) - - var rsaAvail, ecdsaAvail bool - for _, certType := range certReq.certificateTypes { - switch certType { - case certTypeRSASign: - rsaAvail = true - case certTypeECDSASign: - ecdsaAvail = true - } - } - - // We need to search our list of client certs for one - // where SignatureAlgorithm is acceptable to the server and the - // Issuer is in certReq.certificateAuthorities - findCert: - for i, chain := range c.config.Certificates { - if !rsaAvail && !ecdsaAvail { - continue - } - - for j, cert := range chain.Certificate { - x509Cert := chain.Leaf - // parse the certificate if this isn't the leaf - // node, or if chain.Leaf was nil - if j != 0 || x509Cert == nil { - if x509Cert, err = x509.ParseCertificate(cert); err != nil { - c.sendAlert(alertInternalError) - return errors.New("tls: failed to parse client certificate #" + strconv.Itoa(i) + ": " + err.Error()) - } - } - - switch { - case rsaAvail && x509Cert.PublicKeyAlgorithm == x509.RSA: - case ecdsaAvail && x509Cert.PublicKeyAlgorithm == x509.ECDSA: - default: - continue findCert - } - - if len(certReq.certificateAuthorities) == 0 { - // they gave us an empty list, so just take the - // first cert from c.config.Certificates - chainToSend = &chain - break findCert - } - - for _, ca := range certReq.certificateAuthorities { - if bytes.Equal(x509Cert.RawIssuer, ca) { - chainToSend = &chain - break findCert - } - } - } - } - - msg, err = c.readHandshake() - if err != nil { - return err - } - } - - shd, ok := msg.(*serverHelloDoneMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(shd, msg) - } - hs.finishedHash.Write(shd.marshal()) - - // If the server requested a certificate then we have to send a - // Certificate message, even if it's empty because we don't have a - // certificate to send. - if certRequested { - certMsg = new(certificateMsg) - if chainToSend != nil { - certMsg.certificates = chainToSend.Certificate - } - hs.finishedHash.Write(certMsg.marshal()) - c.writeRecord(recordTypeHandshake, certMsg.marshal()) - } - - preMasterSecret, ckx, err := keyAgreement.generateClientKeyExchange(c.config, hs.hello, certs[0]) - if err != nil { - c.sendAlert(alertInternalError) - return err - } - if ckx != nil { - hs.finishedHash.Write(ckx.marshal()) - c.writeRecord(recordTypeHandshake, ckx.marshal()) - } - - if chainToSend != nil { - var signed []byte - certVerify := &certificateVerifyMsg{ - hasSignatureAndHash: c.vers >= VersionTLS12, - } - - key, ok := chainToSend.PrivateKey.(crypto.Signer) - if !ok { - c.sendAlert(alertInternalError) - return fmt.Errorf("tls: client certificate private key of type %T does not implement crypto.Signer", chainToSend.PrivateKey) - } - switch key.Public().(type) { - case *ecdsa.PublicKey: - digest, hashFunc, hashId := hs.finishedHash.hashForClientCertificate(signatureECDSA) - signed, err = key.Sign(c.config.rand(), digest, hashFunc) - certVerify.signatureAndHash.signature = signatureECDSA - certVerify.signatureAndHash.hash = hashId - case *rsa.PublicKey: - digest, hashFunc, hashId := hs.finishedHash.hashForClientCertificate(signatureRSA) - signed, err = key.Sign(c.config.rand(), digest, hashFunc) - certVerify.signatureAndHash.signature = signatureRSA - certVerify.signatureAndHash.hash = hashId - default: - err = fmt.Errorf("tls: unknown client certificate key type: %T", key) - } - if err != nil { - c.sendAlert(alertInternalError) - return errors.New("tls: failed to sign handshake with client certificate: " + err.Error()) - } - certVerify.signature = signed - - hs.finishedHash.Write(certVerify.marshal()) - c.writeRecord(recordTypeHandshake, certVerify.marshal()) - } - - hs.masterSecret = masterFromPreMasterSecret(c.vers, preMasterSecret, hs.hello.random, hs.serverHello.random) - return nil -} - -func (hs *clientHandshakeState) establishKeys() error { - c := hs.c - - clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := - keysFromMasterSecret(c.vers, hs.masterSecret, hs.hello.random, hs.serverHello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen) - var clientCipher, serverCipher interface{} - var clientHash, serverHash macFunction - if hs.suite.cipher != nil { - clientCipher = hs.suite.cipher(clientKey, clientIV, false /* not for reading */) - clientHash = hs.suite.mac(c.vers, clientMAC) - serverCipher = hs.suite.cipher(serverKey, serverIV, true /* for reading */) - serverHash = hs.suite.mac(c.vers, serverMAC) - } else { - clientCipher = hs.suite.aead(clientKey, clientIV) - serverCipher = hs.suite.aead(serverKey, serverIV) - } - - c.in.prepareCipherSpec(c.vers, serverCipher, serverHash) - c.out.prepareCipherSpec(c.vers, clientCipher, clientHash) - return nil -} - -func (hs *clientHandshakeState) serverResumedSession() bool { - // If the server responded with the same sessionId then it means the - // sessionTicket is being used to resume a TLS session. - return hs.session != nil && hs.hello.sessionId != nil && - bytes.Equal(hs.serverHello.sessionId, hs.hello.sessionId) -} - -func (hs *clientHandshakeState) processServerHello() (bool, error) { - c := hs.c - - if hs.serverHello.compressionMethod != compressionNone { - c.sendAlert(alertUnexpectedMessage) - return false, errors.New("tls: server selected unsupported compression format") - } - - clientDidNPN := hs.hello.nextProtoNeg - clientDidALPN := len(hs.hello.alpnProtocols) > 0 - serverHasNPN := hs.serverHello.nextProtoNeg - serverHasALPN := len(hs.serverHello.alpnProtocol) > 0 - - if !clientDidNPN && serverHasNPN { - c.sendAlert(alertHandshakeFailure) - return false, errors.New("server advertised unrequested NPN extension") - } - - if !clientDidALPN && serverHasALPN { - c.sendAlert(alertHandshakeFailure) - return false, errors.New("server advertised unrequested ALPN extension") - } - - if serverHasNPN && serverHasALPN { - c.sendAlert(alertHandshakeFailure) - return false, errors.New("server advertised both NPN and ALPN extensions") - } - - if serverHasALPN { - c.clientProtocol = hs.serverHello.alpnProtocol - c.clientProtocolFallback = false - } - - if hs.serverResumedSession() { - // Restore masterSecret and peerCerts from previous state - hs.masterSecret = hs.session.masterSecret - c.peerCertificates = hs.session.serverCertificates - return true, nil - } - return false, nil -} - -func (hs *clientHandshakeState) readFinished(out []byte) error { - c := hs.c - - c.readRecord(recordTypeChangeCipherSpec) - if err := c.in.error(); err != nil { - return err - } - - msg, err := c.readHandshake() - if err != nil { - return err - } - serverFinished, ok := msg.(*finishedMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(serverFinished, msg) - } - - verify := hs.finishedHash.serverSum(hs.masterSecret) - if len(verify) != len(serverFinished.verifyData) || - subtle.ConstantTimeCompare(verify, serverFinished.verifyData) != 1 { - c.sendAlert(alertHandshakeFailure) - return errors.New("tls: server's Finished message was incorrect") - } - hs.finishedHash.Write(serverFinished.marshal()) - copy(out, verify) - return nil -} - -func (hs *clientHandshakeState) readSessionTicket() error { - if !hs.serverHello.ticketSupported { - return nil - } - - c := hs.c - msg, err := c.readHandshake() - if err != nil { - return err - } - sessionTicketMsg, ok := msg.(*newSessionTicketMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(sessionTicketMsg, msg) - } - hs.finishedHash.Write(sessionTicketMsg.marshal()) - - hs.session = &ClientSessionState{ - sessionTicket: sessionTicketMsg.ticket, - vers: c.vers, - cipherSuite: hs.suite.id, - masterSecret: hs.masterSecret, - serverCertificates: c.peerCertificates, - } - - return nil -} - -func (hs *clientHandshakeState) sendFinished(out []byte) error { - c := hs.c - - c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) - if hs.serverHello.nextProtoNeg { - nextProto := new(nextProtoMsg) - proto, fallback := mutualProtocol(c.config.NextProtos, hs.serverHello.nextProtos) - nextProto.proto = proto - c.clientProtocol = proto - c.clientProtocolFallback = fallback - - hs.finishedHash.Write(nextProto.marshal()) - c.writeRecord(recordTypeHandshake, nextProto.marshal()) - } - - finished := new(finishedMsg) - finished.verifyData = hs.finishedHash.clientSum(hs.masterSecret) - hs.finishedHash.Write(finished.marshal()) - c.writeRecord(recordTypeHandshake, finished.marshal()) - copy(out, finished.verifyData) - return nil -} - -// clientSessionCacheKey returns a key used to cache sessionTickets that could -// be used to resume previously negotiated TLS sessions with a server. -func clientSessionCacheKey(serverAddr net.Addr, config *Config) string { - if len(config.ServerName) > 0 { - return config.ServerName - } - return serverAddr.String() -} - -// mutualProtocol finds the mutual Next Protocol Negotiation or ALPN protocol -// given list of possible protocols and a list of the preference order. The -// first list must not be empty. It returns the resulting protocol and flag -// indicating if the fallback case was reached. -func mutualProtocol(protos, preferenceProtos []string) (string, bool) { - for _, s := range preferenceProtos { - for _, c := range protos { - if s == c { - return s, false - } - } - } - - return protos[0], true -} diff --git a/src/pkg/crypto/tls/handshake_client_test.go b/src/pkg/crypto/tls/handshake_client_test.go deleted file mode 100644 index e5eaa7de2..000000000 --- a/src/pkg/crypto/tls/handshake_client_test.go +++ /dev/null @@ -1,490 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tls - -import ( - "bytes" - "crypto/ecdsa" - "crypto/rsa" - "crypto/x509" - "encoding/pem" - "fmt" - "io" - "net" - "os" - "os/exec" - "path/filepath" - "strconv" - "testing" - "time" -) - -// Note: see comment in handshake_test.go for details of how the reference -// tests work. - -// blockingSource is an io.Reader that blocks a Read call until it's closed. -type blockingSource chan bool - -func (b blockingSource) Read([]byte) (n int, err error) { - <-b - return 0, io.EOF -} - -// clientTest represents a test of the TLS client handshake against a reference -// implementation. -type clientTest struct { - // name is a freeform string identifying the test and the file in which - // the expected results will be stored. - name string - // command, if not empty, contains a series of arguments for the - // command to run for the reference server. - command []string - // config, if not nil, contains a custom Config to use for this test. - config *Config - // cert, if not empty, contains a DER-encoded certificate for the - // reference server. - cert []byte - // key, if not nil, contains either a *rsa.PrivateKey or - // *ecdsa.PrivateKey which is the private key for the reference server. - key interface{} - // validate, if not nil, is a function that will be called with the - // ConnectionState of the resulting connection. It returns a non-nil - // error if the ConnectionState is unacceptable. - validate func(ConnectionState) error -} - -var defaultServerCommand = []string{"openssl", "s_server"} - -// connFromCommand starts the reference server process, connects to it and -// returns a recordingConn for the connection. The stdin return value is a -// blockingSource for the stdin of the child process. It must be closed before -// Waiting for child. -func (test *clientTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, stdin blockingSource, err error) { - cert := testRSACertificate - if len(test.cert) > 0 { - cert = test.cert - } - certPath := tempFile(string(cert)) - defer os.Remove(certPath) - - var key interface{} = testRSAPrivateKey - if test.key != nil { - key = test.key - } - var pemType string - var derBytes []byte - switch key := key.(type) { - case *rsa.PrivateKey: - pemType = "RSA" - derBytes = x509.MarshalPKCS1PrivateKey(key) - case *ecdsa.PrivateKey: - pemType = "EC" - var err error - derBytes, err = x509.MarshalECPrivateKey(key) - if err != nil { - panic(err) - } - default: - panic("unknown key type") - } - - var pemOut bytes.Buffer - pem.Encode(&pemOut, &pem.Block{Type: pemType + " PRIVATE KEY", Bytes: derBytes}) - - keyPath := tempFile(string(pemOut.Bytes())) - defer os.Remove(keyPath) - - var command []string - if len(test.command) > 0 { - command = append(command, test.command...) - } else { - command = append(command, defaultServerCommand...) - } - command = append(command, "-cert", certPath, "-certform", "DER", "-key", keyPath) - // serverPort contains the port that OpenSSL will listen on. OpenSSL - // can't take "0" as an argument here so we have to pick a number and - // hope that it's not in use on the machine. Since this only occurs - // when -update is given and thus when there's a human watching the - // test, this isn't too bad. - const serverPort = 24323 - command = append(command, "-accept", strconv.Itoa(serverPort)) - - cmd := exec.Command(command[0], command[1:]...) - stdin = blockingSource(make(chan bool)) - cmd.Stdin = stdin - var out bytes.Buffer - cmd.Stdout = &out - cmd.Stderr = &out - if err := cmd.Start(); err != nil { - return nil, nil, nil, err - } - - // OpenSSL does print an "ACCEPT" banner, but it does so *before* - // opening the listening socket, so we can't use that to wait until it - // has started listening. Thus we are forced to poll until we get a - // connection. - var tcpConn net.Conn - for i := uint(0); i < 5; i++ { - var err error - tcpConn, err = net.DialTCP("tcp", nil, &net.TCPAddr{ - IP: net.IPv4(127, 0, 0, 1), - Port: serverPort, - }) - if err == nil { - break - } - time.Sleep((1 << i) * 5 * time.Millisecond) - } - if tcpConn == nil { - close(stdin) - out.WriteTo(os.Stdout) - cmd.Process.Kill() - return nil, nil, nil, cmd.Wait() - } - - record := &recordingConn{ - Conn: tcpConn, - } - - return record, cmd, stdin, nil -} - -func (test *clientTest) dataPath() string { - return filepath.Join("testdata", "Client-"+test.name) -} - -func (test *clientTest) loadData() (flows [][]byte, err error) { - in, err := os.Open(test.dataPath()) - if err != nil { - return nil, err - } - defer in.Close() - return parseTestData(in) -} - -func (test *clientTest) run(t *testing.T, write bool) { - var clientConn, serverConn net.Conn - var recordingConn *recordingConn - var childProcess *exec.Cmd - var stdin blockingSource - - if write { - var err error - recordingConn, childProcess, stdin, err = test.connFromCommand() - if err != nil { - t.Fatalf("Failed to start subcommand: %s", err) - } - clientConn = recordingConn - } else { - clientConn, serverConn = net.Pipe() - } - - config := test.config - if config == nil { - config = testConfig - } - client := Client(clientConn, config) - - doneChan := make(chan bool) - go func() { - if _, err := client.Write([]byte("hello\n")); err != nil { - t.Logf("Client.Write failed: %s", err) - } - if test.validate != nil { - if err := test.validate(client.ConnectionState()); err != nil { - t.Logf("validate callback returned error: %s", err) - } - } - client.Close() - clientConn.Close() - doneChan <- true - }() - - if !write { - flows, err := test.loadData() - if err != nil { - t.Fatalf("%s: failed to load data from %s: %v", test.name, test.dataPath(), err) - } - for i, b := range flows { - if i%2 == 1 { - serverConn.Write(b) - continue - } - bb := make([]byte, len(b)) - _, err := io.ReadFull(serverConn, bb) - if err != nil { - t.Fatalf("%s #%d: %s", test.name, i, err) - } - if !bytes.Equal(b, bb) { - t.Fatalf("%s #%d: mismatch on read: got:%x want:%x", test.name, i, bb, b) - } - } - serverConn.Close() - } - - <-doneChan - - if write { - path := test.dataPath() - out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) - if err != nil { - t.Fatalf("Failed to create output file: %s", err) - } - defer out.Close() - recordingConn.Close() - close(stdin) - childProcess.Process.Kill() - childProcess.Wait() - if len(recordingConn.flows) < 3 { - childProcess.Stdout.(*bytes.Buffer).WriteTo(os.Stdout) - t.Fatalf("Client connection didn't work") - } - recordingConn.WriteTo(out) - fmt.Printf("Wrote %s\n", path) - } -} - -func runClientTestForVersion(t *testing.T, template *clientTest, prefix, option string) { - test := *template - test.name = prefix + test.name - if len(test.command) == 0 { - test.command = defaultClientCommand - } - test.command = append([]string(nil), test.command...) - test.command = append(test.command, option) - test.run(t, *update) -} - -func runClientTestTLS10(t *testing.T, template *clientTest) { - runClientTestForVersion(t, template, "TLSv10-", "-tls1") -} - -func runClientTestTLS11(t *testing.T, template *clientTest) { - runClientTestForVersion(t, template, "TLSv11-", "-tls1_1") -} - -func runClientTestTLS12(t *testing.T, template *clientTest) { - runClientTestForVersion(t, template, "TLSv12-", "-tls1_2") -} - -func TestHandshakeClientRSARC4(t *testing.T) { - test := &clientTest{ - name: "RSA-RC4", - command: []string{"openssl", "s_server", "-cipher", "RC4-SHA"}, - } - runClientTestTLS10(t, test) - runClientTestTLS11(t, test) - runClientTestTLS12(t, test) -} - -func TestHandshakeClientECDHERSAAES(t *testing.T) { - test := &clientTest{ - name: "ECDHE-RSA-AES", - command: []string{"openssl", "s_server", "-cipher", "ECDHE-RSA-AES128-SHA"}, - } - runClientTestTLS10(t, test) - runClientTestTLS11(t, test) - runClientTestTLS12(t, test) -} - -func TestHandshakeClientECDHEECDSAAES(t *testing.T) { - test := &clientTest{ - name: "ECDHE-ECDSA-AES", - command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-SHA"}, - cert: testECDSACertificate, - key: testECDSAPrivateKey, - } - runClientTestTLS10(t, test) - runClientTestTLS11(t, test) - runClientTestTLS12(t, test) -} - -func TestHandshakeClientECDHEECDSAAESGCM(t *testing.T) { - test := &clientTest{ - name: "ECDHE-ECDSA-AES-GCM", - command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-GCM-SHA256"}, - cert: testECDSACertificate, - key: testECDSAPrivateKey, - } - runClientTestTLS12(t, test) -} - -func TestHandshakeClientCertRSA(t *testing.T) { - config := *testConfig - cert, _ := X509KeyPair([]byte(clientCertificatePEM), []byte(clientKeyPEM)) - config.Certificates = []Certificate{cert} - - test := &clientTest{ - name: "ClientCert-RSA-RSA", - command: []string{"openssl", "s_server", "-cipher", "RC4-SHA", "-verify", "1"}, - config: &config, - } - - runClientTestTLS10(t, test) - runClientTestTLS12(t, test) - - test = &clientTest{ - name: "ClientCert-RSA-ECDSA", - command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-SHA", "-verify", "1"}, - config: &config, - cert: testECDSACertificate, - key: testECDSAPrivateKey, - } - - runClientTestTLS10(t, test) - runClientTestTLS12(t, test) -} - -func TestHandshakeClientCertECDSA(t *testing.T) { - config := *testConfig - cert, _ := X509KeyPair([]byte(clientECDSACertificatePEM), []byte(clientECDSAKeyPEM)) - config.Certificates = []Certificate{cert} - - test := &clientTest{ - name: "ClientCert-ECDSA-RSA", - command: []string{"openssl", "s_server", "-cipher", "RC4-SHA", "-verify", "1"}, - config: &config, - } - - runClientTestTLS10(t, test) - runClientTestTLS12(t, test) - - test = &clientTest{ - name: "ClientCert-ECDSA-ECDSA", - command: []string{"openssl", "s_server", "-cipher", "ECDHE-ECDSA-AES128-SHA", "-verify", "1"}, - config: &config, - cert: testECDSACertificate, - key: testECDSAPrivateKey, - } - - runClientTestTLS10(t, test) - runClientTestTLS12(t, test) -} - -func TestClientResumption(t *testing.T) { - serverConfig := &Config{ - CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA}, - Certificates: testConfig.Certificates, - } - clientConfig := &Config{ - CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, - InsecureSkipVerify: true, - ClientSessionCache: NewLRUClientSessionCache(32), - } - - testResumeState := func(test string, didResume bool) { - hs, err := testHandshake(clientConfig, serverConfig) - if err != nil { - t.Fatalf("%s: handshake failed: %s", test, err) - } - if hs.DidResume != didResume { - t.Fatalf("%s resumed: %v, expected: %v", test, hs.DidResume, didResume) - } - } - - testResumeState("Handshake", false) - testResumeState("Resume", true) - - if _, err := io.ReadFull(serverConfig.rand(), serverConfig.SessionTicketKey[:]); err != nil { - t.Fatalf("Failed to invalidate SessionTicketKey") - } - testResumeState("InvalidSessionTicketKey", false) - testResumeState("ResumeAfterInvalidSessionTicketKey", true) - - clientConfig.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_RC4_128_SHA} - testResumeState("DifferentCipherSuite", false) - testResumeState("DifferentCipherSuiteRecovers", true) - - clientConfig.ClientSessionCache = nil - testResumeState("WithoutSessionCache", false) -} - -func TestLRUClientSessionCache(t *testing.T) { - // Initialize cache of capacity 4. - cache := NewLRUClientSessionCache(4) - cs := make([]ClientSessionState, 6) - keys := []string{"0", "1", "2", "3", "4", "5", "6"} - - // Add 4 entries to the cache and look them up. - for i := 0; i < 4; i++ { - cache.Put(keys[i], &cs[i]) - } - for i := 0; i < 4; i++ { - if s, ok := cache.Get(keys[i]); !ok || s != &cs[i] { - t.Fatalf("session cache failed lookup for added key: %s", keys[i]) - } - } - - // Add 2 more entries to the cache. First 2 should be evicted. - for i := 4; i < 6; i++ { - cache.Put(keys[i], &cs[i]) - } - for i := 0; i < 2; i++ { - if s, ok := cache.Get(keys[i]); ok || s != nil { - t.Fatalf("session cache should have evicted key: %s", keys[i]) - } - } - - // Touch entry 2. LRU should evict 3 next. - cache.Get(keys[2]) - cache.Put(keys[0], &cs[0]) - if s, ok := cache.Get(keys[3]); ok || s != nil { - t.Fatalf("session cache should have evicted key 3") - } - - // Update entry 0 in place. - cache.Put(keys[0], &cs[3]) - if s, ok := cache.Get(keys[0]); !ok || s != &cs[3] { - t.Fatalf("session cache failed update for key 0") - } - - // Adding a nil entry is valid. - cache.Put(keys[0], nil) - if s, ok := cache.Get(keys[0]); !ok || s != nil { - t.Fatalf("failed to add nil entry to cache") - } -} - -func TestHandshakeClientALPNMatch(t *testing.T) { - config := *testConfig - config.NextProtos = []string{"proto2", "proto1"} - - test := &clientTest{ - name: "ALPN", - // Note that this needs OpenSSL 1.0.2 because that is the first - // version that supports the -alpn flag. - command: []string{"openssl", "s_server", "-alpn", "proto1,proto2"}, - config: &config, - validate: func(state ConnectionState) error { - // The server's preferences should override the client. - if state.NegotiatedProtocol != "proto1" { - return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol) - } - return nil - }, - } - runClientTestTLS12(t, test) -} - -func TestHandshakeClientALPNNoMatch(t *testing.T) { - config := *testConfig - config.NextProtos = []string{"proto3"} - - test := &clientTest{ - name: "ALPN-NoMatch", - // Note that this needs OpenSSL 1.0.2 because that is the first - // version that supports the -alpn flag. - command: []string{"openssl", "s_server", "-alpn", "proto1,proto2"}, - config: &config, - validate: func(state ConnectionState) error { - // There's no overlap so OpenSSL will not select a protocol. - if state.NegotiatedProtocol != "" { - return fmt.Errorf("Got protocol %q, wanted ''", state.NegotiatedProtocol) - } - return nil - }, - } - runClientTestTLS12(t, test) -} diff --git a/src/pkg/crypto/tls/handshake_messages.go b/src/pkg/crypto/tls/handshake_messages.go deleted file mode 100644 index 5d14871a3..000000000 --- a/src/pkg/crypto/tls/handshake_messages.go +++ /dev/null @@ -1,1438 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tls - -import "bytes" - -type clientHelloMsg struct { - raw []byte - vers uint16 - random []byte - sessionId []byte - cipherSuites []uint16 - compressionMethods []uint8 - nextProtoNeg bool - serverName string - ocspStapling bool - supportedCurves []CurveID - supportedPoints []uint8 - ticketSupported bool - sessionTicket []uint8 - signatureAndHashes []signatureAndHash - secureRenegotiation bool - alpnProtocols []string -} - -func (m *clientHelloMsg) equal(i interface{}) bool { - m1, ok := i.(*clientHelloMsg) - if !ok { - return false - } - - return bytes.Equal(m.raw, m1.raw) && - m.vers == m1.vers && - bytes.Equal(m.random, m1.random) && - bytes.Equal(m.sessionId, m1.sessionId) && - eqUint16s(m.cipherSuites, m1.cipherSuites) && - bytes.Equal(m.compressionMethods, m1.compressionMethods) && - m.nextProtoNeg == m1.nextProtoNeg && - m.serverName == m1.serverName && - m.ocspStapling == m1.ocspStapling && - eqCurveIDs(m.supportedCurves, m1.supportedCurves) && - bytes.Equal(m.supportedPoints, m1.supportedPoints) && - m.ticketSupported == m1.ticketSupported && - bytes.Equal(m.sessionTicket, m1.sessionTicket) && - eqSignatureAndHashes(m.signatureAndHashes, m1.signatureAndHashes) && - m.secureRenegotiation == m1.secureRenegotiation && - eqStrings(m.alpnProtocols, m1.alpnProtocols) -} - -func (m *clientHelloMsg) marshal() []byte { - if m.raw != nil { - return m.raw - } - - length := 2 + 32 + 1 + len(m.sessionId) + 2 + len(m.cipherSuites)*2 + 1 + len(m.compressionMethods) - numExtensions := 0 - extensionsLength := 0 - if m.nextProtoNeg { - numExtensions++ - } - if m.ocspStapling { - extensionsLength += 1 + 2 + 2 - numExtensions++ - } - if len(m.serverName) > 0 { - extensionsLength += 5 + len(m.serverName) - numExtensions++ - } - if len(m.supportedCurves) > 0 { - extensionsLength += 2 + 2*len(m.supportedCurves) - numExtensions++ - } - if len(m.supportedPoints) > 0 { - extensionsLength += 1 + len(m.supportedPoints) - numExtensions++ - } - if m.ticketSupported { - extensionsLength += len(m.sessionTicket) - numExtensions++ - } - if len(m.signatureAndHashes) > 0 { - extensionsLength += 2 + 2*len(m.signatureAndHashes) - numExtensions++ - } - if m.secureRenegotiation { - extensionsLength += 1 - numExtensions++ - } - if len(m.alpnProtocols) > 0 { - extensionsLength += 2 - for _, s := range m.alpnProtocols { - if l := len(s); l == 0 || l > 255 { - panic("invalid ALPN protocol") - } - extensionsLength++ - extensionsLength += len(s) - } - numExtensions++ - } - if numExtensions > 0 { - extensionsLength += 4 * numExtensions - length += 2 + extensionsLength - } - - x := make([]byte, 4+length) - x[0] = typeClientHello - x[1] = uint8(length >> 16) - x[2] = uint8(length >> 8) - x[3] = uint8(length) - x[4] = uint8(m.vers >> 8) - x[5] = uint8(m.vers) - copy(x[6:38], m.random) - x[38] = uint8(len(m.sessionId)) - copy(x[39:39+len(m.sessionId)], m.sessionId) - y := x[39+len(m.sessionId):] - y[0] = uint8(len(m.cipherSuites) >> 7) - y[1] = uint8(len(m.cipherSuites) << 1) - for i, suite := range m.cipherSuites { - y[2+i*2] = uint8(suite >> 8) - y[3+i*2] = uint8(suite) - } - z := y[2+len(m.cipherSuites)*2:] - z[0] = uint8(len(m.compressionMethods)) - copy(z[1:], m.compressionMethods) - - z = z[1+len(m.compressionMethods):] - if numExtensions > 0 { - z[0] = byte(extensionsLength >> 8) - z[1] = byte(extensionsLength) - z = z[2:] - } - if m.nextProtoNeg { - z[0] = byte(extensionNextProtoNeg >> 8) - z[1] = byte(extensionNextProtoNeg & 0xff) - // The length is always 0 - z = z[4:] - } - if len(m.serverName) > 0 { - z[0] = byte(extensionServerName >> 8) - z[1] = byte(extensionServerName & 0xff) - l := len(m.serverName) + 5 - z[2] = byte(l >> 8) - z[3] = byte(l) - z = z[4:] - - // RFC 3546, section 3.1 - // - // struct { - // NameType name_type; - // select (name_type) { - // case host_name: HostName; - // } name; - // } ServerName; - // - // enum { - // host_name(0), (255) - // } NameType; - // - // opaque HostName<1..2^16-1>; - // - // struct { - // ServerName server_name_list<1..2^16-1> - // } ServerNameList; - - z[0] = byte((len(m.serverName) + 3) >> 8) - z[1] = byte(len(m.serverName) + 3) - z[3] = byte(len(m.serverName) >> 8) - z[4] = byte(len(m.serverName)) - copy(z[5:], []byte(m.serverName)) - z = z[l:] - } - if m.ocspStapling { - // RFC 4366, section 3.6 - z[0] = byte(extensionStatusRequest >> 8) - z[1] = byte(extensionStatusRequest) - z[2] = 0 - z[3] = 5 - z[4] = 1 // OCSP type - // Two zero valued uint16s for the two lengths. - z = z[9:] - } - if len(m.supportedCurves) > 0 { - // http://tools.ietf.org/html/rfc4492#section-5.5.1 - z[0] = byte(extensionSupportedCurves >> 8) - z[1] = byte(extensionSupportedCurves) - l := 2 + 2*len(m.supportedCurves) - z[2] = byte(l >> 8) - z[3] = byte(l) - l -= 2 - z[4] = byte(l >> 8) - z[5] = byte(l) - z = z[6:] - for _, curve := range m.supportedCurves { - z[0] = byte(curve >> 8) - z[1] = byte(curve) - z = z[2:] - } - } - if len(m.supportedPoints) > 0 { - // http://tools.ietf.org/html/rfc4492#section-5.5.2 - z[0] = byte(extensionSupportedPoints >> 8) - z[1] = byte(extensionSupportedPoints) - l := 1 + len(m.supportedPoints) - z[2] = byte(l >> 8) - z[3] = byte(l) - l-- - z[4] = byte(l) - z = z[5:] - for _, pointFormat := range m.supportedPoints { - z[0] = byte(pointFormat) - z = z[1:] - } - } - if m.ticketSupported { - // http://tools.ietf.org/html/rfc5077#section-3.2 - z[0] = byte(extensionSessionTicket >> 8) - z[1] = byte(extensionSessionTicket) - l := len(m.sessionTicket) - z[2] = byte(l >> 8) - z[3] = byte(l) - z = z[4:] - copy(z, m.sessionTicket) - z = z[len(m.sessionTicket):] - } - if len(m.signatureAndHashes) > 0 { - // https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 - z[0] = byte(extensionSignatureAlgorithms >> 8) - z[1] = byte(extensionSignatureAlgorithms) - l := 2 + 2*len(m.signatureAndHashes) - z[2] = byte(l >> 8) - z[3] = byte(l) - z = z[4:] - - l -= 2 - z[0] = byte(l >> 8) - z[1] = byte(l) - z = z[2:] - for _, sigAndHash := range m.signatureAndHashes { - z[0] = sigAndHash.hash - z[1] = sigAndHash.signature - z = z[2:] - } - } - if m.secureRenegotiation { - z[0] = byte(extensionRenegotiationInfo >> 8) - z[1] = byte(extensionRenegotiationInfo & 0xff) - z[2] = 0 - z[3] = 1 - z = z[5:] - } - if len(m.alpnProtocols) > 0 { - z[0] = byte(extensionALPN >> 8) - z[1] = byte(extensionALPN & 0xff) - lengths := z[2:] - z = z[6:] - - stringsLength := 0 - for _, s := range m.alpnProtocols { - l := len(s) - z[0] = byte(l) - copy(z[1:], s) - z = z[1+l:] - stringsLength += 1 + l - } - - lengths[2] = byte(stringsLength >> 8) - lengths[3] = byte(stringsLength) - stringsLength += 2 - lengths[0] = byte(stringsLength >> 8) - lengths[1] = byte(stringsLength) - } - - m.raw = x - - return x -} - -func (m *clientHelloMsg) unmarshal(data []byte) bool { - if len(data) < 42 { - return false - } - m.raw = data - m.vers = uint16(data[4])<<8 | uint16(data[5]) - m.random = data[6:38] - sessionIdLen := int(data[38]) - if sessionIdLen > 32 || len(data) < 39+sessionIdLen { - return false - } - m.sessionId = data[39 : 39+sessionIdLen] - data = data[39+sessionIdLen:] - if len(data) < 2 { - return false - } - // cipherSuiteLen is the number of bytes of cipher suite numbers. Since - // they are uint16s, the number must be even. - cipherSuiteLen := int(data[0])<<8 | int(data[1]) - if cipherSuiteLen%2 == 1 || len(data) < 2+cipherSuiteLen { - return false - } - numCipherSuites := cipherSuiteLen / 2 - m.cipherSuites = make([]uint16, numCipherSuites) - for i := 0; i < numCipherSuites; i++ { - m.cipherSuites[i] = uint16(data[2+2*i])<<8 | uint16(data[3+2*i]) - if m.cipherSuites[i] == scsvRenegotiation { - m.secureRenegotiation = true - } - } - data = data[2+cipherSuiteLen:] - if len(data) < 1 { - return false - } - compressionMethodsLen := int(data[0]) - if len(data) < 1+compressionMethodsLen { - return false - } - m.compressionMethods = data[1 : 1+compressionMethodsLen] - - data = data[1+compressionMethodsLen:] - - m.nextProtoNeg = false - m.serverName = "" - m.ocspStapling = false - m.ticketSupported = false - m.sessionTicket = nil - m.signatureAndHashes = nil - m.alpnProtocols = nil - - if len(data) == 0 { - // ClientHello is optionally followed by extension data - return true - } - if len(data) < 2 { - return false - } - - extensionsLength := int(data[0])<<8 | int(data[1]) - data = data[2:] - if extensionsLength != len(data) { - return false - } - - for len(data) != 0 { - if len(data) < 4 { - return false - } - extension := uint16(data[0])<<8 | uint16(data[1]) - length := int(data[2])<<8 | int(data[3]) - data = data[4:] - if len(data) < length { - return false - } - - switch extension { - case extensionServerName: - if length < 2 { - return false - } - numNames := int(data[0])<<8 | int(data[1]) - d := data[2:] - for i := 0; i < numNames; i++ { - if len(d) < 3 { - return false - } - nameType := d[0] - nameLen := int(d[1])<<8 | int(d[2]) - d = d[3:] - if len(d) < nameLen { - return false - } - if nameType == 0 { - m.serverName = string(d[0:nameLen]) - break - } - d = d[nameLen:] - } - case extensionNextProtoNeg: - if length > 0 { - return false - } - m.nextProtoNeg = true - case extensionStatusRequest: - m.ocspStapling = length > 0 && data[0] == statusTypeOCSP - case extensionSupportedCurves: - // http://tools.ietf.org/html/rfc4492#section-5.5.1 - if length < 2 { - return false - } - l := int(data[0])<<8 | int(data[1]) - if l%2 == 1 || length != l+2 { - return false - } - numCurves := l / 2 - m.supportedCurves = make([]CurveID, numCurves) - d := data[2:] - for i := 0; i < numCurves; i++ { - m.supportedCurves[i] = CurveID(d[0])<<8 | CurveID(d[1]) - d = d[2:] - } - case extensionSupportedPoints: - // http://tools.ietf.org/html/rfc4492#section-5.5.2 - if length < 1 { - return false - } - l := int(data[0]) - if length != l+1 { - return false - } - m.supportedPoints = make([]uint8, l) - copy(m.supportedPoints, data[1:]) - case extensionSessionTicket: - // http://tools.ietf.org/html/rfc5077#section-3.2 - m.ticketSupported = true - m.sessionTicket = data[:length] - case extensionSignatureAlgorithms: - // https://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 - if length < 2 || length&1 != 0 { - return false - } - l := int(data[0])<<8 | int(data[1]) - if l != length-2 { - return false - } - n := l / 2 - d := data[2:] - m.signatureAndHashes = make([]signatureAndHash, n) - for i := range m.signatureAndHashes { - m.signatureAndHashes[i].hash = d[0] - m.signatureAndHashes[i].signature = d[1] - d = d[2:] - } - case extensionRenegotiationInfo + 1: - if length != 1 || data[0] != 0 { - return false - } - m.secureRenegotiation = true - case extensionALPN: - if length < 2 { - return false - } - l := int(data[0])<<8 | int(data[1]) - if l != length-2 { - return false - } - d := data[2:length] - for len(d) != 0 { - stringLen := int(d[0]) - d = d[1:] - if stringLen == 0 || stringLen > len(d) { - return false - } - m.alpnProtocols = append(m.alpnProtocols, string(d[:stringLen])) - d = d[stringLen:] - } - } - data = data[length:] - } - - return true -} - -type serverHelloMsg struct { - raw []byte - vers uint16 - random []byte - sessionId []byte - cipherSuite uint16 - compressionMethod uint8 - nextProtoNeg bool - nextProtos []string - ocspStapling bool - ticketSupported bool - secureRenegotiation bool - alpnProtocol string -} - -func (m *serverHelloMsg) equal(i interface{}) bool { - m1, ok := i.(*serverHelloMsg) - if !ok { - return false - } - - return bytes.Equal(m.raw, m1.raw) && - m.vers == m1.vers && - bytes.Equal(m.random, m1.random) && - bytes.Equal(m.sessionId, m1.sessionId) && - m.cipherSuite == m1.cipherSuite && - m.compressionMethod == m1.compressionMethod && - m.nextProtoNeg == m1.nextProtoNeg && - eqStrings(m.nextProtos, m1.nextProtos) && - m.ocspStapling == m1.ocspStapling && - m.ticketSupported == m1.ticketSupported && - m.secureRenegotiation == m1.secureRenegotiation && - m.alpnProtocol == m1.alpnProtocol -} - -func (m *serverHelloMsg) marshal() []byte { - if m.raw != nil { - return m.raw - } - - length := 38 + len(m.sessionId) - numExtensions := 0 - extensionsLength := 0 - - nextProtoLen := 0 - if m.nextProtoNeg { - numExtensions++ - for _, v := range m.nextProtos { - nextProtoLen += len(v) - } - nextProtoLen += len(m.nextProtos) - extensionsLength += nextProtoLen - } - if m.ocspStapling { - numExtensions++ - } - if m.ticketSupported { - numExtensions++ - } - if m.secureRenegotiation { - extensionsLength += 1 - numExtensions++ - } - if alpnLen := len(m.alpnProtocol); alpnLen > 0 { - if alpnLen >= 256 { - panic("invalid ALPN protocol") - } - extensionsLength += 2 + 1 + alpnLen - numExtensions++ - } - - if numExtensions > 0 { - extensionsLength += 4 * numExtensions - length += 2 + extensionsLength - } - - x := make([]byte, 4+length) - x[0] = typeServerHello - x[1] = uint8(length >> 16) - x[2] = uint8(length >> 8) - x[3] = uint8(length) - x[4] = uint8(m.vers >> 8) - x[5] = uint8(m.vers) - copy(x[6:38], m.random) - x[38] = uint8(len(m.sessionId)) - copy(x[39:39+len(m.sessionId)], m.sessionId) - z := x[39+len(m.sessionId):] - z[0] = uint8(m.cipherSuite >> 8) - z[1] = uint8(m.cipherSuite) - z[2] = uint8(m.compressionMethod) - - z = z[3:] - if numExtensions > 0 { - z[0] = byte(extensionsLength >> 8) - z[1] = byte(extensionsLength) - z = z[2:] - } - if m.nextProtoNeg { - z[0] = byte(extensionNextProtoNeg >> 8) - z[1] = byte(extensionNextProtoNeg & 0xff) - z[2] = byte(nextProtoLen >> 8) - z[3] = byte(nextProtoLen) - z = z[4:] - - for _, v := range m.nextProtos { - l := len(v) - if l > 255 { - l = 255 - } - z[0] = byte(l) - copy(z[1:], []byte(v[0:l])) - z = z[1+l:] - } - } - if m.ocspStapling { - z[0] = byte(extensionStatusRequest >> 8) - z[1] = byte(extensionStatusRequest) - z = z[4:] - } - if m.ticketSupported { - z[0] = byte(extensionSessionTicket >> 8) - z[1] = byte(extensionSessionTicket) - z = z[4:] - } - if m.secureRenegotiation { - z[0] = byte(extensionRenegotiationInfo >> 8) - z[1] = byte(extensionRenegotiationInfo & 0xff) - z[2] = 0 - z[3] = 1 - z = z[5:] - } - if alpnLen := len(m.alpnProtocol); alpnLen > 0 { - z[0] = byte(extensionALPN >> 8) - z[1] = byte(extensionALPN & 0xff) - l := 2 + 1 + alpnLen - z[2] = byte(l >> 8) - z[3] = byte(l) - l -= 2 - z[4] = byte(l >> 8) - z[5] = byte(l) - l -= 1 - z[6] = byte(l) - copy(z[7:], []byte(m.alpnProtocol)) - z = z[7+alpnLen:] - } - - m.raw = x - - return x -} - -func (m *serverHelloMsg) unmarshal(data []byte) bool { - if len(data) < 42 { - return false - } - m.raw = data - m.vers = uint16(data[4])<<8 | uint16(data[5]) - m.random = data[6:38] - sessionIdLen := int(data[38]) - if sessionIdLen > 32 || len(data) < 39+sessionIdLen { - return false - } - m.sessionId = data[39 : 39+sessionIdLen] - data = data[39+sessionIdLen:] - if len(data) < 3 { - return false - } - m.cipherSuite = uint16(data[0])<<8 | uint16(data[1]) - m.compressionMethod = data[2] - data = data[3:] - - m.nextProtoNeg = false - m.nextProtos = nil - m.ocspStapling = false - m.ticketSupported = false - m.alpnProtocol = "" - - if len(data) == 0 { - // ServerHello is optionally followed by extension data - return true - } - if len(data) < 2 { - return false - } - - extensionsLength := int(data[0])<<8 | int(data[1]) - data = data[2:] - if len(data) != extensionsLength { - return false - } - - for len(data) != 0 { - if len(data) < 4 { - return false - } - extension := uint16(data[0])<<8 | uint16(data[1]) - length := int(data[2])<<8 | int(data[3]) - data = data[4:] - if len(data) < length { - return false - } - - switch extension { - case extensionNextProtoNeg: - m.nextProtoNeg = true - d := data[:length] - for len(d) > 0 { - l := int(d[0]) - d = d[1:] - if l == 0 || l > len(d) { - return false - } - m.nextProtos = append(m.nextProtos, string(d[:l])) - d = d[l:] - } - case extensionStatusRequest: - if length > 0 { - return false - } - m.ocspStapling = true - case extensionSessionTicket: - if length > 0 { - return false - } - m.ticketSupported = true - case extensionRenegotiationInfo: - if length != 1 || data[0] != 0 { - return false - } - m.secureRenegotiation = true - case extensionALPN: - d := data[:length] - if len(d) < 3 { - return false - } - l := int(d[0])<<8 | int(d[1]) - if l != len(d)-2 { - return false - } - d = d[2:] - l = int(d[0]) - if l != len(d)-1 { - return false - } - d = d[1:] - m.alpnProtocol = string(d) - } - data = data[length:] - } - - return true -} - -type certificateMsg struct { - raw []byte - certificates [][]byte -} - -func (m *certificateMsg) equal(i interface{}) bool { - m1, ok := i.(*certificateMsg) - if !ok { - return false - } - - return bytes.Equal(m.raw, m1.raw) && - eqByteSlices(m.certificates, m1.certificates) -} - -func (m *certificateMsg) marshal() (x []byte) { - if m.raw != nil { - return m.raw - } - - var i int - for _, slice := range m.certificates { - i += len(slice) - } - - length := 3 + 3*len(m.certificates) + i - x = make([]byte, 4+length) - x[0] = typeCertificate - x[1] = uint8(length >> 16) - x[2] = uint8(length >> 8) - x[3] = uint8(length) - - certificateOctets := length - 3 - x[4] = uint8(certificateOctets >> 16) - x[5] = uint8(certificateOctets >> 8) - x[6] = uint8(certificateOctets) - - y := x[7:] - for _, slice := range m.certificates { - y[0] = uint8(len(slice) >> 16) - y[1] = uint8(len(slice) >> 8) - y[2] = uint8(len(slice)) - copy(y[3:], slice) - y = y[3+len(slice):] - } - - m.raw = x - return -} - -func (m *certificateMsg) unmarshal(data []byte) bool { - if len(data) < 7 { - return false - } - - m.raw = data - certsLen := uint32(data[4])<<16 | uint32(data[5])<<8 | uint32(data[6]) - if uint32(len(data)) != certsLen+7 { - return false - } - - numCerts := 0 - d := data[7:] - for certsLen > 0 { - if len(d) < 4 { - return false - } - certLen := uint32(d[0])<<16 | uint32(d[1])<<8 | uint32(d[2]) - if uint32(len(d)) < 3+certLen { - return false - } - d = d[3+certLen:] - certsLen -= 3 + certLen - numCerts++ - } - - m.certificates = make([][]byte, numCerts) - d = data[7:] - for i := 0; i < numCerts; i++ { - certLen := uint32(d[0])<<16 | uint32(d[1])<<8 | uint32(d[2]) - m.certificates[i] = d[3 : 3+certLen] - d = d[3+certLen:] - } - - return true -} - -type serverKeyExchangeMsg struct { - raw []byte - key []byte -} - -func (m *serverKeyExchangeMsg) equal(i interface{}) bool { - m1, ok := i.(*serverKeyExchangeMsg) - if !ok { - return false - } - - return bytes.Equal(m.raw, m1.raw) && - bytes.Equal(m.key, m1.key) -} - -func (m *serverKeyExchangeMsg) marshal() []byte { - if m.raw != nil { - return m.raw - } - length := len(m.key) - x := make([]byte, length+4) - x[0] = typeServerKeyExchange - x[1] = uint8(length >> 16) - x[2] = uint8(length >> 8) - x[3] = uint8(length) - copy(x[4:], m.key) - - m.raw = x - return x -} - -func (m *serverKeyExchangeMsg) unmarshal(data []byte) bool { - m.raw = data - if len(data) < 4 { - return false - } - m.key = data[4:] - return true -} - -type certificateStatusMsg struct { - raw []byte - statusType uint8 - response []byte -} - -func (m *certificateStatusMsg) equal(i interface{}) bool { - m1, ok := i.(*certificateStatusMsg) - if !ok { - return false - } - - return bytes.Equal(m.raw, m1.raw) && - m.statusType == m1.statusType && - bytes.Equal(m.response, m1.response) -} - -func (m *certificateStatusMsg) marshal() []byte { - if m.raw != nil { - return m.raw - } - - var x []byte - if m.statusType == statusTypeOCSP { - x = make([]byte, 4+4+len(m.response)) - x[0] = typeCertificateStatus - l := len(m.response) + 4 - x[1] = byte(l >> 16) - x[2] = byte(l >> 8) - x[3] = byte(l) - x[4] = statusTypeOCSP - - l -= 4 - x[5] = byte(l >> 16) - x[6] = byte(l >> 8) - x[7] = byte(l) - copy(x[8:], m.response) - } else { - x = []byte{typeCertificateStatus, 0, 0, 1, m.statusType} - } - - m.raw = x - return x -} - -func (m *certificateStatusMsg) unmarshal(data []byte) bool { - m.raw = data - if len(data) < 5 { - return false - } - m.statusType = data[4] - - m.response = nil - if m.statusType == statusTypeOCSP { - if len(data) < 8 { - return false - } - respLen := uint32(data[5])<<16 | uint32(data[6])<<8 | uint32(data[7]) - if uint32(len(data)) != 4+4+respLen { - return false - } - m.response = data[8:] - } - return true -} - -type serverHelloDoneMsg struct{} - -func (m *serverHelloDoneMsg) equal(i interface{}) bool { - _, ok := i.(*serverHelloDoneMsg) - return ok -} - -func (m *serverHelloDoneMsg) marshal() []byte { - x := make([]byte, 4) - x[0] = typeServerHelloDone - return x -} - -func (m *serverHelloDoneMsg) unmarshal(data []byte) bool { - return len(data) == 4 -} - -type clientKeyExchangeMsg struct { - raw []byte - ciphertext []byte -} - -func (m *clientKeyExchangeMsg) equal(i interface{}) bool { - m1, ok := i.(*clientKeyExchangeMsg) - if !ok { - return false - } - - return bytes.Equal(m.raw, m1.raw) && - bytes.Equal(m.ciphertext, m1.ciphertext) -} - -func (m *clientKeyExchangeMsg) marshal() []byte { - if m.raw != nil { - return m.raw - } - length := len(m.ciphertext) - x := make([]byte, length+4) - x[0] = typeClientKeyExchange - x[1] = uint8(length >> 16) - x[2] = uint8(length >> 8) - x[3] = uint8(length) - copy(x[4:], m.ciphertext) - - m.raw = x - return x -} - -func (m *clientKeyExchangeMsg) unmarshal(data []byte) bool { - m.raw = data - if len(data) < 4 { - return false - } - l := int(data[1])<<16 | int(data[2])<<8 | int(data[3]) - if l != len(data)-4 { - return false - } - m.ciphertext = data[4:] - return true -} - -type finishedMsg struct { - raw []byte - verifyData []byte -} - -func (m *finishedMsg) equal(i interface{}) bool { - m1, ok := i.(*finishedMsg) - if !ok { - return false - } - - return bytes.Equal(m.raw, m1.raw) && - bytes.Equal(m.verifyData, m1.verifyData) -} - -func (m *finishedMsg) marshal() (x []byte) { - if m.raw != nil { - return m.raw - } - - x = make([]byte, 4+len(m.verifyData)) - x[0] = typeFinished - x[3] = byte(len(m.verifyData)) - copy(x[4:], m.verifyData) - m.raw = x - return -} - -func (m *finishedMsg) unmarshal(data []byte) bool { - m.raw = data - if len(data) < 4 { - return false - } - m.verifyData = data[4:] - return true -} - -type nextProtoMsg struct { - raw []byte - proto string -} - -func (m *nextProtoMsg) equal(i interface{}) bool { - m1, ok := i.(*nextProtoMsg) - if !ok { - return false - } - - return bytes.Equal(m.raw, m1.raw) && - m.proto == m1.proto -} - -func (m *nextProtoMsg) marshal() []byte { - if m.raw != nil { - return m.raw - } - l := len(m.proto) - if l > 255 { - l = 255 - } - - padding := 32 - (l+2)%32 - length := l + padding + 2 - x := make([]byte, length+4) - x[0] = typeNextProtocol - x[1] = uint8(length >> 16) - x[2] = uint8(length >> 8) - x[3] = uint8(length) - - y := x[4:] - y[0] = byte(l) - copy(y[1:], []byte(m.proto[0:l])) - y = y[1+l:] - y[0] = byte(padding) - - m.raw = x - - return x -} - -func (m *nextProtoMsg) unmarshal(data []byte) bool { - m.raw = data - - if len(data) < 5 { - return false - } - data = data[4:] - protoLen := int(data[0]) - data = data[1:] - if len(data) < protoLen { - return false - } - m.proto = string(data[0:protoLen]) - data = data[protoLen:] - - if len(data) < 1 { - return false - } - paddingLen := int(data[0]) - data = data[1:] - if len(data) != paddingLen { - return false - } - - return true -} - -type certificateRequestMsg struct { - raw []byte - // hasSignatureAndHash indicates whether this message includes a list - // of signature and hash functions. This change was introduced with TLS - // 1.2. - hasSignatureAndHash bool - - certificateTypes []byte - signatureAndHashes []signatureAndHash - certificateAuthorities [][]byte -} - -func (m *certificateRequestMsg) equal(i interface{}) bool { - m1, ok := i.(*certificateRequestMsg) - if !ok { - return false - } - - return bytes.Equal(m.raw, m1.raw) && - bytes.Equal(m.certificateTypes, m1.certificateTypes) && - eqByteSlices(m.certificateAuthorities, m1.certificateAuthorities) && - eqSignatureAndHashes(m.signatureAndHashes, m1.signatureAndHashes) -} - -func (m *certificateRequestMsg) marshal() (x []byte) { - if m.raw != nil { - return m.raw - } - - // See http://tools.ietf.org/html/rfc4346#section-7.4.4 - length := 1 + len(m.certificateTypes) + 2 - casLength := 0 - for _, ca := range m.certificateAuthorities { - casLength += 2 + len(ca) - } - length += casLength - - if m.hasSignatureAndHash { - length += 2 + 2*len(m.signatureAndHashes) - } - - x = make([]byte, 4+length) - x[0] = typeCertificateRequest - x[1] = uint8(length >> 16) - x[2] = uint8(length >> 8) - x[3] = uint8(length) - - x[4] = uint8(len(m.certificateTypes)) - - copy(x[5:], m.certificateTypes) - y := x[5+len(m.certificateTypes):] - - if m.hasSignatureAndHash { - n := len(m.signatureAndHashes) * 2 - y[0] = uint8(n >> 8) - y[1] = uint8(n) - y = y[2:] - for _, sigAndHash := range m.signatureAndHashes { - y[0] = sigAndHash.hash - y[1] = sigAndHash.signature - y = y[2:] - } - } - - y[0] = uint8(casLength >> 8) - y[1] = uint8(casLength) - y = y[2:] - for _, ca := range m.certificateAuthorities { - y[0] = uint8(len(ca) >> 8) - y[1] = uint8(len(ca)) - y = y[2:] - copy(y, ca) - y = y[len(ca):] - } - - m.raw = x - return -} - -func (m *certificateRequestMsg) unmarshal(data []byte) bool { - m.raw = data - - if len(data) < 5 { - return false - } - - length := uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3]) - if uint32(len(data))-4 != length { - return false - } - - numCertTypes := int(data[4]) - data = data[5:] - if numCertTypes == 0 || len(data) <= numCertTypes { - return false - } - - m.certificateTypes = make([]byte, numCertTypes) - if copy(m.certificateTypes, data) != numCertTypes { - return false - } - - data = data[numCertTypes:] - - if m.hasSignatureAndHash { - if len(data) < 2 { - return false - } - sigAndHashLen := uint16(data[0])<<8 | uint16(data[1]) - data = data[2:] - if sigAndHashLen&1 != 0 { - return false - } - if len(data) < int(sigAndHashLen) { - return false - } - numSigAndHash := sigAndHashLen / 2 - m.signatureAndHashes = make([]signatureAndHash, numSigAndHash) - for i := range m.signatureAndHashes { - m.signatureAndHashes[i].hash = data[0] - m.signatureAndHashes[i].signature = data[1] - data = data[2:] - } - } - - if len(data) < 2 { - return false - } - casLength := uint16(data[0])<<8 | uint16(data[1]) - data = data[2:] - if len(data) < int(casLength) { - return false - } - cas := make([]byte, casLength) - copy(cas, data) - data = data[casLength:] - - m.certificateAuthorities = nil - for len(cas) > 0 { - if len(cas) < 2 { - return false - } - caLen := uint16(cas[0])<<8 | uint16(cas[1]) - cas = cas[2:] - - if len(cas) < int(caLen) { - return false - } - - m.certificateAuthorities = append(m.certificateAuthorities, cas[:caLen]) - cas = cas[caLen:] - } - if len(data) > 0 { - return false - } - - return true -} - -type certificateVerifyMsg struct { - raw []byte - hasSignatureAndHash bool - signatureAndHash signatureAndHash - signature []byte -} - -func (m *certificateVerifyMsg) equal(i interface{}) bool { - m1, ok := i.(*certificateVerifyMsg) - if !ok { - return false - } - - return bytes.Equal(m.raw, m1.raw) && - m.hasSignatureAndHash == m1.hasSignatureAndHash && - m.signatureAndHash.hash == m1.signatureAndHash.hash && - m.signatureAndHash.signature == m1.signatureAndHash.signature && - bytes.Equal(m.signature, m1.signature) -} - -func (m *certificateVerifyMsg) marshal() (x []byte) { - if m.raw != nil { - return m.raw - } - - // See http://tools.ietf.org/html/rfc4346#section-7.4.8 - siglength := len(m.signature) - length := 2 + siglength - if m.hasSignatureAndHash { - length += 2 - } - x = make([]byte, 4+length) - x[0] = typeCertificateVerify - x[1] = uint8(length >> 16) - x[2] = uint8(length >> 8) - x[3] = uint8(length) - y := x[4:] - if m.hasSignatureAndHash { - y[0] = m.signatureAndHash.hash - y[1] = m.signatureAndHash.signature - y = y[2:] - } - y[0] = uint8(siglength >> 8) - y[1] = uint8(siglength) - copy(y[2:], m.signature) - - m.raw = x - - return -} - -func (m *certificateVerifyMsg) unmarshal(data []byte) bool { - m.raw = data - - if len(data) < 6 { - return false - } - - length := uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3]) - if uint32(len(data))-4 != length { - return false - } - - data = data[4:] - if m.hasSignatureAndHash { - m.signatureAndHash.hash = data[0] - m.signatureAndHash.signature = data[1] - data = data[2:] - } - - if len(data) < 2 { - return false - } - siglength := int(data[0])<<8 + int(data[1]) - data = data[2:] - if len(data) != siglength { - return false - } - - m.signature = data - - return true -} - -type newSessionTicketMsg struct { - raw []byte - ticket []byte -} - -func (m *newSessionTicketMsg) equal(i interface{}) bool { - m1, ok := i.(*newSessionTicketMsg) - if !ok { - return false - } - - return bytes.Equal(m.raw, m1.raw) && - bytes.Equal(m.ticket, m1.ticket) -} - -func (m *newSessionTicketMsg) marshal() (x []byte) { - if m.raw != nil { - return m.raw - } - - // See http://tools.ietf.org/html/rfc5077#section-3.3 - ticketLen := len(m.ticket) - length := 2 + 4 + ticketLen - x = make([]byte, 4+length) - x[0] = typeNewSessionTicket - x[1] = uint8(length >> 16) - x[2] = uint8(length >> 8) - x[3] = uint8(length) - x[8] = uint8(ticketLen >> 8) - x[9] = uint8(ticketLen) - copy(x[10:], m.ticket) - - m.raw = x - - return -} - -func (m *newSessionTicketMsg) unmarshal(data []byte) bool { - m.raw = data - - if len(data) < 10 { - return false - } - - length := uint32(data[1])<<16 | uint32(data[2])<<8 | uint32(data[3]) - if uint32(len(data))-4 != length { - return false - } - - ticketLen := int(data[8])<<8 + int(data[9]) - if len(data)-10 != ticketLen { - return false - } - - m.ticket = data[10:] - - return true -} - -func eqUint16s(x, y []uint16) bool { - if len(x) != len(y) { - return false - } - for i, v := range x { - if y[i] != v { - return false - } - } - return true -} - -func eqCurveIDs(x, y []CurveID) bool { - if len(x) != len(y) { - return false - } - for i, v := range x { - if y[i] != v { - return false - } - } - return true -} - -func eqStrings(x, y []string) bool { - if len(x) != len(y) { - return false - } - for i, v := range x { - if y[i] != v { - return false - } - } - return true -} - -func eqByteSlices(x, y [][]byte) bool { - if len(x) != len(y) { - return false - } - for i, v := range x { - if !bytes.Equal(v, y[i]) { - return false - } - } - return true -} - -func eqSignatureAndHashes(x, y []signatureAndHash) bool { - if len(x) != len(y) { - return false - } - for i, v := range x { - v2 := y[i] - if v.hash != v2.hash || v.signature != v2.signature { - return false - } - } - return true -} diff --git a/src/pkg/crypto/tls/handshake_messages_test.go b/src/pkg/crypto/tls/handshake_messages_test.go deleted file mode 100644 index a96e95c3f..000000000 --- a/src/pkg/crypto/tls/handshake_messages_test.go +++ /dev/null @@ -1,251 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tls - -import ( - "math/rand" - "reflect" - "testing" - "testing/quick" -) - -var tests = []interface{}{ - &clientHelloMsg{}, - &serverHelloMsg{}, - &finishedMsg{}, - - &certificateMsg{}, - &certificateRequestMsg{}, - &certificateVerifyMsg{}, - &certificateStatusMsg{}, - &clientKeyExchangeMsg{}, - &nextProtoMsg{}, - &newSessionTicketMsg{}, - &sessionState{}, -} - -type testMessage interface { - marshal() []byte - unmarshal([]byte) bool - equal(interface{}) bool -} - -func TestMarshalUnmarshal(t *testing.T) { - rand := rand.New(rand.NewSource(0)) - - for i, iface := range tests { - ty := reflect.ValueOf(iface).Type() - - n := 100 - if testing.Short() { - n = 5 - } - for j := 0; j < n; j++ { - v, ok := quick.Value(ty, rand) - if !ok { - t.Errorf("#%d: failed to create value", i) - break - } - - m1 := v.Interface().(testMessage) - marshaled := m1.marshal() - m2 := iface.(testMessage) - if !m2.unmarshal(marshaled) { - t.Errorf("#%d failed to unmarshal %#v %x", i, m1, marshaled) - break - } - m2.marshal() // to fill any marshal cache in the message - - if !m1.equal(m2) { - t.Errorf("#%d got:%#v want:%#v %x", i, m2, m1, marshaled) - break - } - - if i >= 3 { - // The first three message types (ClientHello, - // ServerHello and Finished) are allowed to - // have parsable prefixes because the extension - // data is optional and the length of the - // Finished varies across versions. - for j := 0; j < len(marshaled); j++ { - if m2.unmarshal(marshaled[0:j]) { - t.Errorf("#%d unmarshaled a prefix of length %d of %#v", i, j, m1) - break - } - } - } - } - } -} - -func TestFuzz(t *testing.T) { - rand := rand.New(rand.NewSource(0)) - for _, iface := range tests { - m := iface.(testMessage) - - for j := 0; j < 1000; j++ { - len := rand.Intn(100) - bytes := randomBytes(len, rand) - // This just looks for crashes due to bounds errors etc. - m.unmarshal(bytes) - } - } -} - -func randomBytes(n int, rand *rand.Rand) []byte { - r := make([]byte, n) - for i := 0; i < n; i++ { - r[i] = byte(rand.Int31()) - } - return r -} - -func randomString(n int, rand *rand.Rand) string { - b := randomBytes(n, rand) - return string(b) -} - -func (*clientHelloMsg) Generate(rand *rand.Rand, size int) reflect.Value { - m := &clientHelloMsg{} - m.vers = uint16(rand.Intn(65536)) - m.random = randomBytes(32, rand) - m.sessionId = randomBytes(rand.Intn(32), rand) - m.cipherSuites = make([]uint16, rand.Intn(63)+1) - for i := 0; i < len(m.cipherSuites); i++ { - m.cipherSuites[i] = uint16(rand.Int31()) - } - m.compressionMethods = randomBytes(rand.Intn(63)+1, rand) - if rand.Intn(10) > 5 { - m.nextProtoNeg = true - } - if rand.Intn(10) > 5 { - m.serverName = randomString(rand.Intn(255), rand) - } - m.ocspStapling = rand.Intn(10) > 5 - m.supportedPoints = randomBytes(rand.Intn(5)+1, rand) - m.supportedCurves = make([]CurveID, rand.Intn(5)+1) - for i := range m.supportedCurves { - m.supportedCurves[i] = CurveID(rand.Intn(30000)) - } - if rand.Intn(10) > 5 { - m.ticketSupported = true - if rand.Intn(10) > 5 { - m.sessionTicket = randomBytes(rand.Intn(300), rand) - } - } - if rand.Intn(10) > 5 { - m.signatureAndHashes = supportedSKXSignatureAlgorithms - } - m.alpnProtocols = make([]string, rand.Intn(5)) - for i := range m.alpnProtocols { - m.alpnProtocols[i] = randomString(rand.Intn(20)+1, rand) - } - - return reflect.ValueOf(m) -} - -func (*serverHelloMsg) Generate(rand *rand.Rand, size int) reflect.Value { - m := &serverHelloMsg{} - m.vers = uint16(rand.Intn(65536)) - m.random = randomBytes(32, rand) - m.sessionId = randomBytes(rand.Intn(32), rand) - m.cipherSuite = uint16(rand.Int31()) - m.compressionMethod = uint8(rand.Intn(256)) - - if rand.Intn(10) > 5 { - m.nextProtoNeg = true - - n := rand.Intn(10) - m.nextProtos = make([]string, n) - for i := 0; i < n; i++ { - m.nextProtos[i] = randomString(20, rand) - } - } - - if rand.Intn(10) > 5 { - m.ocspStapling = true - } - if rand.Intn(10) > 5 { - m.ticketSupported = true - } - m.alpnProtocol = randomString(rand.Intn(32)+1, rand) - - return reflect.ValueOf(m) -} - -func (*certificateMsg) Generate(rand *rand.Rand, size int) reflect.Value { - m := &certificateMsg{} - numCerts := rand.Intn(20) - m.certificates = make([][]byte, numCerts) - for i := 0; i < numCerts; i++ { - m.certificates[i] = randomBytes(rand.Intn(10)+1, rand) - } - return reflect.ValueOf(m) -} - -func (*certificateRequestMsg) Generate(rand *rand.Rand, size int) reflect.Value { - m := &certificateRequestMsg{} - m.certificateTypes = randomBytes(rand.Intn(5)+1, rand) - numCAs := rand.Intn(100) - m.certificateAuthorities = make([][]byte, numCAs) - for i := 0; i < numCAs; i++ { - m.certificateAuthorities[i] = randomBytes(rand.Intn(15)+1, rand) - } - return reflect.ValueOf(m) -} - -func (*certificateVerifyMsg) Generate(rand *rand.Rand, size int) reflect.Value { - m := &certificateVerifyMsg{} - m.signature = randomBytes(rand.Intn(15)+1, rand) - return reflect.ValueOf(m) -} - -func (*certificateStatusMsg) Generate(rand *rand.Rand, size int) reflect.Value { - m := &certificateStatusMsg{} - if rand.Intn(10) > 5 { - m.statusType = statusTypeOCSP - m.response = randomBytes(rand.Intn(10)+1, rand) - } else { - m.statusType = 42 - } - return reflect.ValueOf(m) -} - -func (*clientKeyExchangeMsg) Generate(rand *rand.Rand, size int) reflect.Value { - m := &clientKeyExchangeMsg{} - m.ciphertext = randomBytes(rand.Intn(1000)+1, rand) - return reflect.ValueOf(m) -} - -func (*finishedMsg) Generate(rand *rand.Rand, size int) reflect.Value { - m := &finishedMsg{} - m.verifyData = randomBytes(12, rand) - return reflect.ValueOf(m) -} - -func (*nextProtoMsg) Generate(rand *rand.Rand, size int) reflect.Value { - m := &nextProtoMsg{} - m.proto = randomString(rand.Intn(255), rand) - return reflect.ValueOf(m) -} - -func (*newSessionTicketMsg) Generate(rand *rand.Rand, size int) reflect.Value { - m := &newSessionTicketMsg{} - m.ticket = randomBytes(rand.Intn(4), rand) - return reflect.ValueOf(m) -} - -func (*sessionState) Generate(rand *rand.Rand, size int) reflect.Value { - s := &sessionState{} - s.vers = uint16(rand.Intn(10000)) - s.cipherSuite = uint16(rand.Intn(10000)) - s.masterSecret = randomBytes(rand.Intn(100), rand) - numCerts := rand.Intn(20) - s.certificates = make([][]byte, numCerts) - for i := 0; i < numCerts; i++ { - s.certificates[i] = randomBytes(rand.Intn(10)+1, rand) - } - return reflect.ValueOf(s) -} diff --git a/src/pkg/crypto/tls/handshake_server.go b/src/pkg/crypto/tls/handshake_server.go deleted file mode 100644 index 684ab288f..000000000 --- a/src/pkg/crypto/tls/handshake_server.go +++ /dev/null @@ -1,669 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tls - -import ( - "crypto" - "crypto/ecdsa" - "crypto/rsa" - "crypto/subtle" - "crypto/x509" - "encoding/asn1" - "errors" - "fmt" - "io" -) - -// serverHandshakeState contains details of a server handshake in progress. -// It's discarded once the handshake has completed. -type serverHandshakeState struct { - c *Conn - clientHello *clientHelloMsg - hello *serverHelloMsg - suite *cipherSuite - ellipticOk bool - ecdsaOk bool - sessionState *sessionState - finishedHash finishedHash - masterSecret []byte - certsFromClient [][]byte - cert *Certificate -} - -// serverHandshake performs a TLS handshake as a server. -func (c *Conn) serverHandshake() error { - config := c.config - - // If this is the first server handshake, we generate a random key to - // encrypt the tickets with. - config.serverInitOnce.Do(config.serverInit) - - hs := serverHandshakeState{ - c: c, - } - isResume, err := hs.readClientHello() - if err != nil { - return err - } - - // For an overview of TLS handshaking, see https://tools.ietf.org/html/rfc5246#section-7.3 - if isResume { - // The client has included a session ticket and so we do an abbreviated handshake. - if err := hs.doResumeHandshake(); err != nil { - return err - } - if err := hs.establishKeys(); err != nil { - return err - } - if err := hs.sendFinished(c.firstFinished[:]); err != nil { - return err - } - if err := hs.readFinished(nil); err != nil { - return err - } - c.didResume = true - } else { - // The client didn't include a session ticket, or it wasn't - // valid so we do a full handshake. - if err := hs.doFullHandshake(); err != nil { - return err - } - if err := hs.establishKeys(); err != nil { - return err - } - if err := hs.readFinished(c.firstFinished[:]); err != nil { - return err - } - if err := hs.sendSessionTicket(); err != nil { - return err - } - if err := hs.sendFinished(nil); err != nil { - return err - } - } - c.handshakeComplete = true - - return nil -} - -// readClientHello reads a ClientHello message from the client and decides -// whether we will perform session resumption. -func (hs *serverHandshakeState) readClientHello() (isResume bool, err error) { - config := hs.c.config - c := hs.c - - msg, err := c.readHandshake() - if err != nil { - return false, err - } - var ok bool - hs.clientHello, ok = msg.(*clientHelloMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return false, unexpectedMessageError(hs.clientHello, msg) - } - c.vers, ok = config.mutualVersion(hs.clientHello.vers) - if !ok { - c.sendAlert(alertProtocolVersion) - return false, fmt.Errorf("tls: client offered an unsupported, maximum protocol version of %x", hs.clientHello.vers) - } - c.haveVers = true - - hs.finishedHash = newFinishedHash(c.vers) - hs.finishedHash.Write(hs.clientHello.marshal()) - - hs.hello = new(serverHelloMsg) - - supportedCurve := false - preferredCurves := config.curvePreferences() -Curves: - for _, curve := range hs.clientHello.supportedCurves { - for _, supported := range preferredCurves { - if supported == curve { - supportedCurve = true - break Curves - } - } - } - - supportedPointFormat := false - for _, pointFormat := range hs.clientHello.supportedPoints { - if pointFormat == pointFormatUncompressed { - supportedPointFormat = true - break - } - } - hs.ellipticOk = supportedCurve && supportedPointFormat - - foundCompression := false - // We only support null compression, so check that the client offered it. - for _, compression := range hs.clientHello.compressionMethods { - if compression == compressionNone { - foundCompression = true - break - } - } - - if !foundCompression { - c.sendAlert(alertHandshakeFailure) - return false, errors.New("tls: client does not support uncompressed connections") - } - - hs.hello.vers = c.vers - hs.hello.random = make([]byte, 32) - _, err = io.ReadFull(config.rand(), hs.hello.random) - if err != nil { - c.sendAlert(alertInternalError) - return false, err - } - hs.hello.secureRenegotiation = hs.clientHello.secureRenegotiation - hs.hello.compressionMethod = compressionNone - if len(hs.clientHello.serverName) > 0 { - c.serverName = hs.clientHello.serverName - } - - if len(hs.clientHello.alpnProtocols) > 0 { - if selectedProto, fallback := mutualProtocol(hs.clientHello.alpnProtocols, c.config.NextProtos); !fallback { - hs.hello.alpnProtocol = selectedProto - c.clientProtocol = selectedProto - } - } else { - // Although sending an empty NPN extension is reasonable, Firefox has - // had a bug around this. Best to send nothing at all if - // config.NextProtos is empty. See - // https://code.google.com/p/go/issues/detail?id=5445. - if hs.clientHello.nextProtoNeg && len(config.NextProtos) > 0 { - hs.hello.nextProtoNeg = true - hs.hello.nextProtos = config.NextProtos - } - } - - if len(config.Certificates) == 0 { - c.sendAlert(alertInternalError) - return false, errors.New("tls: no certificates configured") - } - hs.cert = &config.Certificates[0] - if len(hs.clientHello.serverName) > 0 { - chi := &ClientHelloInfo{ - CipherSuites: hs.clientHello.cipherSuites, - ServerName: hs.clientHello.serverName, - SupportedCurves: hs.clientHello.supportedCurves, - SupportedPoints: hs.clientHello.supportedPoints, - } - if hs.cert, err = config.getCertificate(chi); err != nil { - c.sendAlert(alertInternalError) - return false, err - } - } - - _, hs.ecdsaOk = hs.cert.PrivateKey.(*ecdsa.PrivateKey) - - if hs.checkForResumption() { - return true, nil - } - - var preferenceList, supportedList []uint16 - if c.config.PreferServerCipherSuites { - preferenceList = c.config.cipherSuites() - supportedList = hs.clientHello.cipherSuites - } else { - preferenceList = hs.clientHello.cipherSuites - supportedList = c.config.cipherSuites() - } - - for _, id := range preferenceList { - if hs.suite = c.tryCipherSuite(id, supportedList, c.vers, hs.ellipticOk, hs.ecdsaOk); hs.suite != nil { - break - } - } - - if hs.suite == nil { - c.sendAlert(alertHandshakeFailure) - return false, errors.New("tls: no cipher suite supported by both client and server") - } - - return false, nil -} - -// checkForResumption returns true if we should perform resumption on this connection. -func (hs *serverHandshakeState) checkForResumption() bool { - c := hs.c - - var ok bool - if hs.sessionState, ok = c.decryptTicket(hs.clientHello.sessionTicket); !ok { - return false - } - - if hs.sessionState.vers > hs.clientHello.vers { - return false - } - if vers, ok := c.config.mutualVersion(hs.sessionState.vers); !ok || vers != hs.sessionState.vers { - return false - } - - cipherSuiteOk := false - // Check that the client is still offering the ciphersuite in the session. - for _, id := range hs.clientHello.cipherSuites { - if id == hs.sessionState.cipherSuite { - cipherSuiteOk = true - break - } - } - if !cipherSuiteOk { - return false - } - - // Check that we also support the ciphersuite from the session. - hs.suite = c.tryCipherSuite(hs.sessionState.cipherSuite, c.config.cipherSuites(), hs.sessionState.vers, hs.ellipticOk, hs.ecdsaOk) - if hs.suite == nil { - return false - } - - sessionHasClientCerts := len(hs.sessionState.certificates) != 0 - needClientCerts := c.config.ClientAuth == RequireAnyClientCert || c.config.ClientAuth == RequireAndVerifyClientCert - if needClientCerts && !sessionHasClientCerts { - return false - } - if sessionHasClientCerts && c.config.ClientAuth == NoClientCert { - return false - } - - return true -} - -func (hs *serverHandshakeState) doResumeHandshake() error { - c := hs.c - - hs.hello.cipherSuite = hs.suite.id - // We echo the client's session ID in the ServerHello to let it know - // that we're doing a resumption. - hs.hello.sessionId = hs.clientHello.sessionId - hs.finishedHash.Write(hs.hello.marshal()) - c.writeRecord(recordTypeHandshake, hs.hello.marshal()) - - if len(hs.sessionState.certificates) > 0 { - if _, err := hs.processCertsFromClient(hs.sessionState.certificates); err != nil { - return err - } - } - - hs.masterSecret = hs.sessionState.masterSecret - - return nil -} - -func (hs *serverHandshakeState) doFullHandshake() error { - config := hs.c.config - c := hs.c - - if hs.clientHello.ocspStapling && len(hs.cert.OCSPStaple) > 0 { - hs.hello.ocspStapling = true - } - - hs.hello.ticketSupported = hs.clientHello.ticketSupported && !config.SessionTicketsDisabled - hs.hello.cipherSuite = hs.suite.id - hs.finishedHash.Write(hs.hello.marshal()) - c.writeRecord(recordTypeHandshake, hs.hello.marshal()) - - certMsg := new(certificateMsg) - certMsg.certificates = hs.cert.Certificate - hs.finishedHash.Write(certMsg.marshal()) - c.writeRecord(recordTypeHandshake, certMsg.marshal()) - - if hs.hello.ocspStapling { - certStatus := new(certificateStatusMsg) - certStatus.statusType = statusTypeOCSP - certStatus.response = hs.cert.OCSPStaple - hs.finishedHash.Write(certStatus.marshal()) - c.writeRecord(recordTypeHandshake, certStatus.marshal()) - } - - keyAgreement := hs.suite.ka(c.vers) - skx, err := keyAgreement.generateServerKeyExchange(config, hs.cert, hs.clientHello, hs.hello) - if err != nil { - c.sendAlert(alertHandshakeFailure) - return err - } - if skx != nil { - hs.finishedHash.Write(skx.marshal()) - c.writeRecord(recordTypeHandshake, skx.marshal()) - } - - if config.ClientAuth >= RequestClientCert { - // Request a client certificate - certReq := new(certificateRequestMsg) - certReq.certificateTypes = []byte{ - byte(certTypeRSASign), - byte(certTypeECDSASign), - } - if c.vers >= VersionTLS12 { - certReq.hasSignatureAndHash = true - certReq.signatureAndHashes = supportedClientCertSignatureAlgorithms - } - - // An empty list of certificateAuthorities signals to - // the client that it may send any certificate in response - // to our request. When we know the CAs we trust, then - // we can send them down, so that the client can choose - // an appropriate certificate to give to us. - if config.ClientCAs != nil { - certReq.certificateAuthorities = config.ClientCAs.Subjects() - } - hs.finishedHash.Write(certReq.marshal()) - c.writeRecord(recordTypeHandshake, certReq.marshal()) - } - - helloDone := new(serverHelloDoneMsg) - hs.finishedHash.Write(helloDone.marshal()) - c.writeRecord(recordTypeHandshake, helloDone.marshal()) - - var pub crypto.PublicKey // public key for client auth, if any - - msg, err := c.readHandshake() - if err != nil { - return err - } - - var ok bool - // If we requested a client certificate, then the client must send a - // certificate message, even if it's empty. - if config.ClientAuth >= RequestClientCert { - if certMsg, ok = msg.(*certificateMsg); !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(certMsg, msg) - } - hs.finishedHash.Write(certMsg.marshal()) - - if len(certMsg.certificates) == 0 { - // The client didn't actually send a certificate - switch config.ClientAuth { - case RequireAnyClientCert, RequireAndVerifyClientCert: - c.sendAlert(alertBadCertificate) - return errors.New("tls: client didn't provide a certificate") - } - } - - pub, err = hs.processCertsFromClient(certMsg.certificates) - if err != nil { - return err - } - - msg, err = c.readHandshake() - if err != nil { - return err - } - } - - // Get client key exchange - ckx, ok := msg.(*clientKeyExchangeMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(ckx, msg) - } - hs.finishedHash.Write(ckx.marshal()) - - // If we received a client cert in response to our certificate request message, - // the client will send us a certificateVerifyMsg immediately after the - // clientKeyExchangeMsg. This message is a digest of all preceding - // handshake-layer messages that is signed using the private key corresponding - // to the client's certificate. This allows us to verify that the client is in - // possession of the private key of the certificate. - if len(c.peerCertificates) > 0 { - msg, err = c.readHandshake() - if err != nil { - return err - } - certVerify, ok := msg.(*certificateVerifyMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(certVerify, msg) - } - - switch key := pub.(type) { - case *ecdsa.PublicKey: - ecdsaSig := new(ecdsaSignature) - if _, err = asn1.Unmarshal(certVerify.signature, ecdsaSig); err != nil { - break - } - if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 { - err = errors.New("ECDSA signature contained zero or negative values") - break - } - digest, _, _ := hs.finishedHash.hashForClientCertificate(signatureECDSA) - if !ecdsa.Verify(key, digest, ecdsaSig.R, ecdsaSig.S) { - err = errors.New("ECDSA verification failure") - break - } - case *rsa.PublicKey: - digest, hashFunc, _ := hs.finishedHash.hashForClientCertificate(signatureRSA) - err = rsa.VerifyPKCS1v15(key, hashFunc, digest, certVerify.signature) - } - if err != nil { - c.sendAlert(alertBadCertificate) - return errors.New("could not validate signature of connection nonces: " + err.Error()) - } - - hs.finishedHash.Write(certVerify.marshal()) - } - - preMasterSecret, err := keyAgreement.processClientKeyExchange(config, hs.cert, ckx, c.vers) - if err != nil { - c.sendAlert(alertHandshakeFailure) - return err - } - hs.masterSecret = masterFromPreMasterSecret(c.vers, preMasterSecret, hs.clientHello.random, hs.hello.random) - - return nil -} - -func (hs *serverHandshakeState) establishKeys() error { - c := hs.c - - clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV := - keysFromMasterSecret(c.vers, hs.masterSecret, hs.clientHello.random, hs.hello.random, hs.suite.macLen, hs.suite.keyLen, hs.suite.ivLen) - - var clientCipher, serverCipher interface{} - var clientHash, serverHash macFunction - - if hs.suite.aead == nil { - clientCipher = hs.suite.cipher(clientKey, clientIV, true /* for reading */) - clientHash = hs.suite.mac(c.vers, clientMAC) - serverCipher = hs.suite.cipher(serverKey, serverIV, false /* not for reading */) - serverHash = hs.suite.mac(c.vers, serverMAC) - } else { - clientCipher = hs.suite.aead(clientKey, clientIV) - serverCipher = hs.suite.aead(serverKey, serverIV) - } - - c.in.prepareCipherSpec(c.vers, clientCipher, clientHash) - c.out.prepareCipherSpec(c.vers, serverCipher, serverHash) - - return nil -} - -func (hs *serverHandshakeState) readFinished(out []byte) error { - c := hs.c - - c.readRecord(recordTypeChangeCipherSpec) - if err := c.in.error(); err != nil { - return err - } - - if hs.hello.nextProtoNeg { - msg, err := c.readHandshake() - if err != nil { - return err - } - nextProto, ok := msg.(*nextProtoMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(nextProto, msg) - } - hs.finishedHash.Write(nextProto.marshal()) - c.clientProtocol = nextProto.proto - } - - msg, err := c.readHandshake() - if err != nil { - return err - } - clientFinished, ok := msg.(*finishedMsg) - if !ok { - c.sendAlert(alertUnexpectedMessage) - return unexpectedMessageError(clientFinished, msg) - } - - verify := hs.finishedHash.clientSum(hs.masterSecret) - if len(verify) != len(clientFinished.verifyData) || - subtle.ConstantTimeCompare(verify, clientFinished.verifyData) != 1 { - c.sendAlert(alertHandshakeFailure) - return errors.New("tls: client's Finished message is incorrect") - } - - hs.finishedHash.Write(clientFinished.marshal()) - copy(out, verify) - return nil -} - -func (hs *serverHandshakeState) sendSessionTicket() error { - if !hs.hello.ticketSupported { - return nil - } - - c := hs.c - m := new(newSessionTicketMsg) - - var err error - state := sessionState{ - vers: c.vers, - cipherSuite: hs.suite.id, - masterSecret: hs.masterSecret, - certificates: hs.certsFromClient, - } - m.ticket, err = c.encryptTicket(&state) - if err != nil { - return err - } - - hs.finishedHash.Write(m.marshal()) - c.writeRecord(recordTypeHandshake, m.marshal()) - - return nil -} - -func (hs *serverHandshakeState) sendFinished(out []byte) error { - c := hs.c - - c.writeRecord(recordTypeChangeCipherSpec, []byte{1}) - - finished := new(finishedMsg) - finished.verifyData = hs.finishedHash.serverSum(hs.masterSecret) - hs.finishedHash.Write(finished.marshal()) - c.writeRecord(recordTypeHandshake, finished.marshal()) - - c.cipherSuite = hs.suite.id - copy(out, finished.verifyData) - - return nil -} - -// processCertsFromClient takes a chain of client certificates either from a -// Certificates message or from a sessionState and verifies them. It returns -// the public key of the leaf certificate. -func (hs *serverHandshakeState) processCertsFromClient(certificates [][]byte) (crypto.PublicKey, error) { - c := hs.c - - hs.certsFromClient = certificates - certs := make([]*x509.Certificate, len(certificates)) - var err error - for i, asn1Data := range certificates { - if certs[i], err = x509.ParseCertificate(asn1Data); err != nil { - c.sendAlert(alertBadCertificate) - return nil, errors.New("tls: failed to parse client certificate: " + err.Error()) - } - } - - if c.config.ClientAuth >= VerifyClientCertIfGiven && len(certs) > 0 { - opts := x509.VerifyOptions{ - Roots: c.config.ClientCAs, - CurrentTime: c.config.time(), - Intermediates: x509.NewCertPool(), - KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, - } - - for _, cert := range certs[1:] { - opts.Intermediates.AddCert(cert) - } - - chains, err := certs[0].Verify(opts) - if err != nil { - c.sendAlert(alertBadCertificate) - return nil, errors.New("tls: failed to verify client's certificate: " + err.Error()) - } - - ok := false - for _, ku := range certs[0].ExtKeyUsage { - if ku == x509.ExtKeyUsageClientAuth { - ok = true - break - } - } - if !ok { - c.sendAlert(alertHandshakeFailure) - return nil, errors.New("tls: client's certificate's extended key usage doesn't permit it to be used for client authentication") - } - - c.verifiedChains = chains - } - - if len(certs) > 0 { - var pub crypto.PublicKey - switch key := certs[0].PublicKey.(type) { - case *ecdsa.PublicKey, *rsa.PublicKey: - pub = key - default: - c.sendAlert(alertUnsupportedCertificate) - return nil, fmt.Errorf("tls: client's certificate contains an unsupported public key of type %T", certs[0].PublicKey) - } - c.peerCertificates = certs - return pub, nil - } - - return nil, nil -} - -// tryCipherSuite returns a cipherSuite with the given id if that cipher suite -// is acceptable to use. -func (c *Conn) tryCipherSuite(id uint16, supportedCipherSuites []uint16, version uint16, ellipticOk, ecdsaOk bool) *cipherSuite { - for _, supported := range supportedCipherSuites { - if id == supported { - var candidate *cipherSuite - - for _, s := range cipherSuites { - if s.id == id { - candidate = s - break - } - } - if candidate == nil { - continue - } - // Don't select a ciphersuite which we can't - // support for this client. - if (candidate.flags&suiteECDHE != 0) && !ellipticOk { - continue - } - if (candidate.flags&suiteECDSA != 0) != ecdsaOk { - continue - } - if version < VersionTLS12 && candidate.flags&suiteTLS12 != 0 { - continue - } - return candidate - } - } - - return nil -} diff --git a/src/pkg/crypto/tls/handshake_server_test.go b/src/pkg/crypto/tls/handshake_server_test.go deleted file mode 100644 index 36c79a9b0..000000000 --- a/src/pkg/crypto/tls/handshake_server_test.go +++ /dev/null @@ -1,819 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tls - -import ( - "bytes" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rsa" - "encoding/hex" - "encoding/pem" - "errors" - "fmt" - "io" - "math/big" - "net" - "os" - "os/exec" - "path/filepath" - "strings" - "testing" - "time" -) - -// zeroSource is an io.Reader that returns an unlimited number of zero bytes. -type zeroSource struct{} - -func (zeroSource) Read(b []byte) (n int, err error) { - for i := range b { - b[i] = 0 - } - - return len(b), nil -} - -var testConfig *Config - -func init() { - testConfig = &Config{ - Time: func() time.Time { return time.Unix(0, 0) }, - Rand: zeroSource{}, - Certificates: make([]Certificate, 2), - InsecureSkipVerify: true, - MinVersion: VersionSSL30, - MaxVersion: VersionTLS12, - } - testConfig.Certificates[0].Certificate = [][]byte{testRSACertificate} - testConfig.Certificates[0].PrivateKey = testRSAPrivateKey - testConfig.Certificates[1].Certificate = [][]byte{testSNICertificate} - testConfig.Certificates[1].PrivateKey = testRSAPrivateKey - testConfig.BuildNameToCertificate() -} - -func testClientHelloFailure(t *testing.T, m handshakeMessage, expectedSubStr string) { - // Create in-memory network connection, - // send message to server. Should return - // expected error. - c, s := net.Pipe() - go func() { - cli := Client(c, testConfig) - if ch, ok := m.(*clientHelloMsg); ok { - cli.vers = ch.vers - } - cli.writeRecord(recordTypeHandshake, m.marshal()) - c.Close() - }() - err := Server(s, testConfig).Handshake() - s.Close() - if err == nil || !strings.Contains(err.Error(), expectedSubStr) { - t.Errorf("Got error: %s; expected to match substring '%s'", err, expectedSubStr) - } -} - -func TestSimpleError(t *testing.T) { - testClientHelloFailure(t, &serverHelloDoneMsg{}, "unexpected handshake message") -} - -var badProtocolVersions = []uint16{0x0000, 0x0005, 0x0100, 0x0105, 0x0200, 0x0205} - -func TestRejectBadProtocolVersion(t *testing.T) { - for _, v := range badProtocolVersions { - testClientHelloFailure(t, &clientHelloMsg{vers: v}, "unsupported, maximum protocol version") - } -} - -func TestNoSuiteOverlap(t *testing.T) { - clientHello := &clientHelloMsg{ - vers: 0x0301, - cipherSuites: []uint16{0xff00}, - compressionMethods: []uint8{0}, - } - testClientHelloFailure(t, clientHello, "no cipher suite supported by both client and server") -} - -func TestNoCompressionOverlap(t *testing.T) { - clientHello := &clientHelloMsg{ - vers: 0x0301, - cipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA}, - compressionMethods: []uint8{0xff}, - } - testClientHelloFailure(t, clientHello, "client does not support uncompressed connections") -} - -func TestTLS12OnlyCipherSuites(t *testing.T) { - // Test that a Server doesn't select a TLS 1.2-only cipher suite when - // the client negotiates TLS 1.1. - var zeros [32]byte - - clientHello := &clientHelloMsg{ - vers: VersionTLS11, - random: zeros[:], - cipherSuites: []uint16{ - // The Server, by default, will use the client's - // preference order. So the GCM cipher suite - // will be selected unless it's excluded because - // of the version in this ClientHello. - TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256, - TLS_RSA_WITH_RC4_128_SHA, - }, - compressionMethods: []uint8{compressionNone}, - supportedCurves: []CurveID{CurveP256, CurveP384, CurveP521}, - supportedPoints: []uint8{pointFormatUncompressed}, - } - - c, s := net.Pipe() - var reply interface{} - var clientErr error - go func() { - cli := Client(c, testConfig) - cli.vers = clientHello.vers - cli.writeRecord(recordTypeHandshake, clientHello.marshal()) - reply, clientErr = cli.readHandshake() - c.Close() - }() - config := *testConfig - config.CipherSuites = clientHello.cipherSuites - Server(s, &config).Handshake() - s.Close() - if clientErr != nil { - t.Fatal(clientErr) - } - serverHello, ok := reply.(*serverHelloMsg) - if !ok { - t.Fatalf("didn't get ServerHello message in reply. Got %v\n", reply) - } - if s := serverHello.cipherSuite; s != TLS_RSA_WITH_RC4_128_SHA { - t.Fatalf("bad cipher suite from server: %x", s) - } -} - -func TestAlertForwarding(t *testing.T) { - c, s := net.Pipe() - go func() { - Client(c, testConfig).sendAlert(alertUnknownCA) - c.Close() - }() - - err := Server(s, testConfig).Handshake() - s.Close() - if e, ok := err.(*net.OpError); !ok || e.Err != error(alertUnknownCA) { - t.Errorf("Got error: %s; expected: %s", err, error(alertUnknownCA)) - } -} - -func TestClose(t *testing.T) { - c, s := net.Pipe() - go c.Close() - - err := Server(s, testConfig).Handshake() - s.Close() - if err != io.EOF { - t.Errorf("Got error: %s; expected: %s", err, io.EOF) - } -} - -func testHandshake(clientConfig, serverConfig *Config) (state ConnectionState, err error) { - c, s := net.Pipe() - done := make(chan bool) - go func() { - cli := Client(c, clientConfig) - cli.Handshake() - c.Close() - done <- true - }() - server := Server(s, serverConfig) - err = server.Handshake() - if err == nil { - state = server.ConnectionState() - } - s.Close() - <-done - return -} - -func TestVersion(t *testing.T) { - serverConfig := &Config{ - Certificates: testConfig.Certificates, - MaxVersion: VersionTLS11, - } - clientConfig := &Config{ - InsecureSkipVerify: true, - } - state, err := testHandshake(clientConfig, serverConfig) - if err != nil { - t.Fatalf("handshake failed: %s", err) - } - if state.Version != VersionTLS11 { - t.Fatalf("Incorrect version %x, should be %x", state.Version, VersionTLS11) - } -} - -func TestCipherSuitePreference(t *testing.T) { - serverConfig := &Config{ - CipherSuites: []uint16{TLS_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_ECDHE_RSA_WITH_RC4_128_SHA}, - Certificates: testConfig.Certificates, - MaxVersion: VersionTLS11, - } - clientConfig := &Config{ - CipherSuites: []uint16{TLS_RSA_WITH_AES_128_CBC_SHA, TLS_RSA_WITH_RC4_128_SHA}, - InsecureSkipVerify: true, - } - state, err := testHandshake(clientConfig, serverConfig) - if err != nil { - t.Fatalf("handshake failed: %s", err) - } - if state.CipherSuite != TLS_RSA_WITH_AES_128_CBC_SHA { - // By default the server should use the client's preference. - t.Fatalf("Client's preference was not used, got %x", state.CipherSuite) - } - - serverConfig.PreferServerCipherSuites = true - state, err = testHandshake(clientConfig, serverConfig) - if err != nil { - t.Fatalf("handshake failed: %s", err) - } - if state.CipherSuite != TLS_RSA_WITH_RC4_128_SHA { - t.Fatalf("Server's preference was not used, got %x", state.CipherSuite) - } -} - -// Note: see comment in handshake_test.go for details of how the reference -// tests work. - -// serverTest represents a test of the TLS server handshake against a reference -// implementation. -type serverTest struct { - // name is a freeform string identifying the test and the file in which - // the expected results will be stored. - name string - // command, if not empty, contains a series of arguments for the - // command to run for the reference server. - command []string - // expectedPeerCerts contains a list of PEM blocks of expected - // certificates from the client. - expectedPeerCerts []string - // config, if not nil, contains a custom Config to use for this test. - config *Config - // expectAlert, if true, indicates that a fatal alert should be returned - // when handshaking with the server. - expectAlert bool - // validate, if not nil, is a function that will be called with the - // ConnectionState of the resulting connection. It returns false if the - // ConnectionState is unacceptable. - validate func(ConnectionState) error -} - -var defaultClientCommand = []string{"openssl", "s_client", "-no_ticket"} - -// connFromCommand starts opens a listening socket and starts the reference -// client to connect to it. It returns a recordingConn that wraps the resulting -// connection. -func (test *serverTest) connFromCommand() (conn *recordingConn, child *exec.Cmd, err error) { - l, err := net.ListenTCP("tcp", &net.TCPAddr{ - IP: net.IPv4(127, 0, 0, 1), - Port: 0, - }) - if err != nil { - return nil, nil, err - } - defer l.Close() - - port := l.Addr().(*net.TCPAddr).Port - - var command []string - command = append(command, test.command...) - if len(command) == 0 { - command = defaultClientCommand - } - command = append(command, "-connect") - command = append(command, fmt.Sprintf("127.0.0.1:%d", port)) - cmd := exec.Command(command[0], command[1:]...) - cmd.Stdin = nil - var output bytes.Buffer - cmd.Stdout = &output - cmd.Stderr = &output - if err := cmd.Start(); err != nil { - return nil, nil, err - } - - connChan := make(chan interface{}) - go func() { - tcpConn, err := l.Accept() - if err != nil { - connChan <- err - } - connChan <- tcpConn - }() - - var tcpConn net.Conn - select { - case connOrError := <-connChan: - if err, ok := connOrError.(error); ok { - return nil, nil, err - } - tcpConn = connOrError.(net.Conn) - case <-time.After(2 * time.Second): - output.WriteTo(os.Stdout) - return nil, nil, errors.New("timed out waiting for connection from child process") - } - - record := &recordingConn{ - Conn: tcpConn, - } - - return record, cmd, nil -} - -func (test *serverTest) dataPath() string { - return filepath.Join("testdata", "Server-"+test.name) -} - -func (test *serverTest) loadData() (flows [][]byte, err error) { - in, err := os.Open(test.dataPath()) - if err != nil { - return nil, err - } - defer in.Close() - return parseTestData(in) -} - -func (test *serverTest) run(t *testing.T, write bool) { - var clientConn, serverConn net.Conn - var recordingConn *recordingConn - var childProcess *exec.Cmd - - if write { - var err error - recordingConn, childProcess, err = test.connFromCommand() - if err != nil { - t.Fatalf("Failed to start subcommand: %s", err) - } - serverConn = recordingConn - } else { - clientConn, serverConn = net.Pipe() - } - config := test.config - if config == nil { - config = testConfig - } - server := Server(serverConn, config) - connStateChan := make(chan ConnectionState, 1) - go func() { - if _, err := server.Write([]byte("hello, world\n")); err != nil { - t.Logf("Error from Server.Write: %s", err) - } - server.Close() - serverConn.Close() - connStateChan <- server.ConnectionState() - }() - - if !write { - flows, err := test.loadData() - if err != nil { - if !test.expectAlert { - t.Fatalf("%s: failed to load data from %s", test.name, test.dataPath()) - } - } - for i, b := range flows { - if i%2 == 0 { - clientConn.Write(b) - continue - } - bb := make([]byte, len(b)) - n, err := io.ReadFull(clientConn, bb) - if test.expectAlert { - if err == nil { - t.Fatal("Expected read failure but read succeeded") - } - } else { - if err != nil { - t.Fatalf("%s #%d: %s\nRead %d, wanted %d, got %x, wanted %x\n", test.name, i+1, err, n, len(bb), bb[:n], b) - } - if !bytes.Equal(b, bb) { - t.Fatalf("%s #%d: mismatch on read: got:%x want:%x", test.name, i+1, bb, b) - } - } - } - clientConn.Close() - } - - connState := <-connStateChan - peerCerts := connState.PeerCertificates - if len(peerCerts) == len(test.expectedPeerCerts) { - for i, peerCert := range peerCerts { - block, _ := pem.Decode([]byte(test.expectedPeerCerts[i])) - if !bytes.Equal(block.Bytes, peerCert.Raw) { - t.Fatalf("%s: mismatch on peer cert %d", test.name, i+1) - } - } - } else { - t.Fatalf("%s: mismatch on peer list length: %d (wanted) != %d (got)", test.name, len(test.expectedPeerCerts), len(peerCerts)) - } - - if test.validate != nil { - if err := test.validate(connState); err != nil { - t.Fatalf("validate callback returned error: %s", err) - } - } - - if write { - path := test.dataPath() - out, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644) - if err != nil { - t.Fatalf("Failed to create output file: %s", err) - } - defer out.Close() - recordingConn.Close() - if len(recordingConn.flows) < 3 { - childProcess.Stdout.(*bytes.Buffer).WriteTo(os.Stdout) - t.Fatalf("Handshake failed") - } - recordingConn.WriteTo(out) - fmt.Printf("Wrote %s\n", path) - childProcess.Wait() - } -} - -func runServerTestForVersion(t *testing.T, template *serverTest, prefix, option string) { - test := *template - test.name = prefix + test.name - if len(test.command) == 0 { - test.command = defaultClientCommand - } - test.command = append([]string(nil), test.command...) - test.command = append(test.command, option) - test.run(t, *update) -} - -func runServerTestSSLv3(t *testing.T, template *serverTest) { - runServerTestForVersion(t, template, "SSLv3-", "-ssl3") -} - -func runServerTestTLS10(t *testing.T, template *serverTest) { - runServerTestForVersion(t, template, "TLSv10-", "-tls1") -} - -func runServerTestTLS11(t *testing.T, template *serverTest) { - runServerTestForVersion(t, template, "TLSv11-", "-tls1_1") -} - -func runServerTestTLS12(t *testing.T, template *serverTest) { - runServerTestForVersion(t, template, "TLSv12-", "-tls1_2") -} - -func TestHandshakeServerRSARC4(t *testing.T) { - test := &serverTest{ - name: "RSA-RC4", - command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"}, - } - runServerTestSSLv3(t, test) - runServerTestTLS10(t, test) - runServerTestTLS11(t, test) - runServerTestTLS12(t, test) -} - -func TestHandshakeServerRSA3DES(t *testing.T) { - test := &serverTest{ - name: "RSA-3DES", - command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "DES-CBC3-SHA"}, - } - runServerTestSSLv3(t, test) - runServerTestTLS10(t, test) - runServerTestTLS12(t, test) -} - -func TestHandshakeServerRSAAES(t *testing.T) { - test := &serverTest{ - name: "RSA-AES", - command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA"}, - } - runServerTestSSLv3(t, test) - runServerTestTLS10(t, test) - runServerTestTLS12(t, test) -} - -func TestHandshakeServerAESGCM(t *testing.T) { - test := &serverTest{ - name: "RSA-AES-GCM", - command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-RSA-AES128-GCM-SHA256"}, - } - runServerTestTLS12(t, test) -} - -func TestHandshakeServerECDHEECDSAAES(t *testing.T) { - config := *testConfig - config.Certificates = make([]Certificate, 1) - config.Certificates[0].Certificate = [][]byte{testECDSACertificate} - config.Certificates[0].PrivateKey = testECDSAPrivateKey - config.BuildNameToCertificate() - - test := &serverTest{ - name: "ECDHE-ECDSA-AES", - command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "ECDHE-ECDSA-AES256-SHA"}, - config: &config, - } - runServerTestTLS10(t, test) - runServerTestTLS12(t, test) -} - -func TestHandshakeServerALPN(t *testing.T) { - config := *testConfig - config.NextProtos = []string{"proto1", "proto2"} - - test := &serverTest{ - name: "ALPN", - // Note that this needs OpenSSL 1.0.2 because that is the first - // version that supports the -alpn flag. - command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"}, - config: &config, - validate: func(state ConnectionState) error { - // The server's preferences should override the client. - if state.NegotiatedProtocol != "proto1" { - return fmt.Errorf("Got protocol %q, wanted proto1", state.NegotiatedProtocol) - } - return nil - }, - } - runServerTestTLS12(t, test) -} - -func TestHandshakeServerALPNNoMatch(t *testing.T) { - config := *testConfig - config.NextProtos = []string{"proto3"} - - test := &serverTest{ - name: "ALPN-NoMatch", - // Note that this needs OpenSSL 1.0.2 because that is the first - // version that supports the -alpn flag. - command: []string{"openssl", "s_client", "-alpn", "proto2,proto1"}, - config: &config, - validate: func(state ConnectionState) error { - // Rather than reject the connection, Go doesn't select - // a protocol when there is no overlap. - if state.NegotiatedProtocol != "" { - return fmt.Errorf("Got protocol %q, wanted ''", state.NegotiatedProtocol) - } - return nil - }, - } - runServerTestTLS12(t, test) -} - -// TestHandshakeServerSNI involves a client sending an SNI extension of -// "snitest.com", which happens to match the CN of testSNICertificate. The test -// verifies that the server correctly selects that certificate. -func TestHandshakeServerSNI(t *testing.T) { - test := &serverTest{ - name: "SNI", - command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"}, - } - runServerTestTLS12(t, test) -} - -// TestHandshakeServerSNICertForName is similar to TestHandshakeServerSNI, but -// tests the dynamic GetCertificate method -func TestHandshakeServerSNIGetCertificate(t *testing.T) { - config := *testConfig - - // Replace the NameToCertificate map with a GetCertificate function - nameToCert := config.NameToCertificate - config.NameToCertificate = nil - config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) { - cert, _ := nameToCert[clientHello.ServerName] - return cert, nil - } - test := &serverTest{ - name: "SNI", - command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"}, - config: &config, - } - runServerTestTLS12(t, test) -} - -// TestHandshakeServerSNICertForNameNotFound is similar to -// TestHandshakeServerSNICertForName, but tests to make sure that when the -// GetCertificate method doesn't return a cert, we fall back to what's in -// the NameToCertificate map. -func TestHandshakeServerSNIGetCertificateNotFound(t *testing.T) { - config := *testConfig - - config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) { - return nil, nil - } - test := &serverTest{ - name: "SNI", - command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"}, - config: &config, - } - runServerTestTLS12(t, test) -} - -// TestHandshakeServerSNICertForNameError tests to make sure that errors in -// GetCertificate result in a tls alert. -func TestHandshakeServerSNIGetCertificateError(t *testing.T) { - config := *testConfig - - config.GetCertificate = func(clientHello *ClientHelloInfo) (*Certificate, error) { - return nil, fmt.Errorf("Test error in GetCertificate") - } - test := &serverTest{ - name: "SNI", - command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "AES128-SHA", "-servername", "snitest.com"}, - config: &config, - expectAlert: true, - } - runServerTestTLS12(t, test) -} - -// TestCipherSuiteCertPreferance ensures that we select an RSA ciphersuite with -// an RSA certificate and an ECDSA ciphersuite with an ECDSA certificate. -func TestCipherSuiteCertPreferenceECDSA(t *testing.T) { - config := *testConfig - config.CipherSuites = []uint16{TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA} - config.PreferServerCipherSuites = true - - test := &serverTest{ - name: "CipherSuiteCertPreferenceRSA", - config: &config, - } - runServerTestTLS12(t, test) - - config = *testConfig - config.CipherSuites = []uint16{TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA, TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA} - config.Certificates = []Certificate{ - { - Certificate: [][]byte{testECDSACertificate}, - PrivateKey: testECDSAPrivateKey, - }, - } - config.BuildNameToCertificate() - config.PreferServerCipherSuites = true - - test = &serverTest{ - name: "CipherSuiteCertPreferenceECDSA", - config: &config, - } - runServerTestTLS12(t, test) -} - -func TestResumption(t *testing.T) { - sessionFilePath := tempFile("") - defer os.Remove(sessionFilePath) - - test := &serverTest{ - name: "IssueTicket", - command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_out", sessionFilePath}, - } - runServerTestTLS12(t, test) - - test = &serverTest{ - name: "Resume", - command: []string{"openssl", "s_client", "-cipher", "RC4-SHA", "-sess_in", sessionFilePath}, - } - runServerTestTLS12(t, test) -} - -// cert.pem and key.pem were generated with generate_cert.go -// Thus, they have no ExtKeyUsage fields and trigger an error -// when verification is turned on. - -const clientCertificatePEM = ` ------BEGIN CERTIFICATE----- -MIIB7TCCAVigAwIBAgIBADALBgkqhkiG9w0BAQUwJjEQMA4GA1UEChMHQWNtZSBD -bzESMBAGA1UEAxMJMTI3LjAuMC4xMB4XDTExMTIwODA3NTUxMloXDTEyMTIwNzA4 -MDAxMlowJjEQMA4GA1UEChMHQWNtZSBDbzESMBAGA1UEAxMJMTI3LjAuMC4xMIGc -MAsGCSqGSIb3DQEBAQOBjAAwgYgCgYBO0Hsx44Jk2VnAwoekXh6LczPHY1PfZpIG -hPZk1Y/kNqcdK+izIDZFI7Xjla7t4PUgnI2V339aEu+H5Fto5OkOdOwEin/ekyfE -ARl6vfLcPRSr0FTKIQzQTW6HLlzF0rtNS0/Otiz3fojsfNcCkXSmHgwa2uNKWi7e -E5xMQIhZkwIDAQABozIwMDAOBgNVHQ8BAf8EBAMCAKAwDQYDVR0OBAYEBAECAwQw -DwYDVR0jBAgwBoAEAQIDBDALBgkqhkiG9w0BAQUDgYEANh+zegx1yW43RmEr1b3A -p0vMRpqBWHyFeSnIyMZn3TJWRSt1tukkqVCavh9a+hoV2cxVlXIWg7nCto/9iIw4 -hB2rXZIxE0/9gzvGnfERYraL7KtnvshksBFQRlgXa5kc0x38BvEO5ZaoDPl4ILdE -GFGNEH5PlGffo05wc46QkYU= ------END CERTIFICATE-----` - -const clientKeyPEM = ` ------BEGIN RSA PRIVATE KEY----- -MIICWgIBAAKBgE7QezHjgmTZWcDCh6ReHotzM8djU99mkgaE9mTVj+Q2px0r6LMg -NkUjteOVru3g9SCcjZXff1oS74fkW2jk6Q507ASKf96TJ8QBGXq98tw9FKvQVMoh -DNBNbocuXMXSu01LT862LPd+iOx81wKRdKYeDBra40paLt4TnExAiFmTAgMBAAEC -gYBxvXd8yNteFTns8A/2yomEMC4yeosJJSpp1CsN3BJ7g8/qTnrVPxBy+RU+qr63 -t2WquaOu/cr5P8iEsa6lk20tf8pjKLNXeX0b1RTzK8rJLbS7nGzP3tvOhL096VtQ -dAo4ROEaro0TzYpHmpciSvxVIeEIAAdFDObDJPKqcJAxyQJBAJizfYgK8Gzx9fsx -hxp+VteCbVPg2euASH5Yv3K5LukRdKoSzHE2grUVQgN/LafC0eZibRanxHegYSr7 -7qaswKUCQQCEIWor/X4XTMdVj3Oj+vpiw75y/S9gh682+myZL+d/02IEkwnB098P -RkKVpenBHyrGg0oeN5La7URILWKj7CPXAkBKo6F+d+phNjwIFoN1Xb/RA32w/D1I -saG9sF+UEhRt9AxUfW/U/tIQ9V0ZHHcSg1XaCM5Nvp934brdKdvTOKnJAkBD5h/3 -Rybatlvg/fzBEaJFyq09zhngkxlZOUtBVTqzl17RVvY2orgH02U4HbCHy4phxOn7 -qTdQRYlHRftgnWK1AkANibn9PRYJ7mJyJ9Dyj2QeNcSkSTzrt0tPvUMf4+meJymN -1Ntu5+S1DLLzfxlaljWG6ylW6DNxujCyuXIV2rvA ------END RSA PRIVATE KEY-----` - -const clientECDSACertificatePEM = ` ------BEGIN CERTIFICATE----- -MIIB/DCCAV4CCQCaMIRsJjXZFzAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw -EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0 -eSBMdGQwHhcNMTIxMTE0MTMyNTUzWhcNMjIxMTEyMTMyNTUzWjBBMQswCQYDVQQG -EwJBVTEMMAoGA1UECBMDTlNXMRAwDgYDVQQHEwdQeXJtb250MRIwEAYDVQQDEwlK -b2VsIFNpbmcwgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACVjJF1FMBexFe01MNv -ja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd3kfDdq0Z9kUs -jLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx+U56jb0JuK7q -ixgnTy5w/hOWusPTQBbNZU6sER7m8TAJBgcqhkjOPQQBA4GMADCBiAJCAOAUxGBg -C3JosDJdYUoCdFzCgbkWqD8pyDbHgf9stlvZcPE4O1BIKJTLCRpS8V3ujfK58PDa -2RU6+b0DeoeiIzXsAkIBo9SKeDUcSpoj0gq+KxAxnZxfvuiRs9oa9V2jI/Umi0Vw -jWVim34BmT0Y9hCaOGGbLlfk+syxis7iI6CH8OFnUes= ------END CERTIFICATE-----` - -const clientECDSAKeyPEM = ` ------BEGIN EC PARAMETERS----- -BgUrgQQAIw== ------END EC PARAMETERS----- ------BEGIN EC PRIVATE KEY----- -MIHcAgEBBEIBkJN9X4IqZIguiEVKMqeBUP5xtRsEv4HJEtOpOGLELwO53SD78Ew8 -k+wLWoqizS3NpQyMtrU8JFdWfj+C57UNkOugBwYFK4EEACOhgYkDgYYABACVjJF1 -FMBexFe01MNvja5oHt1vzobhfm6ySD6B5U7ixohLZNz1MLvT/2XMW/TdtWo+PtAd -3kfDdq0Z9kUsjLzYHQFMH3CQRnZIi4+DzEpcj0B22uCJ7B0rxE4wdihBsmKo+1vx -+U56jb0JuK7qixgnTy5w/hOWusPTQBbNZU6sER7m8Q== ------END EC PRIVATE KEY-----` - -func TestClientAuth(t *testing.T) { - var certPath, keyPath, ecdsaCertPath, ecdsaKeyPath string - - if *update { - certPath = tempFile(clientCertificatePEM) - defer os.Remove(certPath) - keyPath = tempFile(clientKeyPEM) - defer os.Remove(keyPath) - ecdsaCertPath = tempFile(clientECDSACertificatePEM) - defer os.Remove(ecdsaCertPath) - ecdsaKeyPath = tempFile(clientECDSAKeyPEM) - defer os.Remove(ecdsaKeyPath) - } - - config := *testConfig - config.ClientAuth = RequestClientCert - - test := &serverTest{ - name: "ClientAuthRequestedNotGiven", - command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA"}, - config: &config, - } - runServerTestTLS12(t, test) - - test = &serverTest{ - name: "ClientAuthRequestedAndGiven", - command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA", "-cert", certPath, "-key", keyPath}, - config: &config, - expectedPeerCerts: []string{clientCertificatePEM}, - } - runServerTestTLS12(t, test) - - test = &serverTest{ - name: "ClientAuthRequestedAndECDSAGiven", - command: []string{"openssl", "s_client", "-no_ticket", "-cipher", "RC4-SHA", "-cert", ecdsaCertPath, "-key", ecdsaKeyPath}, - config: &config, - expectedPeerCerts: []string{clientECDSACertificatePEM}, - } - runServerTestTLS12(t, test) -} - -func bigFromString(s string) *big.Int { - ret := new(big.Int) - ret.SetString(s, 10) - return ret -} - -func fromHex(s string) []byte { - b, _ := hex.DecodeString(s) - return b -} - -var testRSACertificate = fromHex("308202b030820219a00302010202090085b0bba48a7fb8ca300d06092a864886f70d01010505003045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c7464301e170d3130303432343039303933385a170d3131303432343039303933385a3045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746430819f300d06092a864886f70d010101050003818d0030818902818100bb79d6f517b5e5bf4610d0dc69bee62b07435ad0032d8a7a4385b71452e7a5654c2c78b8238cb5b482e5de1f953b7e62a52ca533d6fe125c7a56fcf506bffa587b263fb5cd04d3d0c921964ac7f4549f5abfef427100fe1899077f7e887d7df10439c4a22edb51c97ce3c04c3b326601cfafb11db8719a1ddbdb896baeda2d790203010001a381a73081a4301d0603551d0e04160414b1ade2855acfcb28db69ce2369ded3268e18883930750603551d23046e306c8014b1ade2855acfcb28db69ce2369ded3268e188839a149a4473045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746482090085b0bba48a7fb8ca300c0603551d13040530030101ff300d06092a864886f70d010105050003818100086c4524c76bb159ab0c52ccf2b014d7879d7a6475b55a9566e4c52b8eae12661feb4f38b36e60d392fdf74108b52513b1187a24fb301dbaed98b917ece7d73159db95d31d78ea50565cd5825a2d5a5f33c4b6d8c97590968c0f5298b5cd981f89205ff2a01ca31b9694dda9fd57e970e8266d71999b266e3850296c90a7bdd9") - -var testECDSACertificate = fromHex("3082020030820162020900b8bf2d47a0d2ebf4300906072a8648ce3d04013045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c7464301e170d3132313132323135303633325a170d3232313132303135303633325a3045310b3009060355040613024155311330110603550408130a536f6d652d53746174653121301f060355040a1318496e7465726e6574205769646769747320507479204c746430819b301006072a8648ce3d020106052b81040023038186000400c4a1edbe98f90b4873367ec316561122f23d53c33b4d213dcd6b75e6f6b0dc9adf26c1bcb287f072327cb3642f1c90bcea6823107efee325c0483a69e0286dd33700ef0462dd0da09c706283d881d36431aa9e9731bd96b068c09b23de76643f1a5c7fe9120e5858b65f70dd9bd8ead5d7f5d5ccb9b69f30665b669a20e227e5bffe3b300906072a8648ce3d040103818c0030818802420188a24febe245c5487d1bacf5ed989dae4770c05e1bb62fbdf1b64db76140d311a2ceee0b7e927eff769dc33b7ea53fcefa10e259ec472d7cacda4e970e15a06fd00242014dfcbe67139c2d050ebd3fa38c25c13313830d9406bbd4377af6ec7ac9862eddd711697f857c56defb31782be4c7780daecbbe9e4e3624317b6a0f399512078f2a") - -var testSNICertificate = fromHex("308201f23082015da003020102020100300b06092a864886f70d01010530283110300e060355040a130741636d6520436f311430120603550403130b736e69746573742e636f6d301e170d3132303431313137343033355a170d3133303431313137343533355a30283110300e060355040a130741636d6520436f311430120603550403130b736e69746573742e636f6d30819d300b06092a864886f70d01010103818d0030818902818100bb79d6f517b5e5bf4610d0dc69bee62b07435ad0032d8a7a4385b71452e7a5654c2c78b8238cb5b482e5de1f953b7e62a52ca533d6fe125c7a56fcf506bffa587b263fb5cd04d3d0c921964ac7f4549f5abfef427100fe1899077f7e887d7df10439c4a22edb51c97ce3c04c3b326601cfafb11db8719a1ddbdb896baeda2d790203010001a3323030300e0603551d0f0101ff0404030200a0300d0603551d0e0406040401020304300f0603551d2304083006800401020304300b06092a864886f70d0101050381810089c6455f1c1f5ef8eb1ab174ee2439059f5c4259bb1a8d86cdb1d056f56a717da40e95ab90f59e8deaf627c157995094db0802266eb34fc6842dea8a4b68d9c1389103ab84fb9e1f85d9b5d23ff2312c8670fbb540148245a4ebafe264d90c8a4cf4f85b0fac12ac2fc4a3154bad52462868af96c62c6525d652b6e31845bdcc") - -var testRSAPrivateKey = &rsa.PrivateKey{ - PublicKey: rsa.PublicKey{ - N: bigFromString("131650079503776001033793877885499001334664249354723305978524647182322416328664556247316495448366990052837680518067798333412266673813370895702118944398081598789828837447552603077848001020611640547221687072142537202428102790818451901395596882588063427854225330436740647715202971973145151161964464812406232198521"), - E: 65537, - }, - D: bigFromString("29354450337804273969007277378287027274721892607543397931919078829901848876371746653677097639302788129485893852488285045793268732234230875671682624082413996177431586734171663258657462237320300610850244186316880055243099640544518318093544057213190320837094958164973959123058337475052510833916491060913053867729"), - Primes: []*big.Int{ - bigFromString("11969277782311800166562047708379380720136961987713178380670422671426759650127150688426177829077494755200794297055316163155755835813760102405344560929062149"), - bigFromString("10998999429884441391899182616418192492905073053684657075974935218461686523870125521822756579792315215543092255516093840728890783887287417039645833477273829"), - }, -} - -var testECDSAPrivateKey = &ecdsa.PrivateKey{ - PublicKey: ecdsa.PublicKey{ - Curve: elliptic.P521(), - X: bigFromString("2636411247892461147287360222306590634450676461695221912739908880441342231985950069527906976759812296359387337367668045707086543273113073382714101597903639351"), - Y: bigFromString("3204695818431246682253994090650952614555094516658732116404513121125038617915183037601737180082382202488628239201196033284060130040574800684774115478859677243"), - }, - D: bigFromString("5477294338614160138026852784385529180817726002953041720191098180813046231640184669647735805135001309477695746518160084669446643325196003346204701381388769751"), -} diff --git a/src/pkg/crypto/tls/handshake_test.go b/src/pkg/crypto/tls/handshake_test.go deleted file mode 100644 index f95f274ab..000000000 --- a/src/pkg/crypto/tls/handshake_test.go +++ /dev/null @@ -1,167 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tls - -import ( - "bufio" - "encoding/hex" - "errors" - "flag" - "fmt" - "io" - "io/ioutil" - "net" - "strconv" - "strings" - "sync" -) - -// TLS reference tests run a connection against a reference implementation -// (OpenSSL) of TLS and record the bytes of the resulting connection. The Go -// code, during a test, is configured with deterministic randomness and so the -// reference test can be reproduced exactly in the future. -// -// In order to save everyone who wishes to run the tests from needing the -// reference implementation installed, the reference connections are saved in -// files in the testdata directory. Thus running the tests involves nothing -// external, but creating and updating them requires the reference -// implementation. -// -// Tests can be updated by running them with the -update flag. This will cause -// the test files. Generally one should combine the -update flag with -test.run -// to updated a specific test. Since the reference implementation will always -// generate fresh random numbers, large parts of the reference connection will -// always change. - -var update = flag.Bool("update", false, "update golden files on disk") - -// recordingConn is a net.Conn that records the traffic that passes through it. -// WriteTo can be used to produce output that can be later be loaded with -// ParseTestData. -type recordingConn struct { - net.Conn - sync.Mutex - flows [][]byte - reading bool -} - -func (r *recordingConn) Read(b []byte) (n int, err error) { - if n, err = r.Conn.Read(b); n == 0 { - return - } - b = b[:n] - - r.Lock() - defer r.Unlock() - - if l := len(r.flows); l == 0 || !r.reading { - buf := make([]byte, len(b)) - copy(buf, b) - r.flows = append(r.flows, buf) - } else { - r.flows[l-1] = append(r.flows[l-1], b[:n]...) - } - r.reading = true - return -} - -func (r *recordingConn) Write(b []byte) (n int, err error) { - if n, err = r.Conn.Write(b); n == 0 { - return - } - b = b[:n] - - r.Lock() - defer r.Unlock() - - if l := len(r.flows); l == 0 || r.reading { - buf := make([]byte, len(b)) - copy(buf, b) - r.flows = append(r.flows, buf) - } else { - r.flows[l-1] = append(r.flows[l-1], b[:n]...) - } - r.reading = false - return -} - -// WriteTo writes Go source code to w that contains the recorded traffic. -func (r *recordingConn) WriteTo(w io.Writer) { - // TLS always starts with a client to server flow. - clientToServer := true - - for i, flow := range r.flows { - source, dest := "client", "server" - if !clientToServer { - source, dest = dest, source - } - fmt.Fprintf(w, ">>> Flow %d (%s to %s)\n", i+1, source, dest) - dumper := hex.Dumper(w) - dumper.Write(flow) - dumper.Close() - clientToServer = !clientToServer - } -} - -func parseTestData(r io.Reader) (flows [][]byte, err error) { - var currentFlow []byte - - scanner := bufio.NewScanner(r) - for scanner.Scan() { - line := scanner.Text() - // If the line starts with ">>> " then it marks the beginning - // of a new flow. - if strings.HasPrefix(line, ">>> ") { - if len(currentFlow) > 0 || len(flows) > 0 { - flows = append(flows, currentFlow) - currentFlow = nil - } - continue - } - - // Otherwise the line is a line of hex dump that looks like: - // 00000170 fc f5 06 bf (...) |.....X{&?......!| - // (Some bytes have been omitted from the middle section.) - - if i := strings.IndexByte(line, ' '); i >= 0 { - line = line[i:] - } else { - return nil, errors.New("invalid test data") - } - - if i := strings.IndexByte(line, '|'); i >= 0 { - line = line[:i] - } else { - return nil, errors.New("invalid test data") - } - - hexBytes := strings.Fields(line) - for _, hexByte := range hexBytes { - val, err := strconv.ParseUint(hexByte, 16, 8) - if err != nil { - return nil, errors.New("invalid hex byte in test data: " + err.Error()) - } - currentFlow = append(currentFlow, byte(val)) - } - } - - if len(currentFlow) > 0 { - flows = append(flows, currentFlow) - } - - return flows, nil -} - -// tempFile creates a temp file containing contents and returns its path. -func tempFile(contents string) string { - file, err := ioutil.TempFile("", "go-tls-test") - if err != nil { - panic("failed to create temp file: " + err.Error()) - } - path := file.Name() - file.WriteString(contents) - file.Close() - return path -} diff --git a/src/pkg/crypto/tls/key_agreement.go b/src/pkg/crypto/tls/key_agreement.go deleted file mode 100644 index 0974fc6e0..000000000 --- a/src/pkg/crypto/tls/key_agreement.go +++ /dev/null @@ -1,413 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tls - -import ( - "crypto" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/md5" - "crypto/rsa" - "crypto/sha1" - "crypto/sha256" - "crypto/x509" - "encoding/asn1" - "errors" - "io" - "math/big" -) - -var errClientKeyExchange = errors.New("tls: invalid ClientKeyExchange message") -var errServerKeyExchange = errors.New("tls: invalid ServerKeyExchange message") - -// rsaKeyAgreement implements the standard TLS key agreement where the client -// encrypts the pre-master secret to the server's public key. -type rsaKeyAgreement struct{} - -func (ka rsaKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) { - return nil, nil -} - -func (ka rsaKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) { - preMasterSecret := make([]byte, 48) - _, err := io.ReadFull(config.rand(), preMasterSecret[2:]) - if err != nil { - return nil, err - } - - if len(ckx.ciphertext) < 2 { - return nil, errClientKeyExchange - } - - ciphertext := ckx.ciphertext - if version != VersionSSL30 { - ciphertextLen := int(ckx.ciphertext[0])<<8 | int(ckx.ciphertext[1]) - if ciphertextLen != len(ckx.ciphertext)-2 { - return nil, errClientKeyExchange - } - ciphertext = ckx.ciphertext[2:] - } - - err = rsa.DecryptPKCS1v15SessionKey(config.rand(), cert.PrivateKey.(*rsa.PrivateKey), ciphertext, preMasterSecret) - if err != nil { - return nil, err - } - // We don't check the version number in the premaster secret. For one, - // by checking it, we would leak information about the validity of the - // encrypted pre-master secret. Secondly, it provides only a small - // benefit against a downgrade attack and some implementations send the - // wrong version anyway. See the discussion at the end of section - // 7.4.7.1 of RFC 4346. - return preMasterSecret, nil -} - -func (ka rsaKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error { - return errors.New("tls: unexpected ServerKeyExchange") -} - -func (ka rsaKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) { - preMasterSecret := make([]byte, 48) - preMasterSecret[0] = byte(clientHello.vers >> 8) - preMasterSecret[1] = byte(clientHello.vers) - _, err := io.ReadFull(config.rand(), preMasterSecret[2:]) - if err != nil { - return nil, nil, err - } - - encrypted, err := rsa.EncryptPKCS1v15(config.rand(), cert.PublicKey.(*rsa.PublicKey), preMasterSecret) - if err != nil { - return nil, nil, err - } - ckx := new(clientKeyExchangeMsg) - ckx.ciphertext = make([]byte, len(encrypted)+2) - ckx.ciphertext[0] = byte(len(encrypted) >> 8) - ckx.ciphertext[1] = byte(len(encrypted)) - copy(ckx.ciphertext[2:], encrypted) - return preMasterSecret, ckx, nil -} - -// sha1Hash calculates a SHA1 hash over the given byte slices. -func sha1Hash(slices [][]byte) []byte { - hsha1 := sha1.New() - for _, slice := range slices { - hsha1.Write(slice) - } - return hsha1.Sum(nil) -} - -// md5SHA1Hash implements TLS 1.0's hybrid hash function which consists of the -// concatenation of an MD5 and SHA1 hash. -func md5SHA1Hash(slices [][]byte) []byte { - md5sha1 := make([]byte, md5.Size+sha1.Size) - hmd5 := md5.New() - for _, slice := range slices { - hmd5.Write(slice) - } - copy(md5sha1, hmd5.Sum(nil)) - copy(md5sha1[md5.Size:], sha1Hash(slices)) - return md5sha1 -} - -// sha256Hash implements TLS 1.2's hash function. -func sha256Hash(slices [][]byte) []byte { - h := sha256.New() - for _, slice := range slices { - h.Write(slice) - } - return h.Sum(nil) -} - -// hashForServerKeyExchange hashes the given slices and returns their digest -// and the identifier of the hash function used. The hashFunc argument is only -// used for >= TLS 1.2 and precisely identifies the hash function to use. -func hashForServerKeyExchange(sigType, hashFunc uint8, version uint16, slices ...[]byte) ([]byte, crypto.Hash, error) { - if version >= VersionTLS12 { - switch hashFunc { - case hashSHA256: - return sha256Hash(slices), crypto.SHA256, nil - case hashSHA1: - return sha1Hash(slices), crypto.SHA1, nil - default: - return nil, crypto.Hash(0), errors.New("tls: unknown hash function used by peer") - } - } - if sigType == signatureECDSA { - return sha1Hash(slices), crypto.SHA1, nil - } - return md5SHA1Hash(slices), crypto.MD5SHA1, nil -} - -// pickTLS12HashForSignature returns a TLS 1.2 hash identifier for signing a -// ServerKeyExchange given the signature type being used and the client's -// advertised list of supported signature and hash combinations. -func pickTLS12HashForSignature(sigType uint8, clientSignatureAndHashes []signatureAndHash) (uint8, error) { - if len(clientSignatureAndHashes) == 0 { - // If the client didn't specify any signature_algorithms - // extension then we can assume that it supports SHA1. See - // http://tools.ietf.org/html/rfc5246#section-7.4.1.4.1 - return hashSHA1, nil - } - - for _, sigAndHash := range clientSignatureAndHashes { - if sigAndHash.signature != sigType { - continue - } - switch sigAndHash.hash { - case hashSHA1, hashSHA256: - return sigAndHash.hash, nil - } - } - - return 0, errors.New("tls: client doesn't support any common hash functions") -} - -func curveForCurveID(id CurveID) (elliptic.Curve, bool) { - switch id { - case CurveP256: - return elliptic.P256(), true - case CurveP384: - return elliptic.P384(), true - case CurveP521: - return elliptic.P521(), true - default: - return nil, false - } - -} - -// ecdheRSAKeyAgreement implements a TLS key agreement where the server -// generates a ephemeral EC public/private key pair and signs it. The -// pre-master secret is then calculated using ECDH. The signature may -// either be ECDSA or RSA. -type ecdheKeyAgreement struct { - version uint16 - sigType uint8 - privateKey []byte - curve elliptic.Curve - x, y *big.Int -} - -func (ka *ecdheKeyAgreement) generateServerKeyExchange(config *Config, cert *Certificate, clientHello *clientHelloMsg, hello *serverHelloMsg) (*serverKeyExchangeMsg, error) { - var curveid CurveID - preferredCurves := config.curvePreferences() - -NextCandidate: - for _, candidate := range preferredCurves { - for _, c := range clientHello.supportedCurves { - if candidate == c { - curveid = c - break NextCandidate - } - } - } - - if curveid == 0 { - return nil, errors.New("tls: no supported elliptic curves offered") - } - - var ok bool - if ka.curve, ok = curveForCurveID(curveid); !ok { - return nil, errors.New("tls: preferredCurves includes unsupported curve") - } - - var x, y *big.Int - var err error - ka.privateKey, x, y, err = elliptic.GenerateKey(ka.curve, config.rand()) - if err != nil { - return nil, err - } - ecdhePublic := elliptic.Marshal(ka.curve, x, y) - - // http://tools.ietf.org/html/rfc4492#section-5.4 - serverECDHParams := make([]byte, 1+2+1+len(ecdhePublic)) - serverECDHParams[0] = 3 // named curve - serverECDHParams[1] = byte(curveid >> 8) - serverECDHParams[2] = byte(curveid) - serverECDHParams[3] = byte(len(ecdhePublic)) - copy(serverECDHParams[4:], ecdhePublic) - - var tls12HashId uint8 - if ka.version >= VersionTLS12 { - if tls12HashId, err = pickTLS12HashForSignature(ka.sigType, clientHello.signatureAndHashes); err != nil { - return nil, err - } - } - - digest, hashFunc, err := hashForServerKeyExchange(ka.sigType, tls12HashId, ka.version, clientHello.random, hello.random, serverECDHParams) - if err != nil { - return nil, err - } - var sig []byte - switch ka.sigType { - case signatureECDSA: - privKey, ok := cert.PrivateKey.(*ecdsa.PrivateKey) - if !ok { - return nil, errors.New("ECDHE ECDSA requires an ECDSA server private key") - } - r, s, err := ecdsa.Sign(config.rand(), privKey, digest) - if err != nil { - return nil, errors.New("failed to sign ECDHE parameters: " + err.Error()) - } - sig, err = asn1.Marshal(ecdsaSignature{r, s}) - case signatureRSA: - privKey, ok := cert.PrivateKey.(*rsa.PrivateKey) - if !ok { - return nil, errors.New("ECDHE RSA requires a RSA server private key") - } - sig, err = rsa.SignPKCS1v15(config.rand(), privKey, hashFunc, digest) - if err != nil { - return nil, errors.New("failed to sign ECDHE parameters: " + err.Error()) - } - default: - return nil, errors.New("unknown ECDHE signature algorithm") - } - - skx := new(serverKeyExchangeMsg) - sigAndHashLen := 0 - if ka.version >= VersionTLS12 { - sigAndHashLen = 2 - } - skx.key = make([]byte, len(serverECDHParams)+sigAndHashLen+2+len(sig)) - copy(skx.key, serverECDHParams) - k := skx.key[len(serverECDHParams):] - if ka.version >= VersionTLS12 { - k[0] = tls12HashId - k[1] = ka.sigType - k = k[2:] - } - k[0] = byte(len(sig) >> 8) - k[1] = byte(len(sig)) - copy(k[2:], sig) - - return skx, nil -} - -func (ka *ecdheKeyAgreement) processClientKeyExchange(config *Config, cert *Certificate, ckx *clientKeyExchangeMsg, version uint16) ([]byte, error) { - if len(ckx.ciphertext) == 0 || int(ckx.ciphertext[0]) != len(ckx.ciphertext)-1 { - return nil, errClientKeyExchange - } - x, y := elliptic.Unmarshal(ka.curve, ckx.ciphertext[1:]) - if x == nil { - return nil, errClientKeyExchange - } - if !ka.curve.IsOnCurve(x, y) { - return nil, errClientKeyExchange - } - x, _ = ka.curve.ScalarMult(x, y, ka.privateKey) - preMasterSecret := make([]byte, (ka.curve.Params().BitSize+7)>>3) - xBytes := x.Bytes() - copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes) - - return preMasterSecret, nil -} - -func (ka *ecdheKeyAgreement) processServerKeyExchange(config *Config, clientHello *clientHelloMsg, serverHello *serverHelloMsg, cert *x509.Certificate, skx *serverKeyExchangeMsg) error { - if len(skx.key) < 4 { - return errServerKeyExchange - } - if skx.key[0] != 3 { // named curve - return errors.New("tls: server selected unsupported curve") - } - curveid := CurveID(skx.key[1])<<8 | CurveID(skx.key[2]) - - var ok bool - if ka.curve, ok = curveForCurveID(curveid); !ok { - return errors.New("tls: server selected unsupported curve") - } - - publicLen := int(skx.key[3]) - if publicLen+4 > len(skx.key) { - return errServerKeyExchange - } - ka.x, ka.y = elliptic.Unmarshal(ka.curve, skx.key[4:4+publicLen]) - if ka.x == nil { - return errServerKeyExchange - } - if !ka.curve.IsOnCurve(ka.x, ka.y) { - return errServerKeyExchange - } - serverECDHParams := skx.key[:4+publicLen] - - sig := skx.key[4+publicLen:] - if len(sig) < 2 { - return errServerKeyExchange - } - - var tls12HashId uint8 - if ka.version >= VersionTLS12 { - // handle SignatureAndHashAlgorithm - var sigAndHash []uint8 - sigAndHash, sig = sig[:2], sig[2:] - if sigAndHash[1] != ka.sigType { - return errServerKeyExchange - } - tls12HashId = sigAndHash[0] - if len(sig) < 2 { - return errServerKeyExchange - } - } - sigLen := int(sig[0])<<8 | int(sig[1]) - if sigLen+2 != len(sig) { - return errServerKeyExchange - } - sig = sig[2:] - - digest, hashFunc, err := hashForServerKeyExchange(ka.sigType, tls12HashId, ka.version, clientHello.random, serverHello.random, serverECDHParams) - if err != nil { - return err - } - switch ka.sigType { - case signatureECDSA: - pubKey, ok := cert.PublicKey.(*ecdsa.PublicKey) - if !ok { - return errors.New("ECDHE ECDSA requires a ECDSA server public key") - } - ecdsaSig := new(ecdsaSignature) - if _, err := asn1.Unmarshal(sig, ecdsaSig); err != nil { - return err - } - if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 { - return errors.New("ECDSA signature contained zero or negative values") - } - if !ecdsa.Verify(pubKey, digest, ecdsaSig.R, ecdsaSig.S) { - return errors.New("ECDSA verification failure") - } - case signatureRSA: - pubKey, ok := cert.PublicKey.(*rsa.PublicKey) - if !ok { - return errors.New("ECDHE RSA requires a RSA server public key") - } - if err := rsa.VerifyPKCS1v15(pubKey, hashFunc, digest, sig); err != nil { - return err - } - default: - return errors.New("unknown ECDHE signature algorithm") - } - - return nil -} - -func (ka *ecdheKeyAgreement) generateClientKeyExchange(config *Config, clientHello *clientHelloMsg, cert *x509.Certificate) ([]byte, *clientKeyExchangeMsg, error) { - if ka.curve == nil { - return nil, nil, errors.New("missing ServerKeyExchange message") - } - priv, mx, my, err := elliptic.GenerateKey(ka.curve, config.rand()) - if err != nil { - return nil, nil, err - } - x, _ := ka.curve.ScalarMult(ka.x, ka.y, priv) - preMasterSecret := make([]byte, (ka.curve.Params().BitSize+7)>>3) - xBytes := x.Bytes() - copy(preMasterSecret[len(preMasterSecret)-len(xBytes):], xBytes) - - serialized := elliptic.Marshal(ka.curve, mx, my) - - ckx := new(clientKeyExchangeMsg) - ckx.ciphertext = make([]byte, 1+len(serialized)) - ckx.ciphertext[0] = byte(len(serialized)) - copy(ckx.ciphertext[1:], serialized) - - return preMasterSecret, ckx, nil -} diff --git a/src/pkg/crypto/tls/prf.go b/src/pkg/crypto/tls/prf.go deleted file mode 100644 index fb8b3ab4d..000000000 --- a/src/pkg/crypto/tls/prf.go +++ /dev/null @@ -1,291 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tls - -import ( - "crypto" - "crypto/hmac" - "crypto/md5" - "crypto/sha1" - "crypto/sha256" - "hash" -) - -// Split a premaster secret in two as specified in RFC 4346, section 5. -func splitPreMasterSecret(secret []byte) (s1, s2 []byte) { - s1 = secret[0 : (len(secret)+1)/2] - s2 = secret[len(secret)/2:] - return -} - -// pHash implements the P_hash function, as defined in RFC 4346, section 5. -func pHash(result, secret, seed []byte, hash func() hash.Hash) { - h := hmac.New(hash, secret) - h.Write(seed) - a := h.Sum(nil) - - j := 0 - for j < len(result) { - h.Reset() - h.Write(a) - h.Write(seed) - b := h.Sum(nil) - todo := len(b) - if j+todo > len(result) { - todo = len(result) - j - } - copy(result[j:j+todo], b) - j += todo - - h.Reset() - h.Write(a) - a = h.Sum(nil) - } -} - -// prf10 implements the TLS 1.0 pseudo-random function, as defined in RFC 2246, section 5. -func prf10(result, secret, label, seed []byte) { - hashSHA1 := sha1.New - hashMD5 := md5.New - - labelAndSeed := make([]byte, len(label)+len(seed)) - copy(labelAndSeed, label) - copy(labelAndSeed[len(label):], seed) - - s1, s2 := splitPreMasterSecret(secret) - pHash(result, s1, labelAndSeed, hashMD5) - result2 := make([]byte, len(result)) - pHash(result2, s2, labelAndSeed, hashSHA1) - - for i, b := range result2 { - result[i] ^= b - } -} - -// prf12 implements the TLS 1.2 pseudo-random function, as defined in RFC 5246, section 5. -func prf12(result, secret, label, seed []byte) { - labelAndSeed := make([]byte, len(label)+len(seed)) - copy(labelAndSeed, label) - copy(labelAndSeed[len(label):], seed) - - pHash(result, secret, labelAndSeed, sha256.New) -} - -// prf30 implements the SSL 3.0 pseudo-random function, as defined in -// www.mozilla.org/projects/security/pki/nss/ssl/draft302.txt section 6. -func prf30(result, secret, label, seed []byte) { - hashSHA1 := sha1.New() - hashMD5 := md5.New() - - done := 0 - i := 0 - // RFC5246 section 6.3 says that the largest PRF output needed is 128 - // bytes. Since no more ciphersuites will be added to SSLv3, this will - // remain true. Each iteration gives us 16 bytes so 10 iterations will - // be sufficient. - var b [11]byte - for done < len(result) { - for j := 0; j <= i; j++ { - b[j] = 'A' + byte(i) - } - - hashSHA1.Reset() - hashSHA1.Write(b[:i+1]) - hashSHA1.Write(secret) - hashSHA1.Write(seed) - digest := hashSHA1.Sum(nil) - - hashMD5.Reset() - hashMD5.Write(secret) - hashMD5.Write(digest) - - done += copy(result[done:], hashMD5.Sum(nil)) - i++ - } -} - -const ( - tlsRandomLength = 32 // Length of a random nonce in TLS 1.1. - masterSecretLength = 48 // Length of a master secret in TLS 1.1. - finishedVerifyLength = 12 // Length of verify_data in a Finished message. -) - -var masterSecretLabel = []byte("master secret") -var keyExpansionLabel = []byte("key expansion") -var clientFinishedLabel = []byte("client finished") -var serverFinishedLabel = []byte("server finished") - -func prfForVersion(version uint16) func(result, secret, label, seed []byte) { - switch version { - case VersionSSL30: - return prf30 - case VersionTLS10, VersionTLS11: - return prf10 - case VersionTLS12: - return prf12 - default: - panic("unknown version") - } -} - -// masterFromPreMasterSecret generates the master secret from the pre-master -// secret. See http://tools.ietf.org/html/rfc5246#section-8.1 -func masterFromPreMasterSecret(version uint16, preMasterSecret, clientRandom, serverRandom []byte) []byte { - var seed [tlsRandomLength * 2]byte - copy(seed[0:len(clientRandom)], clientRandom) - copy(seed[len(clientRandom):], serverRandom) - masterSecret := make([]byte, masterSecretLength) - prfForVersion(version)(masterSecret, preMasterSecret, masterSecretLabel, seed[0:]) - return masterSecret -} - -// keysFromMasterSecret generates the connection keys from the master -// secret, given the lengths of the MAC key, cipher key and IV, as defined in -// RFC 2246, section 6.3. -func keysFromMasterSecret(version uint16, masterSecret, clientRandom, serverRandom []byte, macLen, keyLen, ivLen int) (clientMAC, serverMAC, clientKey, serverKey, clientIV, serverIV []byte) { - var seed [tlsRandomLength * 2]byte - copy(seed[0:len(clientRandom)], serverRandom) - copy(seed[len(serverRandom):], clientRandom) - - n := 2*macLen + 2*keyLen + 2*ivLen - keyMaterial := make([]byte, n) - prfForVersion(version)(keyMaterial, masterSecret, keyExpansionLabel, seed[0:]) - clientMAC = keyMaterial[:macLen] - keyMaterial = keyMaterial[macLen:] - serverMAC = keyMaterial[:macLen] - keyMaterial = keyMaterial[macLen:] - clientKey = keyMaterial[:keyLen] - keyMaterial = keyMaterial[keyLen:] - serverKey = keyMaterial[:keyLen] - keyMaterial = keyMaterial[keyLen:] - clientIV = keyMaterial[:ivLen] - keyMaterial = keyMaterial[ivLen:] - serverIV = keyMaterial[:ivLen] - return -} - -func newFinishedHash(version uint16) finishedHash { - if version >= VersionTLS12 { - return finishedHash{sha256.New(), sha256.New(), nil, nil, version} - } - return finishedHash{sha1.New(), sha1.New(), md5.New(), md5.New(), version} -} - -// A finishedHash calculates the hash of a set of handshake messages suitable -// for including in a Finished message. -type finishedHash struct { - client hash.Hash - server hash.Hash - - // Prior to TLS 1.2, an additional MD5 hash is required. - clientMD5 hash.Hash - serverMD5 hash.Hash - - version uint16 -} - -func (h finishedHash) Write(msg []byte) (n int, err error) { - h.client.Write(msg) - h.server.Write(msg) - - if h.version < VersionTLS12 { - h.clientMD5.Write(msg) - h.serverMD5.Write(msg) - } - return len(msg), nil -} - -// finishedSum30 calculates the contents of the verify_data member of a SSLv3 -// Finished message given the MD5 and SHA1 hashes of a set of handshake -// messages. -func finishedSum30(md5, sha1 hash.Hash, masterSecret []byte, magic [4]byte) []byte { - md5.Write(magic[:]) - md5.Write(masterSecret) - md5.Write(ssl30Pad1[:]) - md5Digest := md5.Sum(nil) - - md5.Reset() - md5.Write(masterSecret) - md5.Write(ssl30Pad2[:]) - md5.Write(md5Digest) - md5Digest = md5.Sum(nil) - - sha1.Write(magic[:]) - sha1.Write(masterSecret) - sha1.Write(ssl30Pad1[:40]) - sha1Digest := sha1.Sum(nil) - - sha1.Reset() - sha1.Write(masterSecret) - sha1.Write(ssl30Pad2[:40]) - sha1.Write(sha1Digest) - sha1Digest = sha1.Sum(nil) - - ret := make([]byte, len(md5Digest)+len(sha1Digest)) - copy(ret, md5Digest) - copy(ret[len(md5Digest):], sha1Digest) - return ret -} - -var ssl3ClientFinishedMagic = [4]byte{0x43, 0x4c, 0x4e, 0x54} -var ssl3ServerFinishedMagic = [4]byte{0x53, 0x52, 0x56, 0x52} - -// clientSum returns the contents of the verify_data member of a client's -// Finished message. -func (h finishedHash) clientSum(masterSecret []byte) []byte { - if h.version == VersionSSL30 { - return finishedSum30(h.clientMD5, h.client, masterSecret, ssl3ClientFinishedMagic) - } - - out := make([]byte, finishedVerifyLength) - if h.version >= VersionTLS12 { - seed := h.client.Sum(nil) - prf12(out, masterSecret, clientFinishedLabel, seed) - } else { - seed := make([]byte, 0, md5.Size+sha1.Size) - seed = h.clientMD5.Sum(seed) - seed = h.client.Sum(seed) - prf10(out, masterSecret, clientFinishedLabel, seed) - } - return out -} - -// serverSum returns the contents of the verify_data member of a server's -// Finished message. -func (h finishedHash) serverSum(masterSecret []byte) []byte { - if h.version == VersionSSL30 { - return finishedSum30(h.serverMD5, h.server, masterSecret, ssl3ServerFinishedMagic) - } - - out := make([]byte, finishedVerifyLength) - if h.version >= VersionTLS12 { - seed := h.server.Sum(nil) - prf12(out, masterSecret, serverFinishedLabel, seed) - } else { - seed := make([]byte, 0, md5.Size+sha1.Size) - seed = h.serverMD5.Sum(seed) - seed = h.server.Sum(seed) - prf10(out, masterSecret, serverFinishedLabel, seed) - } - return out -} - -// hashForClientCertificate returns a digest, hash function, and TLS 1.2 hash -// id suitable for signing by a TLS client certificate. -func (h finishedHash) hashForClientCertificate(sigType uint8) ([]byte, crypto.Hash, uint8) { - if h.version >= VersionTLS12 { - digest := h.server.Sum(nil) - return digest, crypto.SHA256, hashSHA256 - } - if sigType == signatureECDSA { - digest := h.server.Sum(nil) - return digest, crypto.SHA1, hashSHA1 - } - - digest := make([]byte, 0, 36) - digest = h.serverMD5.Sum(digest) - digest = h.server.Sum(digest) - return digest, crypto.MD5SHA1, 0 /* not specified in TLS 1.2. */ -} diff --git a/src/pkg/crypto/tls/prf_test.go b/src/pkg/crypto/tls/prf_test.go deleted file mode 100644 index a9b6c9e4c..000000000 --- a/src/pkg/crypto/tls/prf_test.go +++ /dev/null @@ -1,126 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tls - -import ( - "encoding/hex" - "testing" -) - -type testSplitPreMasterSecretTest struct { - in, out1, out2 string -} - -var testSplitPreMasterSecretTests = []testSplitPreMasterSecretTest{ - {"", "", ""}, - {"00", "00", "00"}, - {"0011", "00", "11"}, - {"001122", "0011", "1122"}, - {"00112233", "0011", "2233"}, -} - -func TestSplitPreMasterSecret(t *testing.T) { - for i, test := range testSplitPreMasterSecretTests { - in, _ := hex.DecodeString(test.in) - out1, out2 := splitPreMasterSecret(in) - s1 := hex.EncodeToString(out1) - s2 := hex.EncodeToString(out2) - if s1 != test.out1 || s2 != test.out2 { - t.Errorf("#%d: got: (%s, %s) want: (%s, %s)", i, s1, s2, test.out1, test.out2) - } - } -} - -type testKeysFromTest struct { - version uint16 - preMasterSecret string - clientRandom, serverRandom string - masterSecret string - clientMAC, serverMAC string - clientKey, serverKey string - macLen, keyLen int -} - -func TestKeysFromPreMasterSecret(t *testing.T) { - for i, test := range testKeysFromTests { - in, _ := hex.DecodeString(test.preMasterSecret) - clientRandom, _ := hex.DecodeString(test.clientRandom) - serverRandom, _ := hex.DecodeString(test.serverRandom) - - masterSecret := masterFromPreMasterSecret(test.version, in, clientRandom, serverRandom) - if s := hex.EncodeToString(masterSecret); s != test.masterSecret { - t.Errorf("#%d: bad master secret %s, want %s", i, s, test.masterSecret) - continue - } - - clientMAC, serverMAC, clientKey, serverKey, _, _ := keysFromMasterSecret(test.version, masterSecret, clientRandom, serverRandom, test.macLen, test.keyLen, 0) - clientMACString := hex.EncodeToString(clientMAC) - serverMACString := hex.EncodeToString(serverMAC) - clientKeyString := hex.EncodeToString(clientKey) - serverKeyString := hex.EncodeToString(serverKey) - if clientMACString != test.clientMAC || - serverMACString != test.serverMAC || - clientKeyString != test.clientKey || - serverKeyString != test.serverKey { - t.Errorf("#%d: got: (%s, %s, %s, %s) want: (%s, %s, %s, %s)", i, clientMACString, serverMACString, clientKeyString, serverKeyString, test.clientMAC, test.serverMAC, test.clientKey, test.serverKey) - } - } -} - -// These test vectors were generated from GnuTLS using `gnutls-cli --insecure -d 9 ` -var testKeysFromTests = []testKeysFromTest{ - { - VersionTLS10, - "0302cac83ad4b1db3b9ab49ad05957de2a504a634a386fc600889321e1a971f57479466830ac3e6f468e87f5385fa0c5", - "4ae66303755184a3917fcb44880605fcc53baa01912b22ed94473fc69cebd558", - "4ae663020ec16e6bb5130be918cfcafd4d765979a3136a5d50c593446e4e44db", - "3d851bab6e5556e959a16bc36d66cfae32f672bfa9ecdef6096cbb1b23472df1da63dbbd9827606413221d149ed08ceb", - "805aaa19b3d2c0a0759a4b6c9959890e08480119", - "2d22f9fe519c075c16448305ceee209fc24ad109", - "d50b5771244f850cd8117a9ccafe2cf1", - "e076e33206b30507a85c32855acd0919", - 20, - 16, - }, - { - VersionTLS10, - "03023f7527316bc12cbcd69e4b9e8275d62c028f27e65c745cfcddc7ce01bd3570a111378b63848127f1c36e5f9e4890", - "4ae66364b5ea56b20ce4e25555aed2d7e67f42788dd03f3fee4adae0459ab106", - "4ae66363ab815cbf6a248b87d6b556184e945e9b97fbdf247858b0bdafacfa1c", - "7d64be7c80c59b740200b4b9c26d0baaa1c5ae56705acbcf2307fe62beb4728c19392c83f20483801cce022c77645460", - "97742ed60a0554ca13f04f97ee193177b971e3b0", - "37068751700400e03a8477a5c7eec0813ab9e0dc", - "207cddbc600d2a200abac6502053ee5c", - "df3f94f6e1eacc753b815fe16055cd43", - 20, - 16, - }, - { - VersionTLS10, - "832d515f1d61eebb2be56ba0ef79879efb9b527504abb386fb4310ed5d0e3b1f220d3bb6b455033a2773e6d8bdf951d278a187482b400d45deb88a5d5a6bb7d6a7a1decc04eb9ef0642876cd4a82d374d3b6ff35f0351dc5d411104de431375355addc39bfb1f6329fb163b0bc298d658338930d07d313cd980a7e3d9196cac1", - "4ae663b2ee389c0de147c509d8f18f5052afc4aaf9699efe8cb05ece883d3a5e", - "4ae664d503fd4cff50cfc1fb8fc606580f87b0fcdac9554ba0e01d785bdf278e", - "1aff2e7a2c4279d0126f57a65a77a8d9d0087cf2733366699bec27eb53d5740705a8574bb1acc2abbe90e44f0dd28d6c", - "3c7647c93c1379a31a609542aa44e7f117a70085", - "0d73102994be74a575a3ead8532590ca32a526d4", - "ac7581b0b6c10d85bbd905ffbf36c65e", - "ff07edde49682b45466bd2e39464b306", - 20, - 16, - }, - { - VersionSSL30, - "832d515f1d61eebb2be56ba0ef79879efb9b527504abb386fb4310ed5d0e3b1f220d3bb6b455033a2773e6d8bdf951d278a187482b400d45deb88a5d5a6bb7d6a7a1decc04eb9ef0642876cd4a82d374d3b6ff35f0351dc5d411104de431375355addc39bfb1f6329fb163b0bc298d658338930d07d313cd980a7e3d9196cac1", - "4ae663b2ee389c0de147c509d8f18f5052afc4aaf9699efe8cb05ece883d3a5e", - "4ae664d503fd4cff50cfc1fb8fc606580f87b0fcdac9554ba0e01d785bdf278e", - "a614863e56299dcffeea2938f22c2ba023768dbe4b3f6877bc9c346c6ae529b51d9cb87ff9695ea4d01f2205584405b2", - "2c450d5b6f6e2013ac6bea6a0b32200d4e1ffb94", - "7a7a7438769536f2fb1ae49a61f0703b79b2dc53", - "f8f6b26c10f12855c9aafb1e0e839ccf", - "2b9d4b4a60cb7f396780ebff50650419", - 20, - 16, - }, -} diff --git a/src/pkg/crypto/tls/testdata/Client-TLSv10-ClientCert-ECDSA-ECDSA b/src/pkg/crypto/tls/testdata/Client-TLSv10-ClientCert-ECDSA-ECDSA deleted file mode 100644 index 00722cba9..000000000 --- a/src/pkg/crypto/tls/testdata/Client-TLSv10-ClientCert-ECDSA-ECDSA +++ /dev/null @@ -1,129 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 75 01 00 00 71 03 03 00 00 00 00 00 |....u...q.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 1a c0 2f |.............../| -00000030 c0 2b c0 11 c0 07 c0 13 c0 09 c0 14 c0 0a 00 05 |.+..............| -00000040 00 2f 00 35 c0 12 00 0a 01 00 00 2e 00 05 00 05 |./.5............| -00000050 01 00 00 00 00 00 0a 00 08 00 06 00 17 00 18 00 |................| -00000060 19 00 0b 00 02 01 00 00 0d 00 0a 00 08 04 01 04 |................| -00000070 03 02 01 02 03 ff 01 00 01 00 |..........| ->>> Flow 2 (server to client) -00000000 16 03 01 00 59 02 00 00 55 03 01 53 04 f1 03 46 |....Y...U..S...F| -00000010 0f 84 c4 cb 55 ef 85 f6 4f d7 0e e1 4b 10 d4 bb |....U...O...K...| -00000020 35 87 2d f3 d7 18 ec 4e 95 4b f4 20 28 82 94 d9 |5.-....N.K. (...| -00000030 df c4 fc ee 21 23 c1 e2 76 3e 7b 09 af 2c 39 23 |....!#..v>{..,9#| -00000040 f8 46 6c 31 88 42 f0 79 de 37 2b 00 c0 09 00 00 |.Fl1.B.y.7+.....| -00000050 0d ff 01 00 01 00 00 0b 00 04 03 00 01 02 16 03 |................| -00000060 01 02 0e 0b 00 02 0a 00 02 07 00 02 04 30 82 02 |.............0..| -00000070 00 30 82 01 62 02 09 00 b8 bf 2d 47 a0 d2 eb f4 |.0..b.....-G....| -00000080 30 09 06 07 2a 86 48 ce 3d 04 01 30 45 31 0b 30 |0...*.H.=..0E1.0| -00000090 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 03 |...U....AU1.0...| -000000a0 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 31 |U....Some-State1| -000000b0 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 6e |!0...U....Intern| -000000c0 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 4c |et Widgits Pty L| -000000d0 74 64 30 1e 17 0d 31 32 31 31 32 32 31 35 30 36 |td0...1211221506| -000000e0 33 32 5a 17 0d 32 32 31 31 32 30 31 35 30 36 33 |32Z..22112015063| -000000f0 32 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 41 |2Z0E1.0...U....A| -00000100 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d 65 |U1.0...U....Some| -00000110 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a 13 |-State1!0...U...| -00000120 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 74 |.Internet Widgit| -00000130 73 20 50 74 79 20 4c 74 64 30 81 9b 30 10 06 07 |s Pty Ltd0..0...| -00000140 2a 86 48 ce 3d 02 01 06 05 2b 81 04 00 23 03 81 |*.H.=....+...#..| -00000150 86 00 04 00 c4 a1 ed be 98 f9 0b 48 73 36 7e c3 |...........Hs6~.| -00000160 16 56 11 22 f2 3d 53 c3 3b 4d 21 3d cd 6b 75 e6 |.V.".=S.;M!=.ku.| -00000170 f6 b0 dc 9a df 26 c1 bc b2 87 f0 72 32 7c b3 64 |.....&.....r2|.d| -00000180 2f 1c 90 bc ea 68 23 10 7e fe e3 25 c0 48 3a 69 |/....h#.~..%.H:i| -00000190 e0 28 6d d3 37 00 ef 04 62 dd 0d a0 9c 70 62 83 |.(m.7...b....pb.| -000001a0 d8 81 d3 64 31 aa 9e 97 31 bd 96 b0 68 c0 9b 23 |...d1...1...h..#| -000001b0 de 76 64 3f 1a 5c 7f e9 12 0e 58 58 b6 5f 70 dd |.vd?.\....XX._p.| -000001c0 9b d8 ea d5 d7 f5 d5 cc b9 b6 9f 30 66 5b 66 9a |...........0f[f.| -000001d0 20 e2 27 e5 bf fe 3b 30 09 06 07 2a 86 48 ce 3d | .'...;0...*.H.=| -000001e0 04 01 03 81 8c 00 30 81 88 02 42 01 88 a2 4f eb |......0...B...O.| -000001f0 e2 45 c5 48 7d 1b ac f5 ed 98 9d ae 47 70 c0 5e |.E.H}.......Gp.^| -00000200 1b b6 2f bd f1 b6 4d b7 61 40 d3 11 a2 ce ee 0b |../...M.a@......| -00000210 7e 92 7e ff 76 9d c3 3b 7e a5 3f ce fa 10 e2 59 |~.~.v..;~.?....Y| -00000220 ec 47 2d 7c ac da 4e 97 0e 15 a0 6f d0 02 42 01 |.G-|..N....o..B.| -00000230 4d fc be 67 13 9c 2d 05 0e bd 3f a3 8c 25 c1 33 |M..g..-...?..%.3| -00000240 13 83 0d 94 06 bb d4 37 7a f6 ec 7a c9 86 2e dd |.......7z..z....| -00000250 d7 11 69 7f 85 7c 56 de fb 31 78 2b e4 c7 78 0d |..i..|V..1x+..x.| -00000260 ae cb be 9e 4e 36 24 31 7b 6a 0f 39 95 12 07 8f |....N6$1{j.9....| -00000270 2a 16 03 01 00 d5 0c 00 00 d1 03 00 17 41 04 4f |*............A.O| -00000280 47 16 72 98 9e 9f 2e 8e 78 e9 0f fe 95 83 7b aa |G.r.....x.....{.| -00000290 e5 3d c0 7d cf 83 bd 22 0b fd 48 f1 a7 49 a5 7d |.=.}..."..H..I.}| -000002a0 8e 0c 83 7f e1 2d 71 03 cc 90 09 ab f7 35 81 48 |.....-q......5.H| -000002b0 a4 1e 7d 87 21 23 12 58 2c 47 f3 af c7 6c 71 00 |..}.!#.X,G...lq.| -000002c0 8a 30 81 87 02 42 00 b4 03 38 60 43 d9 32 ef 64 |.0...B...8`C.2.d| -000002d0 5a 9c 91 95 0d 10 21 53 c7 78 f8 bf 50 ed 13 5d |Z.....!S.x..P..]| -000002e0 c3 e7 71 d6 11 04 f1 e4 9d ce 17 99 8d 1a 87 1f |..q.............| -000002f0 cb dd f8 1b ae cd bc 4a 77 ab 7c 50 bf 73 c3 ea |.......Jw.|P.s..| -00000300 d6 df 88 56 f6 b1 03 83 02 41 66 3d fb 4e 7e af |...V.....Af=.N~.| -00000310 4e c1 60 fe 09 fa 7e 74 99 66 7f de b4 b2 74 89 |N.`...~t.f....t.| -00000320 1c a4 cf 74 1a 55 a5 be 74 f9 36 21 3d ae c8 c3 |...t.U..t.6!=...| -00000330 24 8e ad db a3 26 67 8f 98 27 e3 93 ee d9 5c fb |$....&g..'....\.| -00000340 85 82 e2 13 c3 50 ab e9 f6 39 2b 16 03 01 00 0e |.....P...9+.....| -00000350 0d 00 00 06 03 01 02 40 00 00 0e 00 00 00 |.......@......| ->>> Flow 3 (client to server) -00000000 16 03 01 02 0a 0b 00 02 06 00 02 03 00 02 00 30 |...............0| -00000010 82 01 fc 30 82 01 5e 02 09 00 9a 30 84 6c 26 35 |...0..^....0.l&5| -00000020 d9 17 30 09 06 07 2a 86 48 ce 3d 04 01 30 45 31 |..0...*.H.=..0E1| -00000030 0b 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 |.0...U....AU1.0.| -00000040 06 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 |..U....Some-Stat| -00000050 65 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 |e1!0...U....Inte| -00000060 72 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 |rnet Widgits Pty| -00000070 20 4c 74 64 30 1e 17 0d 31 32 31 31 31 34 31 33 | Ltd0...12111413| -00000080 32 35 35 33 5a 17 0d 32 32 31 31 31 32 31 33 32 |2553Z..221112132| -00000090 35 35 33 5a 30 41 31 0b 30 09 06 03 55 04 06 13 |553Z0A1.0...U...| -000000a0 02 41 55 31 0c 30 0a 06 03 55 04 08 13 03 4e 53 |.AU1.0...U....NS| -000000b0 57 31 10 30 0e 06 03 55 04 07 13 07 50 79 72 6d |W1.0...U....Pyrm| -000000c0 6f 6e 74 31 12 30 10 06 03 55 04 03 13 09 4a 6f |ont1.0...U....Jo| -000000d0 65 6c 20 53 69 6e 67 30 81 9b 30 10 06 07 2a 86 |el Sing0..0...*.| -000000e0 48 ce 3d 02 01 06 05 2b 81 04 00 23 03 81 86 00 |H.=....+...#....| -000000f0 04 00 95 8c 91 75 14 c0 5e c4 57 b4 d4 c3 6f 8d |.....u..^.W...o.| -00000100 ae 68 1e dd 6f ce 86 e1 7e 6e b2 48 3e 81 e5 4e |.h..o...~n.H>..N| -00000110 e2 c6 88 4b 64 dc f5 30 bb d3 ff 65 cc 5b f4 dd |...Kd..0...e.[..| -00000120 b5 6a 3e 3e d0 1d de 47 c3 76 ad 19 f6 45 2c 8c |.j>>...G.v...E,.| -00000130 bc d8 1d 01 4c 1f 70 90 46 76 48 8b 8f 83 cc 4a |....L.p.FvH....J| -00000140 5c 8f 40 76 da e0 89 ec 1d 2b c4 4e 30 76 28 41 |\.@v.....+.N0v(A| -00000150 b2 62 a8 fb 5b f1 f9 4e 7a 8d bd 09 b8 ae ea 8b |.b..[..Nz.......| -00000160 18 27 4f 2e 70 fe 13 96 ba c3 d3 40 16 cd 65 4e |.'O.p......@..eN| -00000170 ac 11 1e e6 f1 30 09 06 07 2a 86 48 ce 3d 04 01 |.....0...*.H.=..| -00000180 03 81 8c 00 30 81 88 02 42 00 e0 14 c4 60 60 0b |....0...B....``.| -00000190 72 68 b0 32 5d 61 4a 02 74 5c c2 81 b9 16 a8 3f |rh.2]aJ.t\.....?| -000001a0 29 c8 36 c7 81 ff 6c b6 5b d9 70 f1 38 3b 50 48 |).6...l.[.p.8;PH| -000001b0 28 94 cb 09 1a 52 f1 5d ee 8d f2 b9 f0 f0 da d9 |(....R.]........| -000001c0 15 3a f9 bd 03 7a 87 a2 23 35 ec 02 42 01 a3 d4 |.:...z..#5..B...| -000001d0 8a 78 35 1c 4a 9a 23 d2 0a be 2b 10 31 9d 9c 5f |.x5.J.#...+.1.._| -000001e0 be e8 91 b3 da 1a f5 5d a3 23 f5 26 8b 45 70 8d |.......].#.&.Ep.| -000001f0 65 62 9b 7e 01 99 3d 18 f6 10 9a 38 61 9b 2e 57 |eb.~..=....8a..W| -00000200 e4 fa cc b1 8a ce e2 23 a0 87 f0 e1 67 51 eb 16 |.......#....gQ..| -00000210 03 01 00 46 10 00 00 42 41 04 1e 18 37 ef 0d 19 |...F...BA...7...| -00000220 51 88 35 75 71 b5 e5 54 5b 12 2e 8f 09 67 fd a7 |Q.5uq..T[....g..| -00000230 24 20 3e b2 56 1c ce 97 28 5e f8 2b 2d 4f 9e f1 |$ >.V...(^.+-O..| -00000240 07 9f 6c 4b 5b 83 56 e2 32 42 e9 58 b6 d7 49 a6 |..lK[.V.2B.X..I.| -00000250 b5 68 1a 41 03 56 6b dc 5a 89 16 03 01 00 90 0f |.h.A.Vk.Z.......| -00000260 00 00 8c 00 8a 30 81 87 02 42 00 c6 85 8e 06 b7 |.....0...B......| -00000270 04 04 e9 cd 9e 3e cb 66 23 95 b4 42 9c 64 81 39 |.....>.f#..B.d.9| -00000280 05 3f b5 21 f8 28 af 60 6b 4d 3d ba a1 4b 5e 77 |.?.!.(.`kM=..K^w| -00000290 ef e7 59 28 fe 1d c1 27 a2 ff a8 de 33 48 b3 c1 |..Y(...'....3H..| -000002a0 85 6a 42 9b f9 7e 7e 31 c2 e5 bd 66 02 41 4b 49 |.jB..~~1...f.AKI| -000002b0 c6 cd 02 e3 83 f7 03 50 18 6d b4 c9 51 02 c0 ab |.......P.m..Q...| -000002c0 87 bc e0 3e 4b 89 53 3a e2 65 89 97 02 c1 87 f1 |...>K.S:.e......| -000002d0 67 d0 f2 06 28 4e 51 4e fd f0 01 be 41 3c 52 42 |g...(NQN....AD$..w.wo...| -000002f0 03 01 00 01 01 16 03 01 00 30 a3 da 45 22 96 83 |.........0..E"..| -00000300 59 90 e9 6b ec 3b 77 50 05 89 e6 0c 61 d1 1d 2b |Y..k.;wP....a..+| -00000310 da d4 49 bf b9 c6 dd ad c3 9c 82 bd 53 62 e8 57 |..I.........Sb.W| -00000320 a4 6a e7 9f b1 d5 39 77 88 6d |.j....9w.m| ->>> Flow 4 (server to client) -00000000 14 03 01 00 01 01 16 03 01 00 30 a4 45 dd 99 df |..........0.E...| -00000010 66 ae f5 c7 bd 1a eb 6a ff ac a6 38 14 81 b5 07 |f......j...8....| -00000020 86 24 80 f1 09 59 ad 33 3d 43 ed 9e 43 b1 1e 9f |.$...Y.3=C..C...| -00000030 bd 8c b3 e0 41 83 a1 34 91 c5 a1 |....A..4...| ->>> Flow 5 (client to server) -00000000 17 03 01 00 20 ae e3 ae 7f 2d e3 a2 f7 1b 4e 69 |.... ....-....Ni| -00000010 cb 18 c6 68 42 f8 de 61 92 4c fa d6 19 7c 8c 09 |...hB..a.L...|..| -00000020 82 e2 f2 32 19 17 03 01 00 20 2a 77 65 1f c1 fd |...2..... *we...| -00000030 5e 37 b7 15 f6 1f 4c 7f 5f 89 52 b4 32 27 4d 17 |^7....L._.R.2'M.| -00000040 33 c6 e8 50 ac 70 c8 b9 2d 0a 15 03 01 00 20 e0 |3..P.p..-..... .| -00000050 cb ce 07 80 55 a0 46 ca a7 25 4c 5f 9d 7c 73 37 |....U.F..%L_.|s7| -00000060 de 72 6d 36 a8 e4 be fd 2a e7 f8 8d 14 80 b7 |.rm6....*......| diff --git a/src/pkg/crypto/tls/testdata/Client-TLSv10-ClientCert-ECDSA-RSA b/src/pkg/crypto/tls/testdata/Client-TLSv10-ClientCert-ECDSA-RSA deleted file mode 100644 index c0be82491..000000000 --- a/src/pkg/crypto/tls/testdata/Client-TLSv10-ClientCert-ECDSA-RSA +++ /dev/null @@ -1,125 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 75 01 00 00 71 03 03 00 00 00 00 00 |....u...q.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 1a c0 2f |.............../| -00000030 c0 2b c0 11 c0 07 c0 13 c0 09 c0 14 c0 0a 00 05 |.+..............| -00000040 00 2f 00 35 c0 12 00 0a 01 00 00 2e 00 05 00 05 |./.5............| -00000050 01 00 00 00 00 00 0a 00 08 00 06 00 17 00 18 00 |................| -00000060 19 00 0b 00 02 01 00 00 0d 00 0a 00 08 04 01 04 |................| -00000070 03 02 01 02 03 ff 01 00 01 00 |..........| ->>> Flow 2 (server to client) -00000000 16 03 01 00 51 02 00 00 4d 03 01 53 04 f1 02 ed |....Q...M..S....| -00000010 86 9c 56 84 5a d3 7d d7 f3 4e 6f 2c 69 0d f0 59 |..V.Z.}..No,i..Y| -00000020 a5 d1 de 2d 03 2f dd 63 c3 ab fa 20 30 d6 5a 24 |...-./.c... 0.Z$| -00000030 5c 31 67 36 8d 4c 43 e1 64 c4 8a 2c a5 fd 39 92 |\1g6.LC.d..,..9.| -00000040 c5 6f 58 47 a3 fe 63 14 98 92 11 90 00 05 00 00 |.oXG..c.........| -00000050 05 ff 01 00 01 00 16 03 01 02 be 0b 00 02 ba 00 |................| -00000060 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000070 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000080 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000090 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -000000a0 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -000000b0 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000c0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000d0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000e0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000f0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -00000100 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -00000110 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000120 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000130 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000140 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000150 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000160 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000170 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000180 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000190 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -000001a0 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -000001b0 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001c0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001d0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001e0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001f0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -00000200 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -00000210 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000220 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000230 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000240 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000250 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000260 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000270 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000280 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000290 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -000002a0 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -000002b0 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002c0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002d0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002e0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002f0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -00000300 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -00000310 6e 38 50 29 6c 90 a7 bd d9 16 03 01 00 0e 0d 00 |n8P)l...........| -00000320 00 06 03 01 02 40 00 00 0e 00 00 00 |.....@......| ->>> Flow 3 (client to server) -00000000 16 03 01 02 0a 0b 00 02 06 00 02 03 00 02 00 30 |...............0| -00000010 82 01 fc 30 82 01 5e 02 09 00 9a 30 84 6c 26 35 |...0..^....0.l&5| -00000020 d9 17 30 09 06 07 2a 86 48 ce 3d 04 01 30 45 31 |..0...*.H.=..0E1| -00000030 0b 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 |.0...U....AU1.0.| -00000040 06 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 |..U....Some-Stat| -00000050 65 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 |e1!0...U....Inte| -00000060 72 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 |rnet Widgits Pty| -00000070 20 4c 74 64 30 1e 17 0d 31 32 31 31 31 34 31 33 | Ltd0...12111413| -00000080 32 35 35 33 5a 17 0d 32 32 31 31 31 32 31 33 32 |2553Z..221112132| -00000090 35 35 33 5a 30 41 31 0b 30 09 06 03 55 04 06 13 |553Z0A1.0...U...| -000000a0 02 41 55 31 0c 30 0a 06 03 55 04 08 13 03 4e 53 |.AU1.0...U....NS| -000000b0 57 31 10 30 0e 06 03 55 04 07 13 07 50 79 72 6d |W1.0...U....Pyrm| -000000c0 6f 6e 74 31 12 30 10 06 03 55 04 03 13 09 4a 6f |ont1.0...U....Jo| -000000d0 65 6c 20 53 69 6e 67 30 81 9b 30 10 06 07 2a 86 |el Sing0..0...*.| -000000e0 48 ce 3d 02 01 06 05 2b 81 04 00 23 03 81 86 00 |H.=....+...#....| -000000f0 04 00 95 8c 91 75 14 c0 5e c4 57 b4 d4 c3 6f 8d |.....u..^.W...o.| -00000100 ae 68 1e dd 6f ce 86 e1 7e 6e b2 48 3e 81 e5 4e |.h..o...~n.H>..N| -00000110 e2 c6 88 4b 64 dc f5 30 bb d3 ff 65 cc 5b f4 dd |...Kd..0...e.[..| -00000120 b5 6a 3e 3e d0 1d de 47 c3 76 ad 19 f6 45 2c 8c |.j>>...G.v...E,.| -00000130 bc d8 1d 01 4c 1f 70 90 46 76 48 8b 8f 83 cc 4a |....L.p.FvH....J| -00000140 5c 8f 40 76 da e0 89 ec 1d 2b c4 4e 30 76 28 41 |\.@v.....+.N0v(A| -00000150 b2 62 a8 fb 5b f1 f9 4e 7a 8d bd 09 b8 ae ea 8b |.b..[..Nz.......| -00000160 18 27 4f 2e 70 fe 13 96 ba c3 d3 40 16 cd 65 4e |.'O.p......@..eN| -00000170 ac 11 1e e6 f1 30 09 06 07 2a 86 48 ce 3d 04 01 |.....0...*.H.=..| -00000180 03 81 8c 00 30 81 88 02 42 00 e0 14 c4 60 60 0b |....0...B....``.| -00000190 72 68 b0 32 5d 61 4a 02 74 5c c2 81 b9 16 a8 3f |rh.2]aJ.t\.....?| -000001a0 29 c8 36 c7 81 ff 6c b6 5b d9 70 f1 38 3b 50 48 |).6...l.[.p.8;PH| -000001b0 28 94 cb 09 1a 52 f1 5d ee 8d f2 b9 f0 f0 da d9 |(....R.]........| -000001c0 15 3a f9 bd 03 7a 87 a2 23 35 ec 02 42 01 a3 d4 |.:...z..#5..B...| -000001d0 8a 78 35 1c 4a 9a 23 d2 0a be 2b 10 31 9d 9c 5f |.x5.J.#...+.1.._| -000001e0 be e8 91 b3 da 1a f5 5d a3 23 f5 26 8b 45 70 8d |.......].#.&.Ep.| -000001f0 65 62 9b 7e 01 99 3d 18 f6 10 9a 38 61 9b 2e 57 |eb.~..=....8a..W| -00000200 e4 fa cc b1 8a ce e2 23 a0 87 f0 e1 67 51 eb 16 |.......#....gQ..| -00000210 03 01 00 86 10 00 00 82 00 80 6d 51 f3 7f f9 3e |..........mQ...>| -00000220 fb 75 82 41 36 83 e8 6a ee 2a 2e 25 90 67 4c 8e |.u.A6..j.*.%.gL.| -00000230 62 2f 30 81 17 e0 85 09 0c 2b b7 23 d7 b0 e2 1d |b/0......+.#....| -00000240 f7 3b d7 f5 a1 27 b6 ee 24 b6 1b cc 5b ea 66 0d |.;...'..$...[.f.| -00000250 6a f4 e5 85 f9 da 43 b4 0e 86 85 e1 f5 aa be c8 |j.....C.........| -00000260 ce 39 4c 9c 86 00 08 c2 4b e2 c6 ec 2f f7 ce e6 |.9L.....K.../...| -00000270 bd 77 82 6f 23 b6 e0 bd a2 92 b7 3a ac e8 56 f1 |.w.o#......:..V.| -00000280 af 54 5e 46 87 e9 3b 33 e7 b8 28 b7 d6 c8 90 35 |.T^F..;3..(....5| -00000290 d4 1c 43 d1 30 6f 55 4e 0a 70 16 03 01 00 90 0f |..C.0oUN.p......| -000002a0 00 00 8c 00 8a 30 81 87 02 42 00 c6 85 8e 06 b7 |.....0...B......| -000002b0 04 04 e9 cd 9e 3e cb 66 23 95 b4 42 9c 64 81 39 |.....>.f#..B.d.9| -000002c0 05 3f b5 21 f8 28 af 60 6b 4d 3d ba a1 4b 5e 77 |.?.!.(.`kM=..K^w| -000002d0 ef e7 59 28 fe 1d c1 27 a2 ff a8 de 33 48 b3 c1 |..Y(...'....3H..| -000002e0 85 6a 42 9b f9 7e 7e 31 c2 e5 bd 66 02 41 4b 49 |.jB..~~1...f.AKI| -000002f0 c6 cd 02 e3 83 f7 03 50 18 6d b4 c9 51 02 c0 ab |.......P.m..Q...| -00000300 87 bc e0 3e 4b 89 53 3a e2 65 89 97 02 c1 87 f1 |...>K.S:.e......| -00000310 67 d0 f2 06 28 4e 51 4e fd f0 01 47 e7 c9 d9 23 |g...(NQN...G...#| -00000320 21 6b 87 d2 55 e3 c9 f7 eb 86 d5 1e 50 df d5 14 |!k..U.......P...| -00000330 03 01 00 01 01 16 03 01 00 24 95 62 42 be 90 39 |.........$.bB..9| -00000340 68 ae f5 77 47 21 14 b9 ac ee 81 2d e3 9e c7 34 |h..wG!.....-...4| -00000350 3a 00 5c c9 12 1d c0 5a 7c e7 ef e0 cd fd |:.\....Z|.....| ->>> Flow 4 (server to client) -00000000 14 03 01 00 01 01 16 03 01 00 24 ea 98 c0 fb 86 |..........$.....| -00000010 87 7a 2e e1 c7 68 61 3e 5b cc da 1f d6 7b ab 5a |.z...ha>[....{.Z| -00000020 a0 ae a2 cf d0 54 44 19 12 db 75 2b 8c 73 8c |.....TD...u+.s.| ->>> Flow 5 (client to server) -00000000 17 03 01 00 1a f3 28 77 31 33 4c b3 7c 4b 75 61 |......(w13L.|Kua| -00000010 38 69 6b ae c9 36 ab 2e 56 16 29 6a 9a 00 2f 15 |8ik..6..V.)j../.| -00000020 03 01 00 16 6b ed 68 18 ed ff 44 39 9b 4a e4 a2 |....k.h...D9.J..| -00000030 cd 79 ef 2a 3e 5a 4d b1 5d 56 |.y.*>ZM.]V| diff --git a/src/pkg/crypto/tls/testdata/Client-TLSv10-ClientCert-RSA-ECDSA b/src/pkg/crypto/tls/testdata/Client-TLSv10-ClientCert-RSA-ECDSA deleted file mode 100644 index 3e6dbc271..000000000 --- a/src/pkg/crypto/tls/testdata/Client-TLSv10-ClientCert-RSA-ECDSA +++ /dev/null @@ -1,128 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 75 01 00 00 71 03 03 00 00 00 00 00 |....u...q.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 1a c0 2f |.............../| -00000030 c0 2b c0 11 c0 07 c0 13 c0 09 c0 14 c0 0a 00 05 |.+..............| -00000040 00 2f 00 35 c0 12 00 0a 01 00 00 2e 00 05 00 05 |./.5............| -00000050 01 00 00 00 00 00 0a 00 08 00 06 00 17 00 18 00 |................| -00000060 19 00 0b 00 02 01 00 00 0d 00 0a 00 08 04 01 04 |................| -00000070 03 02 01 02 03 ff 01 00 01 00 |..........| ->>> Flow 2 (server to client) -00000000 16 03 01 00 59 02 00 00 55 03 01 53 04 f1 02 4f |....Y...U..S...O| -00000010 73 06 2d 72 41 36 a1 b2 d3 50 97 55 8c c5 f1 43 |s.-rA6...P.U...C| -00000020 37 1f 1a 2a fe 51 70 0b 2f 25 9e 20 50 61 86 80 |7..*.Qp./%. Pa..| -00000030 9a 9c 6d 6f c9 ea 5c ce 0c b7 7c ce e3 be d0 e5 |..mo..\...|.....| -00000040 be d0 c4 80 78 c3 c7 17 0c 2d 8e c8 c0 09 00 00 |....x....-......| -00000050 0d ff 01 00 01 00 00 0b 00 04 03 00 01 02 16 03 |................| -00000060 01 02 0e 0b 00 02 0a 00 02 07 00 02 04 30 82 02 |.............0..| -00000070 00 30 82 01 62 02 09 00 b8 bf 2d 47 a0 d2 eb f4 |.0..b.....-G....| -00000080 30 09 06 07 2a 86 48 ce 3d 04 01 30 45 31 0b 30 |0...*.H.=..0E1.0| -00000090 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 03 |...U....AU1.0...| -000000a0 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 31 |U....Some-State1| -000000b0 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 6e |!0...U....Intern| -000000c0 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 4c |et Widgits Pty L| -000000d0 74 64 30 1e 17 0d 31 32 31 31 32 32 31 35 30 36 |td0...1211221506| -000000e0 33 32 5a 17 0d 32 32 31 31 32 30 31 35 30 36 33 |32Z..22112015063| -000000f0 32 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 41 |2Z0E1.0...U....A| -00000100 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d 65 |U1.0...U....Some| -00000110 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a 13 |-State1!0...U...| -00000120 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 74 |.Internet Widgit| -00000130 73 20 50 74 79 20 4c 74 64 30 81 9b 30 10 06 07 |s Pty Ltd0..0...| -00000140 2a 86 48 ce 3d 02 01 06 05 2b 81 04 00 23 03 81 |*.H.=....+...#..| -00000150 86 00 04 00 c4 a1 ed be 98 f9 0b 48 73 36 7e c3 |...........Hs6~.| -00000160 16 56 11 22 f2 3d 53 c3 3b 4d 21 3d cd 6b 75 e6 |.V.".=S.;M!=.ku.| -00000170 f6 b0 dc 9a df 26 c1 bc b2 87 f0 72 32 7c b3 64 |.....&.....r2|.d| -00000180 2f 1c 90 bc ea 68 23 10 7e fe e3 25 c0 48 3a 69 |/....h#.~..%.H:i| -00000190 e0 28 6d d3 37 00 ef 04 62 dd 0d a0 9c 70 62 83 |.(m.7...b....pb.| -000001a0 d8 81 d3 64 31 aa 9e 97 31 bd 96 b0 68 c0 9b 23 |...d1...1...h..#| -000001b0 de 76 64 3f 1a 5c 7f e9 12 0e 58 58 b6 5f 70 dd |.vd?.\....XX._p.| -000001c0 9b d8 ea d5 d7 f5 d5 cc b9 b6 9f 30 66 5b 66 9a |...........0f[f.| -000001d0 20 e2 27 e5 bf fe 3b 30 09 06 07 2a 86 48 ce 3d | .'...;0...*.H.=| -000001e0 04 01 03 81 8c 00 30 81 88 02 42 01 88 a2 4f eb |......0...B...O.| -000001f0 e2 45 c5 48 7d 1b ac f5 ed 98 9d ae 47 70 c0 5e |.E.H}.......Gp.^| -00000200 1b b6 2f bd f1 b6 4d b7 61 40 d3 11 a2 ce ee 0b |../...M.a@......| -00000210 7e 92 7e ff 76 9d c3 3b 7e a5 3f ce fa 10 e2 59 |~.~.v..;~.?....Y| -00000220 ec 47 2d 7c ac da 4e 97 0e 15 a0 6f d0 02 42 01 |.G-|..N....o..B.| -00000230 4d fc be 67 13 9c 2d 05 0e bd 3f a3 8c 25 c1 33 |M..g..-...?..%.3| -00000240 13 83 0d 94 06 bb d4 37 7a f6 ec 7a c9 86 2e dd |.......7z..z....| -00000250 d7 11 69 7f 85 7c 56 de fb 31 78 2b e4 c7 78 0d |..i..|V..1x+..x.| -00000260 ae cb be 9e 4e 36 24 31 7b 6a 0f 39 95 12 07 8f |....N6$1{j.9....| -00000270 2a 16 03 01 00 d6 0c 00 00 d2 03 00 17 41 04 b1 |*............A..| -00000280 0f 0f 4a 18 ed 25 32 b3 a3 19 ed 4b 61 b6 eb e4 |..J..%2....Ka...| -00000290 d3 f7 77 13 ac 9f 60 c7 8d 6d cb f1 ee 99 1a 71 |..w...`..m.....q| -000002a0 68 aa d3 a7 70 7f 38 d0 f6 23 ab 9a f6 dd 19 4f |h...p.8..#.....O| -000002b0 ce 10 ef d5 cf 64 85 2f 75 f6 20 06 4b f0 b9 00 |.....d./u. .K...| -000002c0 8b 30 81 88 02 42 01 00 b9 6b 80 91 59 0a 48 3f |.0...B...k..Y.H?| -000002d0 72 16 96 8f 21 2c 28 e4 6d 03 74 66 35 16 7d ec |r...!,(.m.tf5.}.| -000002e0 c7 08 9b 52 b5 05 d9 38 d8 b7 51 42 a7 4a 9f 9b |...R...8..QB.J..| -000002f0 1a 37 14 de c5 f5 16 96 83 81 58 d3 a6 1e ce 8a |.7........X.....| -00000300 bc 19 47 30 fe c5 85 55 02 42 01 4f 61 59 68 85 |..G0...U.B.OaYh.| -00000310 c7 64 23 22 f6 83 53 cc 58 38 25 b5 ce 74 c1 68 |.d#"..S.X8%..t.h| -00000320 9f 32 72 33 ea c9 62 e0 26 63 92 e3 5f 34 10 0b |.2r3..b.&c.._4..| -00000330 3c d5 83 fe 9f 67 69 ef 33 6b 19 c1 ec d6 6c 35 |<....gi.3k....l5| -00000340 89 33 17 d3 9d 93 e2 e5 6e 89 9a a1 16 03 01 00 |.3......n.......| -00000350 0e 0d 00 00 06 03 01 02 40 00 00 0e 00 00 00 |........@......| ->>> Flow 3 (client to server) -00000000 16 03 01 01 fb 0b 00 01 f7 00 01 f4 00 01 f1 30 |...............0| -00000010 82 01 ed 30 82 01 58 a0 03 02 01 02 02 01 00 30 |...0..X........0| -00000020 0b 06 09 2a 86 48 86 f7 0d 01 01 05 30 26 31 10 |...*.H......0&1.| -00000030 30 0e 06 03 55 04 0a 13 07 41 63 6d 65 20 43 6f |0...U....Acme Co| -00000040 31 12 30 10 06 03 55 04 03 13 09 31 32 37 2e 30 |1.0...U....127.0| -00000050 2e 30 2e 31 30 1e 17 0d 31 31 31 32 30 38 30 37 |.0.10...11120807| -00000060 35 35 31 32 5a 17 0d 31 32 31 32 30 37 30 38 30 |5512Z..121207080| -00000070 30 31 32 5a 30 26 31 10 30 0e 06 03 55 04 0a 13 |012Z0&1.0...U...| -00000080 07 41 63 6d 65 20 43 6f 31 12 30 10 06 03 55 04 |.Acme Co1.0...U.| -00000090 03 13 09 31 32 37 2e 30 2e 30 2e 31 30 81 9c 30 |...127.0.0.10..0| -000000a0 0b 06 09 2a 86 48 86 f7 0d 01 01 01 03 81 8c 00 |...*.H..........| -000000b0 30 81 88 02 81 80 4e d0 7b 31 e3 82 64 d9 59 c0 |0.....N.{1..d.Y.| -000000c0 c2 87 a4 5e 1e 8b 73 33 c7 63 53 df 66 92 06 84 |...^..s3.cS.f...| -000000d0 f6 64 d5 8f e4 36 a7 1d 2b e8 b3 20 36 45 23 b5 |.d...6..+.. 6E#.| -000000e0 e3 95 ae ed e0 f5 20 9c 8d 95 df 7f 5a 12 ef 87 |...... .....Z...| -000000f0 e4 5b 68 e4 e9 0e 74 ec 04 8a 7f de 93 27 c4 01 |.[h...t......'..| -00000100 19 7a bd f2 dc 3d 14 ab d0 54 ca 21 0c d0 4d 6e |.z...=...T.!..Mn| -00000110 87 2e 5c c5 d2 bb 4d 4b 4f ce b6 2c f7 7e 88 ec |..\...MKO..,.~..| -00000120 7c d7 02 91 74 a6 1e 0c 1a da e3 4a 5a 2e de 13 ||...t......JZ...| -00000130 9c 4c 40 88 59 93 02 03 01 00 01 a3 32 30 30 30 |.L@.Y.......2000| -00000140 0e 06 03 55 1d 0f 01 01 ff 04 04 03 02 00 a0 30 |...U...........0| -00000150 0d 06 03 55 1d 0e 04 06 04 04 01 02 03 04 30 0f |...U..........0.| -00000160 06 03 55 1d 23 04 08 30 06 80 04 01 02 03 04 30 |..U.#..0.......0| -00000170 0b 06 09 2a 86 48 86 f7 0d 01 01 05 03 81 81 00 |...*.H..........| -00000180 36 1f b3 7a 0c 75 c9 6e 37 46 61 2b d5 bd c0 a7 |6..z.u.n7Fa+....| -00000190 4b cc 46 9a 81 58 7c 85 79 29 c8 c8 c6 67 dd 32 |K.F..X|.y)...g.2| -000001a0 56 45 2b 75 b6 e9 24 a9 50 9a be 1f 5a fa 1a 15 |VE+u..$.P...Z...| -000001b0 d9 cc 55 95 72 16 83 b9 c2 b6 8f fd 88 8c 38 84 |..U.r.........8.| -000001c0 1d ab 5d 92 31 13 4f fd 83 3b c6 9d f1 11 62 b6 |..].1.O..;....b.| -000001d0 8b ec ab 67 be c8 64 b0 11 50 46 58 17 6b 99 1c |...g..d..PFX.k..| -000001e0 d3 1d fc 06 f1 0e e5 96 a8 0c f9 78 20 b7 44 18 |...........x .D.| -000001f0 51 8d 10 7e 4f 94 67 df a3 4e 70 73 8e 90 91 85 |Q..~O.g..Nps....| -00000200 16 03 01 00 46 10 00 00 42 41 04 1e 18 37 ef 0d |....F...BA...7..| -00000210 19 51 88 35 75 71 b5 e5 54 5b 12 2e 8f 09 67 fd |.Q.5uq..T[....g.| -00000220 a7 24 20 3e b2 56 1c ce 97 28 5e f8 2b 2d 4f 9e |.$ >.V...(^.+-O.| -00000230 f1 07 9f 6c 4b 5b 83 56 e2 32 42 e9 58 b6 d7 49 |...lK[.V.2B.X..I| -00000240 a6 b5 68 1a 41 03 56 6b dc 5a 89 16 03 01 00 86 |..h.A.Vk.Z......| -00000250 0f 00 00 82 00 80 20 2c 5a 08 3a 00 33 50 19 b2 |...... ,Z.:.3P..| -00000260 0f ba 6c 76 7f 5c 92 e2 78 55 3e 32 32 bb 33 bc |..lv.\..xU>22.3.| -00000270 ab a9 34 e0 83 cf 82 cd 9e 6b 3f 9d e6 49 61 29 |..4......k?..Ia)| -00000280 8b b4 ed e8 12 cd a9 52 86 11 48 64 08 61 72 8d |.......R..Hd.ar.| -00000290 d6 6a ac 42 cc e4 07 5f 08 56 9f 2f c5 35 d3 9b |.j.B..._.V./.5..| -000002a0 e9 0d 91 82 c0 e9 bb 9f a9 8f df 96 85 08 9a 69 |...............i| -000002b0 a4 93 b3 72 37 ba f9 b1 a4 0b b0 9f 43 6a 15 ec |...r7.......Cj..| -000002c0 79 b8 fd 9c 1f 5f 0d 2c 56 33 c7 15 d5 4a b7 82 |y...._.,V3...J..| -000002d0 ea 44 80 20 c5 80 14 03 01 00 01 01 16 03 01 00 |.D. ............| -000002e0 30 c9 c0 7c d7 57 d3 00 ab 87 eb 78 56 6b a1 69 |0..|.W.....xVk.i| -000002f0 1d fa ec ae 38 f3 ef 5d 49 19 0d 4b f0 73 63 af |....8..]I..K.sc.| -00000300 89 b6 cb 76 cf fb b9 c1 99 98 06 0a 54 67 a0 6e |...v........Tg.n| -00000310 e7 |.| ->>> Flow 4 (server to client) -00000000 14 03 01 00 01 01 16 03 01 00 30 20 db fd ed ed |..........0 ....| -00000010 7c d5 bf 8f 06 3b 86 1b c1 60 7d a4 74 e9 a6 c9 ||....;...`}.t...| -00000020 f5 7c c7 f4 65 91 06 d5 53 88 d7 57 a4 22 b6 1f |.|..e...S..W."..| -00000030 f1 02 e9 79 36 e6 a1 22 51 3a 4c |...y6.."Q:L| ->>> Flow 5 (client to server) -00000000 17 03 01 00 20 00 66 51 6a 14 ca ea e2 21 48 74 |.... .fQj....!Ht| -00000010 c4 c1 6e b9 8b 23 af 7c 33 c9 00 f8 0b ec ab 35 |..n..#.|3......5| -00000020 e7 42 0a d1 ae 17 03 01 00 20 00 1c 6d 60 75 5d |.B....... ..m`u]| -00000030 b3 fb 40 2e e0 b7 0d 48 f4 87 ac d4 bf ea 01 0d |..@....H........| -00000040 fe 10 0d 05 04 43 6b 19 ed f2 15 03 01 00 20 f8 |.....Ck....... .| -00000050 03 ac 62 4b 1f db 2e d2 4e 00 c3 a4 57 3c 0a 62 |..bK....N...W<.b| -00000060 05 a0 ef bd 2b 9b 9a 63 27 72 d7 d8 f1 8d 84 |....+..c'r.....| diff --git a/src/pkg/crypto/tls/testdata/Client-TLSv10-ClientCert-RSA-RSA b/src/pkg/crypto/tls/testdata/Client-TLSv10-ClientCert-RSA-RSA deleted file mode 100644 index 94e686004..000000000 --- a/src/pkg/crypto/tls/testdata/Client-TLSv10-ClientCert-RSA-RSA +++ /dev/null @@ -1,124 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 75 01 00 00 71 03 03 00 00 00 00 00 |....u...q.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 1a c0 2f |.............../| -00000030 c0 2b c0 11 c0 07 c0 13 c0 09 c0 14 c0 0a 00 05 |.+..............| -00000040 00 2f 00 35 c0 12 00 0a 01 00 00 2e 00 05 00 05 |./.5............| -00000050 01 00 00 00 00 00 0a 00 08 00 06 00 17 00 18 00 |................| -00000060 19 00 0b 00 02 01 00 00 0d 00 0a 00 08 04 01 04 |................| -00000070 03 02 01 02 03 ff 01 00 01 00 |..........| ->>> Flow 2 (server to client) -00000000 16 03 01 00 51 02 00 00 4d 03 01 53 04 f1 02 73 |....Q...M..S...s| -00000010 ee 5f 70 a4 aa 0d be d7 46 a3 25 3f e3 5d ef 7b |._p.....F.%?.].{| -00000020 73 49 7c b6 82 4d 99 2f 31 fc 8b 20 2d a3 33 7c |sI|..M./1.. -.3|| -00000030 a5 c3 85 86 ba 61 4d 05 b0 5e d3 5e 88 6e c3 4b |.....aM..^.^.n.K| -00000040 95 d3 e9 67 f1 96 24 58 7a 6f e6 c5 00 05 00 00 |...g..$Xzo......| -00000050 05 ff 01 00 01 00 16 03 01 02 be 0b 00 02 ba 00 |................| -00000060 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000070 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000080 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000090 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -000000a0 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -000000b0 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000c0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000d0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000e0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000f0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -00000100 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -00000110 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000120 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000130 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000140 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000150 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000160 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000170 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000180 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000190 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -000001a0 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -000001b0 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001c0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001d0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001e0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001f0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -00000200 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -00000210 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000220 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000230 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000240 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000250 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000260 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000270 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000280 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000290 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -000002a0 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -000002b0 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002c0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002d0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002e0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002f0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -00000300 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -00000310 6e 38 50 29 6c 90 a7 bd d9 16 03 01 00 0e 0d 00 |n8P)l...........| -00000320 00 06 03 01 02 40 00 00 0e 00 00 00 |.....@......| ->>> Flow 3 (client to server) -00000000 16 03 01 01 fb 0b 00 01 f7 00 01 f4 00 01 f1 30 |...............0| -00000010 82 01 ed 30 82 01 58 a0 03 02 01 02 02 01 00 30 |...0..X........0| -00000020 0b 06 09 2a 86 48 86 f7 0d 01 01 05 30 26 31 10 |...*.H......0&1.| -00000030 30 0e 06 03 55 04 0a 13 07 41 63 6d 65 20 43 6f |0...U....Acme Co| -00000040 31 12 30 10 06 03 55 04 03 13 09 31 32 37 2e 30 |1.0...U....127.0| -00000050 2e 30 2e 31 30 1e 17 0d 31 31 31 32 30 38 30 37 |.0.10...11120807| -00000060 35 35 31 32 5a 17 0d 31 32 31 32 30 37 30 38 30 |5512Z..121207080| -00000070 30 31 32 5a 30 26 31 10 30 0e 06 03 55 04 0a 13 |012Z0&1.0...U...| -00000080 07 41 63 6d 65 20 43 6f 31 12 30 10 06 03 55 04 |.Acme Co1.0...U.| -00000090 03 13 09 31 32 37 2e 30 2e 30 2e 31 30 81 9c 30 |...127.0.0.10..0| -000000a0 0b 06 09 2a 86 48 86 f7 0d 01 01 01 03 81 8c 00 |...*.H..........| -000000b0 30 81 88 02 81 80 4e d0 7b 31 e3 82 64 d9 59 c0 |0.....N.{1..d.Y.| -000000c0 c2 87 a4 5e 1e 8b 73 33 c7 63 53 df 66 92 06 84 |...^..s3.cS.f...| -000000d0 f6 64 d5 8f e4 36 a7 1d 2b e8 b3 20 36 45 23 b5 |.d...6..+.. 6E#.| -000000e0 e3 95 ae ed e0 f5 20 9c 8d 95 df 7f 5a 12 ef 87 |...... .....Z...| -000000f0 e4 5b 68 e4 e9 0e 74 ec 04 8a 7f de 93 27 c4 01 |.[h...t......'..| -00000100 19 7a bd f2 dc 3d 14 ab d0 54 ca 21 0c d0 4d 6e |.z...=...T.!..Mn| -00000110 87 2e 5c c5 d2 bb 4d 4b 4f ce b6 2c f7 7e 88 ec |..\...MKO..,.~..| -00000120 7c d7 02 91 74 a6 1e 0c 1a da e3 4a 5a 2e de 13 ||...t......JZ...| -00000130 9c 4c 40 88 59 93 02 03 01 00 01 a3 32 30 30 30 |.L@.Y.......2000| -00000140 0e 06 03 55 1d 0f 01 01 ff 04 04 03 02 00 a0 30 |...U...........0| -00000150 0d 06 03 55 1d 0e 04 06 04 04 01 02 03 04 30 0f |...U..........0.| -00000160 06 03 55 1d 23 04 08 30 06 80 04 01 02 03 04 30 |..U.#..0.......0| -00000170 0b 06 09 2a 86 48 86 f7 0d 01 01 05 03 81 81 00 |...*.H..........| -00000180 36 1f b3 7a 0c 75 c9 6e 37 46 61 2b d5 bd c0 a7 |6..z.u.n7Fa+....| -00000190 4b cc 46 9a 81 58 7c 85 79 29 c8 c8 c6 67 dd 32 |K.F..X|.y)...g.2| -000001a0 56 45 2b 75 b6 e9 24 a9 50 9a be 1f 5a fa 1a 15 |VE+u..$.P...Z...| -000001b0 d9 cc 55 95 72 16 83 b9 c2 b6 8f fd 88 8c 38 84 |..U.r.........8.| -000001c0 1d ab 5d 92 31 13 4f fd 83 3b c6 9d f1 11 62 b6 |..].1.O..;....b.| -000001d0 8b ec ab 67 be c8 64 b0 11 50 46 58 17 6b 99 1c |...g..d..PFX.k..| -000001e0 d3 1d fc 06 f1 0e e5 96 a8 0c f9 78 20 b7 44 18 |...........x .D.| -000001f0 51 8d 10 7e 4f 94 67 df a3 4e 70 73 8e 90 91 85 |Q..~O.g..Nps....| -00000200 16 03 01 00 86 10 00 00 82 00 80 6d 51 f3 7f f9 |...........mQ...| -00000210 3e fb 75 82 41 36 83 e8 6a ee 2a 2e 25 90 67 4c |>.u.A6..j.*.%.gL| -00000220 8e 62 2f 30 81 17 e0 85 09 0c 2b b7 23 d7 b0 e2 |.b/0......+.#...| -00000230 1d f7 3b d7 f5 a1 27 b6 ee 24 b6 1b cc 5b ea 66 |..;...'..$...[.f| -00000240 0d 6a f4 e5 85 f9 da 43 b4 0e 86 85 e1 f5 aa be |.j.....C........| -00000250 c8 ce 39 4c 9c 86 00 08 c2 4b e2 c6 ec 2f f7 ce |..9L.....K.../..| -00000260 e6 bd 77 82 6f 23 b6 e0 bd a2 92 b7 3a ac e8 56 |..w.o#......:..V| -00000270 f1 af 54 5e 46 87 e9 3b 33 e7 b8 28 b7 d6 c8 90 |..T^F..;3..(....| -00000280 35 d4 1c 43 d1 30 6f 55 4e 0a 70 16 03 01 00 86 |5..C.0oUN.p.....| -00000290 0f 00 00 82 00 80 0f 4c d2 b2 f0 94 6d 61 d1 2c |.......L....ma.,| -000002a0 db 6f 79 03 bd 40 b2 d2 1d 61 ef 83 1b 4a 0c 7b |.oy..@...a...J.{| -000002b0 c5 73 1e 1a 81 e7 67 0a d6 aa 2d 04 04 cc 0e 4b |.s....g...-....K| -000002c0 2e da 96 7f 15 6c 05 ee c4 53 7e 33 89 28 7d db |.....l...S~3.(}.| -000002d0 a1 77 43 ba a3 51 a9 1c b9 f5 ec 9a 8d eb 2c 46 |.wC..Q........,F| -000002e0 5c 33 59 6b 16 af de f4 9b 80 76 a3 22 30 5d bb |\3Yk......v."0].| -000002f0 02 b9 77 96 8a db 36 9f 54 95 00 d8 58 e1 aa 04 |..w...6.T...X...| -00000300 98 c9 0c 32 ae 62 81 12 0c f6 1b 76 c6 58 a7 8c |...2.b.....v.X..| -00000310 0e d8 b7 8e ed 0f 14 03 01 00 01 01 16 03 01 00 |................| -00000320 24 1d c0 20 02 2d da 69 54 29 8c ff af 5c 56 a8 |$.. .-.iT)...\V.| -00000330 eb d0 09 95 29 8f 52 8c e2 7b 9f 36 3e 47 a0 33 |....).R..{.6>G.3| -00000340 2e 63 a2 24 93 |.c.$.| ->>> Flow 4 (server to client) -00000000 14 03 01 00 01 01 16 03 01 00 24 99 e8 fb 65 f4 |..........$...e.| -00000010 95 ae 8b 71 cc 5d a4 95 a7 27 98 fd 16 3f 7a 1a |...q.]...'...?z.| -00000020 b6 bd bf 0a 58 72 77 97 1f 8e b1 dd 4b 12 12 |....Xrw.....K..| ->>> Flow 5 (client to server) -00000000 17 03 01 00 1a 42 70 c0 89 78 12 5c 91 7e 88 2d |.....Bp..x.\.~.-| -00000010 2f 8f be f2 f2 12 9d 81 ae 78 08 38 5e 6d 1b 15 |/........x.8^m..| -00000020 03 01 00 16 1a 64 b1 6f 8a ff d3 63 6a c7 b8 95 |.....d.o...cj...| -00000030 3d b0 87 bc 62 e9 88 5b 26 bd |=...b..[&.| diff --git a/src/pkg/crypto/tls/testdata/Client-TLSv10-ECDHE-ECDSA-AES b/src/pkg/crypto/tls/testdata/Client-TLSv10-ECDHE-ECDSA-AES deleted file mode 100644 index 30c4c6b83..000000000 --- a/src/pkg/crypto/tls/testdata/Client-TLSv10-ECDHE-ECDSA-AES +++ /dev/null @@ -1,87 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 75 01 00 00 71 03 03 00 00 00 00 00 |....u...q.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 1a c0 2f |.............../| -00000030 c0 2b c0 11 c0 07 c0 13 c0 09 c0 14 c0 0a 00 05 |.+..............| -00000040 00 2f 00 35 c0 12 00 0a 01 00 00 2e 00 05 00 05 |./.5............| -00000050 01 00 00 00 00 00 0a 00 08 00 06 00 17 00 18 00 |................| -00000060 19 00 0b 00 02 01 00 00 0d 00 0a 00 08 04 01 04 |................| -00000070 03 02 01 02 03 ff 01 00 01 00 |..........| ->>> Flow 2 (server to client) -00000000 16 03 01 00 59 02 00 00 55 03 01 53 04 f1 02 b2 |....Y...U..S....| -00000010 e0 f6 f6 b5 c9 5b 28 d0 5d 58 1b 6f 4e 2b 9d 05 |.....[(.]X.oN+..| -00000020 2a b9 b4 da 45 cf f3 10 b2 23 44 20 f8 4d 59 05 |*...E....#D .MY.| -00000030 ad 27 f2 a0 ee 7f ec cc 20 dc e7 a2 1b 07 b3 a5 |.'...... .......| -00000040 37 7e 61 3d d6 5c 03 cf cc f5 9b ca c0 09 00 00 |7~a=.\..........| -00000050 0d ff 01 00 01 00 00 0b 00 04 03 00 01 02 16 03 |................| -00000060 01 02 0e 0b 00 02 0a 00 02 07 00 02 04 30 82 02 |.............0..| -00000070 00 30 82 01 62 02 09 00 b8 bf 2d 47 a0 d2 eb f4 |.0..b.....-G....| -00000080 30 09 06 07 2a 86 48 ce 3d 04 01 30 45 31 0b 30 |0...*.H.=..0E1.0| -00000090 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 03 |...U....AU1.0...| -000000a0 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 31 |U....Some-State1| -000000b0 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 6e |!0...U....Intern| -000000c0 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 4c |et Widgits Pty L| -000000d0 74 64 30 1e 17 0d 31 32 31 31 32 32 31 35 30 36 |td0...1211221506| -000000e0 33 32 5a 17 0d 32 32 31 31 32 30 31 35 30 36 33 |32Z..22112015063| -000000f0 32 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 41 |2Z0E1.0...U....A| -00000100 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d 65 |U1.0...U....Some| -00000110 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a 13 |-State1!0...U...| -00000120 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 74 |.Internet Widgit| -00000130 73 20 50 74 79 20 4c 74 64 30 81 9b 30 10 06 07 |s Pty Ltd0..0...| -00000140 2a 86 48 ce 3d 02 01 06 05 2b 81 04 00 23 03 81 |*.H.=....+...#..| -00000150 86 00 04 00 c4 a1 ed be 98 f9 0b 48 73 36 7e c3 |...........Hs6~.| -00000160 16 56 11 22 f2 3d 53 c3 3b 4d 21 3d cd 6b 75 e6 |.V.".=S.;M!=.ku.| -00000170 f6 b0 dc 9a df 26 c1 bc b2 87 f0 72 32 7c b3 64 |.....&.....r2|.d| -00000180 2f 1c 90 bc ea 68 23 10 7e fe e3 25 c0 48 3a 69 |/....h#.~..%.H:i| -00000190 e0 28 6d d3 37 00 ef 04 62 dd 0d a0 9c 70 62 83 |.(m.7...b....pb.| -000001a0 d8 81 d3 64 31 aa 9e 97 31 bd 96 b0 68 c0 9b 23 |...d1...1...h..#| -000001b0 de 76 64 3f 1a 5c 7f e9 12 0e 58 58 b6 5f 70 dd |.vd?.\....XX._p.| -000001c0 9b d8 ea d5 d7 f5 d5 cc b9 b6 9f 30 66 5b 66 9a |...........0f[f.| -000001d0 20 e2 27 e5 bf fe 3b 30 09 06 07 2a 86 48 ce 3d | .'...;0...*.H.=| -000001e0 04 01 03 81 8c 00 30 81 88 02 42 01 88 a2 4f eb |......0...B...O.| -000001f0 e2 45 c5 48 7d 1b ac f5 ed 98 9d ae 47 70 c0 5e |.E.H}.......Gp.^| -00000200 1b b6 2f bd f1 b6 4d b7 61 40 d3 11 a2 ce ee 0b |../...M.a@......| -00000210 7e 92 7e ff 76 9d c3 3b 7e a5 3f ce fa 10 e2 59 |~.~.v..;~.?....Y| -00000220 ec 47 2d 7c ac da 4e 97 0e 15 a0 6f d0 02 42 01 |.G-|..N....o..B.| -00000230 4d fc be 67 13 9c 2d 05 0e bd 3f a3 8c 25 c1 33 |M..g..-...?..%.3| -00000240 13 83 0d 94 06 bb d4 37 7a f6 ec 7a c9 86 2e dd |.......7z..z....| -00000250 d7 11 69 7f 85 7c 56 de fb 31 78 2b e4 c7 78 0d |..i..|V..1x+..x.| -00000260 ae cb be 9e 4e 36 24 31 7b 6a 0f 39 95 12 07 8f |....N6$1{j.9....| -00000270 2a 16 03 01 00 d5 0c 00 00 d1 03 00 17 41 04 da |*............A..| -00000280 5a fd 09 e5 d6 c0 70 41 5e 3a 87 eb df 0c ad 90 |Z.....pA^:......| -00000290 22 8a 2f 90 81 0c 24 00 68 92 f3 d5 95 2f 93 43 |"./...$.h..../.C| -000002a0 e9 58 2d 18 28 62 ee 33 5b 21 2e 49 87 21 4d 32 |.X-.(b.3[!.I.!M2| -000002b0 32 19 b3 ba fe 2d 9a 85 12 0e a1 77 08 06 75 00 |2....-.....w..u.| -000002c0 8a 30 81 87 02 42 01 91 14 fc 68 74 95 10 4b d4 |.0...B....ht..K.| -000002d0 67 60 12 46 bb b0 f6 98 77 a3 41 b8 01 5c 49 54 |g`.F....w.A..\IT| -000002e0 9e 3e 81 e7 97 a3 b9 73 6e 15 74 67 be e5 d9 eb |.>.....sn.tg....| -000002f0 8b 87 c5 22 ab ab 58 28 4f d1 b6 80 94 1b f5 f7 |..."..X(O.......| -00000300 12 43 ef 0a c7 3e 1a 76 02 41 7a 00 49 cb 9f 3b |.C...>.v.Az.I..;| -00000310 91 6e 38 58 0a d3 d0 d1 ee 67 f0 b6 5d cd fa 23 |.n8X.....g..]..#| -00000320 b6 98 43 af 9c 71 90 1e 1d 50 a2 6e 61 5b f2 92 |..C..q...P.na[..| -00000330 b4 69 73 f2 3b 54 bf 1c 9d 05 19 97 e4 4e 41 9e |.is.;T.......NA.| -00000340 f2 9a 76 77 9a 86 43 1f 1f 30 a2 16 03 01 00 04 |..vw..C..0......| -00000350 0e 00 00 00 |....| ->>> Flow 3 (client to server) -00000000 16 03 01 00 46 10 00 00 42 41 04 1e 18 37 ef 0d |....F...BA...7..| -00000010 19 51 88 35 75 71 b5 e5 54 5b 12 2e 8f 09 67 fd |.Q.5uq..T[....g.| -00000020 a7 24 20 3e b2 56 1c ce 97 28 5e f8 2b 2d 4f 9e |.$ >.V...(^.+-O.| -00000030 f1 07 9f 6c 4b 5b 83 56 e2 32 42 e9 58 b6 d7 49 |...lK[.V.2B.X..I| -00000040 a6 b5 68 1a 41 03 56 6b dc 5a 89 14 03 01 00 01 |..h.A.Vk.Z......| -00000050 01 16 03 01 00 30 88 60 65 b2 d7 51 1f ad 96 56 |.....0.`e..Q...V| -00000060 4e 0a 20 eb b5 b0 1a dd 4c f6 1a cf d4 5c 47 c4 |N. .....L....\G.| -00000070 9c 7c a0 36 dd d1 1b 96 91 99 c0 a7 2d 9a 7c 42 |.|.6........-.|B| -00000080 51 d1 de 87 2b a4 |Q...+.| ->>> Flow 4 (server to client) -00000000 14 03 01 00 01 01 16 03 01 00 30 86 6c b5 94 69 |..........0.l..i| -00000010 2e e0 55 a2 4d a8 63 f2 5b 1f ae 34 21 c8 21 6a |..U.M.c.[..4!.!j| -00000020 00 b6 56 ed 4e 2a b0 ff 01 2f da ce a1 c0 41 03 |..V.N*.../....A.| -00000030 a9 1b 6e 2e e1 88 50 ba 62 14 88 |..n...P.b..| ->>> Flow 5 (client to server) -00000000 17 03 01 00 20 a6 63 0a 2f a5 dc e1 fb cb 7b 1f |.... .c./.....{.| -00000010 f2 da 74 c3 ff e9 f5 8b 9c 5f 0c d3 f7 1f 44 e6 |..t......_....D.| -00000020 90 13 5c 48 50 17 03 01 00 20 c7 75 b5 ff bc 09 |..\HP.... .u....| -00000030 34 f2 45 db 0d 22 08 8e f1 35 cd b6 0f b0 eb 2a |4.E.."...5.....*| -00000040 b7 1a d0 8e 14 a4 54 84 f9 dc 15 03 01 00 20 e0 |......T....... .| -00000050 36 3d aa b3 a9 b4 20 23 ca 9e 8c 5d fc a8 c8 b7 |6=.... #...]....| -00000060 f5 c2 b6 d0 5a e2 ce a5 7b 68 a0 48 86 95 6a |....Z...{h.H..j| diff --git a/src/pkg/crypto/tls/testdata/Client-TLSv10-ECDHE-RSA-AES b/src/pkg/crypto/tls/testdata/Client-TLSv10-ECDHE-RSA-AES deleted file mode 100644 index 868f0ceb0..000000000 --- a/src/pkg/crypto/tls/testdata/Client-TLSv10-ECDHE-RSA-AES +++ /dev/null @@ -1,97 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 75 01 00 00 71 03 03 00 00 00 00 00 |....u...q.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 1a c0 2f |.............../| -00000030 c0 2b c0 11 c0 07 c0 13 c0 09 c0 14 c0 0a 00 05 |.+..............| -00000040 00 2f 00 35 c0 12 00 0a 01 00 00 2e 00 05 00 05 |./.5............| -00000050 01 00 00 00 00 00 0a 00 08 00 06 00 17 00 18 00 |................| -00000060 19 00 0b 00 02 01 00 00 0d 00 0a 00 08 04 01 04 |................| -00000070 03 02 01 02 03 ff 01 00 01 00 |..........| ->>> Flow 2 (server to client) -00000000 16 03 01 00 59 02 00 00 55 03 01 53 04 f1 02 21 |....Y...U..S...!| -00000010 67 b5 2b 34 fb 62 d7 36 4f cf 68 2e 29 39 d0 28 |g.+4.b.6O.h.)9.(| -00000020 3a 02 32 82 8f 95 de 62 d6 03 77 20 e6 98 56 cd |:.2....b..w ..V.| -00000030 96 24 d1 b9 4d eb 51 19 bb b7 71 f4 9c 29 32 d4 |.$..M.Q...q..)2.| -00000040 e5 c6 0a 54 e0 4a 20 29 3e bd 06 0d c0 13 00 00 |...T.J )>.......| -00000050 0d ff 01 00 01 00 00 0b 00 04 03 00 01 02 16 03 |................| -00000060 01 02 be 0b 00 02 ba 00 02 b7 00 02 b4 30 82 02 |.............0..| -00000070 b0 30 82 02 19 a0 03 02 01 02 02 09 00 85 b0 bb |.0..............| -00000080 a4 8a 7f b8 ca 30 0d 06 09 2a 86 48 86 f7 0d 01 |.....0...*.H....| -00000090 01 05 05 00 30 45 31 0b 30 09 06 03 55 04 06 13 |....0E1.0...U...| -000000a0 02 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f |.AU1.0...U....So| -000000b0 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 |me-State1!0...U.| -000000c0 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 |...Internet Widg| -000000d0 69 74 73 20 50 74 79 20 4c 74 64 30 1e 17 0d 31 |its Pty Ltd0...1| -000000e0 30 30 34 32 34 30 39 30 39 33 38 5a 17 0d 31 31 |00424090938Z..11| -000000f0 30 34 32 34 30 39 30 39 33 38 5a 30 45 31 0b 30 |0424090938Z0E1.0| -00000100 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 03 |...U....AU1.0...| -00000110 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 31 |U....Some-State1| -00000120 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 6e |!0...U....Intern| -00000130 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 4c |et Widgits Pty L| -00000140 74 64 30 81 9f 30 0d 06 09 2a 86 48 86 f7 0d 01 |td0..0...*.H....| -00000150 01 01 05 00 03 81 8d 00 30 81 89 02 81 81 00 bb |........0.......| -00000160 79 d6 f5 17 b5 e5 bf 46 10 d0 dc 69 be e6 2b 07 |y......F...i..+.| -00000170 43 5a d0 03 2d 8a 7a 43 85 b7 14 52 e7 a5 65 4c |CZ..-.zC...R..eL| -00000180 2c 78 b8 23 8c b5 b4 82 e5 de 1f 95 3b 7e 62 a5 |,x.#........;~b.| -00000190 2c a5 33 d6 fe 12 5c 7a 56 fc f5 06 bf fa 58 7b |,.3...\zV.....X{| -000001a0 26 3f b5 cd 04 d3 d0 c9 21 96 4a c7 f4 54 9f 5a |&?......!.J..T.Z| -000001b0 bf ef 42 71 00 fe 18 99 07 7f 7e 88 7d 7d f1 04 |..Bq......~.}}..| -000001c0 39 c4 a2 2e db 51 c9 7c e3 c0 4c 3b 32 66 01 cf |9....Q.|..L;2f..| -000001d0 af b1 1d b8 71 9a 1d db db 89 6b ae da 2d 79 02 |....q.....k..-y.| -000001e0 03 01 00 01 a3 81 a7 30 81 a4 30 1d 06 03 55 1d |.......0..0...U.| -000001f0 0e 04 16 04 14 b1 ad e2 85 5a cf cb 28 db 69 ce |.........Z..(.i.| -00000200 23 69 de d3 26 8e 18 88 39 30 75 06 03 55 1d 23 |#i..&...90u..U.#| -00000210 04 6e 30 6c 80 14 b1 ad e2 85 5a cf cb 28 db 69 |.n0l......Z..(.i| -00000220 ce 23 69 de d3 26 8e 18 88 39 a1 49 a4 47 30 45 |.#i..&...9.I.G0E| -00000230 31 0b 30 09 06 03 55 04 06 13 02 41 55 31 13 30 |1.0...U....AU1.0| -00000240 11 06 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 |...U....Some-Sta| -00000250 74 65 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 |te1!0...U....Int| -00000260 65 72 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 |ernet Widgits Pt| -00000270 79 20 4c 74 64 82 09 00 85 b0 bb a4 8a 7f b8 ca |y Ltd...........| -00000280 30 0c 06 03 55 1d 13 04 05 30 03 01 01 ff 30 0d |0...U....0....0.| -00000290 06 09 2a 86 48 86 f7 0d 01 01 05 05 00 03 81 81 |..*.H...........| -000002a0 00 08 6c 45 24 c7 6b b1 59 ab 0c 52 cc f2 b0 14 |..lE$.k.Y..R....| -000002b0 d7 87 9d 7a 64 75 b5 5a 95 66 e4 c5 2b 8e ae 12 |...zdu.Z.f..+...| -000002c0 66 1f eb 4f 38 b3 6e 60 d3 92 fd f7 41 08 b5 25 |f..O8.n`....A..%| -000002d0 13 b1 18 7a 24 fb 30 1d ba ed 98 b9 17 ec e7 d7 |...z$.0.........| -000002e0 31 59 db 95 d3 1d 78 ea 50 56 5c d5 82 5a 2d 5a |1Y....x.PV\..Z-Z| -000002f0 5f 33 c4 b6 d8 c9 75 90 96 8c 0f 52 98 b5 cd 98 |_3....u....R....| -00000300 1f 89 20 5f f2 a0 1c a3 1b 96 94 dd a9 fd 57 e9 |.. _..........W.| -00000310 70 e8 26 6d 71 99 9b 26 6e 38 50 29 6c 90 a7 bd |p.&mq..&n8P)l...| -00000320 d9 16 03 01 00 cb 0c 00 00 c7 03 00 17 41 04 05 |.............A..| -00000330 45 33 f8 4b e9 96 0e 4a fd ec 54 76 21 9b 24 8a |E3.K...J..Tv!.$.| -00000340 75 0b 80 84 c7 30 2b 22 f0 85 57 a4 a9 79 d6 f6 |u....0+"..W..y..| -00000350 6d 80 b0 71 d9 66 c9 6c dd 76 fc 32 d0 c6 bc 52 |m..q.f.l.v.2...R| -00000360 2f f1 c9 62 17 53 76 ec be a6 1c 93 f2 b4 5d 00 |/..b.Sv.......].| -00000370 80 72 d9 20 52 70 7c 03 b1 33 fa 51 23 cd 05 97 |.r. Rp|..3.Q#...| -00000380 6f d6 89 2f 8d 2e 3a 17 32 eb f2 ff 6b 39 70 5e |o../..:.2...k9p^| -00000390 21 41 8d 69 02 c8 9a 17 19 e4 48 9b 51 c3 7f 9b |!A.i......H.Q...| -000003a0 8d 4a 83 97 07 0e 30 f1 8b 6b e9 92 12 01 d6 96 |.J....0..k......| -000003b0 f2 1a a2 10 7f 59 87 16 1a fb 55 67 68 fc 78 c6 |.....Y....Ugh.x.| -000003c0 57 ac 05 dd f3 6f 77 84 eb ae b0 33 2d 19 2c ba |W....ow....3-.,.| -000003d0 b8 ae 9f 95 69 85 95 45 5e 37 f4 17 17 9b 03 c1 |....i..E^7......| -000003e0 50 b1 36 42 bd 60 5c 8b d8 b6 f3 c8 34 c8 9d 9d |P.6B.`\.....4...| -000003f0 75 16 03 01 00 04 0e 00 00 00 |u.........| ->>> Flow 3 (client to server) -00000000 16 03 01 00 46 10 00 00 42 41 04 1e 18 37 ef 0d |....F...BA...7..| -00000010 19 51 88 35 75 71 b5 e5 54 5b 12 2e 8f 09 67 fd |.Q.5uq..T[....g.| -00000020 a7 24 20 3e b2 56 1c ce 97 28 5e f8 2b 2d 4f 9e |.$ >.V...(^.+-O.| -00000030 f1 07 9f 6c 4b 5b 83 56 e2 32 42 e9 58 b6 d7 49 |...lK[.V.2B.X..I| -00000040 a6 b5 68 1a 41 03 56 6b dc 5a 89 14 03 01 00 01 |..h.A.Vk.Z......| -00000050 01 16 03 01 00 30 ca d1 1b 08 27 9b 44 e7 e9 b4 |.....0....'.D...| -00000060 90 16 4d 30 4e 65 5c 0d 47 ba 46 86 cf c9 80 e7 |..M0Ne\.G.F.....| -00000070 64 31 f5 a1 9e dc 39 15 d3 be 16 4f c7 90 b6 62 |d1....9....O...b| -00000080 5d 6d 7f 41 4e 3e |]m.AN>| ->>> Flow 4 (server to client) -00000000 14 03 01 00 01 01 16 03 01 00 30 98 81 24 8e cd |..........0..$..| -00000010 b6 48 2f 80 de 8e 24 3c cd 02 67 80 34 97 d7 92 |.H/...$<..g.4...| -00000020 78 c2 44 3d 5d 05 eb 88 76 79 46 7a c3 fa ca 73 |x.D=]...vyFz...s| -00000030 45 82 ad c1 81 00 ca 40 c1 2f 13 |E......@./.| ->>> Flow 5 (client to server) -00000000 17 03 01 00 20 ee 19 59 67 67 a9 8b db 99 87 50 |.... ..Ygg.....P| -00000010 01 e2 02 c1 d5 6d 36 79 af aa ec 1b 80 0e b6 5e |.....m6y.......^| -00000020 5f fa 03 01 cc 17 03 01 00 20 ec e2 04 b7 3b a5 |_........ ....;.| -00000030 f2 e0 13 1f 17 48 e7 6e d3 eb f0 fa 36 ef 6e 2e |.....H.n....6.n.| -00000040 fb ea c8 39 c4 5f 4b 28 d4 50 15 03 01 00 20 c7 |...9._K(.P.... .| -00000050 45 ff fb c7 07 0c d8 0e 35 a3 c5 31 47 b7 03 0e |E.......5..1G...| -00000060 14 c8 29 fd 53 70 5f 15 ac d2 1c 4c 69 fb d6 |..).Sp_....Li..| diff --git a/src/pkg/crypto/tls/testdata/Client-TLSv10-RSA-RC4 b/src/pkg/crypto/tls/testdata/Client-TLSv10-RSA-RC4 deleted file mode 100644 index 395d53bba..000000000 --- a/src/pkg/crypto/tls/testdata/Client-TLSv10-RSA-RC4 +++ /dev/null @@ -1,83 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 75 01 00 00 71 03 03 00 00 00 00 00 |....u...q.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 1a c0 2f |.............../| -00000030 c0 2b c0 11 c0 07 c0 13 c0 09 c0 14 c0 0a 00 05 |.+..............| -00000040 00 2f 00 35 c0 12 00 0a 01 00 00 2e 00 05 00 05 |./.5............| -00000050 01 00 00 00 00 00 0a 00 08 00 06 00 17 00 18 00 |................| -00000060 19 00 0b 00 02 01 00 00 0d 00 0a 00 08 04 01 04 |................| -00000070 03 02 01 02 03 ff 01 00 01 00 |..........| ->>> Flow 2 (server to client) -00000000 16 03 01 00 51 02 00 00 4d 03 01 53 04 f1 02 76 |....Q...M..S...v| -00000010 e8 45 7f 57 f3 42 4b 33 0b 06 fa a6 fa c4 3d 84 |.E.W.BK3......=.| -00000020 5a 45 dc 93 41 a5 8d 79 6e 8f 11 20 e7 c6 29 2b |ZE..A..yn.. ..)+| -00000030 ff 4a 6e 63 67 a6 10 cb 49 19 46 1e 5e 0a d5 70 |.Jncg...I.F.^..p| -00000040 96 88 9a 32 48 ef c3 4a 45 4c 6d e0 00 05 00 00 |...2H..JELm.....| -00000050 05 ff 01 00 01 00 16 03 01 02 be 0b 00 02 ba 00 |................| -00000060 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000070 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000080 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000090 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -000000a0 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -000000b0 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000c0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000d0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000e0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000f0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -00000100 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -00000110 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000120 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000130 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000140 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000150 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000160 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000170 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000180 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000190 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -000001a0 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -000001b0 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001c0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001d0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001e0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001f0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -00000200 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -00000210 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000220 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000230 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000240 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000250 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000260 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000270 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000280 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000290 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -000002a0 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -000002b0 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002c0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002d0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002e0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002f0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -00000300 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -00000310 6e 38 50 29 6c 90 a7 bd d9 16 03 01 00 04 0e 00 |n8P)l...........| -00000320 00 00 |..| ->>> Flow 3 (client to server) -00000000 16 03 01 00 86 10 00 00 82 00 80 6d 51 f3 7f f9 |...........mQ...| -00000010 3e fb 75 82 41 36 83 e8 6a ee 2a 2e 25 90 67 4c |>.u.A6..j.*.%.gL| -00000020 8e 62 2f 30 81 17 e0 85 09 0c 2b b7 23 d7 b0 e2 |.b/0......+.#...| -00000030 1d f7 3b d7 f5 a1 27 b6 ee 24 b6 1b cc 5b ea 66 |..;...'..$...[.f| -00000040 0d 6a f4 e5 85 f9 da 43 b4 0e 86 85 e1 f5 aa be |.j.....C........| -00000050 c8 ce 39 4c 9c 86 00 08 c2 4b e2 c6 ec 2f f7 ce |..9L.....K.../..| -00000060 e6 bd 77 82 6f 23 b6 e0 bd a2 92 b7 3a ac e8 56 |..w.o#......:..V| -00000070 f1 af 54 5e 46 87 e9 3b 33 e7 b8 28 b7 d6 c8 90 |..T^F..;3..(....| -00000080 35 d4 1c 43 d1 30 6f 55 4e 0a 70 14 03 01 00 01 |5..C.0oUN.p.....| -00000090 01 16 03 01 00 24 cd c0 68 dc 2e 69 cc c7 5b c5 |.....$..h..i..[.| -000000a0 3f bd 40 cf a0 0f 41 34 ce 16 37 10 26 c8 3f d1 |?.@...A4..7.&.?.| -000000b0 46 3b ad 7b b0 31 f3 c5 36 e7 |F;.{.1..6.| ->>> Flow 4 (server to client) -00000000 14 03 01 00 01 01 16 03 01 00 24 ea 77 6f 3c 42 |..........$.wo....]| ->>> Flow 5 (client to server) -00000000 17 03 01 00 1a 9e ae ca 55 df c4 d9 47 04 55 dd |........U...G.U.| -00000010 3b 33 e1 a6 16 6f a1 94 b1 9b 4d 0d cb 6c 3b 15 |;3...o....M..l;.| -00000020 03 01 00 16 92 5d 76 07 e9 b7 31 29 09 c5 b1 09 |.....]v...1)....| -00000030 2d 64 3d 85 8d f1 d1 40 54 b8 |-d=....@T.| diff --git a/src/pkg/crypto/tls/testdata/Client-TLSv11-ECDHE-ECDSA-AES b/src/pkg/crypto/tls/testdata/Client-TLSv11-ECDHE-ECDSA-AES deleted file mode 100644 index 9f941f8ef..000000000 --- a/src/pkg/crypto/tls/testdata/Client-TLSv11-ECDHE-ECDSA-AES +++ /dev/null @@ -1,89 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 75 01 00 00 71 03 03 00 00 00 00 00 |....u...q.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 1a c0 2f |.............../| -00000030 c0 2b c0 11 c0 07 c0 13 c0 09 c0 14 c0 0a 00 05 |.+..............| -00000040 00 2f 00 35 c0 12 00 0a 01 00 00 2e 00 05 00 05 |./.5............| -00000050 01 00 00 00 00 00 0a 00 08 00 06 00 17 00 18 00 |................| -00000060 19 00 0b 00 02 01 00 00 0d 00 0a 00 08 04 01 04 |................| -00000070 03 02 01 02 03 ff 01 00 01 00 |..........| ->>> Flow 2 (server to client) -00000000 16 03 02 00 59 02 00 00 55 03 02 53 04 f1 02 1c |....Y...U..S....| -00000010 d1 1c 6a 5f 7a 5c 26 69 92 cd ee c3 57 ed 96 90 |..j_z\&i....W...| -00000020 e3 c5 f1 ee 8b ee 99 5f 46 2c e6 20 c8 50 6a a4 |......._F,. .Pj.| -00000030 4b 93 e6 da ba 6d d4 87 f6 75 a8 9d 44 db b5 43 |K....m...u..D..C| -00000040 df 12 57 de a4 f1 bc fb b8 7a 3f 6a c0 09 00 00 |..W......z?j....| -00000050 0d ff 01 00 01 00 00 0b 00 04 03 00 01 02 16 03 |................| -00000060 02 02 0e 0b 00 02 0a 00 02 07 00 02 04 30 82 02 |.............0..| -00000070 00 30 82 01 62 02 09 00 b8 bf 2d 47 a0 d2 eb f4 |.0..b.....-G....| -00000080 30 09 06 07 2a 86 48 ce 3d 04 01 30 45 31 0b 30 |0...*.H.=..0E1.0| -00000090 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 03 |...U....AU1.0...| -000000a0 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 31 |U....Some-State1| -000000b0 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 6e |!0...U....Intern| -000000c0 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 4c |et Widgits Pty L| -000000d0 74 64 30 1e 17 0d 31 32 31 31 32 32 31 35 30 36 |td0...1211221506| -000000e0 33 32 5a 17 0d 32 32 31 31 32 30 31 35 30 36 33 |32Z..22112015063| -000000f0 32 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 41 |2Z0E1.0...U....A| -00000100 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d 65 |U1.0...U....Some| -00000110 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a 13 |-State1!0...U...| -00000120 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 74 |.Internet Widgit| -00000130 73 20 50 74 79 20 4c 74 64 30 81 9b 30 10 06 07 |s Pty Ltd0..0...| -00000140 2a 86 48 ce 3d 02 01 06 05 2b 81 04 00 23 03 81 |*.H.=....+...#..| -00000150 86 00 04 00 c4 a1 ed be 98 f9 0b 48 73 36 7e c3 |...........Hs6~.| -00000160 16 56 11 22 f2 3d 53 c3 3b 4d 21 3d cd 6b 75 e6 |.V.".=S.;M!=.ku.| -00000170 f6 b0 dc 9a df 26 c1 bc b2 87 f0 72 32 7c b3 64 |.....&.....r2|.d| -00000180 2f 1c 90 bc ea 68 23 10 7e fe e3 25 c0 48 3a 69 |/....h#.~..%.H:i| -00000190 e0 28 6d d3 37 00 ef 04 62 dd 0d a0 9c 70 62 83 |.(m.7...b....pb.| -000001a0 d8 81 d3 64 31 aa 9e 97 31 bd 96 b0 68 c0 9b 23 |...d1...1...h..#| -000001b0 de 76 64 3f 1a 5c 7f e9 12 0e 58 58 b6 5f 70 dd |.vd?.\....XX._p.| -000001c0 9b d8 ea d5 d7 f5 d5 cc b9 b6 9f 30 66 5b 66 9a |...........0f[f.| -000001d0 20 e2 27 e5 bf fe 3b 30 09 06 07 2a 86 48 ce 3d | .'...;0...*.H.=| -000001e0 04 01 03 81 8c 00 30 81 88 02 42 01 88 a2 4f eb |......0...B...O.| -000001f0 e2 45 c5 48 7d 1b ac f5 ed 98 9d ae 47 70 c0 5e |.E.H}.......Gp.^| -00000200 1b b6 2f bd f1 b6 4d b7 61 40 d3 11 a2 ce ee 0b |../...M.a@......| -00000210 7e 92 7e ff 76 9d c3 3b 7e a5 3f ce fa 10 e2 59 |~.~.v..;~.?....Y| -00000220 ec 47 2d 7c ac da 4e 97 0e 15 a0 6f d0 02 42 01 |.G-|..N....o..B.| -00000230 4d fc be 67 13 9c 2d 05 0e bd 3f a3 8c 25 c1 33 |M..g..-...?..%.3| -00000240 13 83 0d 94 06 bb d4 37 7a f6 ec 7a c9 86 2e dd |.......7z..z....| -00000250 d7 11 69 7f 85 7c 56 de fb 31 78 2b e4 c7 78 0d |..i..|V..1x+..x.| -00000260 ae cb be 9e 4e 36 24 31 7b 6a 0f 39 95 12 07 8f |....N6$1{j.9....| -00000270 2a 16 03 02 00 d4 0c 00 00 d0 03 00 17 41 04 7b |*............A.{| -00000280 c4 00 37 35 51 de c3 f2 a4 95 2c 19 21 3e a6 94 |..75Q.....,.!>..| -00000290 7b fd 04 d7 b7 1c 56 e6 af 3c ee 36 cb 55 e6 f0 |{.....V..<.6.U..| -000002a0 e6 24 34 6b 8a 02 66 71 f9 e2 f5 a6 c9 d7 6c dc |.$4k..fq......l.| -000002b0 65 59 ff 1c c9 ec a9 8b 07 d6 52 2c 01 3c c3 00 |eY........R,.<..| -000002c0 89 30 81 86 02 41 74 89 1a 31 72 e6 8b c0 4a ce |.0...At..1r...J.| -000002d0 8f 5a 49 a7 52 2d 6d b9 8b 50 17 62 2a 99 d6 3b |.ZI.R-m..P.b*..;| -000002e0 02 85 41 4d 34 53 b5 09 bd e3 ac 16 c1 9b e9 83 |..AM4S..........| -000002f0 cc 83 e3 9c 23 34 67 71 72 d4 05 a2 34 f7 08 29 |....#4gqr...4..)| -00000300 62 43 2e cc bc 08 01 02 41 59 de 5a d0 dd d7 6b |bC......AY.Z...k| -00000310 db 9c 35 29 79 f8 96 91 56 74 1f 18 7b ee 25 83 |..5)y...Vt..{.%.| -00000320 f2 37 0e 77 ab 38 fb 5e 04 0b 09 d9 b4 1f 3f be |.7.w.8.^......?.| -00000330 2e e3 60 e3 96 f3 29 c1 6d 8f 56 1b fd 62 14 48 |..`...).m.V..b.H| -00000340 e3 d9 2a ea 2f be 93 d0 8b 31 16 03 02 00 04 0e |..*./....1......| -00000350 00 00 00 |...| ->>> Flow 3 (client to server) -00000000 16 03 02 00 46 10 00 00 42 41 04 1e 18 37 ef 0d |....F...BA...7..| -00000010 19 51 88 35 75 71 b5 e5 54 5b 12 2e 8f 09 67 fd |.Q.5uq..T[....g.| -00000020 a7 24 20 3e b2 56 1c ce 97 28 5e f8 2b 2d 4f 9e |.$ >.V...(^.+-O.| -00000030 f1 07 9f 6c 4b 5b 83 56 e2 32 42 e9 58 b6 d7 49 |...lK[.V.2B.X..I| -00000040 a6 b5 68 1a 41 03 56 6b dc 5a 89 14 03 02 00 01 |..h.A.Vk.Z......| -00000050 01 16 03 02 00 40 00 00 00 00 00 00 00 00 00 00 |.....@..........| -00000060 00 00 00 00 00 00 b6 98 a2 a9 48 34 12 6b 0a 94 |..........H4.k..| -00000070 89 fc 38 04 63 5a 6f 63 36 3e d9 35 12 64 8c 28 |..8.cZoc6>.5.d.(| -00000080 99 a6 cf 2e 57 e3 14 6d 0a 8a ab f0 a6 58 37 7c |....W..m.....X7|| -00000090 96 04 d3 71 bc d4 |...q..| ->>> Flow 4 (server to client) -00000000 14 03 02 00 01 01 16 03 02 00 40 c5 01 c9 0a b0 |..........@.....| -00000010 d8 ca 5e c1 19 dc 37 6c 2e a0 b3 11 a8 87 65 5a |..^...7l......eZ| -00000020 09 41 b9 fe 53 c4 c9 76 97 6d 7f ac c0 be d2 07 |.A..S..v.m......| -00000030 84 e5 5b 78 37 34 ee da 3b cb 3e 82 52 79 91 44 |..[x74..;.>.Ry.D| -00000040 b4 e4 1c ec 3a c0 c0 9d cd ff 13 |....:......| ->>> Flow 5 (client to server) -00000000 17 03 02 00 30 00 00 00 00 00 00 00 00 00 00 00 |....0...........| -00000010 00 00 00 00 00 46 60 13 39 2b 2f 72 95 ed 0e aa |.....F`.9+/r....| -00000020 69 6e b4 64 3e 83 43 d0 f9 7f 37 7c 1d b9 ce 11 |in.d>.C...7|....| -00000030 d9 41 66 60 6d 15 03 02 00 30 00 00 00 00 00 00 |.Af`m....0......| -00000040 00 00 00 00 00 00 00 00 00 00 b1 26 d0 5d 08 98 |...........&.]..| -00000050 eb 28 42 74 31 58 42 95 c5 ad 1a 92 0a f5 5f ed |.(Bt1XB......._.| -00000060 45 98 e0 90 e5 a3 b6 8b 8d 18 |E.........| diff --git a/src/pkg/crypto/tls/testdata/Client-TLSv11-ECDHE-RSA-AES b/src/pkg/crypto/tls/testdata/Client-TLSv11-ECDHE-RSA-AES deleted file mode 100644 index fc723396a..000000000 --- a/src/pkg/crypto/tls/testdata/Client-TLSv11-ECDHE-RSA-AES +++ /dev/null @@ -1,99 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 75 01 00 00 71 03 03 00 00 00 00 00 |....u...q.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 1a c0 2f |.............../| -00000030 c0 2b c0 11 c0 07 c0 13 c0 09 c0 14 c0 0a 00 05 |.+..............| -00000040 00 2f 00 35 c0 12 00 0a 01 00 00 2e 00 05 00 05 |./.5............| -00000050 01 00 00 00 00 00 0a 00 08 00 06 00 17 00 18 00 |................| -00000060 19 00 0b 00 02 01 00 00 0d 00 0a 00 08 04 01 04 |................| -00000070 03 02 01 02 03 ff 01 00 01 00 |..........| ->>> Flow 2 (server to client) -00000000 16 03 02 00 59 02 00 00 55 03 02 53 04 f1 02 fe |....Y...U..S....| -00000010 17 8b 79 ad 93 2e d3 89 66 9b 5d 9b b4 03 3e ba |..y.....f.]...>.| -00000020 65 2a f1 55 f9 3c 33 de 2c a7 47 20 fa 4f 82 11 |e*.U.<3.,.G .O..| -00000030 96 81 d0 70 2e 65 b3 68 2e 3a 6d d7 6c 74 22 33 |...p.e.h.:m.lt"3| -00000040 d4 ae 6c aa c8 f0 c7 20 8b 10 21 e7 c0 13 00 00 |..l.... ..!.....| -00000050 0d ff 01 00 01 00 00 0b 00 04 03 00 01 02 16 03 |................| -00000060 02 02 be 0b 00 02 ba 00 02 b7 00 02 b4 30 82 02 |.............0..| -00000070 b0 30 82 02 19 a0 03 02 01 02 02 09 00 85 b0 bb |.0..............| -00000080 a4 8a 7f b8 ca 30 0d 06 09 2a 86 48 86 f7 0d 01 |.....0...*.H....| -00000090 01 05 05 00 30 45 31 0b 30 09 06 03 55 04 06 13 |....0E1.0...U...| -000000a0 02 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f |.AU1.0...U....So| -000000b0 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 |me-State1!0...U.| -000000c0 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 |...Internet Widg| -000000d0 69 74 73 20 50 74 79 20 4c 74 64 30 1e 17 0d 31 |its Pty Ltd0...1| -000000e0 30 30 34 32 34 30 39 30 39 33 38 5a 17 0d 31 31 |00424090938Z..11| -000000f0 30 34 32 34 30 39 30 39 33 38 5a 30 45 31 0b 30 |0424090938Z0E1.0| -00000100 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 03 |...U....AU1.0...| -00000110 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 31 |U....Some-State1| -00000120 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 6e |!0...U....Intern| -00000130 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 4c |et Widgits Pty L| -00000140 74 64 30 81 9f 30 0d 06 09 2a 86 48 86 f7 0d 01 |td0..0...*.H....| -00000150 01 01 05 00 03 81 8d 00 30 81 89 02 81 81 00 bb |........0.......| -00000160 79 d6 f5 17 b5 e5 bf 46 10 d0 dc 69 be e6 2b 07 |y......F...i..+.| -00000170 43 5a d0 03 2d 8a 7a 43 85 b7 14 52 e7 a5 65 4c |CZ..-.zC...R..eL| -00000180 2c 78 b8 23 8c b5 b4 82 e5 de 1f 95 3b 7e 62 a5 |,x.#........;~b.| -00000190 2c a5 33 d6 fe 12 5c 7a 56 fc f5 06 bf fa 58 7b |,.3...\zV.....X{| -000001a0 26 3f b5 cd 04 d3 d0 c9 21 96 4a c7 f4 54 9f 5a |&?......!.J..T.Z| -000001b0 bf ef 42 71 00 fe 18 99 07 7f 7e 88 7d 7d f1 04 |..Bq......~.}}..| -000001c0 39 c4 a2 2e db 51 c9 7c e3 c0 4c 3b 32 66 01 cf |9....Q.|..L;2f..| -000001d0 af b1 1d b8 71 9a 1d db db 89 6b ae da 2d 79 02 |....q.....k..-y.| -000001e0 03 01 00 01 a3 81 a7 30 81 a4 30 1d 06 03 55 1d |.......0..0...U.| -000001f0 0e 04 16 04 14 b1 ad e2 85 5a cf cb 28 db 69 ce |.........Z..(.i.| -00000200 23 69 de d3 26 8e 18 88 39 30 75 06 03 55 1d 23 |#i..&...90u..U.#| -00000210 04 6e 30 6c 80 14 b1 ad e2 85 5a cf cb 28 db 69 |.n0l......Z..(.i| -00000220 ce 23 69 de d3 26 8e 18 88 39 a1 49 a4 47 30 45 |.#i..&...9.I.G0E| -00000230 31 0b 30 09 06 03 55 04 06 13 02 41 55 31 13 30 |1.0...U....AU1.0| -00000240 11 06 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 |...U....Some-Sta| -00000250 74 65 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 |te1!0...U....Int| -00000260 65 72 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 |ernet Widgits Pt| -00000270 79 20 4c 74 64 82 09 00 85 b0 bb a4 8a 7f b8 ca |y Ltd...........| -00000280 30 0c 06 03 55 1d 13 04 05 30 03 01 01 ff 30 0d |0...U....0....0.| -00000290 06 09 2a 86 48 86 f7 0d 01 01 05 05 00 03 81 81 |..*.H...........| -000002a0 00 08 6c 45 24 c7 6b b1 59 ab 0c 52 cc f2 b0 14 |..lE$.k.Y..R....| -000002b0 d7 87 9d 7a 64 75 b5 5a 95 66 e4 c5 2b 8e ae 12 |...zdu.Z.f..+...| -000002c0 66 1f eb 4f 38 b3 6e 60 d3 92 fd f7 41 08 b5 25 |f..O8.n`....A..%| -000002d0 13 b1 18 7a 24 fb 30 1d ba ed 98 b9 17 ec e7 d7 |...z$.0.........| -000002e0 31 59 db 95 d3 1d 78 ea 50 56 5c d5 82 5a 2d 5a |1Y....x.PV\..Z-Z| -000002f0 5f 33 c4 b6 d8 c9 75 90 96 8c 0f 52 98 b5 cd 98 |_3....u....R....| -00000300 1f 89 20 5f f2 a0 1c a3 1b 96 94 dd a9 fd 57 e9 |.. _..........W.| -00000310 70 e8 26 6d 71 99 9b 26 6e 38 50 29 6c 90 a7 bd |p.&mq..&n8P)l...| -00000320 d9 16 03 02 00 cb 0c 00 00 c7 03 00 17 41 04 26 |.............A.&| -00000330 56 18 02 e5 66 d4 aa 24 7e ae 39 e5 ca 78 6c c1 |V...f..$~.9..xl.| -00000340 90 02 c3 c4 ad 79 2c 47 a8 bf 54 e2 8a 22 b6 ef |.....y,G..T.."..| -00000350 99 d4 7a 7f 8f 78 6a 78 4e 14 2a 16 0d bb 54 38 |..z..xjxN.*...T8| -00000360 59 1f 7a 53 1b c7 73 10 89 4b de c3 66 39 7a 00 |Y.zS..s..K..f9z.| -00000370 80 3a 88 38 c8 15 07 ab 2f 0f 0d cb 19 07 84 ac |.:.8..../.......| -00000380 24 fd 8b d2 9d 05 45 c6 11 c3 d6 84 58 95 5a 08 |$.....E.....X.Z.| -00000390 b9 a4 2c c0 41 4e 34 e0 b2 24 98 94 b7 67 27 50 |..,.AN4..$...g'P| -000003a0 ba 82 35 28 a9 bf 16 ee e3 7b 49 9c 4c 81 80 69 |..5(.....{I.L..i| -000003b0 d7 aa ed 46 ea 9a 68 c4 97 b7 11 d4 35 91 74 5e |...F..h.....5.t^| -000003c0 54 10 34 83 cd c4 06 18 49 7d 7a 28 c9 53 06 73 |T.4.....I}z(.S.s| -000003d0 00 7b 04 b6 d8 36 a7 4b 67 7f 81 30 94 de 40 4d |.{...6.Kg..0..@M| -000003e0 18 f8 c4 b7 02 00 44 8e bc 72 06 24 53 15 74 72 |......D..r.$S.tr| -000003f0 8d 16 03 02 00 04 0e 00 00 00 |..........| ->>> Flow 3 (client to server) -00000000 16 03 02 00 46 10 00 00 42 41 04 1e 18 37 ef 0d |....F...BA...7..| -00000010 19 51 88 35 75 71 b5 e5 54 5b 12 2e 8f 09 67 fd |.Q.5uq..T[....g.| -00000020 a7 24 20 3e b2 56 1c ce 97 28 5e f8 2b 2d 4f 9e |.$ >.V...(^.+-O.| -00000030 f1 07 9f 6c 4b 5b 83 56 e2 32 42 e9 58 b6 d7 49 |...lK[.V.2B.X..I| -00000040 a6 b5 68 1a 41 03 56 6b dc 5a 89 14 03 02 00 01 |..h.A.Vk.Z......| -00000050 01 16 03 02 00 40 00 00 00 00 00 00 00 00 00 00 |.....@..........| -00000060 00 00 00 00 00 00 8a 87 81 38 35 c0 4c bb f8 12 |.........85.L...| -00000070 fa 75 04 cd 1e 3a 61 96 93 c8 fb 07 d1 6d b4 55 |.u...:a......m.U| -00000080 0f b5 0f 07 35 0a 96 ce 5c 6f 24 62 d3 68 e4 b0 |....5...\o$b.h..| -00000090 5d be 81 37 c2 9c |]..7..| ->>> Flow 4 (server to client) -00000000 14 03 02 00 01 01 16 03 02 00 40 66 36 8d f8 8c |..........@f6...| -00000010 7f db 38 e8 39 df f8 2f cb 88 9c 14 d9 89 10 b4 |..8.9../........| -00000020 be 59 88 d7 f3 73 62 af a3 42 66 6e 74 38 64 9f |.Y...sb..Bfnt8d.| -00000030 16 79 09 d7 14 7e 91 8a 70 73 63 28 30 58 fe cc |.y...~..psc(0X..| -00000040 42 45 d6 37 fb 9e 8c c1 01 af 34 |BE.7......4| ->>> Flow 5 (client to server) -00000000 17 03 02 00 30 00 00 00 00 00 00 00 00 00 00 00 |....0...........| -00000010 00 00 00 00 00 31 0b e3 9d 2a 05 83 19 7d 10 36 |.....1...*...}.6| -00000020 23 dc da fe 00 ab d3 aa 8f ce 28 5f 08 fd b7 59 |#.........(_...Y| -00000030 1e 00 2e 25 5a 15 03 02 00 30 00 00 00 00 00 00 |...%Z....0......| -00000040 00 00 00 00 00 00 00 00 00 00 10 91 fd fa 59 07 |..............Y.| -00000050 df 2c 92 25 15 7b 7c 83 44 89 0d 4f 65 43 99 2e |.,.%.{|.D..OeC..| -00000060 41 5d 51 c9 09 89 ed 02 08 bc |A]Q.......| diff --git a/src/pkg/crypto/tls/testdata/Client-TLSv11-RSA-RC4 b/src/pkg/crypto/tls/testdata/Client-TLSv11-RSA-RC4 deleted file mode 100644 index f7be3f7e9..000000000 --- a/src/pkg/crypto/tls/testdata/Client-TLSv11-RSA-RC4 +++ /dev/null @@ -1,83 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 75 01 00 00 71 03 03 00 00 00 00 00 |....u...q.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 1a c0 2f |.............../| -00000030 c0 2b c0 11 c0 07 c0 13 c0 09 c0 14 c0 0a 00 05 |.+..............| -00000040 00 2f 00 35 c0 12 00 0a 01 00 00 2e 00 05 00 05 |./.5............| -00000050 01 00 00 00 00 00 0a 00 08 00 06 00 17 00 18 00 |................| -00000060 19 00 0b 00 02 01 00 00 0d 00 0a 00 08 04 01 04 |................| -00000070 03 02 01 02 03 ff 01 00 01 00 |..........| ->>> Flow 2 (server to client) -00000000 16 03 02 00 51 02 00 00 4d 03 02 53 04 f1 02 d4 |....Q...M..S....| -00000010 69 65 aa 96 3d 42 96 eb 9e 7d 8a 18 af 4c 7c 5d |ie..=B...}...L|]| -00000020 fb 97 5f da 94 62 13 69 1f 66 06 20 aa 52 e3 08 |.._..b.i.f. .R..| -00000030 35 0a 87 d5 ef 93 49 ab 1a 74 dd 90 bd 69 70 d1 |5.....I..t...ip.| -00000040 e9 f1 44 17 3a dc 33 98 f5 e5 ab 93 00 05 00 00 |..D.:.3.........| -00000050 05 ff 01 00 01 00 16 03 02 02 be 0b 00 02 ba 00 |................| -00000060 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000070 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000080 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000090 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -000000a0 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -000000b0 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000c0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000d0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000e0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000f0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -00000100 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -00000110 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000120 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000130 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000140 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000150 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000160 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000170 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000180 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000190 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -000001a0 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -000001b0 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001c0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001d0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001e0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001f0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -00000200 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -00000210 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000220 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000230 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000240 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000250 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000260 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000270 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000280 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000290 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -000002a0 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -000002b0 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002c0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002d0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002e0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002f0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -00000300 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -00000310 6e 38 50 29 6c 90 a7 bd d9 16 03 02 00 04 0e 00 |n8P)l...........| -00000320 00 00 |..| ->>> Flow 3 (client to server) -00000000 16 03 02 00 86 10 00 00 82 00 80 6d 51 f3 7f f9 |...........mQ...| -00000010 3e fb 75 82 41 36 83 e8 6a ee 2a 2e 25 90 67 4c |>.u.A6..j.*.%.gL| -00000020 8e 62 2f 30 81 17 e0 85 09 0c 2b b7 23 d7 b0 e2 |.b/0......+.#...| -00000030 1d f7 3b d7 f5 a1 27 b6 ee 24 b6 1b cc 5b ea 66 |..;...'..$...[.f| -00000040 0d 6a f4 e5 85 f9 da 43 b4 0e 86 85 e1 f5 aa be |.j.....C........| -00000050 c8 ce 39 4c 9c 86 00 08 c2 4b e2 c6 ec 2f f7 ce |..9L.....K.../..| -00000060 e6 bd 77 82 6f 23 b6 e0 bd a2 92 b7 3a ac e8 56 |..w.o#......:..V| -00000070 f1 af 54 5e 46 87 e9 3b 33 e7 b8 28 b7 d6 c8 90 |..T^F..;3..(....| -00000080 35 d4 1c 43 d1 30 6f 55 4e 0a 70 14 03 02 00 01 |5..C.0oUN.p.....| -00000090 01 16 03 02 00 24 07 9f dc df 2d c3 a6 88 06 28 |.....$....-....(| -000000a0 21 e0 e0 d3 31 99 fc 89 b8 82 6e 95 f4 4b 9e e2 |!...1.....n..K..| -000000b0 d9 36 5c 14 ce d7 db e2 78 4e |.6\.....xN| ->>> Flow 4 (server to client) -00000000 14 03 02 00 01 01 16 03 02 00 24 81 72 75 80 d4 |..........$.ru..| -00000010 1b 1a 32 00 89 bf 9e 79 30 b9 6b 67 e0 8e c7 eb |..2....y0.kg....| -00000020 73 f2 e4 93 51 65 9b 5f 91 b1 b4 b1 f7 44 76 |s...Qe._.....Dv| ->>> Flow 5 (client to server) -00000000 17 03 02 00 1a b2 91 39 63 c0 38 3c 4d 25 fd 14 |.......9c.8>> Flow 1 (client to server) -00000000 16 03 01 00 8d 01 00 00 89 03 03 00 00 00 00 00 |................| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 1a c0 2f |.............../| -00000030 c0 2b c0 11 c0 07 c0 13 c0 09 c0 14 c0 0a 00 05 |.+..............| -00000040 00 2f 00 35 c0 12 00 0a 01 00 00 46 33 74 00 00 |./.5.......F3t..| -00000050 00 05 00 05 01 00 00 00 00 00 0a 00 08 00 06 00 |................| -00000060 17 00 18 00 19 00 0b 00 02 01 00 00 0d 00 0a 00 |................| -00000070 08 04 01 04 03 02 01 02 03 ff 01 00 01 00 00 10 |................| -00000080 00 10 00 0e 06 70 72 6f 74 6f 32 06 70 72 6f 74 |.....proto2.prot| -00000090 6f 31 |o1| ->>> Flow 2 (server to client) -00000000 16 03 03 00 66 02 00 00 62 03 03 77 a9 7d 9c 4b |....f...b..w.}.K| -00000010 69 65 aa dc 95 cb 78 08 3d d2 1a 0a 45 69 23 73 |ie....x.=...Ei#s| -00000020 4f 41 4f 24 12 2e 57 47 b7 53 64 20 82 9a f8 e7 |OAO$..WG.Sd ....| -00000030 79 f8 13 2c 9d cd b5 cb cb 9a 95 56 0e e9 cb a8 |y..,.......V....| -00000040 e4 a2 8a d6 bc dc fa 25 b3 57 cc cf c0 2f 00 00 |.......%.W.../..| -00000050 1a ff 01 00 01 00 00 0b 00 04 03 00 01 02 00 10 |................| -00000060 00 09 00 07 06 70 72 6f 74 6f 31 16 03 03 02 be |.....proto1.....| -00000070 0b 00 02 ba 00 02 b7 00 02 b4 30 82 02 b0 30 82 |..........0...0.| -00000080 02 19 a0 03 02 01 02 02 09 00 85 b0 bb a4 8a 7f |................| -00000090 b8 ca 30 0d 06 09 2a 86 48 86 f7 0d 01 01 05 05 |..0...*.H.......| -000000a0 00 30 45 31 0b 30 09 06 03 55 04 06 13 02 41 55 |.0E1.0...U....AU| -000000b0 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d 65 2d |1.0...U....Some-| -000000c0 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a 13 18 |State1!0...U....| -000000d0 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 74 73 |Internet Widgits| -000000e0 20 50 74 79 20 4c 74 64 30 1e 17 0d 31 30 30 34 | Pty Ltd0...1004| -000000f0 32 34 30 39 30 39 33 38 5a 17 0d 31 31 30 34 32 |24090938Z..11042| -00000100 34 30 39 30 39 33 38 5a 30 45 31 0b 30 09 06 03 |4090938Z0E1.0...| -00000110 55 04 06 13 02 41 55 31 13 30 11 06 03 55 04 08 |U....AU1.0...U..| -00000120 13 0a 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f |..Some-State1!0.| -00000130 06 03 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 |..U....Internet | -00000140 57 69 64 67 69 74 73 20 50 74 79 20 4c 74 64 30 |Widgits Pty Ltd0| -00000150 81 9f 30 0d 06 09 2a 86 48 86 f7 0d 01 01 01 05 |..0...*.H.......| -00000160 00 03 81 8d 00 30 81 89 02 81 81 00 bb 79 d6 f5 |.....0.......y..| -00000170 17 b5 e5 bf 46 10 d0 dc 69 be e6 2b 07 43 5a d0 |....F...i..+.CZ.| -00000180 03 2d 8a 7a 43 85 b7 14 52 e7 a5 65 4c 2c 78 b8 |.-.zC...R..eL,x.| -00000190 23 8c b5 b4 82 e5 de 1f 95 3b 7e 62 a5 2c a5 33 |#........;~b.,.3| -000001a0 d6 fe 12 5c 7a 56 fc f5 06 bf fa 58 7b 26 3f b5 |...\zV.....X{&?.| -000001b0 cd 04 d3 d0 c9 21 96 4a c7 f4 54 9f 5a bf ef 42 |.....!.J..T.Z..B| -000001c0 71 00 fe 18 99 07 7f 7e 88 7d 7d f1 04 39 c4 a2 |q......~.}}..9..| -000001d0 2e db 51 c9 7c e3 c0 4c 3b 32 66 01 cf af b1 1d |..Q.|..L;2f.....| -000001e0 b8 71 9a 1d db db 89 6b ae da 2d 79 02 03 01 00 |.q.....k..-y....| -000001f0 01 a3 81 a7 30 81 a4 30 1d 06 03 55 1d 0e 04 16 |....0..0...U....| -00000200 04 14 b1 ad e2 85 5a cf cb 28 db 69 ce 23 69 de |......Z..(.i.#i.| -00000210 d3 26 8e 18 88 39 30 75 06 03 55 1d 23 04 6e 30 |.&...90u..U.#.n0| -00000220 6c 80 14 b1 ad e2 85 5a cf cb 28 db 69 ce 23 69 |l......Z..(.i.#i| -00000230 de d3 26 8e 18 88 39 a1 49 a4 47 30 45 31 0b 30 |..&...9.I.G0E1.0| -00000240 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 03 |...U....AU1.0...| -00000250 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 31 |U....Some-State1| -00000260 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 6e |!0...U....Intern| -00000270 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 4c |et Widgits Pty L| -00000280 74 64 82 09 00 85 b0 bb a4 8a 7f b8 ca 30 0c 06 |td...........0..| -00000290 03 55 1d 13 04 05 30 03 01 01 ff 30 0d 06 09 2a |.U....0....0...*| -000002a0 86 48 86 f7 0d 01 01 05 05 00 03 81 81 00 08 6c |.H.............l| -000002b0 45 24 c7 6b b1 59 ab 0c 52 cc f2 b0 14 d7 87 9d |E$.k.Y..R.......| -000002c0 7a 64 75 b5 5a 95 66 e4 c5 2b 8e ae 12 66 1f eb |zdu.Z.f..+...f..| -000002d0 4f 38 b3 6e 60 d3 92 fd f7 41 08 b5 25 13 b1 18 |O8.n`....A..%...| -000002e0 7a 24 fb 30 1d ba ed 98 b9 17 ec e7 d7 31 59 db |z$.0.........1Y.| -000002f0 95 d3 1d 78 ea 50 56 5c d5 82 5a 2d 5a 5f 33 c4 |...x.PV\..Z-Z_3.| -00000300 b6 d8 c9 75 90 96 8c 0f 52 98 b5 cd 98 1f 89 20 |...u....R...... | -00000310 5f f2 a0 1c a3 1b 96 94 dd a9 fd 57 e9 70 e8 26 |_..........W.p.&| -00000320 6d 71 99 9b 26 6e 38 50 29 6c 90 a7 bd d9 16 03 |mq..&n8P)l......| -00000330 03 00 cd 0c 00 00 c9 03 00 17 41 04 1b 42 c3 ae |..........A..B..| -00000340 44 19 d3 84 7c 6c 98 cb b9 22 a2 67 63 95 aa cc |D...|l...".gc...| -00000350 bd e4 1e f8 08 e6 60 f3 bc 83 9f 81 da 9c 1c 8c |......`.........| -00000360 ff 6f f4 3e 1e e5 3b f6 49 61 f9 70 43 7f c1 69 |.o.>..;.Ia.pC..i| -00000370 de 73 98 4b bd 5c c3 78 24 18 a8 ec 04 01 00 80 |.s.K.\.x$.......| -00000380 70 d2 5b e1 39 cf 4d 54 de d2 74 4e 5e a8 b3 ca |p.[.9.MT..tN^...| -00000390 e1 f2 4e 76 3c 77 8b ef f7 d1 df b9 ad c1 70 39 |..Nv>> Flow 3 (client to server) -00000000 16 03 03 00 46 10 00 00 42 41 04 1e 18 37 ef 0d |....F...BA...7..| -00000010 19 51 88 35 75 71 b5 e5 54 5b 12 2e 8f 09 67 fd |.Q.5uq..T[....g.| -00000020 a7 24 20 3e b2 56 1c ce 97 28 5e f8 2b 2d 4f 9e |.$ >.V...(^.+-O.| -00000030 f1 07 9f 6c 4b 5b 83 56 e2 32 42 e9 58 b6 d7 49 |...lK[.V.2B.X..I| -00000040 a6 b5 68 1a 41 03 56 6b dc 5a 89 14 03 03 00 01 |..h.A.Vk.Z......| -00000050 01 16 03 03 00 28 00 00 00 00 00 00 00 00 35 9d |.....(........5.| -00000060 92 e8 bf df 7f a7 77 1b cf 03 2a bf e2 6c 62 2b |......w...*..lb+| -00000070 26 f0 fb 93 d3 df fd 55 84 d3 ed 88 31 cb |&......U....1.| ->>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 28 c8 c0 78 09 73 |..........(..x.s| -00000010 58 41 73 66 88 cf db f3 fe c6 57 ab 45 be 2e d8 |XAsf......W.E...| -00000020 4e e5 ff 42 57 13 74 d2 cc c2 62 07 39 8b 06 46 |N..BW.t...b.9..F| -00000030 1d 8f 88 |...| ->>> Flow 5 (client to server) -00000000 17 03 03 00 1e 00 00 00 00 00 00 00 01 10 c3 5f |..............._| -00000010 3f c8 92 6c 7a a7 23 05 f3 d8 31 20 01 52 f1 99 |?..lz.#...1 .R..| -00000020 33 c1 2a 15 03 03 00 1a 00 00 00 00 00 00 00 02 |3.*.............| -00000030 cc ef eb 78 e4 e1 9d 90 05 6d 95 ac f2 49 ba 8e |...x.....m...I..| -00000040 6b 8d |k.| diff --git a/src/pkg/crypto/tls/testdata/Client-TLSv12-ALPN-NoMatch b/src/pkg/crypto/tls/testdata/Client-TLSv12-ALPN-NoMatch deleted file mode 100644 index f24a70cc8..000000000 --- a/src/pkg/crypto/tls/testdata/Client-TLSv12-ALPN-NoMatch +++ /dev/null @@ -1,95 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 86 01 00 00 82 03 03 00 00 00 00 00 |................| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 1a c0 2f |.............../| -00000030 c0 2b c0 11 c0 07 c0 13 c0 09 c0 14 c0 0a 00 05 |.+..............| -00000040 00 2f 00 35 c0 12 00 0a 01 00 00 3f 33 74 00 00 |./.5.......?3t..| -00000050 00 05 00 05 01 00 00 00 00 00 0a 00 08 00 06 00 |................| -00000060 17 00 18 00 19 00 0b 00 02 01 00 00 0d 00 0a 00 |................| -00000070 08 04 01 04 03 02 01 02 03 ff 01 00 01 00 00 10 |................| -00000080 00 09 00 07 06 70 72 6f 74 6f 33 |.....proto3| ->>> Flow 2 (server to client) -00000000 16 03 03 00 59 02 00 00 55 03 03 69 84 d1 d3 44 |....Y...U..i...D| -00000010 e9 66 08 48 bc 70 d8 ae 40 0b 17 69 e7 27 f6 7a |.f.H.p..@..i.'.z| -00000020 d5 ee 86 74 54 9e a8 bb 79 76 89 20 57 53 1b 02 |...tT...yv. WS..| -00000030 5b 70 81 a6 f1 53 bc 9d b7 42 5e ac 92 93 b5 20 |[p...S...B^.... | -00000040 8a bb 36 cc 8f cb 7e a0 61 a2 e8 ef c0 2f 00 00 |..6...~.a..../..| -00000050 0d ff 01 00 01 00 00 0b 00 04 03 00 01 02 16 03 |................| -00000060 03 02 be 0b 00 02 ba 00 02 b7 00 02 b4 30 82 02 |.............0..| -00000070 b0 30 82 02 19 a0 03 02 01 02 02 09 00 85 b0 bb |.0..............| -00000080 a4 8a 7f b8 ca 30 0d 06 09 2a 86 48 86 f7 0d 01 |.....0...*.H....| -00000090 01 05 05 00 30 45 31 0b 30 09 06 03 55 04 06 13 |....0E1.0...U...| -000000a0 02 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f |.AU1.0...U....So| -000000b0 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 |me-State1!0...U.| -000000c0 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 |...Internet Widg| -000000d0 69 74 73 20 50 74 79 20 4c 74 64 30 1e 17 0d 31 |its Pty Ltd0...1| -000000e0 30 30 34 32 34 30 39 30 39 33 38 5a 17 0d 31 31 |00424090938Z..11| -000000f0 30 34 32 34 30 39 30 39 33 38 5a 30 45 31 0b 30 |0424090938Z0E1.0| -00000100 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 03 |...U....AU1.0...| -00000110 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 31 |U....Some-State1| -00000120 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 6e |!0...U....Intern| -00000130 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 4c |et Widgits Pty L| -00000140 74 64 30 81 9f 30 0d 06 09 2a 86 48 86 f7 0d 01 |td0..0...*.H....| -00000150 01 01 05 00 03 81 8d 00 30 81 89 02 81 81 00 bb |........0.......| -00000160 79 d6 f5 17 b5 e5 bf 46 10 d0 dc 69 be e6 2b 07 |y......F...i..+.| -00000170 43 5a d0 03 2d 8a 7a 43 85 b7 14 52 e7 a5 65 4c |CZ..-.zC...R..eL| -00000180 2c 78 b8 23 8c b5 b4 82 e5 de 1f 95 3b 7e 62 a5 |,x.#........;~b.| -00000190 2c a5 33 d6 fe 12 5c 7a 56 fc f5 06 bf fa 58 7b |,.3...\zV.....X{| -000001a0 26 3f b5 cd 04 d3 d0 c9 21 96 4a c7 f4 54 9f 5a |&?......!.J..T.Z| -000001b0 bf ef 42 71 00 fe 18 99 07 7f 7e 88 7d 7d f1 04 |..Bq......~.}}..| -000001c0 39 c4 a2 2e db 51 c9 7c e3 c0 4c 3b 32 66 01 cf |9....Q.|..L;2f..| -000001d0 af b1 1d b8 71 9a 1d db db 89 6b ae da 2d 79 02 |....q.....k..-y.| -000001e0 03 01 00 01 a3 81 a7 30 81 a4 30 1d 06 03 55 1d |.......0..0...U.| -000001f0 0e 04 16 04 14 b1 ad e2 85 5a cf cb 28 db 69 ce |.........Z..(.i.| -00000200 23 69 de d3 26 8e 18 88 39 30 75 06 03 55 1d 23 |#i..&...90u..U.#| -00000210 04 6e 30 6c 80 14 b1 ad e2 85 5a cf cb 28 db 69 |.n0l......Z..(.i| -00000220 ce 23 69 de d3 26 8e 18 88 39 a1 49 a4 47 30 45 |.#i..&...9.I.G0E| -00000230 31 0b 30 09 06 03 55 04 06 13 02 41 55 31 13 30 |1.0...U....AU1.0| -00000240 11 06 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 |...U....Some-Sta| -00000250 74 65 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 |te1!0...U....Int| -00000260 65 72 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 |ernet Widgits Pt| -00000270 79 20 4c 74 64 82 09 00 85 b0 bb a4 8a 7f b8 ca |y Ltd...........| -00000280 30 0c 06 03 55 1d 13 04 05 30 03 01 01 ff 30 0d |0...U....0....0.| -00000290 06 09 2a 86 48 86 f7 0d 01 01 05 05 00 03 81 81 |..*.H...........| -000002a0 00 08 6c 45 24 c7 6b b1 59 ab 0c 52 cc f2 b0 14 |..lE$.k.Y..R....| -000002b0 d7 87 9d 7a 64 75 b5 5a 95 66 e4 c5 2b 8e ae 12 |...zdu.Z.f..+...| -000002c0 66 1f eb 4f 38 b3 6e 60 d3 92 fd f7 41 08 b5 25 |f..O8.n`....A..%| -000002d0 13 b1 18 7a 24 fb 30 1d ba ed 98 b9 17 ec e7 d7 |...z$.0.........| -000002e0 31 59 db 95 d3 1d 78 ea 50 56 5c d5 82 5a 2d 5a |1Y....x.PV\..Z-Z| -000002f0 5f 33 c4 b6 d8 c9 75 90 96 8c 0f 52 98 b5 cd 98 |_3....u....R....| -00000300 1f 89 20 5f f2 a0 1c a3 1b 96 94 dd a9 fd 57 e9 |.. _..........W.| -00000310 70 e8 26 6d 71 99 9b 26 6e 38 50 29 6c 90 a7 bd |p.&mq..&n8P)l...| -00000320 d9 16 03 03 00 cd 0c 00 00 c9 03 00 17 41 04 04 |.............A..| -00000330 be 27 08 6f 12 83 1b 04 76 fa 5f 16 d6 e3 64 76 |.'.o....v._...dv| -00000340 ad 0a 77 37 71 64 44 4c 3f 1a be dc 85 ce 46 c8 |..w7qdDL?.....F.| -00000350 29 a1 e2 24 78 66 1f 35 90 05 46 c0 91 d1 fd dd |)..$xf.5..F.....| -00000360 b5 5b 87 d7 6d 9d 77 a7 f7 b3 df 68 27 fd 6d 04 |.[..m.w....h'.m.| -00000370 01 00 80 7b 9b fd 0d 62 57 07 ef 97 f5 ff a9 00 |...{...bW.......| -00000380 a0 89 35 5a 8a e6 e7 ae 7b 55 c5 dc 21 64 87 6e |..5Z....{U..!d.n| -00000390 0f ab 85 6d 82 e8 83 fd 7d 3b 49 a7 ae 92 5f 6d |...m....};I..._m| -000003a0 a3 42 ce ff ef a6 00 6a 33 32 1f 7b eb b7 c2 5c |.B.....j32.{...\| -000003b0 2d 38 cf 10 4b 59 69 4d 15 e0 68 49 39 ba cb 2a |-8..KYiM..hI9..*| -000003c0 d9 b9 f3 fe 33 01 4f 7e ac 69 02 35 a5 e0 33 8d |....3.O~.i.5..3.| -000003d0 b3 74 34 14 45 9c 89 ad 41 2d d0 27 22 90 58 c6 |.t4.E...A-.'".X.| -000003e0 e0 2c b4 6e 19 04 e4 46 26 ec 13 35 48 a6 3f 64 |.,.n...F&..5H.?d| -000003f0 dc 85 2b 16 03 03 00 04 0e 00 00 00 |..+.........| ->>> Flow 3 (client to server) -00000000 16 03 03 00 46 10 00 00 42 41 04 1e 18 37 ef 0d |....F...BA...7..| -00000010 19 51 88 35 75 71 b5 e5 54 5b 12 2e 8f 09 67 fd |.Q.5uq..T[....g.| -00000020 a7 24 20 3e b2 56 1c ce 97 28 5e f8 2b 2d 4f 9e |.$ >.V...(^.+-O.| -00000030 f1 07 9f 6c 4b 5b 83 56 e2 32 42 e9 58 b6 d7 49 |...lK[.V.2B.X..I| -00000040 a6 b5 68 1a 41 03 56 6b dc 5a 89 14 03 03 00 01 |..h.A.Vk.Z......| -00000050 01 16 03 03 00 28 00 00 00 00 00 00 00 00 88 0d |.....(..........| -00000060 04 8b 8e 93 55 58 d6 75 ca 16 26 42 a3 60 20 67 |....UX.u..&B.` g| -00000070 84 cf d7 b3 10 fe 63 6c 2f 40 64 0c d6 78 |......cl/@d..x| ->>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 28 bd 6c 2f 70 b9 |..........(.l/p.| -00000010 2f 9c 29 70 af 34 49 4c 5b 25 c3 14 b6 6d 28 81 |/.)p.4IL[%...m(.| -00000020 ff 54 d9 71 8d 2c c7 38 dd 44 27 6b 54 1e 53 7b |.T.q.,.8.D'kT.S{| -00000030 22 cb 65 |".e| ->>> Flow 5 (client to server) -00000000 17 03 03 00 1e 00 00 00 00 00 00 00 01 7f 0d d7 |................| -00000010 d9 4b 87 7b 36 fb 24 92 69 22 43 50 1e 46 fb c4 |.K.{6.$.i"CP.F..| -00000020 86 64 6f 15 03 03 00 1a 00 00 00 00 00 00 00 02 |.do.............| -00000030 37 d5 2d 0a be c5 a8 ae d4 bd 2b 09 34 18 a0 87 |7.-.......+.4...| -00000040 08 a6 |..| diff --git a/src/pkg/crypto/tls/testdata/Client-TLSv12-ClientCert-ECDSA-ECDSA b/src/pkg/crypto/tls/testdata/Client-TLSv12-ClientCert-ECDSA-ECDSA deleted file mode 100644 index 207327036..000000000 --- a/src/pkg/crypto/tls/testdata/Client-TLSv12-ClientCert-ECDSA-ECDSA +++ /dev/null @@ -1,134 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 75 01 00 00 71 03 03 00 00 00 00 00 |....u...q.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 1a c0 2f |.............../| -00000030 c0 2b c0 11 c0 07 c0 13 c0 09 c0 14 c0 0a 00 05 |.+..............| -00000040 00 2f 00 35 c0 12 00 0a 01 00 00 2e 00 05 00 05 |./.5............| -00000050 01 00 00 00 00 00 0a 00 08 00 06 00 17 00 18 00 |................| -00000060 19 00 0b 00 02 01 00 00 0d 00 0a 00 08 04 01 04 |................| -00000070 03 02 01 02 03 ff 01 00 01 00 |..........| ->>> Flow 2 (server to client) -00000000 16 03 03 00 59 02 00 00 55 03 03 53 04 f1 03 6f |....Y...U..S...o| -00000010 c6 4b 55 27 fe e8 fe 4d 7c 0e d4 20 98 b8 7c 81 |.KU'...M|.. ..|.| -00000020 3d 31 f8 35 66 2f 0a 0b f1 2c e3 20 86 4d 12 32 |=1.5f/...,. .M.2| -00000030 73 e3 ba be 25 50 a4 a2 a1 7b f1 9a 76 7a 75 fb |s...%P...{..vzu.| -00000040 e2 64 a2 12 ec f3 e7 9d 9a 24 6e 94 c0 09 00 00 |.d.......$n.....| -00000050 0d ff 01 00 01 00 00 0b 00 04 03 00 01 02 16 03 |................| -00000060 03 02 0e 0b 00 02 0a 00 02 07 00 02 04 30 82 02 |.............0..| -00000070 00 30 82 01 62 02 09 00 b8 bf 2d 47 a0 d2 eb f4 |.0..b.....-G....| -00000080 30 09 06 07 2a 86 48 ce 3d 04 01 30 45 31 0b 30 |0...*.H.=..0E1.0| -00000090 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 03 |...U....AU1.0...| -000000a0 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 31 |U....Some-State1| -000000b0 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 6e |!0...U....Intern| -000000c0 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 4c |et Widgits Pty L| -000000d0 74 64 30 1e 17 0d 31 32 31 31 32 32 31 35 30 36 |td0...1211221506| -000000e0 33 32 5a 17 0d 32 32 31 31 32 30 31 35 30 36 33 |32Z..22112015063| -000000f0 32 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 41 |2Z0E1.0...U....A| -00000100 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d 65 |U1.0...U....Some| -00000110 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a 13 |-State1!0...U...| -00000120 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 74 |.Internet Widgit| -00000130 73 20 50 74 79 20 4c 74 64 30 81 9b 30 10 06 07 |s Pty Ltd0..0...| -00000140 2a 86 48 ce 3d 02 01 06 05 2b 81 04 00 23 03 81 |*.H.=....+...#..| -00000150 86 00 04 00 c4 a1 ed be 98 f9 0b 48 73 36 7e c3 |...........Hs6~.| -00000160 16 56 11 22 f2 3d 53 c3 3b 4d 21 3d cd 6b 75 e6 |.V.".=S.;M!=.ku.| -00000170 f6 b0 dc 9a df 26 c1 bc b2 87 f0 72 32 7c b3 64 |.....&.....r2|.d| -00000180 2f 1c 90 bc ea 68 23 10 7e fe e3 25 c0 48 3a 69 |/....h#.~..%.H:i| -00000190 e0 28 6d d3 37 00 ef 04 62 dd 0d a0 9c 70 62 83 |.(m.7...b....pb.| -000001a0 d8 81 d3 64 31 aa 9e 97 31 bd 96 b0 68 c0 9b 23 |...d1...1...h..#| -000001b0 de 76 64 3f 1a 5c 7f e9 12 0e 58 58 b6 5f 70 dd |.vd?.\....XX._p.| -000001c0 9b d8 ea d5 d7 f5 d5 cc b9 b6 9f 30 66 5b 66 9a |...........0f[f.| -000001d0 20 e2 27 e5 bf fe 3b 30 09 06 07 2a 86 48 ce 3d | .'...;0...*.H.=| -000001e0 04 01 03 81 8c 00 30 81 88 02 42 01 88 a2 4f eb |......0...B...O.| -000001f0 e2 45 c5 48 7d 1b ac f5 ed 98 9d ae 47 70 c0 5e |.E.H}.......Gp.^| -00000200 1b b6 2f bd f1 b6 4d b7 61 40 d3 11 a2 ce ee 0b |../...M.a@......| -00000210 7e 92 7e ff 76 9d c3 3b 7e a5 3f ce fa 10 e2 59 |~.~.v..;~.?....Y| -00000220 ec 47 2d 7c ac da 4e 97 0e 15 a0 6f d0 02 42 01 |.G-|..N....o..B.| -00000230 4d fc be 67 13 9c 2d 05 0e bd 3f a3 8c 25 c1 33 |M..g..-...?..%.3| -00000240 13 83 0d 94 06 bb d4 37 7a f6 ec 7a c9 86 2e dd |.......7z..z....| -00000250 d7 11 69 7f 85 7c 56 de fb 31 78 2b e4 c7 78 0d |..i..|V..1x+..x.| -00000260 ae cb be 9e 4e 36 24 31 7b 6a 0f 39 95 12 07 8f |....N6$1{j.9....| -00000270 2a 16 03 03 00 d7 0c 00 00 d3 03 00 17 41 04 a3 |*............A..| -00000280 03 8c de d2 b0 68 c8 25 0e 85 ea d7 ae 13 0d 79 |.....h.%.......y| -00000290 ec 59 0d b5 4d 51 96 d9 7f 64 36 fb 4c d5 6a 26 |.Y..MQ...d6.L.j&| -000002a0 ae 0e 48 61 df 5c 2b d4 ff 09 41 15 c4 14 8e 1b |..Ha.\+...A.....| -000002b0 84 a8 c8 cd ef 10 97 95 66 67 85 dd fd dc 2a 04 |........fg....*.| -000002c0 03 00 8a 30 81 87 02 41 11 75 5d bc bd 08 28 d4 |...0...A.u]...(.| -000002d0 5b 1b 45 7f 9c d3 8d 0b 91 fa f6 82 ba 59 bd 3e |[.E..........Y.>| -000002e0 96 01 c6 1d 38 db fe 08 e7 56 89 fc 10 b0 37 6a |....8....V....7j| -000002f0 3d d6 c9 50 16 53 f7 c2 a2 60 67 82 1f 74 b8 d5 |=..P.S...`g..t..| -00000300 bc 02 ec 96 db 82 18 8c 87 02 42 01 0d df f7 b7 |..........B.....| -00000310 05 3c 8c 56 f0 1d 33 18 cf c5 4c 80 7e 0b d9 f9 |.<.V..3...L.~...| -00000320 f0 51 69 fe 5d b8 0b 64 c0 c7 0d f4 75 65 ae 07 |.Qi.]..d....ue..| -00000330 9d cf f4 4b ad 52 f6 b8 10 26 18 bd d6 e2 0d a8 |...K.R...&......| -00000340 80 10 50 34 15 cd 72 0b 7d a9 94 de 4c 16 03 03 |..P4..r.}...L...| -00000350 00 30 0d 00 00 28 03 01 02 40 00 20 06 01 06 02 |.0...(...@. ....| -00000360 06 03 05 01 05 02 05 03 04 01 04 02 04 03 03 01 |................| -00000370 03 02 03 03 02 01 02 02 02 03 01 01 00 00 0e 00 |................| -00000380 00 00 |..| ->>> Flow 3 (client to server) -00000000 16 03 03 02 0a 0b 00 02 06 00 02 03 00 02 00 30 |...............0| -00000010 82 01 fc 30 82 01 5e 02 09 00 9a 30 84 6c 26 35 |...0..^....0.l&5| -00000020 d9 17 30 09 06 07 2a 86 48 ce 3d 04 01 30 45 31 |..0...*.H.=..0E1| -00000030 0b 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 |.0...U....AU1.0.| -00000040 06 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 |..U....Some-Stat| -00000050 65 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 |e1!0...U....Inte| -00000060 72 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 |rnet Widgits Pty| -00000070 20 4c 74 64 30 1e 17 0d 31 32 31 31 31 34 31 33 | Ltd0...12111413| -00000080 32 35 35 33 5a 17 0d 32 32 31 31 31 32 31 33 32 |2553Z..221112132| -00000090 35 35 33 5a 30 41 31 0b 30 09 06 03 55 04 06 13 |553Z0A1.0...U...| -000000a0 02 41 55 31 0c 30 0a 06 03 55 04 08 13 03 4e 53 |.AU1.0...U....NS| -000000b0 57 31 10 30 0e 06 03 55 04 07 13 07 50 79 72 6d |W1.0...U....Pyrm| -000000c0 6f 6e 74 31 12 30 10 06 03 55 04 03 13 09 4a 6f |ont1.0...U....Jo| -000000d0 65 6c 20 53 69 6e 67 30 81 9b 30 10 06 07 2a 86 |el Sing0..0...*.| -000000e0 48 ce 3d 02 01 06 05 2b 81 04 00 23 03 81 86 00 |H.=....+...#....| -000000f0 04 00 95 8c 91 75 14 c0 5e c4 57 b4 d4 c3 6f 8d |.....u..^.W...o.| -00000100 ae 68 1e dd 6f ce 86 e1 7e 6e b2 48 3e 81 e5 4e |.h..o...~n.H>..N| -00000110 e2 c6 88 4b 64 dc f5 30 bb d3 ff 65 cc 5b f4 dd |...Kd..0...e.[..| -00000120 b5 6a 3e 3e d0 1d de 47 c3 76 ad 19 f6 45 2c 8c |.j>>...G.v...E,.| -00000130 bc d8 1d 01 4c 1f 70 90 46 76 48 8b 8f 83 cc 4a |....L.p.FvH....J| -00000140 5c 8f 40 76 da e0 89 ec 1d 2b c4 4e 30 76 28 41 |\.@v.....+.N0v(A| -00000150 b2 62 a8 fb 5b f1 f9 4e 7a 8d bd 09 b8 ae ea 8b |.b..[..Nz.......| -00000160 18 27 4f 2e 70 fe 13 96 ba c3 d3 40 16 cd 65 4e |.'O.p......@..eN| -00000170 ac 11 1e e6 f1 30 09 06 07 2a 86 48 ce 3d 04 01 |.....0...*.H.=..| -00000180 03 81 8c 00 30 81 88 02 42 00 e0 14 c4 60 60 0b |....0...B....``.| -00000190 72 68 b0 32 5d 61 4a 02 74 5c c2 81 b9 16 a8 3f |rh.2]aJ.t\.....?| -000001a0 29 c8 36 c7 81 ff 6c b6 5b d9 70 f1 38 3b 50 48 |).6...l.[.p.8;PH| -000001b0 28 94 cb 09 1a 52 f1 5d ee 8d f2 b9 f0 f0 da d9 |(....R.]........| -000001c0 15 3a f9 bd 03 7a 87 a2 23 35 ec 02 42 01 a3 d4 |.:...z..#5..B...| -000001d0 8a 78 35 1c 4a 9a 23 d2 0a be 2b 10 31 9d 9c 5f |.x5.J.#...+.1.._| -000001e0 be e8 91 b3 da 1a f5 5d a3 23 f5 26 8b 45 70 8d |.......].#.&.Ep.| -000001f0 65 62 9b 7e 01 99 3d 18 f6 10 9a 38 61 9b 2e 57 |eb.~..=....8a..W| -00000200 e4 fa cc b1 8a ce e2 23 a0 87 f0 e1 67 51 eb 16 |.......#....gQ..| -00000210 03 03 00 46 10 00 00 42 41 04 1e 18 37 ef 0d 19 |...F...BA...7...| -00000220 51 88 35 75 71 b5 e5 54 5b 12 2e 8f 09 67 fd a7 |Q.5uq..T[....g..| -00000230 24 20 3e b2 56 1c ce 97 28 5e f8 2b 2d 4f 9e f1 |$ >.V...(^.+-O..| -00000240 07 9f 6c 4b 5b 83 56 e2 32 42 e9 58 b6 d7 49 a6 |..lK[.V.2B.X..I.| -00000250 b5 68 1a 41 03 56 6b dc 5a 89 16 03 03 00 92 0f |.h.A.Vk.Z.......| -00000260 00 00 8e 04 03 00 8a 30 81 87 02 42 00 c6 85 8e |.......0...B....| -00000270 06 b7 04 04 e9 cd 9e 3e cb 66 23 95 b4 42 9c 64 |.......>.f#..B.d| -00000280 81 39 05 3f b5 21 f8 28 af 60 6b 4d 3d ba a1 4b |.9.?.!.(.`kM=..K| -00000290 5e 77 ef e7 59 28 fe 1d c1 27 a2 ff a8 de 33 48 |^w..Y(...'....3H| -000002a0 b3 c1 85 6a 42 9b f9 7e 7e 31 c2 e5 bd 66 02 41 |...jB..~~1...f.A| -000002b0 4b 49 c6 cd 02 e3 83 f7 03 50 18 6d b4 c9 51 02 |KI.......P.m..Q.| -000002c0 c0 ab 87 bc e0 3e 4b 89 53 3a e2 65 89 97 02 c1 |.....>K.S:.e....| -000002d0 88 0d 64 db 8e 4f 73 4e ea 29 0b ed a0 f5 ce 3d |..d..OsN.).....=| -000002e0 5f cc 20 ef 0a 22 02 82 f2 14 2a b7 42 68 bd c7 |_. .."....*.Bh..| -000002f0 4d 14 03 03 00 01 01 16 03 03 00 40 00 00 00 00 |M..........@....| -00000300 00 00 00 00 00 00 00 00 00 00 00 00 f0 cc 4f c7 |..............O.| -00000310 b6 0f c9 38 4d 4b 97 2c 4f be 53 08 4c d6 5b 4e |...8MK.,O.S.L.[N| -00000320 24 70 30 81 82 3a 7f 62 95 03 4d fc 54 78 ec 13 |$p0..:.b..M.Tx..| -00000330 b2 a1 00 85 2b 04 e4 1d 7b 6e 87 60 |....+...{n.`| ->>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 40 d5 2a 76 79 1c |..........@.*vy.| -00000010 e7 d5 b1 5c 65 6b d1 45 73 53 4c 05 3a 6c 5d 81 |...\ek.EsSL.:l].| -00000020 dd 2f f0 74 62 e4 8e f8 ed 21 99 c7 4f d6 28 40 |./.tb....!..O.(@| -00000030 63 d9 6d e5 b0 04 73 27 7a 1d 08 19 31 10 da ef |c.m...s'z...1...| -00000040 79 26 33 fb 45 23 be a4 7c 03 66 |y&3.E#..|.f| ->>> Flow 5 (client to server) -00000000 17 03 03 00 30 00 00 00 00 00 00 00 00 00 00 00 |....0...........| -00000010 00 00 00 00 00 e2 53 bd c0 ef 9e e6 44 94 ea 5d |......S.....D..]| -00000020 f5 c5 a9 4b ed eb 1c 49 9f 79 44 f9 cd d7 de 02 |...K...I.yD.....| -00000030 51 10 ae 87 7d 15 03 03 00 30 00 00 00 00 00 00 |Q...}....0......| -00000040 00 00 00 00 00 00 00 00 00 00 d3 95 13 7f 5f 58 |.............._X| -00000050 ab d6 17 ea 01 2c 2a ea 5d 7c 44 61 4a 27 97 52 |.....,*.]|DaJ'.R| -00000060 cc 9b 86 f6 37 42 2b 94 01 49 |....7B+..I| diff --git a/src/pkg/crypto/tls/testdata/Client-TLSv12-ClientCert-ECDSA-RSA b/src/pkg/crypto/tls/testdata/Client-TLSv12-ClientCert-ECDSA-RSA deleted file mode 100644 index c3b753a7b..000000000 --- a/src/pkg/crypto/tls/testdata/Client-TLSv12-ClientCert-ECDSA-RSA +++ /dev/null @@ -1,127 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 75 01 00 00 71 03 03 00 00 00 00 00 |....u...q.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 1a c0 2f |.............../| -00000030 c0 2b c0 11 c0 07 c0 13 c0 09 c0 14 c0 0a 00 05 |.+..............| -00000040 00 2f 00 35 c0 12 00 0a 01 00 00 2e 00 05 00 05 |./.5............| -00000050 01 00 00 00 00 00 0a 00 08 00 06 00 17 00 18 00 |................| -00000060 19 00 0b 00 02 01 00 00 0d 00 0a 00 08 04 01 04 |................| -00000070 03 02 01 02 03 ff 01 00 01 00 |..........| ->>> Flow 2 (server to client) -00000000 16 03 03 00 51 02 00 00 4d 03 03 53 04 f1 03 b0 |....Q...M..S....| -00000010 43 00 97 24 a7 a8 ea b2 24 fe 96 24 a1 49 64 fd |C..$....$..$.Id.| -00000020 1c a3 30 35 2d 85 a7 40 42 86 6b 20 af 27 7f ac |..05-..@B.k .'..| -00000030 8b 16 89 6c 78 b7 f5 29 02 58 a6 8b 61 43 c2 b0 |...lx..).X..aC..| -00000040 e0 a8 96 c8 fa 2b 26 ad 9a 5f 2d d6 00 05 00 00 |.....+&.._-.....| -00000050 05 ff 01 00 01 00 16 03 03 02 be 0b 00 02 ba 00 |................| -00000060 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000070 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000080 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000090 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -000000a0 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -000000b0 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000c0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000d0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000e0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000f0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -00000100 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -00000110 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000120 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000130 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000140 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000150 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000160 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000170 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000180 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000190 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -000001a0 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -000001b0 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001c0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001d0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001e0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001f0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -00000200 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -00000210 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000220 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000230 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000240 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000250 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000260 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000270 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000280 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000290 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -000002a0 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -000002b0 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002c0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002d0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002e0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002f0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -00000300 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -00000310 6e 38 50 29 6c 90 a7 bd d9 16 03 03 00 30 0d 00 |n8P)l........0..| -00000320 00 28 03 01 02 40 00 20 06 01 06 02 06 03 05 01 |.(...@. ........| -00000330 05 02 05 03 04 01 04 02 04 03 03 01 03 02 03 03 |................| -00000340 02 01 02 02 02 03 01 01 00 00 0e 00 00 00 |..............| ->>> Flow 3 (client to server) -00000000 16 03 03 02 0a 0b 00 02 06 00 02 03 00 02 00 30 |...............0| -00000010 82 01 fc 30 82 01 5e 02 09 00 9a 30 84 6c 26 35 |...0..^....0.l&5| -00000020 d9 17 30 09 06 07 2a 86 48 ce 3d 04 01 30 45 31 |..0...*.H.=..0E1| -00000030 0b 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 |.0...U....AU1.0.| -00000040 06 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 |..U....Some-Stat| -00000050 65 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 |e1!0...U....Inte| -00000060 72 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 |rnet Widgits Pty| -00000070 20 4c 74 64 30 1e 17 0d 31 32 31 31 31 34 31 33 | Ltd0...12111413| -00000080 32 35 35 33 5a 17 0d 32 32 31 31 31 32 31 33 32 |2553Z..221112132| -00000090 35 35 33 5a 30 41 31 0b 30 09 06 03 55 04 06 13 |553Z0A1.0...U...| -000000a0 02 41 55 31 0c 30 0a 06 03 55 04 08 13 03 4e 53 |.AU1.0...U....NS| -000000b0 57 31 10 30 0e 06 03 55 04 07 13 07 50 79 72 6d |W1.0...U....Pyrm| -000000c0 6f 6e 74 31 12 30 10 06 03 55 04 03 13 09 4a 6f |ont1.0...U....Jo| -000000d0 65 6c 20 53 69 6e 67 30 81 9b 30 10 06 07 2a 86 |el Sing0..0...*.| -000000e0 48 ce 3d 02 01 06 05 2b 81 04 00 23 03 81 86 00 |H.=....+...#....| -000000f0 04 00 95 8c 91 75 14 c0 5e c4 57 b4 d4 c3 6f 8d |.....u..^.W...o.| -00000100 ae 68 1e dd 6f ce 86 e1 7e 6e b2 48 3e 81 e5 4e |.h..o...~n.H>..N| -00000110 e2 c6 88 4b 64 dc f5 30 bb d3 ff 65 cc 5b f4 dd |...Kd..0...e.[..| -00000120 b5 6a 3e 3e d0 1d de 47 c3 76 ad 19 f6 45 2c 8c |.j>>...G.v...E,.| -00000130 bc d8 1d 01 4c 1f 70 90 46 76 48 8b 8f 83 cc 4a |....L.p.FvH....J| -00000140 5c 8f 40 76 da e0 89 ec 1d 2b c4 4e 30 76 28 41 |\.@v.....+.N0v(A| -00000150 b2 62 a8 fb 5b f1 f9 4e 7a 8d bd 09 b8 ae ea 8b |.b..[..Nz.......| -00000160 18 27 4f 2e 70 fe 13 96 ba c3 d3 40 16 cd 65 4e |.'O.p......@..eN| -00000170 ac 11 1e e6 f1 30 09 06 07 2a 86 48 ce 3d 04 01 |.....0...*.H.=..| -00000180 03 81 8c 00 30 81 88 02 42 00 e0 14 c4 60 60 0b |....0...B....``.| -00000190 72 68 b0 32 5d 61 4a 02 74 5c c2 81 b9 16 a8 3f |rh.2]aJ.t\.....?| -000001a0 29 c8 36 c7 81 ff 6c b6 5b d9 70 f1 38 3b 50 48 |).6...l.[.p.8;PH| -000001b0 28 94 cb 09 1a 52 f1 5d ee 8d f2 b9 f0 f0 da d9 |(....R.]........| -000001c0 15 3a f9 bd 03 7a 87 a2 23 35 ec 02 42 01 a3 d4 |.:...z..#5..B...| -000001d0 8a 78 35 1c 4a 9a 23 d2 0a be 2b 10 31 9d 9c 5f |.x5.J.#...+.1.._| -000001e0 be e8 91 b3 da 1a f5 5d a3 23 f5 26 8b 45 70 8d |.......].#.&.Ep.| -000001f0 65 62 9b 7e 01 99 3d 18 f6 10 9a 38 61 9b 2e 57 |eb.~..=....8a..W| -00000200 e4 fa cc b1 8a ce e2 23 a0 87 f0 e1 67 51 eb 16 |.......#....gQ..| -00000210 03 03 00 86 10 00 00 82 00 80 6d 51 f3 7f f9 3e |..........mQ...>| -00000220 fb 75 82 41 36 83 e8 6a ee 2a 2e 25 90 67 4c 8e |.u.A6..j.*.%.gL.| -00000230 62 2f 30 81 17 e0 85 09 0c 2b b7 23 d7 b0 e2 1d |b/0......+.#....| -00000240 f7 3b d7 f5 a1 27 b6 ee 24 b6 1b cc 5b ea 66 0d |.;...'..$...[.f.| -00000250 6a f4 e5 85 f9 da 43 b4 0e 86 85 e1 f5 aa be c8 |j.....C.........| -00000260 ce 39 4c 9c 86 00 08 c2 4b e2 c6 ec 2f f7 ce e6 |.9L.....K.../...| -00000270 bd 77 82 6f 23 b6 e0 bd a2 92 b7 3a ac e8 56 f1 |.w.o#......:..V.| -00000280 af 54 5e 46 87 e9 3b 33 e7 b8 28 b7 d6 c8 90 35 |.T^F..;3..(....5| -00000290 d4 1c 43 d1 30 6f 55 4e 0a 70 16 03 03 00 92 0f |..C.0oUN.p......| -000002a0 00 00 8e 04 03 00 8a 30 81 87 02 42 00 c6 85 8e |.......0...B....| -000002b0 06 b7 04 04 e9 cd 9e 3e cb 66 23 95 b4 42 9c 64 |.......>.f#..B.d| -000002c0 81 39 05 3f b5 21 f8 28 af 60 6b 4d 3d ba a1 4b |.9.?.!.(.`kM=..K| -000002d0 5e 77 ef e7 59 28 fe 1d c1 27 a2 ff a8 de 33 48 |^w..Y(...'....3H| -000002e0 b3 c1 85 6a 42 9b f9 7e 7e 31 c2 e5 bd 66 02 41 |...jB..~~1...f.A| -000002f0 4b 49 c6 cd 02 e3 83 f7 03 50 18 6d b4 c9 51 02 |KI.......P.m..Q.| -00000300 c0 ab 87 bc e0 3e 4b 89 53 3a e2 65 89 97 02 c1 |.....>K.S:.e....| -00000310 88 5a 97 82 3e 55 6b 7c d8 db b8 cc 1b 30 84 0a |.Z..>Uk|.....0..| -00000320 7a 97 71 e4 10 bb a4 39 8c 2a cf f5 88 c7 d1 95 |z.q....9.*......| -00000330 73 14 03 03 00 01 01 16 03 03 00 24 9f 1e f0 72 |s..........$...r| -00000340 92 ea dc f7 56 96 37 e4 69 db db 66 1d f6 94 c4 |....V.7.i..f....| -00000350 18 31 4f d0 5d c5 f4 53 21 aa 98 b1 dc 08 94 94 |.1O.]..S!.......| ->>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 24 ee 68 c1 87 9f |..........$.h...| -00000010 d7 90 94 f1 3b 6d 26 0b 3d 89 7a 45 3b 52 5d 3c |....;m&.=.zE;R]<| -00000020 dd 7c c1 4e 57 3e a9 ee 91 be cf 2b a3 98 9d |.|.NW>.....+...| ->>> Flow 5 (client to server) -00000000 17 03 03 00 1a 88 33 3e 2b 22 6b 92 d0 bb 8a 1e |......3>+"k.....| -00000010 9b f4 9e aa 91 8b 2b 95 ea 53 c8 03 0a 93 58 15 |......+..S....X.| -00000020 03 03 00 16 c4 67 79 ba ec cf 90 b1 f9 ac ec 64 |.....gy........d| -00000030 72 01 08 8f 3a 98 aa 66 25 00 |r...:..f%.| diff --git a/src/pkg/crypto/tls/testdata/Client-TLSv12-ClientCert-RSA-ECDSA b/src/pkg/crypto/tls/testdata/Client-TLSv12-ClientCert-RSA-ECDSA deleted file mode 100644 index 0037af61a..000000000 --- a/src/pkg/crypto/tls/testdata/Client-TLSv12-ClientCert-RSA-ECDSA +++ /dev/null @@ -1,133 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 75 01 00 00 71 03 03 00 00 00 00 00 |....u...q.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 1a c0 2f |.............../| -00000030 c0 2b c0 11 c0 07 c0 13 c0 09 c0 14 c0 0a 00 05 |.+..............| -00000040 00 2f 00 35 c0 12 00 0a 01 00 00 2e 00 05 00 05 |./.5............| -00000050 01 00 00 00 00 00 0a 00 08 00 06 00 17 00 18 00 |................| -00000060 19 00 0b 00 02 01 00 00 0d 00 0a 00 08 04 01 04 |................| -00000070 03 02 01 02 03 ff 01 00 01 00 |..........| ->>> Flow 2 (server to client) -00000000 16 03 03 00 59 02 00 00 55 03 03 53 04 f1 02 fd |....Y...U..S....| -00000010 41 bd ef ee f3 da fc 1a 31 8c 77 f2 e9 66 54 a0 |A.......1.w..fT.| -00000020 f4 15 b1 1c 84 0d 6d 74 87 ac 7d 20 78 17 8b 08 |......mt..} x...| -00000030 10 20 c9 44 e4 8a 43 af 4a c7 b8 3d 99 f2 f7 af |. .D..C.J..=....| -00000040 bb a3 21 2f 40 cc ed b6 da a8 a1 d5 c0 09 00 00 |..!/@...........| -00000050 0d ff 01 00 01 00 00 0b 00 04 03 00 01 02 16 03 |................| -00000060 03 02 0e 0b 00 02 0a 00 02 07 00 02 04 30 82 02 |.............0..| -00000070 00 30 82 01 62 02 09 00 b8 bf 2d 47 a0 d2 eb f4 |.0..b.....-G....| -00000080 30 09 06 07 2a 86 48 ce 3d 04 01 30 45 31 0b 30 |0...*.H.=..0E1.0| -00000090 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 03 |...U....AU1.0...| -000000a0 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 31 |U....Some-State1| -000000b0 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 6e |!0...U....Intern| -000000c0 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 4c |et Widgits Pty L| -000000d0 74 64 30 1e 17 0d 31 32 31 31 32 32 31 35 30 36 |td0...1211221506| -000000e0 33 32 5a 17 0d 32 32 31 31 32 30 31 35 30 36 33 |32Z..22112015063| -000000f0 32 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 41 |2Z0E1.0...U....A| -00000100 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d 65 |U1.0...U....Some| -00000110 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a 13 |-State1!0...U...| -00000120 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 74 |.Internet Widgit| -00000130 73 20 50 74 79 20 4c 74 64 30 81 9b 30 10 06 07 |s Pty Ltd0..0...| -00000140 2a 86 48 ce 3d 02 01 06 05 2b 81 04 00 23 03 81 |*.H.=....+...#..| -00000150 86 00 04 00 c4 a1 ed be 98 f9 0b 48 73 36 7e c3 |...........Hs6~.| -00000160 16 56 11 22 f2 3d 53 c3 3b 4d 21 3d cd 6b 75 e6 |.V.".=S.;M!=.ku.| -00000170 f6 b0 dc 9a df 26 c1 bc b2 87 f0 72 32 7c b3 64 |.....&.....r2|.d| -00000180 2f 1c 90 bc ea 68 23 10 7e fe e3 25 c0 48 3a 69 |/....h#.~..%.H:i| -00000190 e0 28 6d d3 37 00 ef 04 62 dd 0d a0 9c 70 62 83 |.(m.7...b....pb.| -000001a0 d8 81 d3 64 31 aa 9e 97 31 bd 96 b0 68 c0 9b 23 |...d1...1...h..#| -000001b0 de 76 64 3f 1a 5c 7f e9 12 0e 58 58 b6 5f 70 dd |.vd?.\....XX._p.| -000001c0 9b d8 ea d5 d7 f5 d5 cc b9 b6 9f 30 66 5b 66 9a |...........0f[f.| -000001d0 20 e2 27 e5 bf fe 3b 30 09 06 07 2a 86 48 ce 3d | .'...;0...*.H.=| -000001e0 04 01 03 81 8c 00 30 81 88 02 42 01 88 a2 4f eb |......0...B...O.| -000001f0 e2 45 c5 48 7d 1b ac f5 ed 98 9d ae 47 70 c0 5e |.E.H}.......Gp.^| -00000200 1b b6 2f bd f1 b6 4d b7 61 40 d3 11 a2 ce ee 0b |../...M.a@......| -00000210 7e 92 7e ff 76 9d c3 3b 7e a5 3f ce fa 10 e2 59 |~.~.v..;~.?....Y| -00000220 ec 47 2d 7c ac da 4e 97 0e 15 a0 6f d0 02 42 01 |.G-|..N....o..B.| -00000230 4d fc be 67 13 9c 2d 05 0e bd 3f a3 8c 25 c1 33 |M..g..-...?..%.3| -00000240 13 83 0d 94 06 bb d4 37 7a f6 ec 7a c9 86 2e dd |.......7z..z....| -00000250 d7 11 69 7f 85 7c 56 de fb 31 78 2b e4 c7 78 0d |..i..|V..1x+..x.| -00000260 ae cb be 9e 4e 36 24 31 7b 6a 0f 39 95 12 07 8f |....N6$1{j.9....| -00000270 2a 16 03 03 00 d8 0c 00 00 d4 03 00 17 41 04 a9 |*............A..| -00000280 19 8b d9 9b 5c 7c 6a 7d 85 d2 70 4e 89 7e 0b 5b |....\|j}..pN.~.[| -00000290 dd 5e a1 63 8d 15 bc 0b 0c 47 3d 4d e8 a7 56 88 |.^.c.....G=M..V.| -000002a0 2e f6 7f e2 4d fc ed cc 03 ed a1 2d ac ae 81 a5 |....M......-....| -000002b0 e2 6d 7f 9f a3 93 e9 10 c1 0e 48 1b f3 f4 38 04 |.m........H...8.| -000002c0 03 00 8b 30 81 88 02 42 00 87 fe 7e 63 82 14 57 |...0...B...~c..W| -000002d0 dc 7d e2 0f cc 97 2d ba 3c a7 56 4a 17 a8 09 6a |.}....-.<.VJ...j| -000002e0 28 2e f2 66 1a 3f 2d 48 2b 6f 79 a1 60 cd 5e 10 |(..f.?-H+oy.`.^.| -000002f0 0b 0a 28 f2 5f e4 3f 4f f9 c9 91 34 d9 dc bc fc |..(._.?O...4....| -00000300 98 ea 77 0b 99 f8 a2 11 c4 bd 02 42 01 a0 b0 dc |..w........B....| -00000310 db 5b c2 09 99 bd ee a0 b9 aa 31 b9 10 84 22 be |.[........1...".| -00000320 5a 63 12 5a 43 00 8e c1 33 cc 91 bb c2 70 7a 63 |Zc.ZC...3....pzc| -00000330 19 82 c0 74 48 a1 c7 3d 1f f1 6f 4a 6f 6a 8c 3f |...tH..=..oJoj.?| -00000340 28 31 a8 0c 65 19 26 62 4b 7a 7c 4b ea 1a 16 03 |(1..e.&bKz|K....| -00000350 03 00 30 0d 00 00 28 03 01 02 40 00 20 06 01 06 |..0...(...@. ...| -00000360 02 06 03 05 01 05 02 05 03 04 01 04 02 04 03 03 |................| -00000370 01 03 02 03 03 02 01 02 02 02 03 01 01 00 00 0e |................| -00000380 00 00 00 |...| ->>> Flow 3 (client to server) -00000000 16 03 03 01 fb 0b 00 01 f7 00 01 f4 00 01 f1 30 |...............0| -00000010 82 01 ed 30 82 01 58 a0 03 02 01 02 02 01 00 30 |...0..X........0| -00000020 0b 06 09 2a 86 48 86 f7 0d 01 01 05 30 26 31 10 |...*.H......0&1.| -00000030 30 0e 06 03 55 04 0a 13 07 41 63 6d 65 20 43 6f |0...U....Acme Co| -00000040 31 12 30 10 06 03 55 04 03 13 09 31 32 37 2e 30 |1.0...U....127.0| -00000050 2e 30 2e 31 30 1e 17 0d 31 31 31 32 30 38 30 37 |.0.10...11120807| -00000060 35 35 31 32 5a 17 0d 31 32 31 32 30 37 30 38 30 |5512Z..121207080| -00000070 30 31 32 5a 30 26 31 10 30 0e 06 03 55 04 0a 13 |012Z0&1.0...U...| -00000080 07 41 63 6d 65 20 43 6f 31 12 30 10 06 03 55 04 |.Acme Co1.0...U.| -00000090 03 13 09 31 32 37 2e 30 2e 30 2e 31 30 81 9c 30 |...127.0.0.10..0| -000000a0 0b 06 09 2a 86 48 86 f7 0d 01 01 01 03 81 8c 00 |...*.H..........| -000000b0 30 81 88 02 81 80 4e d0 7b 31 e3 82 64 d9 59 c0 |0.....N.{1..d.Y.| -000000c0 c2 87 a4 5e 1e 8b 73 33 c7 63 53 df 66 92 06 84 |...^..s3.cS.f...| -000000d0 f6 64 d5 8f e4 36 a7 1d 2b e8 b3 20 36 45 23 b5 |.d...6..+.. 6E#.| -000000e0 e3 95 ae ed e0 f5 20 9c 8d 95 df 7f 5a 12 ef 87 |...... .....Z...| -000000f0 e4 5b 68 e4 e9 0e 74 ec 04 8a 7f de 93 27 c4 01 |.[h...t......'..| -00000100 19 7a bd f2 dc 3d 14 ab d0 54 ca 21 0c d0 4d 6e |.z...=...T.!..Mn| -00000110 87 2e 5c c5 d2 bb 4d 4b 4f ce b6 2c f7 7e 88 ec |..\...MKO..,.~..| -00000120 7c d7 02 91 74 a6 1e 0c 1a da e3 4a 5a 2e de 13 ||...t......JZ...| -00000130 9c 4c 40 88 59 93 02 03 01 00 01 a3 32 30 30 30 |.L@.Y.......2000| -00000140 0e 06 03 55 1d 0f 01 01 ff 04 04 03 02 00 a0 30 |...U...........0| -00000150 0d 06 03 55 1d 0e 04 06 04 04 01 02 03 04 30 0f |...U..........0.| -00000160 06 03 55 1d 23 04 08 30 06 80 04 01 02 03 04 30 |..U.#..0.......0| -00000170 0b 06 09 2a 86 48 86 f7 0d 01 01 05 03 81 81 00 |...*.H..........| -00000180 36 1f b3 7a 0c 75 c9 6e 37 46 61 2b d5 bd c0 a7 |6..z.u.n7Fa+....| -00000190 4b cc 46 9a 81 58 7c 85 79 29 c8 c8 c6 67 dd 32 |K.F..X|.y)...g.2| -000001a0 56 45 2b 75 b6 e9 24 a9 50 9a be 1f 5a fa 1a 15 |VE+u..$.P...Z...| -000001b0 d9 cc 55 95 72 16 83 b9 c2 b6 8f fd 88 8c 38 84 |..U.r.........8.| -000001c0 1d ab 5d 92 31 13 4f fd 83 3b c6 9d f1 11 62 b6 |..].1.O..;....b.| -000001d0 8b ec ab 67 be c8 64 b0 11 50 46 58 17 6b 99 1c |...g..d..PFX.k..| -000001e0 d3 1d fc 06 f1 0e e5 96 a8 0c f9 78 20 b7 44 18 |...........x .D.| -000001f0 51 8d 10 7e 4f 94 67 df a3 4e 70 73 8e 90 91 85 |Q..~O.g..Nps....| -00000200 16 03 03 00 46 10 00 00 42 41 04 1e 18 37 ef 0d |....F...BA...7..| -00000210 19 51 88 35 75 71 b5 e5 54 5b 12 2e 8f 09 67 fd |.Q.5uq..T[....g.| -00000220 a7 24 20 3e b2 56 1c ce 97 28 5e f8 2b 2d 4f 9e |.$ >.V...(^.+-O.| -00000230 f1 07 9f 6c 4b 5b 83 56 e2 32 42 e9 58 b6 d7 49 |...lK[.V.2B.X..I| -00000240 a6 b5 68 1a 41 03 56 6b dc 5a 89 16 03 03 00 88 |..h.A.Vk.Z......| -00000250 0f 00 00 84 04 01 00 80 38 f2 16 e5 b5 86 16 62 |........8......b| -00000260 86 e1 7d 01 f1 a8 e1 f7 e7 85 b1 a0 17 ee 84 25 |..}............%| -00000270 cb 3c 46 61 1a 78 7b 1e ee 32 bc d9 6c fa 6b 76 |.>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 40 ee a8 82 bc 3f |..........@....?| -00000010 bf ab a6 e4 30 e0 3d f1 2f 19 a2 ac 7a 81 57 f1 |....0.=./...z.W.| -00000020 ee 67 3f 55 2b 30 fa 72 b5 10 03 ec 8d 0a 8f bb |.g?U+0.r........| -00000030 24 f5 45 f5 4e 53 4b 93 a5 0d 42 6c 46 69 98 fb |$.E.NSK...BlFi..| -00000040 63 c5 9f 95 65 d1 b6 f0 a4 15 bd |c...e......| ->>> Flow 5 (client to server) -00000000 17 03 03 00 30 00 00 00 00 00 00 00 00 00 00 00 |....0...........| -00000010 00 00 00 00 00 cb 4e bc d1 a9 58 ef c8 39 a9 36 |......N...X..9.6| -00000020 f4 35 05 96 8e a4 50 bc f4 15 06 f9 fd 41 6d 1e |.5....P......Am.| -00000030 5e 7c 82 63 94 15 03 03 00 30 00 00 00 00 00 00 |^|.c.....0......| -00000040 00 00 00 00 00 00 00 00 00 00 bd 77 87 a5 5a d4 |...........w..Z.| -00000050 b8 59 e6 6b 0f dd ea f9 ed 18 b2 9f a9 61 b4 3a |.Y.k.........a.:| -00000060 47 15 15 3b 83 ef e1 6d db a8 |G..;...m..| diff --git a/src/pkg/crypto/tls/testdata/Client-TLSv12-ClientCert-RSA-RSA b/src/pkg/crypto/tls/testdata/Client-TLSv12-ClientCert-RSA-RSA deleted file mode 100644 index df3eaa440..000000000 --- a/src/pkg/crypto/tls/testdata/Client-TLSv12-ClientCert-RSA-RSA +++ /dev/null @@ -1,126 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 75 01 00 00 71 03 03 00 00 00 00 00 |....u...q.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 1a c0 2f |.............../| -00000030 c0 2b c0 11 c0 07 c0 13 c0 09 c0 14 c0 0a 00 05 |.+..............| -00000040 00 2f 00 35 c0 12 00 0a 01 00 00 2e 00 05 00 05 |./.5............| -00000050 01 00 00 00 00 00 0a 00 08 00 06 00 17 00 18 00 |................| -00000060 19 00 0b 00 02 01 00 00 0d 00 0a 00 08 04 01 04 |................| -00000070 03 02 01 02 03 ff 01 00 01 00 |..........| ->>> Flow 2 (server to client) -00000000 16 03 03 00 51 02 00 00 4d 03 03 53 04 f1 02 1d |....Q...M..S....| -00000010 0e dc 86 e5 a9 07 71 46 15 34 af 47 15 3f 03 9c |......qF.4.G.?..| -00000020 fc d6 fd 44 7c f4 f1 c7 8d 6f f8 20 28 ea 3c dc |...D|....o. (.<.| -00000030 b2 4c b7 ba 20 88 c4 db a5 73 ea 93 ab 3a 85 a6 |.L.. ....s...:..| -00000040 8f 59 49 d9 a9 31 14 d5 a6 2b 4f d1 00 05 00 00 |.YI..1...+O.....| -00000050 05 ff 01 00 01 00 16 03 03 02 be 0b 00 02 ba 00 |................| -00000060 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000070 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000080 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000090 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -000000a0 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -000000b0 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000c0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000d0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000e0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000f0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -00000100 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -00000110 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000120 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000130 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000140 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000150 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000160 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000170 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000180 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000190 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -000001a0 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -000001b0 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001c0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001d0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001e0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001f0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -00000200 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -00000210 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000220 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000230 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000240 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000250 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000260 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000270 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000280 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000290 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -000002a0 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -000002b0 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002c0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002d0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002e0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002f0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -00000300 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -00000310 6e 38 50 29 6c 90 a7 bd d9 16 03 03 00 30 0d 00 |n8P)l........0..| -00000320 00 28 03 01 02 40 00 20 06 01 06 02 06 03 05 01 |.(...@. ........| -00000330 05 02 05 03 04 01 04 02 04 03 03 01 03 02 03 03 |................| -00000340 02 01 02 02 02 03 01 01 00 00 0e 00 00 00 |..............| ->>> Flow 3 (client to server) -00000000 16 03 03 01 fb 0b 00 01 f7 00 01 f4 00 01 f1 30 |...............0| -00000010 82 01 ed 30 82 01 58 a0 03 02 01 02 02 01 00 30 |...0..X........0| -00000020 0b 06 09 2a 86 48 86 f7 0d 01 01 05 30 26 31 10 |...*.H......0&1.| -00000030 30 0e 06 03 55 04 0a 13 07 41 63 6d 65 20 43 6f |0...U....Acme Co| -00000040 31 12 30 10 06 03 55 04 03 13 09 31 32 37 2e 30 |1.0...U....127.0| -00000050 2e 30 2e 31 30 1e 17 0d 31 31 31 32 30 38 30 37 |.0.10...11120807| -00000060 35 35 31 32 5a 17 0d 31 32 31 32 30 37 30 38 30 |5512Z..121207080| -00000070 30 31 32 5a 30 26 31 10 30 0e 06 03 55 04 0a 13 |012Z0&1.0...U...| -00000080 07 41 63 6d 65 20 43 6f 31 12 30 10 06 03 55 04 |.Acme Co1.0...U.| -00000090 03 13 09 31 32 37 2e 30 2e 30 2e 31 30 81 9c 30 |...127.0.0.10..0| -000000a0 0b 06 09 2a 86 48 86 f7 0d 01 01 01 03 81 8c 00 |...*.H..........| -000000b0 30 81 88 02 81 80 4e d0 7b 31 e3 82 64 d9 59 c0 |0.....N.{1..d.Y.| -000000c0 c2 87 a4 5e 1e 8b 73 33 c7 63 53 df 66 92 06 84 |...^..s3.cS.f...| -000000d0 f6 64 d5 8f e4 36 a7 1d 2b e8 b3 20 36 45 23 b5 |.d...6..+.. 6E#.| -000000e0 e3 95 ae ed e0 f5 20 9c 8d 95 df 7f 5a 12 ef 87 |...... .....Z...| -000000f0 e4 5b 68 e4 e9 0e 74 ec 04 8a 7f de 93 27 c4 01 |.[h...t......'..| -00000100 19 7a bd f2 dc 3d 14 ab d0 54 ca 21 0c d0 4d 6e |.z...=...T.!..Mn| -00000110 87 2e 5c c5 d2 bb 4d 4b 4f ce b6 2c f7 7e 88 ec |..\...MKO..,.~..| -00000120 7c d7 02 91 74 a6 1e 0c 1a da e3 4a 5a 2e de 13 ||...t......JZ...| -00000130 9c 4c 40 88 59 93 02 03 01 00 01 a3 32 30 30 30 |.L@.Y.......2000| -00000140 0e 06 03 55 1d 0f 01 01 ff 04 04 03 02 00 a0 30 |...U...........0| -00000150 0d 06 03 55 1d 0e 04 06 04 04 01 02 03 04 30 0f |...U..........0.| -00000160 06 03 55 1d 23 04 08 30 06 80 04 01 02 03 04 30 |..U.#..0.......0| -00000170 0b 06 09 2a 86 48 86 f7 0d 01 01 05 03 81 81 00 |...*.H..........| -00000180 36 1f b3 7a 0c 75 c9 6e 37 46 61 2b d5 bd c0 a7 |6..z.u.n7Fa+....| -00000190 4b cc 46 9a 81 58 7c 85 79 29 c8 c8 c6 67 dd 32 |K.F..X|.y)...g.2| -000001a0 56 45 2b 75 b6 e9 24 a9 50 9a be 1f 5a fa 1a 15 |VE+u..$.P...Z...| -000001b0 d9 cc 55 95 72 16 83 b9 c2 b6 8f fd 88 8c 38 84 |..U.r.........8.| -000001c0 1d ab 5d 92 31 13 4f fd 83 3b c6 9d f1 11 62 b6 |..].1.O..;....b.| -000001d0 8b ec ab 67 be c8 64 b0 11 50 46 58 17 6b 99 1c |...g..d..PFX.k..| -000001e0 d3 1d fc 06 f1 0e e5 96 a8 0c f9 78 20 b7 44 18 |...........x .D.| -000001f0 51 8d 10 7e 4f 94 67 df a3 4e 70 73 8e 90 91 85 |Q..~O.g..Nps....| -00000200 16 03 03 00 86 10 00 00 82 00 80 6d 51 f3 7f f9 |...........mQ...| -00000210 3e fb 75 82 41 36 83 e8 6a ee 2a 2e 25 90 67 4c |>.u.A6..j.*.%.gL| -00000220 8e 62 2f 30 81 17 e0 85 09 0c 2b b7 23 d7 b0 e2 |.b/0......+.#...| -00000230 1d f7 3b d7 f5 a1 27 b6 ee 24 b6 1b cc 5b ea 66 |..;...'..$...[.f| -00000240 0d 6a f4 e5 85 f9 da 43 b4 0e 86 85 e1 f5 aa be |.j.....C........| -00000250 c8 ce 39 4c 9c 86 00 08 c2 4b e2 c6 ec 2f f7 ce |..9L.....K.../..| -00000260 e6 bd 77 82 6f 23 b6 e0 bd a2 92 b7 3a ac e8 56 |..w.o#......:..V| -00000270 f1 af 54 5e 46 87 e9 3b 33 e7 b8 28 b7 d6 c8 90 |..T^F..;3..(....| -00000280 35 d4 1c 43 d1 30 6f 55 4e 0a 70 16 03 03 00 88 |5..C.0oUN.p.....| -00000290 0f 00 00 84 04 01 00 80 2a 1f ae 48 9f 86 16 dc |........*..H....| -000002a0 c2 55 1f 5f 95 81 ed 56 00 5d 35 46 e5 b6 57 d5 |.U._...V.]5F..W.| -000002b0 a6 3e 32 38 8b e2 c6 1c b9 b1 38 b2 da 66 45 ed |.>28......8..fE.| -000002c0 58 6a 7f 43 41 93 a5 09 da b9 04 ce 3f 13 8a 19 |Xj.CA.......?...| -000002d0 13 e9 2c 1f c5 e7 35 b4 2d ea 7c 81 90 33 c0 66 |..,...5.-.|..3.f| -000002e0 dc 41 8b 23 08 8f 69 d4 d6 a2 5f c1 bd 26 e6 2e |.A.#..i..._..&..| -000002f0 7f c8 7c a8 2d d4 08 95 ce 6e 58 54 04 a2 a6 63 |..|.-....nXT...c| -00000300 54 72 67 f2 7f 61 0a 6b 58 46 d4 88 95 38 37 f2 |Trg..a.kXF...87.| -00000310 93 95 48 56 14 a7 b9 7c 14 03 03 00 01 01 16 03 |..HV...|........| -00000320 03 00 24 64 bb 41 3a cb a2 2f 95 53 5c 2f f7 83 |..$d.A:../.S\/..| -00000330 a2 35 18 f6 d0 8d 6f e2 54 ed 2f 07 10 f4 36 e2 |.5....o.T./...6.| -00000340 3d e5 30 1d e3 63 01 |=.0..c.| ->>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 24 0a 22 b6 bc da |..........$."...| -00000010 34 38 53 8e 80 e2 25 7b 31 2f 70 8e 3a db e8 a3 |48S...%{1/p.:...| -00000020 70 0e 88 22 b4 a8 be d4 a3 e3 cc 13 94 ef 47 |p.."..........G| ->>> Flow 5 (client to server) -00000000 17 03 03 00 1a b4 9c b1 57 ea 01 03 fe 01 e7 1e |........W.......| -00000010 c4 a7 0f 25 14 99 00 4f 88 51 c1 98 6e 99 01 15 |...%...O.Q..n...| -00000020 03 03 00 16 2e c4 11 8b 1a fc 37 81 18 33 e4 9f |..........7..3..| -00000030 48 a3 29 e3 ad 9b 9b ec 9f 99 |H.).......| diff --git a/src/pkg/crypto/tls/testdata/Client-TLSv12-ECDHE-ECDSA-AES b/src/pkg/crypto/tls/testdata/Client-TLSv12-ECDHE-ECDSA-AES deleted file mode 100644 index 76445903b..000000000 --- a/src/pkg/crypto/tls/testdata/Client-TLSv12-ECDHE-ECDSA-AES +++ /dev/null @@ -1,89 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 75 01 00 00 71 03 03 00 00 00 00 00 |....u...q.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 1a c0 2f |.............../| -00000030 c0 2b c0 11 c0 07 c0 13 c0 09 c0 14 c0 0a 00 05 |.+..............| -00000040 00 2f 00 35 c0 12 00 0a 01 00 00 2e 00 05 00 05 |./.5............| -00000050 01 00 00 00 00 00 0a 00 08 00 06 00 17 00 18 00 |................| -00000060 19 00 0b 00 02 01 00 00 0d 00 0a 00 08 04 01 04 |................| -00000070 03 02 01 02 03 ff 01 00 01 00 |..........| ->>> Flow 2 (server to client) -00000000 16 03 03 00 59 02 00 00 55 03 03 53 04 f1 02 a0 |....Y...U..S....| -00000010 5f bd a4 8d 98 93 b8 da 08 86 9f b2 be 9a a4 91 |_...............| -00000020 2b 3c 1f 18 f0 75 7c a9 a8 a0 f7 20 4a 89 9a d2 |+<...u|.... J...| -00000030 34 3b d9 b1 c2 fd 61 bd 97 19 22 ce b9 d1 5b a7 |4;....a..."...[.| -00000040 83 80 9c 19 d0 f5 a0 aa 4c ac 06 20 c0 09 00 00 |........L.. ....| -00000050 0d ff 01 00 01 00 00 0b 00 04 03 00 01 02 16 03 |................| -00000060 03 02 0e 0b 00 02 0a 00 02 07 00 02 04 30 82 02 |.............0..| -00000070 00 30 82 01 62 02 09 00 b8 bf 2d 47 a0 d2 eb f4 |.0..b.....-G....| -00000080 30 09 06 07 2a 86 48 ce 3d 04 01 30 45 31 0b 30 |0...*.H.=..0E1.0| -00000090 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 03 |...U....AU1.0...| -000000a0 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 31 |U....Some-State1| -000000b0 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 6e |!0...U....Intern| -000000c0 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 4c |et Widgits Pty L| -000000d0 74 64 30 1e 17 0d 31 32 31 31 32 32 31 35 30 36 |td0...1211221506| -000000e0 33 32 5a 17 0d 32 32 31 31 32 30 31 35 30 36 33 |32Z..22112015063| -000000f0 32 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 41 |2Z0E1.0...U....A| -00000100 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d 65 |U1.0...U....Some| -00000110 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a 13 |-State1!0...U...| -00000120 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 74 |.Internet Widgit| -00000130 73 20 50 74 79 20 4c 74 64 30 81 9b 30 10 06 07 |s Pty Ltd0..0...| -00000140 2a 86 48 ce 3d 02 01 06 05 2b 81 04 00 23 03 81 |*.H.=....+...#..| -00000150 86 00 04 00 c4 a1 ed be 98 f9 0b 48 73 36 7e c3 |...........Hs6~.| -00000160 16 56 11 22 f2 3d 53 c3 3b 4d 21 3d cd 6b 75 e6 |.V.".=S.;M!=.ku.| -00000170 f6 b0 dc 9a df 26 c1 bc b2 87 f0 72 32 7c b3 64 |.....&.....r2|.d| -00000180 2f 1c 90 bc ea 68 23 10 7e fe e3 25 c0 48 3a 69 |/....h#.~..%.H:i| -00000190 e0 28 6d d3 37 00 ef 04 62 dd 0d a0 9c 70 62 83 |.(m.7...b....pb.| -000001a0 d8 81 d3 64 31 aa 9e 97 31 bd 96 b0 68 c0 9b 23 |...d1...1...h..#| -000001b0 de 76 64 3f 1a 5c 7f e9 12 0e 58 58 b6 5f 70 dd |.vd?.\....XX._p.| -000001c0 9b d8 ea d5 d7 f5 d5 cc b9 b6 9f 30 66 5b 66 9a |...........0f[f.| -000001d0 20 e2 27 e5 bf fe 3b 30 09 06 07 2a 86 48 ce 3d | .'...;0...*.H.=| -000001e0 04 01 03 81 8c 00 30 81 88 02 42 01 88 a2 4f eb |......0...B...O.| -000001f0 e2 45 c5 48 7d 1b ac f5 ed 98 9d ae 47 70 c0 5e |.E.H}.......Gp.^| -00000200 1b b6 2f bd f1 b6 4d b7 61 40 d3 11 a2 ce ee 0b |../...M.a@......| -00000210 7e 92 7e ff 76 9d c3 3b 7e a5 3f ce fa 10 e2 59 |~.~.v..;~.?....Y| -00000220 ec 47 2d 7c ac da 4e 97 0e 15 a0 6f d0 02 42 01 |.G-|..N....o..B.| -00000230 4d fc be 67 13 9c 2d 05 0e bd 3f a3 8c 25 c1 33 |M..g..-...?..%.3| -00000240 13 83 0d 94 06 bb d4 37 7a f6 ec 7a c9 86 2e dd |.......7z..z....| -00000250 d7 11 69 7f 85 7c 56 de fb 31 78 2b e4 c7 78 0d |..i..|V..1x+..x.| -00000260 ae cb be 9e 4e 36 24 31 7b 6a 0f 39 95 12 07 8f |....N6$1{j.9....| -00000270 2a 16 03 03 00 d7 0c 00 00 d3 03 00 17 41 04 3c |*............A.<| -00000280 8f 35 1e 47 5d 7b ad 13 0c e9 5c c0 97 c7 83 06 |.5.G]{....\.....| -00000290 49 0f 6c cf e5 4d 3b ed f7 1b c6 96 8d ba 54 35 |I.l..M;.......T5| -000002a0 7f df 35 e3 6e 28 e9 71 f2 24 b5 ab 17 2b 4b 2b |..5.n(.q.$...+K+| -000002b0 0c 8f 9f 48 89 73 8f 09 69 84 af 7f ec 43 7a 04 |...H.s..i....Cz.| -000002c0 03 00 8a 30 81 87 02 41 79 84 43 0c 78 fa 7e e2 |...0...Ay.C.x.~.| -000002d0 c5 51 c1 60 88 c4 4a 59 7d 02 fa dc 19 68 33 ed |.Q.`..JY}....h3.| -000002e0 19 ef a1 df ef 6b 21 a6 98 aa ba a9 13 70 91 0f |.....k!......p..| -000002f0 cc 6c 5c 1e 99 53 1b 42 51 6c 06 a7 3c c4 04 22 |.l\..S.BQl..<.."| -00000300 5d 0d c1 30 ab e3 ec b4 54 02 42 01 15 15 1a 6e |]..0....T.B....n| -00000310 6f f1 c6 b1 10 84 2c c8 04 de 2b 52 d5 b4 f7 c9 |o.....,...+R....| -00000320 4f 6d 0e 0e 26 45 1d 7a 28 59 2b 8b f6 92 3a 23 |Om..&E.z(Y+...:#| -00000330 7a 39 9c d5 4e cc 5d c5 45 92 9c d0 5f 33 12 e3 |z9..N.].E..._3..| -00000340 2b 29 39 52 bb 16 aa e1 72 9e b5 fe 99 16 03 03 |+)9R....r.......| -00000350 00 04 0e 00 00 00 |......| ->>> Flow 3 (client to server) -00000000 16 03 03 00 46 10 00 00 42 41 04 1e 18 37 ef 0d |....F...BA...7..| -00000010 19 51 88 35 75 71 b5 e5 54 5b 12 2e 8f 09 67 fd |.Q.5uq..T[....g.| -00000020 a7 24 20 3e b2 56 1c ce 97 28 5e f8 2b 2d 4f 9e |.$ >.V...(^.+-O.| -00000030 f1 07 9f 6c 4b 5b 83 56 e2 32 42 e9 58 b6 d7 49 |...lK[.V.2B.X..I| -00000040 a6 b5 68 1a 41 03 56 6b dc 5a 89 14 03 03 00 01 |..h.A.Vk.Z......| -00000050 01 16 03 03 00 40 00 00 00 00 00 00 00 00 00 00 |.....@..........| -00000060 00 00 00 00 00 00 20 a3 f8 5a e2 ea f3 09 19 3e |...... ..Z.....>| -00000070 4a 54 69 70 06 5b 17 35 0f ed e7 30 3b 6f eb a1 |JTip.[.5...0;o..| -00000080 cb 9c 35 81 10 2e 34 f7 12 a5 e4 63 20 b2 65 31 |..5...4....c .e1| -00000090 19 da 30 43 39 59 |..0C9Y| ->>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 40 8d 4d 31 07 df |..........@.M1..| -00000010 ab 41 f5 19 9c 1a 57 fc 33 ab 5f e6 bd 45 b9 fa |.A....W.3._..E..| -00000020 7f db c0 df 72 f2 3b ef aa d4 5e 34 e6 3d 44 7c |....r.;...^4.=D|| -00000030 12 05 c7 57 da 54 b1 e3 66 f0 0a ab cd 15 a5 bf |...W.T..f.......| -00000040 c5 c2 07 a9 d9 a7 2e 5e 29 da da |.......^)..| ->>> Flow 5 (client to server) -00000000 17 03 03 00 30 00 00 00 00 00 00 00 00 00 00 00 |....0...........| -00000010 00 00 00 00 00 dc 03 7b 29 2c 49 64 58 2d dc f7 |.......{),IdX-..| -00000020 26 a1 3b ec 2d e8 30 c4 6c a3 ff e2 bc b5 a4 a6 |&.;.-.0.l.......| -00000030 93 ce 14 bd da 15 03 03 00 30 00 00 00 00 00 00 |.........0......| -00000040 00 00 00 00 00 00 00 00 00 00 a6 77 10 30 15 eb |...........w.0..| -00000050 ed cf 73 5b 74 5d 09 52 4a 5b e2 f0 e4 67 f8 7a |..s[t].RJ[...g.z| -00000060 5e 5e fc ba 7f 80 0a d2 f4 fb |^^........| diff --git a/src/pkg/crypto/tls/testdata/Client-TLSv12-ECDHE-ECDSA-AES-GCM b/src/pkg/crypto/tls/testdata/Client-TLSv12-ECDHE-ECDSA-AES-GCM deleted file mode 100644 index fb5af17f0..000000000 --- a/src/pkg/crypto/tls/testdata/Client-TLSv12-ECDHE-ECDSA-AES-GCM +++ /dev/null @@ -1,84 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 75 01 00 00 71 03 03 00 00 00 00 00 |....u...q.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 1a c0 2f |.............../| -00000030 c0 2b c0 11 c0 07 c0 13 c0 09 c0 14 c0 0a 00 05 |.+..............| -00000040 00 2f 00 35 c0 12 00 0a 01 00 00 2e 00 05 00 05 |./.5............| -00000050 01 00 00 00 00 00 0a 00 08 00 06 00 17 00 18 00 |................| -00000060 19 00 0b 00 02 01 00 00 0d 00 0a 00 08 04 01 04 |................| -00000070 03 02 01 02 03 ff 01 00 01 00 |..........| ->>> Flow 2 (server to client) -00000000 16 03 03 00 59 02 00 00 55 03 03 53 04 f1 02 48 |....Y...U..S...H| -00000010 03 36 01 05 56 6f f0 54 d2 c3 d3 41 c2 e2 69 7b |.6..Vo.T...A..i{| -00000020 50 f8 03 ef 3f 5d 7c e6 9c cb fe 20 82 a0 81 fd |P...?]|.... ....| -00000030 72 4b b8 e6 29 76 3b 0f 1d 0a b7 82 9d 0b cf a0 |rK..)v;.........| -00000040 65 b1 56 53 c9 d5 58 7b f0 b6 2d cf c0 2b 00 00 |e.VS..X{..-..+..| -00000050 0d ff 01 00 01 00 00 0b 00 04 03 00 01 02 16 03 |................| -00000060 03 02 0e 0b 00 02 0a 00 02 07 00 02 04 30 82 02 |.............0..| -00000070 00 30 82 01 62 02 09 00 b8 bf 2d 47 a0 d2 eb f4 |.0..b.....-G....| -00000080 30 09 06 07 2a 86 48 ce 3d 04 01 30 45 31 0b 30 |0...*.H.=..0E1.0| -00000090 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 03 |...U....AU1.0...| -000000a0 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 31 |U....Some-State1| -000000b0 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 6e |!0...U....Intern| -000000c0 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 4c |et Widgits Pty L| -000000d0 74 64 30 1e 17 0d 31 32 31 31 32 32 31 35 30 36 |td0...1211221506| -000000e0 33 32 5a 17 0d 32 32 31 31 32 30 31 35 30 36 33 |32Z..22112015063| -000000f0 32 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 41 |2Z0E1.0...U....A| -00000100 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d 65 |U1.0...U....Some| -00000110 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a 13 |-State1!0...U...| -00000120 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 74 |.Internet Widgit| -00000130 73 20 50 74 79 20 4c 74 64 30 81 9b 30 10 06 07 |s Pty Ltd0..0...| -00000140 2a 86 48 ce 3d 02 01 06 05 2b 81 04 00 23 03 81 |*.H.=....+...#..| -00000150 86 00 04 00 c4 a1 ed be 98 f9 0b 48 73 36 7e c3 |...........Hs6~.| -00000160 16 56 11 22 f2 3d 53 c3 3b 4d 21 3d cd 6b 75 e6 |.V.".=S.;M!=.ku.| -00000170 f6 b0 dc 9a df 26 c1 bc b2 87 f0 72 32 7c b3 64 |.....&.....r2|.d| -00000180 2f 1c 90 bc ea 68 23 10 7e fe e3 25 c0 48 3a 69 |/....h#.~..%.H:i| -00000190 e0 28 6d d3 37 00 ef 04 62 dd 0d a0 9c 70 62 83 |.(m.7...b....pb.| -000001a0 d8 81 d3 64 31 aa 9e 97 31 bd 96 b0 68 c0 9b 23 |...d1...1...h..#| -000001b0 de 76 64 3f 1a 5c 7f e9 12 0e 58 58 b6 5f 70 dd |.vd?.\....XX._p.| -000001c0 9b d8 ea d5 d7 f5 d5 cc b9 b6 9f 30 66 5b 66 9a |...........0f[f.| -000001d0 20 e2 27 e5 bf fe 3b 30 09 06 07 2a 86 48 ce 3d | .'...;0...*.H.=| -000001e0 04 01 03 81 8c 00 30 81 88 02 42 01 88 a2 4f eb |......0...B...O.| -000001f0 e2 45 c5 48 7d 1b ac f5 ed 98 9d ae 47 70 c0 5e |.E.H}.......Gp.^| -00000200 1b b6 2f bd f1 b6 4d b7 61 40 d3 11 a2 ce ee 0b |../...M.a@......| -00000210 7e 92 7e ff 76 9d c3 3b 7e a5 3f ce fa 10 e2 59 |~.~.v..;~.?....Y| -00000220 ec 47 2d 7c ac da 4e 97 0e 15 a0 6f d0 02 42 01 |.G-|..N....o..B.| -00000230 4d fc be 67 13 9c 2d 05 0e bd 3f a3 8c 25 c1 33 |M..g..-...?..%.3| -00000240 13 83 0d 94 06 bb d4 37 7a f6 ec 7a c9 86 2e dd |.......7z..z....| -00000250 d7 11 69 7f 85 7c 56 de fb 31 78 2b e4 c7 78 0d |..i..|V..1x+..x.| -00000260 ae cb be 9e 4e 36 24 31 7b 6a 0f 39 95 12 07 8f |....N6$1{j.9....| -00000270 2a 16 03 03 00 d7 0c 00 00 d3 03 00 17 41 04 86 |*............A..| -00000280 36 b4 78 76 87 70 ed ae 0d 34 70 3d 16 e5 a4 db |6.xv.p...4p=....| -00000290 ae 28 58 4c 01 5a 56 73 a7 0d 34 59 a7 04 75 69 |.(XL.ZVs..4Y..ui| -000002a0 f2 55 24 40 b0 33 c6 93 ff ae e0 14 f5 4b ce a8 |.U$@.3.......K..| -000002b0 e2 e6 9a 67 1d 66 fb 8f fd 56 59 e7 73 f2 2c 04 |...g.f...VY.s.,.| -000002c0 03 00 8a 30 81 87 02 41 73 ab a8 3c 64 17 69 9f |...0...As..>> Flow 3 (client to server) -00000000 16 03 03 00 46 10 00 00 42 41 04 1e 18 37 ef 0d |....F...BA...7..| -00000010 19 51 88 35 75 71 b5 e5 54 5b 12 2e 8f 09 67 fd |.Q.5uq..T[....g.| -00000020 a7 24 20 3e b2 56 1c ce 97 28 5e f8 2b 2d 4f 9e |.$ >.V...(^.+-O.| -00000030 f1 07 9f 6c 4b 5b 83 56 e2 32 42 e9 58 b6 d7 49 |...lK[.V.2B.X..I| -00000040 a6 b5 68 1a 41 03 56 6b dc 5a 89 14 03 03 00 01 |..h.A.Vk.Z......| -00000050 01 16 03 03 00 28 00 00 00 00 00 00 00 00 87 7a |.....(.........z| -00000060 82 d7 46 25 1d a6 bb c2 a8 a8 4e a5 d1 f8 02 db |..F%......N.....| -00000070 33 33 ca 78 b6 d3 bd 77 8a 33 23 a7 95 fb |33.x...w.3#...| ->>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 28 ce a1 9d 01 c0 |..........(.....| -00000010 31 e5 d5 57 16 e1 a6 b3 8b 25 58 0f fa 2a de 3e |1..W.....%X..*.>| -00000020 0c d9 06 11 a6 b0 d7 b0 33 ad 31 73 5b 26 b4 d2 |........3.1s[&..| -00000030 12 56 c8 |.V.| ->>> Flow 5 (client to server) -00000000 17 03 03 00 1e 00 00 00 00 00 00 00 01 d5 04 4c |...............L| -00000010 7b 35 b4 d7 90 ae fe 00 d2 f2 4b 76 f1 36 5e 24 |{5........Kv.6^$| -00000020 4a aa 94 15 03 03 00 1a 00 00 00 00 00 00 00 02 |J...............| -00000030 d3 1c 41 37 ab f6 17 79 f0 01 a4 19 a5 75 7a 8e |..A7...y.....uz.| -00000040 a3 b2 |..| diff --git a/src/pkg/crypto/tls/testdata/Client-TLSv12-ECDHE-RSA-AES b/src/pkg/crypto/tls/testdata/Client-TLSv12-ECDHE-RSA-AES deleted file mode 100644 index 5336bbbad..000000000 --- a/src/pkg/crypto/tls/testdata/Client-TLSv12-ECDHE-RSA-AES +++ /dev/null @@ -1,99 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 75 01 00 00 71 03 03 00 00 00 00 00 |....u...q.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 1a c0 2f |.............../| -00000030 c0 2b c0 11 c0 07 c0 13 c0 09 c0 14 c0 0a 00 05 |.+..............| -00000040 00 2f 00 35 c0 12 00 0a 01 00 00 2e 00 05 00 05 |./.5............| -00000050 01 00 00 00 00 00 0a 00 08 00 06 00 17 00 18 00 |................| -00000060 19 00 0b 00 02 01 00 00 0d 00 0a 00 08 04 01 04 |................| -00000070 03 02 01 02 03 ff 01 00 01 00 |..........| ->>> Flow 2 (server to client) -00000000 16 03 03 00 59 02 00 00 55 03 03 53 04 f1 02 41 |....Y...U..S...A| -00000010 95 cc 56 30 65 46 24 75 d5 9e 3c a7 5b 6c 99 fe |..V0eF$u..<.[l..| -00000020 86 35 23 42 3a 8f 4d 4c b9 98 7d 20 a7 46 43 72 |.5#B:.ML..} .FCr| -00000030 66 bb b6 ad ff ad cf 63 37 fe 6b b4 78 94 08 49 |f......c7.k.x..I| -00000040 54 06 ed f4 85 73 38 4a c6 fe b6 98 c0 13 00 00 |T....s8J........| -00000050 0d ff 01 00 01 00 00 0b 00 04 03 00 01 02 16 03 |................| -00000060 03 02 be 0b 00 02 ba 00 02 b7 00 02 b4 30 82 02 |.............0..| -00000070 b0 30 82 02 19 a0 03 02 01 02 02 09 00 85 b0 bb |.0..............| -00000080 a4 8a 7f b8 ca 30 0d 06 09 2a 86 48 86 f7 0d 01 |.....0...*.H....| -00000090 01 05 05 00 30 45 31 0b 30 09 06 03 55 04 06 13 |....0E1.0...U...| -000000a0 02 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f |.AU1.0...U....So| -000000b0 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 |me-State1!0...U.| -000000c0 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 |...Internet Widg| -000000d0 69 74 73 20 50 74 79 20 4c 74 64 30 1e 17 0d 31 |its Pty Ltd0...1| -000000e0 30 30 34 32 34 30 39 30 39 33 38 5a 17 0d 31 31 |00424090938Z..11| -000000f0 30 34 32 34 30 39 30 39 33 38 5a 30 45 31 0b 30 |0424090938Z0E1.0| -00000100 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 03 |...U....AU1.0...| -00000110 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 31 |U....Some-State1| -00000120 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 6e |!0...U....Intern| -00000130 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 4c |et Widgits Pty L| -00000140 74 64 30 81 9f 30 0d 06 09 2a 86 48 86 f7 0d 01 |td0..0...*.H....| -00000150 01 01 05 00 03 81 8d 00 30 81 89 02 81 81 00 bb |........0.......| -00000160 79 d6 f5 17 b5 e5 bf 46 10 d0 dc 69 be e6 2b 07 |y......F...i..+.| -00000170 43 5a d0 03 2d 8a 7a 43 85 b7 14 52 e7 a5 65 4c |CZ..-.zC...R..eL| -00000180 2c 78 b8 23 8c b5 b4 82 e5 de 1f 95 3b 7e 62 a5 |,x.#........;~b.| -00000190 2c a5 33 d6 fe 12 5c 7a 56 fc f5 06 bf fa 58 7b |,.3...\zV.....X{| -000001a0 26 3f b5 cd 04 d3 d0 c9 21 96 4a c7 f4 54 9f 5a |&?......!.J..T.Z| -000001b0 bf ef 42 71 00 fe 18 99 07 7f 7e 88 7d 7d f1 04 |..Bq......~.}}..| -000001c0 39 c4 a2 2e db 51 c9 7c e3 c0 4c 3b 32 66 01 cf |9....Q.|..L;2f..| -000001d0 af b1 1d b8 71 9a 1d db db 89 6b ae da 2d 79 02 |....q.....k..-y.| -000001e0 03 01 00 01 a3 81 a7 30 81 a4 30 1d 06 03 55 1d |.......0..0...U.| -000001f0 0e 04 16 04 14 b1 ad e2 85 5a cf cb 28 db 69 ce |.........Z..(.i.| -00000200 23 69 de d3 26 8e 18 88 39 30 75 06 03 55 1d 23 |#i..&...90u..U.#| -00000210 04 6e 30 6c 80 14 b1 ad e2 85 5a cf cb 28 db 69 |.n0l......Z..(.i| -00000220 ce 23 69 de d3 26 8e 18 88 39 a1 49 a4 47 30 45 |.#i..&...9.I.G0E| -00000230 31 0b 30 09 06 03 55 04 06 13 02 41 55 31 13 30 |1.0...U....AU1.0| -00000240 11 06 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 |...U....Some-Sta| -00000250 74 65 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 |te1!0...U....Int| -00000260 65 72 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 |ernet Widgits Pt| -00000270 79 20 4c 74 64 82 09 00 85 b0 bb a4 8a 7f b8 ca |y Ltd...........| -00000280 30 0c 06 03 55 1d 13 04 05 30 03 01 01 ff 30 0d |0...U....0....0.| -00000290 06 09 2a 86 48 86 f7 0d 01 01 05 05 00 03 81 81 |..*.H...........| -000002a0 00 08 6c 45 24 c7 6b b1 59 ab 0c 52 cc f2 b0 14 |..lE$.k.Y..R....| -000002b0 d7 87 9d 7a 64 75 b5 5a 95 66 e4 c5 2b 8e ae 12 |...zdu.Z.f..+...| -000002c0 66 1f eb 4f 38 b3 6e 60 d3 92 fd f7 41 08 b5 25 |f..O8.n`....A..%| -000002d0 13 b1 18 7a 24 fb 30 1d ba ed 98 b9 17 ec e7 d7 |...z$.0.........| -000002e0 31 59 db 95 d3 1d 78 ea 50 56 5c d5 82 5a 2d 5a |1Y....x.PV\..Z-Z| -000002f0 5f 33 c4 b6 d8 c9 75 90 96 8c 0f 52 98 b5 cd 98 |_3....u....R....| -00000300 1f 89 20 5f f2 a0 1c a3 1b 96 94 dd a9 fd 57 e9 |.. _..........W.| -00000310 70 e8 26 6d 71 99 9b 26 6e 38 50 29 6c 90 a7 bd |p.&mq..&n8P)l...| -00000320 d9 16 03 03 00 cd 0c 00 00 c9 03 00 17 41 04 48 |.............A.H| -00000330 68 d8 8a 10 b4 bf eb 8d d1 98 b0 a6 f4 47 5d 91 |h............G].| -00000340 61 da 50 d9 85 7b 5d 90 02 2c 38 c9 af 81 d3 55 |a.P..{]..,8....U| -00000350 07 62 b1 62 58 7f 39 94 d7 91 96 a8 1f 47 60 a5 |.b.bX.9......G`.| -00000360 c0 04 f2 fb cb 15 75 a6 16 3f 94 53 7c ff dd 04 |......u..?.S|...| -00000370 01 00 80 b9 82 fa 0b f8 8c 94 2c 6e 05 81 7d 80 |..........,n..}.| -00000380 5d 9a 77 78 af c8 33 5d 89 7e 2e 3c e5 72 66 a8 |].wx..3].~.<.rf.| -00000390 f1 5c 02 04 02 70 76 7b 45 ff 0d 29 a0 cb 0d db |.\...pv{E..)....| -000003a0 7a 4c c4 13 19 cd 47 b2 f1 c9 43 4f 95 d2 f1 c6 |zL....G...CO....| -000003b0 bc ae 31 4a 9d de 80 b2 a4 b7 b6 dd 8c 03 3e 2a |..1J..........>*| -000003c0 46 5e d1 e7 5b c5 9e 06 58 f3 55 b2 77 09 f3 98 |F^..[...X.U.w...| -000003d0 d5 7f 5a 74 64 7e 48 22 8f 7d a8 68 b6 1d 90 df |..Ztd~H".}.h....| -000003e0 2c 91 d7 c5 07 3d d1 6f e9 c1 91 03 3c 23 5a 56 |,....=.o....<#ZV| -000003f0 3b b2 c2 16 03 03 00 04 0e 00 00 00 |;...........| ->>> Flow 3 (client to server) -00000000 16 03 03 00 46 10 00 00 42 41 04 1e 18 37 ef 0d |....F...BA...7..| -00000010 19 51 88 35 75 71 b5 e5 54 5b 12 2e 8f 09 67 fd |.Q.5uq..T[....g.| -00000020 a7 24 20 3e b2 56 1c ce 97 28 5e f8 2b 2d 4f 9e |.$ >.V...(^.+-O.| -00000030 f1 07 9f 6c 4b 5b 83 56 e2 32 42 e9 58 b6 d7 49 |...lK[.V.2B.X..I| -00000040 a6 b5 68 1a 41 03 56 6b dc 5a 89 14 03 03 00 01 |..h.A.Vk.Z......| -00000050 01 16 03 03 00 40 00 00 00 00 00 00 00 00 00 00 |.....@..........| -00000060 00 00 00 00 00 00 59 e6 92 05 27 ec 09 2c b0 a5 |......Y...'..,..| -00000070 2a fb 7e f1 03 53 16 63 68 a1 86 13 bb da 98 27 |*.~..S.ch......'| -00000080 6d 42 08 35 6a ec 58 61 2a 4d 44 ec ae c5 b9 d2 |mB.5j.Xa*MD.....| -00000090 76 57 1f 75 9f 8d |vW.u..| ->>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 40 6e 03 d0 e6 98 |..........@n....| -00000010 1f f5 39 7b 06 9f 95 f0 7a 88 35 7c 55 db c3 2f |..9{....z.5|U../| -00000020 00 ef 5b d3 62 87 a2 94 da 2f f6 4a 89 c9 a8 3d |..[.b..../.J...=| -00000030 3a 92 db 77 35 92 01 4b f5 c5 6b 95 09 9f cd 79 |:..w5..K..k....y| -00000040 3c af 37 5b 27 bf 93 3e 04 55 71 |<.7['..>.Uq| ->>> Flow 5 (client to server) -00000000 17 03 03 00 30 00 00 00 00 00 00 00 00 00 00 00 |....0...........| -00000010 00 00 00 00 00 bc c9 d0 8e 80 14 de 32 18 49 e8 |............2.I.| -00000020 20 dc 5e 6c e4 6d 14 00 df 51 71 fb 86 95 16 4c | .^l.m...Qq....L| -00000030 04 8e 71 e1 48 15 03 03 00 30 00 00 00 00 00 00 |..q.H....0......| -00000040 00 00 00 00 00 00 00 00 00 00 b7 6d 30 72 61 53 |...........m0raS| -00000050 d8 0a d4 1d ae e5 d4 22 46 c9 d5 4e 4a 86 f5 ac |......."F..NJ...| -00000060 72 98 c6 db 38 29 97 2c 84 0b |r...8).,..| diff --git a/src/pkg/crypto/tls/testdata/Client-TLSv12-RSA-RC4 b/src/pkg/crypto/tls/testdata/Client-TLSv12-RSA-RC4 deleted file mode 100644 index 0377f052a..000000000 --- a/src/pkg/crypto/tls/testdata/Client-TLSv12-RSA-RC4 +++ /dev/null @@ -1,83 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 75 01 00 00 71 03 03 00 00 00 00 00 |....u...q.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 1a c0 2f |.............../| -00000030 c0 2b c0 11 c0 07 c0 13 c0 09 c0 14 c0 0a 00 05 |.+..............| -00000040 00 2f 00 35 c0 12 00 0a 01 00 00 2e 00 05 00 05 |./.5............| -00000050 01 00 00 00 00 00 0a 00 08 00 06 00 17 00 18 00 |................| -00000060 19 00 0b 00 02 01 00 00 0d 00 0a 00 08 04 01 04 |................| -00000070 03 02 01 02 03 ff 01 00 01 00 |..........| ->>> Flow 2 (server to client) -00000000 16 03 03 00 51 02 00 00 4d 03 03 53 04 f1 02 9d |....Q...M..S....| -00000010 2e 4e d9 17 4a 35 fa 9d 94 f6 45 0a f6 6b 5d 1c |.N..J5....E..k].| -00000020 1e 15 19 8d 6d 94 cc 90 d9 39 94 20 8b 4b de 76 |....m....9. .K.v| -00000030 d5 64 5d b7 19 df e7 eb 7e a0 22 c4 09 38 a0 12 |.d].....~."..8..| -00000040 d5 59 10 c8 31 06 dc fc e4 9d d1 80 00 05 00 00 |.Y..1...........| -00000050 05 ff 01 00 01 00 16 03 03 02 be 0b 00 02 ba 00 |................| -00000060 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000070 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000080 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000090 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -000000a0 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -000000b0 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000c0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000d0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000e0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000f0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -00000100 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -00000110 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000120 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000130 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000140 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000150 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000160 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000170 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000180 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000190 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -000001a0 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -000001b0 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001c0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001d0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001e0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001f0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -00000200 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -00000210 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000220 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000230 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000240 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000250 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000260 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000270 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000280 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000290 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -000002a0 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -000002b0 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002c0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002d0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002e0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002f0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -00000300 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -00000310 6e 38 50 29 6c 90 a7 bd d9 16 03 03 00 04 0e 00 |n8P)l...........| -00000320 00 00 |..| ->>> Flow 3 (client to server) -00000000 16 03 03 00 86 10 00 00 82 00 80 6d 51 f3 7f f9 |...........mQ...| -00000010 3e fb 75 82 41 36 83 e8 6a ee 2a 2e 25 90 67 4c |>.u.A6..j.*.%.gL| -00000020 8e 62 2f 30 81 17 e0 85 09 0c 2b b7 23 d7 b0 e2 |.b/0......+.#...| -00000030 1d f7 3b d7 f5 a1 27 b6 ee 24 b6 1b cc 5b ea 66 |..;...'..$...[.f| -00000040 0d 6a f4 e5 85 f9 da 43 b4 0e 86 85 e1 f5 aa be |.j.....C........| -00000050 c8 ce 39 4c 9c 86 00 08 c2 4b e2 c6 ec 2f f7 ce |..9L.....K.../..| -00000060 e6 bd 77 82 6f 23 b6 e0 bd a2 92 b7 3a ac e8 56 |..w.o#......:..V| -00000070 f1 af 54 5e 46 87 e9 3b 33 e7 b8 28 b7 d6 c8 90 |..T^F..;3..(....| -00000080 35 d4 1c 43 d1 30 6f 55 4e 0a 70 14 03 03 00 01 |5..C.0oUN.p.....| -00000090 01 16 03 03 00 24 37 14 b2 97 7b b5 f0 9a 38 05 |.....$7...{...8.| -000000a0 22 35 69 9c 95 2f 86 4b 37 98 22 db 4e 9a 46 9c |"5i../.K7.".N.F.| -000000b0 b9 81 74 72 58 18 53 0c 5c 3c |..trX.S.\<| ->>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 24 3c b3 e7 77 5a |..........$<..wZ| -00000010 7c 36 5a 74 74 26 8d 5b 5a 09 96 60 e8 24 45 2f ||6Ztt&.[Z..`.$E/| -00000020 c2 39 14 5e db 58 12 49 ad a8 b6 ea ef 58 16 |.9.^.X.I.....X.| ->>> Flow 5 (client to server) -00000000 17 03 03 00 1a 6d 29 d7 ba 2f 85 02 b6 f0 82 64 |.....m)../.....d| -00000010 6c 55 ae ab f6 fd 14 ff b8 38 f0 f8 a6 ea cc 15 |lU.......8......| -00000020 03 03 00 16 10 c5 d9 41 7b e2 89 67 dc 29 8e f8 |.......A{..g.)..| -00000030 b5 ab 32 91 44 2c 27 84 49 f7 |..2.D,'.I.| diff --git a/src/pkg/crypto/tls/testdata/Server-SSLv3-RSA-3DES b/src/pkg/crypto/tls/testdata/Server-SSLv3-RSA-3DES deleted file mode 100644 index a6c7a4196..000000000 --- a/src/pkg/crypto/tls/testdata/Server-SSLv3-RSA-3DES +++ /dev/null @@ -1,83 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 00 00 2f 01 00 00 2b 03 00 52 cc 57 59 d8 |..../...+..R.WY.| -00000010 86 d6 07 ae e0 8d 63 b7 1e cb aa c6 67 32 c8 dd |......c.....g2..| -00000020 68 03 d8 3d 37 18 72 c3 c0 f1 9d 00 00 04 00 0a |h..=7.r.........| -00000030 00 ff 01 00 |....| ->>> Flow 2 (server to client) -00000000 16 03 00 00 31 02 00 00 2d 03 00 00 00 00 00 00 |....1...-.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 0a 00 00 |................| -00000030 05 ff 01 00 01 00 16 03 00 02 be 0b 00 02 ba 00 |................| -00000040 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000050 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000060 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000070 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -00000080 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -00000090 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000a0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000b0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000c0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000d0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -000000e0 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -000000f0 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000100 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000110 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000120 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000130 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000140 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000150 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000160 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000170 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -00000180 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -00000190 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001a0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001b0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001c0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001d0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -000001e0 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -000001f0 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000200 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000210 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000220 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000230 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000240 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000250 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000260 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000270 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -00000280 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -00000290 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002a0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002b0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002c0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002d0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -000002e0 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -000002f0 6e 38 50 29 6c 90 a7 bd d9 16 03 00 00 04 0e 00 |n8P)l...........| -00000300 00 00 |..| ->>> Flow 3 (client to server) -00000000 16 03 00 00 84 10 00 00 80 75 e0 c9 76 d6 e9 34 |.........u..v..4| -00000010 1d e3 31 9e db 3b 03 41 93 e8 db 73 7c e9 3f 6a |..1..;.A...s|.?j| -00000020 d8 2a 7b 25 83 4f 45 de 3f 78 3f b6 53 a7 b4 6c |.*{%.OE.?x?.S..l| -00000030 e3 87 c4 c3 70 55 71 79 55 dc 74 98 84 21 19 13 |....pUqyU.t..!..| -00000040 be d5 8e 0a ff 2f 9f 7a 6b d4 6c ef 78 d1 cb 65 |...../.zk.l.x..e| -00000050 32 4c 0c c5 29 b9 60 94 c6 79 56 a2 aa 2d d9 ad |2L..).`..yV..-..| -00000060 51 2c 54 1b 28 23 33 54 cd 48 cb 80 13 45 3d 4a |Q,T.(#3T.H...E=J| -00000070 8e 2f f2 da bd 68 3e 1b eb 73 f9 2d 35 6b b1 40 |./...h>..s.-5k.@| -00000080 2e 6d 9d 1c e9 c1 02 80 37 14 03 00 00 01 01 16 |.m......7.......| -00000090 03 00 00 40 f7 c3 dd a4 64 3d 81 24 de a2 81 7d |...@....d=.$...}| -000000a0 e4 df 78 46 e7 ba 93 6c 36 43 05 96 fc 75 ef ec |..xF...l6C...u..| -000000b0 a5 46 6d 47 a5 be 74 ad 15 93 d9 87 4f 1d e2 b3 |.FmG..t.....O...| -000000c0 03 ff 2e 89 6e 50 f4 d6 a6 e2 b3 54 cb 74 07 f7 |....nP.....T.t..| -000000d0 ca 1b 8c 0a |....| ->>> Flow 4 (server to client) -00000000 14 03 00 00 01 01 16 03 00 00 40 6d 3d d8 d5 cf |..........@m=...| -00000010 05 7d 98 8c 28 28 e2 43 ab ad 4a fa ae bf ec c3 |.}..((.C..J.....| -00000020 9c 0a 13 4d 28 a4 45 c4 b9 f2 bc c5 12 a2 68 91 |...M(.E.......h.| -00000030 77 fa 72 f8 9e 4e b7 1f b4 02 02 e3 5d 57 b0 8b |w.r..N......]W..| -00000040 d8 90 0c 9d e6 df 5b 90 92 a1 0d 17 03 00 00 18 |......[.........| -00000050 91 48 8a e1 d6 bf 79 1c d5 0a 70 d5 94 20 25 78 |.H....y...p.. %x| -00000060 d8 84 c8 6e 54 f0 99 01 17 03 00 00 28 74 19 90 |...nT.......(t..| -00000070 41 44 53 27 bb fb 1f fd 71 34 20 61 a0 eb a4 7c |ADS'....q4 a...|| -00000080 fe 36 f8 4b d7 b0 27 d3 b9 36 e1 67 af 2d 0e 23 |.6.K..'..6.g.-.#| -00000090 2b 76 a7 2f c3 15 03 00 00 18 db fc e9 fd 87 5f |+v./..........._| -000000a0 92 a8 3d 4b 35 f5 c6 48 2c b4 42 50 c3 81 28 f0 |..=K5..H,.BP..(.| -000000b0 2b 41 |+A| diff --git a/src/pkg/crypto/tls/testdata/Server-SSLv3-RSA-AES b/src/pkg/crypto/tls/testdata/Server-SSLv3-RSA-AES deleted file mode 100644 index 4885b267d..000000000 --- a/src/pkg/crypto/tls/testdata/Server-SSLv3-RSA-AES +++ /dev/null @@ -1,84 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 00 00 2f 01 00 00 2b 03 00 52 cc 57 59 30 |..../...+..R.WY0| -00000010 e1 ee 8c 60 5b 40 dd 95 bd b4 84 87 2f 01 15 e7 |...`[@....../...| -00000020 50 88 4c 82 6b 6d 93 8a 57 d0 27 00 00 04 00 2f |P.L.km..W.'..../| -00000030 00 ff 01 00 |....| ->>> Flow 2 (server to client) -00000000 16 03 00 00 31 02 00 00 2d 03 00 00 00 00 00 00 |....1...-.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 2f 00 00 |............./..| -00000030 05 ff 01 00 01 00 16 03 00 02 be 0b 00 02 ba 00 |................| -00000040 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000050 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000060 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000070 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -00000080 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -00000090 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000a0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000b0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000c0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000d0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -000000e0 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -000000f0 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000100 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000110 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000120 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000130 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000140 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000150 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000160 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000170 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -00000180 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -00000190 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001a0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001b0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001c0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001d0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -000001e0 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -000001f0 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000200 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000210 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000220 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000230 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000240 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000250 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000260 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000270 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -00000280 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -00000290 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002a0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002b0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002c0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002d0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -000002e0 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -000002f0 6e 38 50 29 6c 90 a7 bd d9 16 03 00 00 04 0e 00 |n8P)l...........| -00000300 00 00 |..| ->>> Flow 3 (client to server) -00000000 16 03 00 00 84 10 00 00 80 74 50 05 6f f5 83 c9 |.........tP.o...| -00000010 f5 0c 5a 65 c7 4e c6 f3 87 96 d7 5d 3e 88 27 32 |..Ze.N.....]>.'2| -00000020 89 12 ba ec db ef c0 85 70 84 ed b6 83 03 8f 44 |........p......D| -00000030 f5 6f fa fa d0 1f 95 30 d1 ae a7 71 cf ee e9 b1 |.o.....0...q....| -00000040 80 7b 34 a9 ea 1b 5e e5 71 40 3f e8 7d 30 d1 8b |.{4...^.q@?.}0..| -00000050 11 f1 68 1f c8 25 f0 77 c5 af b3 92 6e d9 81 cc |..h..%.w....n...| -00000060 f8 fd 82 95 cc 1f 4a b1 05 15 7a b3 a1 22 33 09 |......J...z.."3.| -00000070 e7 a5 c2 89 7f 03 e0 91 b6 61 a3 a0 4e 17 0d 7a |.........a..N..z| -00000080 13 01 c4 b6 50 c7 d9 81 15 14 03 00 00 01 01 16 |....P...........| -00000090 03 00 00 40 56 da 56 ab e6 26 98 58 53 1f 36 b5 |...@V.V..&.XS.6.| -000000a0 03 14 bd 42 29 ee 9c 7c e4 48 26 82 68 ae fd fe |...B)..|.H&.h...| -000000b0 5e a4 43 22 75 95 7b c8 77 88 fd d6 d4 9b c9 b5 |^.C"u.{.w.......| -000000c0 ee 3e a6 e8 c5 04 90 63 3f ac be 56 67 da 30 d4 |.>.....c?..Vg.0.| -000000d0 64 fb a8 a0 |d...| ->>> Flow 4 (server to client) -00000000 14 03 00 00 01 01 16 03 00 00 40 96 af fb 79 96 |..........@...y.| -00000010 92 97 2d d0 67 46 1e 08 b5 35 65 ef dc bc 8e 57 |..-.gF...5e....W| -00000020 53 b7 36 58 74 d7 88 b1 55 fc eb fa 2e f3 17 b7 |S.6Xt...U.......| -00000030 62 58 a0 9d 99 e1 85 d4 33 e0 b4 1f 1d 94 f2 88 |bX......3.......| -00000040 d5 9a 34 5b 74 cd d2 ff 87 bd 52 17 03 00 00 20 |..4[t.....R.... | -00000050 c6 61 c2 28 ac d2 0c 08 7f f1 c2 62 af 37 7e 78 |.a.(.......b.7~x| -00000060 e8 e2 a1 54 f2 3a 80 97 f8 47 64 f2 cd 94 dd 0b |...T.:...Gd.....| -00000070 17 03 00 00 30 b8 40 8f a3 18 ff 03 84 d4 1c 28 |....0.@........(| -00000080 82 ce d8 9a 81 3a dd 23 7c 65 d8 ca f7 f1 46 1b |.....:.#|e....F.| -00000090 70 f0 d7 d9 54 a7 71 e6 4d d4 25 61 5a e4 30 d3 |p...T.q.M.%aZ.0.| -000000a0 4a 42 ae 26 a5 15 03 00 00 20 c4 e8 ed 40 57 00 |JB.&..... ...@W.| -000000b0 dc a5 0e 82 90 47 92 08 dd 7e 50 6b 30 66 5e 90 |.....G...~Pk0f^.| -000000c0 73 7c 81 93 8d 24 b1 06 e7 39 |s|...$...9| diff --git a/src/pkg/crypto/tls/testdata/Server-SSLv3-RSA-RC4 b/src/pkg/crypto/tls/testdata/Server-SSLv3-RSA-RC4 deleted file mode 100644 index 1314b659b..000000000 --- a/src/pkg/crypto/tls/testdata/Server-SSLv3-RSA-RC4 +++ /dev/null @@ -1,79 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 00 00 2f 01 00 00 2b 03 00 52 cc 57 59 79 |..../...+..R.WYy| -00000010 b9 3b ef df 53 fb 09 f6 01 e5 18 0a fc 3d 65 bb |.;..S........=e.| -00000020 cf 9c 4c 77 b1 e8 6b 4f 5f c7 94 00 00 04 00 05 |..Lw..kO_.......| -00000030 00 ff 01 00 |....| ->>> Flow 2 (server to client) -00000000 16 03 00 00 31 02 00 00 2d 03 00 00 00 00 00 00 |....1...-.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 05 00 00 |................| -00000030 05 ff 01 00 01 00 16 03 00 02 be 0b 00 02 ba 00 |................| -00000040 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000050 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000060 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000070 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -00000080 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -00000090 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000a0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000b0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000c0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000d0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -000000e0 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -000000f0 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000100 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000110 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000120 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000130 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000140 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000150 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000160 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000170 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -00000180 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -00000190 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001a0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001b0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001c0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001d0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -000001e0 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -000001f0 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000200 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000210 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000220 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000230 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000240 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000250 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000260 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000270 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -00000280 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -00000290 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002a0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002b0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002c0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002d0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -000002e0 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -000002f0 6e 38 50 29 6c 90 a7 bd d9 16 03 00 00 04 0e 00 |n8P)l...........| -00000300 00 00 |..| ->>> Flow 3 (client to server) -00000000 16 03 00 00 84 10 00 00 80 4d 66 7a f3 f8 ab 86 |.........Mfz....| -00000010 43 4c 5f 7c 52 ca e7 3f ba 62 b3 82 88 16 7d ca |CL_|R..?.b....}.| -00000020 3a 66 15 c0 36 55 2c ab bf 30 6b cd 9c d8 b9 48 |:f..6U,..0k....H| -00000030 03 c9 d0 98 ab 0b a6 5b 39 c8 fe 82 8e bb f0 16 |.......[9.......| -00000040 6f 96 62 81 f2 dc 52 02 c9 de e4 47 73 21 6e 1e |o.b...R....Gs!n.| -00000050 3a 11 89 7a e2 6b 9e 04 64 72 15 ba 2d 10 a2 69 |:..z.k..dr..-..i| -00000060 07 e6 ba 17 cf 54 d6 4e 5f 99 e8 59 8b 54 ce 8e |.....T.N_..Y.T..| -00000070 6b 58 ba 83 68 46 4a 5f 43 3e 9b e1 32 a2 19 42 |kX..hFJ_C>..2..B| -00000080 46 0f e4 47 1a 3b 16 5f e1 14 03 00 00 01 01 16 |F..G.;._........| -00000090 03 00 00 3c 78 7e ee da 0d 38 0b 1a d6 d4 8e d5 |...>> Flow 4 (server to client) -00000000 14 03 00 00 01 01 16 03 00 00 3c 23 29 64 62 23 |..........<#)db#| -00000010 19 20 f8 2e 15 07 ee c8 f4 ab f0 3e 66 c3 ed 7b |. .........>f..{| -00000020 7c a7 c2 7e c3 25 3c 8f f3 04 dc 37 e8 fc 0a 1d ||..~.%<....7....| -00000030 fa 7a 09 d4 21 11 e3 24 21 4b 37 d1 85 cc 40 bf |.z..!..$!K7...@.| -00000040 bd bd f8 59 6b cd 73 17 03 00 00 21 47 1d ac 54 |...Yk.s....!G..T| -00000050 bd 58 a6 c0 04 e2 0c 6b 66 64 5a 85 09 0e 47 fc |.X.....kfdZ...G.| -00000060 0b 57 ee f1 24 b6 89 57 46 be 6b 0d f2 15 03 00 |.W..$..WF.k.....| -00000070 00 16 b4 f7 34 99 19 43 b6 b3 5a 8b c3 d2 67 2f |....4..C..Z...g/| -00000080 3b 19 1c 31 d4 f9 bd 96 |;..1....| diff --git a/src/pkg/crypto/tls/testdata/Server-TLSv10-ECDHE-ECDSA-AES b/src/pkg/crypto/tls/testdata/Server-TLSv10-ECDHE-ECDSA-AES deleted file mode 100644 index 9b8cb4d9b..000000000 --- a/src/pkg/crypto/tls/testdata/Server-TLSv10-ECDHE-ECDSA-AES +++ /dev/null @@ -1,84 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 76 01 00 00 72 03 01 53 04 f0 f9 4b |....v...r..S...K| -00000010 30 a8 68 d0 79 13 14 69 ee 3b 5d 05 cb 71 63 43 |0.h.y..i.;]..qcC| -00000020 4a 55 6b 05 25 53 19 ba e0 2f b1 00 00 04 c0 0a |JUk.%S.../......| -00000030 00 ff 01 00 00 45 00 0b 00 04 03 00 01 02 00 0a |.....E..........| -00000040 00 34 00 32 00 0e 00 0d 00 19 00 0b 00 0c 00 18 |.4.2............| -00000050 00 09 00 0a 00 16 00 17 00 08 00 06 00 07 00 14 |................| -00000060 00 15 00 04 00 05 00 12 00 13 00 01 00 02 00 03 |................| -00000070 00 0f 00 10 00 11 00 0f 00 01 01 |...........| ->>> Flow 2 (server to client) -00000000 16 03 01 00 31 02 00 00 2d 03 01 00 00 00 00 00 |....1...-.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 c0 0a 00 00 |................| -00000030 05 ff 01 00 01 00 16 03 01 02 0e 0b 00 02 0a 00 |................| -00000040 02 07 00 02 04 30 82 02 00 30 82 01 62 02 09 00 |.....0...0..b...| -00000050 b8 bf 2d 47 a0 d2 eb f4 30 09 06 07 2a 86 48 ce |..-G....0...*.H.| -00000060 3d 04 01 30 45 31 0b 30 09 06 03 55 04 06 13 02 |=..0E1.0...U....| -00000070 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -00000080 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000090 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -000000a0 74 73 20 50 74 79 20 4c 74 64 30 1e 17 0d 31 32 |ts Pty Ltd0...12| -000000b0 31 31 32 32 31 35 30 36 33 32 5a 17 0d 32 32 31 |1122150632Z..221| -000000c0 31 32 30 31 35 30 36 33 32 5a 30 45 31 0b 30 09 |120150632Z0E1.0.| -000000d0 06 03 55 04 06 13 02 41 55 31 13 30 11 06 03 55 |..U....AU1.0...U| -000000e0 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 31 21 |....Some-State1!| -000000f0 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 6e 65 |0...U....Interne| -00000100 74 20 57 69 64 67 69 74 73 20 50 74 79 20 4c 74 |t Widgits Pty Lt| -00000110 64 30 81 9b 30 10 06 07 2a 86 48 ce 3d 02 01 06 |d0..0...*.H.=...| -00000120 05 2b 81 04 00 23 03 81 86 00 04 00 c4 a1 ed be |.+...#..........| -00000130 98 f9 0b 48 73 36 7e c3 16 56 11 22 f2 3d 53 c3 |...Hs6~..V.".=S.| -00000140 3b 4d 21 3d cd 6b 75 e6 f6 b0 dc 9a df 26 c1 bc |;M!=.ku......&..| -00000150 b2 87 f0 72 32 7c b3 64 2f 1c 90 bc ea 68 23 10 |...r2|.d/....h#.| -00000160 7e fe e3 25 c0 48 3a 69 e0 28 6d d3 37 00 ef 04 |~..%.H:i.(m.7...| -00000170 62 dd 0d a0 9c 70 62 83 d8 81 d3 64 31 aa 9e 97 |b....pb....d1...| -00000180 31 bd 96 b0 68 c0 9b 23 de 76 64 3f 1a 5c 7f e9 |1...h..#.vd?.\..| -00000190 12 0e 58 58 b6 5f 70 dd 9b d8 ea d5 d7 f5 d5 cc |..XX._p.........| -000001a0 b9 b6 9f 30 66 5b 66 9a 20 e2 27 e5 bf fe 3b 30 |...0f[f. .'...;0| -000001b0 09 06 07 2a 86 48 ce 3d 04 01 03 81 8c 00 30 81 |...*.H.=......0.| -000001c0 88 02 42 01 88 a2 4f eb e2 45 c5 48 7d 1b ac f5 |..B...O..E.H}...| -000001d0 ed 98 9d ae 47 70 c0 5e 1b b6 2f bd f1 b6 4d b7 |....Gp.^../...M.| -000001e0 61 40 d3 11 a2 ce ee 0b 7e 92 7e ff 76 9d c3 3b |a@......~.~.v..;| -000001f0 7e a5 3f ce fa 10 e2 59 ec 47 2d 7c ac da 4e 97 |~.?....Y.G-|..N.| -00000200 0e 15 a0 6f d0 02 42 01 4d fc be 67 13 9c 2d 05 |...o..B.M..g..-.| -00000210 0e bd 3f a3 8c 25 c1 33 13 83 0d 94 06 bb d4 37 |..?..%.3.......7| -00000220 7a f6 ec 7a c9 86 2e dd d7 11 69 7f 85 7c 56 de |z..z......i..|V.| -00000230 fb 31 78 2b e4 c7 78 0d ae cb be 9e 4e 36 24 31 |.1x+..x.....N6$1| -00000240 7b 6a 0f 39 95 12 07 8f 2a 16 03 01 00 d6 0c 00 |{j.9....*.......| -00000250 00 d2 03 00 17 41 04 1e 18 37 ef 0d 19 51 88 35 |.....A...7...Q.5| -00000260 75 71 b5 e5 54 5b 12 2e 8f 09 67 fd a7 24 20 3e |uq..T[....g..$ >| -00000270 b2 56 1c ce 97 28 5e f8 2b 2d 4f 9e f1 07 9f 6c |.V...(^.+-O....l| -00000280 4b 5b 83 56 e2 32 42 e9 58 b6 d7 49 a6 b5 68 1a |K[.V.2B.X..I..h.| -00000290 41 03 56 6b dc 5a 89 00 8b 30 81 88 02 42 00 c6 |A.Vk.Z...0...B..| -000002a0 85 8e 06 b7 04 04 e9 cd 9e 3e cb 66 23 95 b4 42 |.........>.f#..B| -000002b0 9c 64 81 39 05 3f b5 21 f8 28 af 60 6b 4d 3d ba |.d.9.?.!.(.`kM=.| -000002c0 a1 4b 5e 77 ef e7 59 28 fe 1d c1 27 a2 ff a8 de |.K^w..Y(...'....| -000002d0 33 48 b3 c1 85 6a 42 9b f9 7e 7e 31 c2 e5 bd 66 |3H...jB..~~1...f| -000002e0 02 42 00 ad 7d 06 35 ab ec 8d ac d4 ba 1b 49 5e |.B..}.5.......I^| -000002f0 05 5f f0 97 93 82 b8 2b 8d 91 98 63 8e b4 14 62 |._.....+...c...b| -00000300 db 1e c9 2b 30 f8 41 9b a6 e6 bc de 0e 68 30 21 |...+0.A......h0!| -00000310 d8 ef 2f 05 42 da f2 e0 2c 06 33 1d 0d 9a 1a 75 |../.B...,.3....u| -00000320 59 a7 3a bc 16 03 01 00 04 0e 00 00 00 |Y.:..........| ->>> Flow 3 (client to server) -00000000 16 03 01 00 46 10 00 00 42 41 04 08 28 cf bd 3c |....F...BA..(..<| -00000010 3c cc 98 9e 73 3f 92 a7 cb 22 83 3b c7 61 46 0e |<...s?...".;.aF.| -00000020 4d 7c 30 b5 06 85 2f 01 be b5 40 e2 64 1e 45 c1 |M|0.../...@.d.E.| -00000030 9d 73 95 d5 65 92 0b 9b e7 6f c6 91 ab b6 fa be |.s..e....o......| -00000040 61 83 a7 f2 eb f5 65 31 fe 24 7b 14 03 01 00 01 |a.....e1.${.....| -00000050 01 16 03 01 00 30 15 d1 c4 ca 0b 01 84 13 5a ba |.....0........Z.| -00000060 89 04 87 73 7c bb d8 89 7e 10 27 ba 6f 5d dc d3 |...s|...~.'.o]..| -00000070 b5 ef 32 86 58 cc fb eb 5c 32 9e 95 ef 01 1c ac |..2.X...\2......| -00000080 dc 8e df 7f fe 0a |......| ->>> Flow 4 (server to client) -00000000 14 03 01 00 01 01 16 03 01 00 30 e8 48 86 81 3c |..........0.H..<| -00000010 f5 25 5c 94 a9 06 c4 5c 71 62 b1 43 76 ec 2c 44 |.%\....\qb.Cv.,D| -00000020 95 b5 8c 95 d2 ff 82 92 b6 fc 52 75 03 c6 a1 f0 |..........Ru....| -00000030 99 6d b1 ed ec 68 6c d7 9f 18 50 17 03 01 00 20 |.m...hl...P.... | -00000040 32 d9 26 8a 81 b8 9d a5 7b fd d5 4e 7a db 2e 29 |2.&.....{..Nz..)| -00000050 58 9a 4f 6a 27 18 bc dc c2 49 b8 65 cb 8e 16 5a |X.Oj'....I.e...Z| -00000060 17 03 01 00 30 c4 56 0a ad 9a 82 cb 3e 32 f1 7c |....0.V.....>2.|| -00000070 95 6e dd cd e9 4d f0 e5 2d c9 a3 f7 de bb d7 fd |.n...M..-.......| -00000080 84 bb df 34 8c 64 1f 03 58 64 19 4a 5b 7a a8 81 |...4.d..Xd.J[z..| -00000090 52 bb 51 0a 43 15 03 01 00 20 89 18 7a 40 ec 49 |R.Q.C.... ..z@.I| -000000a0 52 d5 d3 20 ac 07 eb e9 4a 78 23 cf e7 21 32 74 |R.. ....Jx#..!2t| -000000b0 ec 40 8d a8 f4 33 1c ae 93 cf |.@...3....| diff --git a/src/pkg/crypto/tls/testdata/Server-TLSv10-RSA-3DES b/src/pkg/crypto/tls/testdata/Server-TLSv10-RSA-3DES deleted file mode 100644 index c0e6241c0..000000000 --- a/src/pkg/crypto/tls/testdata/Server-TLSv10-RSA-3DES +++ /dev/null @@ -1,79 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 36 01 00 00 32 03 01 52 cc 57 59 13 |....6...2..R.WY.| -00000010 8b e6 5b a3 1d cb 94 ef 48 e4 59 7e 20 6d 07 67 |..[.....H.Y~ m.g| -00000020 1e 28 6d 31 a2 e7 96 b3 7d 32 cc 00 00 04 00 0a |.(m1....}2......| -00000030 00 ff 01 00 00 05 00 0f 00 01 01 |...........| ->>> Flow 2 (server to client) -00000000 16 03 01 00 31 02 00 00 2d 03 01 00 00 00 00 00 |....1...-.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 0a 00 00 |................| -00000030 05 ff 01 00 01 00 16 03 01 02 be 0b 00 02 ba 00 |................| -00000040 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000050 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000060 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000070 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -00000080 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -00000090 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000a0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000b0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000c0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000d0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -000000e0 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -000000f0 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000100 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000110 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000120 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000130 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000140 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000150 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000160 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000170 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -00000180 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -00000190 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001a0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001b0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001c0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001d0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -000001e0 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -000001f0 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000200 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000210 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000220 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000230 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000240 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000250 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000260 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000270 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -00000280 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -00000290 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002a0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002b0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002c0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002d0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -000002e0 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -000002f0 6e 38 50 29 6c 90 a7 bd d9 16 03 01 00 04 0e 00 |n8P)l...........| -00000300 00 00 |..| ->>> Flow 3 (client to server) -00000000 16 03 01 00 86 10 00 00 82 00 80 2e af d2 61 f6 |..............a.| -00000010 e2 b8 24 da 28 17 55 99 fd 11 bd 7a ab 98 dd f2 |..$.(.U....z....| -00000020 f6 5f e0 11 6b 12 61 6f 86 48 b2 6e db f0 dd d5 |._..k.ao.H.n....| -00000030 07 88 e5 95 f4 2d 6b 0c d0 09 1a 5e 5f 50 1f dc |.....-k....^_P..| -00000040 f2 e7 02 7d 5e a0 70 29 80 ef 87 aa cc 95 3f 2e |...}^.p)......?.| -00000050 24 d1 40 b6 62 53 1d 25 31 87 1e 2f 77 d3 e1 1c |$.@.bS.%1../w...| -00000060 c4 99 89 bc 99 09 e9 ad 1f ce 09 e6 36 1c 3e 97 |............6.>.| -00000070 be 62 69 a0 4e 14 20 9c 82 2a 3e fc 7e 9b c4 7a |.bi.N. ..*>.~..z| -00000080 5a f7 ad 1a 03 17 2a f8 7a 5f 44 14 03 01 00 01 |Z.....*.z_D.....| -00000090 01 16 03 01 00 28 49 6b da 73 07 ad 85 9a 0e fb |.....(Ik.s......| -000000a0 dd e0 69 ef c9 22 2d 86 91 51 26 63 d0 24 7d 16 |..i.."-..Q&c.$}.| -000000b0 3c db 9b 00 c9 7e 64 e2 69 02 85 7d f7 47 |<....~d.i..}.G| ->>> Flow 4 (server to client) -00000000 14 03 01 00 01 01 16 03 01 00 28 dc 60 83 43 6c |..........(.`.Cl| -00000010 37 79 ab 6e 92 1f 66 d0 b1 12 ce c1 64 9d 2b 68 |7y.n..f.....d.+h| -00000020 c7 1a e5 1f 8c 80 08 d2 86 3e a1 2c e3 7e f4 64 |.........>.,.~.d| -00000030 e7 96 b2 17 03 01 00 18 8d b5 7c 03 78 cf dc 09 |..........|.x...| -00000040 95 06 4b a6 82 f9 30 d2 6b 26 cb 0a 9a 9d 47 9f |..K...0.k&....G.| -00000050 17 03 01 00 28 30 a9 55 dd b9 4d 6a 76 00 39 96 |....(0.U..Mjv.9.| -00000060 a3 94 6a df e5 af 1e a2 eb bb e4 ac 95 2c f7 93 |..j..........,..| -00000070 ef d1 b5 13 d8 e2 06 1a ad 5c 00 dd 0c 15 03 01 |.........\......| -00000080 00 18 a5 62 e4 8b 51 1d 28 46 bc 8a c8 50 a3 32 |...b..Q.(F...P.2| -00000090 6b 7b f1 b6 19 43 63 1f 7d 38 |k{...Cc.}8| diff --git a/src/pkg/crypto/tls/testdata/Server-TLSv10-RSA-AES b/src/pkg/crypto/tls/testdata/Server-TLSv10-RSA-AES deleted file mode 100644 index 1670997b0..000000000 --- a/src/pkg/crypto/tls/testdata/Server-TLSv10-RSA-AES +++ /dev/null @@ -1,82 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 36 01 00 00 32 03 01 52 cc 57 59 5d |....6...2..R.WY]| -00000010 0d 77 24 3e b3 32 3d ba 0f b0 aa 1d e3 13 06 f6 |.w$>.2=.........| -00000020 0f be 3c 92 ba 93 bd a6 6d 69 53 00 00 04 00 2f |..<.....miS..../| -00000030 00 ff 01 00 00 05 00 0f 00 01 01 |...........| ->>> Flow 2 (server to client) -00000000 16 03 01 00 31 02 00 00 2d 03 01 00 00 00 00 00 |....1...-.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 2f 00 00 |............./..| -00000030 05 ff 01 00 01 00 16 03 01 02 be 0b 00 02 ba 00 |................| -00000040 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000050 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000060 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000070 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -00000080 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -00000090 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000a0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000b0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000c0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000d0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -000000e0 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -000000f0 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000100 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000110 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000120 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000130 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000140 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000150 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000160 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000170 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -00000180 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -00000190 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001a0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001b0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001c0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001d0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -000001e0 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -000001f0 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000200 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000210 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000220 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000230 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000240 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000250 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000260 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000270 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -00000280 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -00000290 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002a0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002b0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002c0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002d0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -000002e0 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -000002f0 6e 38 50 29 6c 90 a7 bd d9 16 03 01 00 04 0e 00 |n8P)l...........| -00000300 00 00 |..| ->>> Flow 3 (client to server) -00000000 16 03 01 00 86 10 00 00 82 00 80 20 e6 80 f7 48 |........... ...H| -00000010 7e 7d 08 08 54 e1 b4 e3 98 27 5f 90 9d 3b e3 c2 |~}..T....'_..;..| -00000020 c8 8b dc 9e ff 75 fa fc 60 e1 9e 67 7c c4 08 27 |.....u..`..g|..'| -00000030 cc 6f 15 6c bc 7c 96 de 83 8f 98 6d 4a c7 b7 20 |.o.l.|.....mJ.. | -00000040 8c 19 47 5a ff 76 92 0a df df 66 d2 b6 9d 2d 06 |..GZ.v....f...-.| -00000050 fb ac 07 cf 38 08 f1 fd 0d fe 07 d7 69 3e 8a 79 |....8.......i>.y| -00000060 dc 2d ab bb f7 18 3c 51 14 6e c6 70 95 a2 59 b1 |.-........0| -000000c0 ed c6 bc c2 38 b6 |....8.| ->>> Flow 4 (server to client) -00000000 14 03 01 00 01 01 16 03 01 00 30 5d 0c a2 18 13 |..........0]....| -00000010 40 a1 84 ce c5 d8 4e fc a4 8a 14 b5 94 18 b1 86 |@.....N.........| -00000020 da 6a 7d 26 08 d6 a0 f8 78 5b 42 7e f8 83 54 56 |.j}&....x[B~..TV| -00000030 36 a4 91 37 67 5a d7 68 37 c4 4f 17 03 01 00 20 |6..7gZ.h7.O.... | -00000040 fd aa 5e cf 4b 12 c5 be a4 a2 65 5d 6e 65 46 5f |..^.K.....e]neF_| -00000050 d2 fe 46 e7 77 2d 9c 1e 0b 39 40 48 c2 2f be 21 |..F.w-...9@H./.!| -00000060 17 03 01 00 30 03 af 9e 6b d6 76 ed 9e 1d 8b 8b |....0...k.v.....| -00000070 2e 2a 5d da c4 73 95 ac 0e 6f 69 cb 63 df 50 27 |.*]..s...oi.c.P'| -00000080 30 de 2e 55 86 85 ad 3e 33 22 49 72 f2 e2 9f 8f |0..U...>3"Ir....| -00000090 ba cf 4e 30 34 15 03 01 00 20 4c 4c 97 61 70 ea |..N04.... LL.ap.| -000000a0 ae fc a2 e9 c6 c2 b6 2e 4d 85 f6 ae 2b 56 46 82 |........M...+VF.| -000000b0 9d d8 a5 82 17 fa 3e 62 67 7e |......>bg~| diff --git a/src/pkg/crypto/tls/testdata/Server-TLSv10-RSA-RC4 b/src/pkg/crypto/tls/testdata/Server-TLSv10-RSA-RC4 deleted file mode 100644 index d653561f9..000000000 --- a/src/pkg/crypto/tls/testdata/Server-TLSv10-RSA-RC4 +++ /dev/null @@ -1,76 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 36 01 00 00 32 03 01 52 cc 57 59 cf |....6...2..R.WY.| -00000010 00 a1 49 a4 37 69 74 d8 a7 93 ea 8d e7 50 b7 b3 |..I.7it......P..| -00000020 8c ec e5 56 fb dc 5f 1a 2e ab 18 00 00 04 00 05 |...V.._.........| -00000030 00 ff 01 00 00 05 00 0f 00 01 01 |...........| ->>> Flow 2 (server to client) -00000000 16 03 01 00 31 02 00 00 2d 03 01 00 00 00 00 00 |....1...-.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 05 00 00 |................| -00000030 05 ff 01 00 01 00 16 03 01 02 be 0b 00 02 ba 00 |................| -00000040 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000050 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000060 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000070 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -00000080 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -00000090 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000a0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000b0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000c0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000d0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -000000e0 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -000000f0 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000100 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000110 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000120 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000130 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000140 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000150 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000160 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000170 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -00000180 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -00000190 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001a0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001b0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001c0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001d0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -000001e0 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -000001f0 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000200 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000210 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000220 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000230 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000240 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000250 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000260 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000270 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -00000280 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -00000290 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002a0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002b0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002c0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002d0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -000002e0 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -000002f0 6e 38 50 29 6c 90 a7 bd d9 16 03 01 00 04 0e 00 |n8P)l...........| -00000300 00 00 |..| ->>> Flow 3 (client to server) -00000000 16 03 01 00 86 10 00 00 82 00 80 b1 96 7b 6f f5 |.............{o.| -00000010 a0 cb 0d 60 9b 64 d3 f5 17 76 47 7b bc a5 0e 96 |...`.d...vG{....| -00000020 53 af 68 0c 96 22 f7 28 0c 24 37 9c 51 69 ed b2 |S.h..".(.$7.Qi..| -00000030 47 14 ba 33 c5 79 6b 96 f2 ab 3c 02 5c 37 a4 97 |G..3.yk...<.\7..| -00000040 23 fc 7f d3 95 2d 85 99 1a 10 1b 38 e5 f1 83 55 |#....-.....8...U| -00000050 4a ab 60 f8 89 0a 6a c4 eb 45 f5 b0 f4 f8 09 31 |J.`...j..E.....1| -00000060 6e f0 25 30 fd 5e 68 61 bc cb 0d 9e 05 73 0a f4 |n.%0.^ha.....s..| -00000070 a5 2e d9 d5 4e 08 f6 3b 8d 2d 21 f5 79 b6 97 55 |....N..;.-!.y..U| -00000080 b9 99 03 49 ea 96 36 49 21 56 bf 14 03 01 00 01 |...I..6I!V......| -00000090 01 16 03 01 00 24 f0 4f 30 06 c3 25 01 93 34 ab |.....$.O0..%..4.| -000000a0 93 8f 59 26 83 6e 8a fd 5a a6 cf af ad b1 a2 83 |..Y&.n..Z.......| -000000b0 28 ff c2 66 5f ac e5 a5 a5 03 |(..f_.....| ->>> Flow 4 (server to client) -00000000 14 03 01 00 01 01 16 03 01 00 24 9d b4 ea d8 be |..........$.....| -00000010 b5 9f 00 fd b5 99 04 12 6b 7a 3f b8 52 d7 52 a9 |........kz?.R.R.| -00000020 e9 bd 5b 63 ad b0 53 ac 46 80 be 48 6e dd ee 17 |..[c..S.F..Hn...| -00000030 03 01 00 21 07 ac c4 fb 21 e4 b8 6b 64 3b b5 27 |...!....!..kd;.'| -00000040 29 67 a1 10 2e d2 71 d5 59 5e fc 1d 84 31 15 6e |)g....q.Y^...1.n| -00000050 4d 4b dc a9 3a 15 03 01 00 16 25 22 a5 78 23 5a |MK..:.....%".x#Z| -00000060 69 6f 99 a1 b3 1c 8d bf f3 bd 1b c8 1c 57 15 75 |io...........W.u| diff --git a/src/pkg/crypto/tls/testdata/Server-TLSv11-RSA-RC4 b/src/pkg/crypto/tls/testdata/Server-TLSv11-RSA-RC4 deleted file mode 100644 index 9237db078..000000000 --- a/src/pkg/crypto/tls/testdata/Server-TLSv11-RSA-RC4 +++ /dev/null @@ -1,76 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 36 01 00 00 32 03 02 52 cc 57 59 bd |....6...2..R.WY.| -00000010 cd 9d 1e 17 38 43 a5 e3 e7 30 e4 2b 2a ef f7 5b |....8C...0.+*..[| -00000020 81 91 0c 0b 52 f8 2d 2c 61 d3 13 00 00 04 00 05 |....R.-,a.......| -00000030 00 ff 01 00 00 05 00 0f 00 01 01 |...........| ->>> Flow 2 (server to client) -00000000 16 03 02 00 31 02 00 00 2d 03 02 00 00 00 00 00 |....1...-.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 05 00 00 |................| -00000030 05 ff 01 00 01 00 16 03 02 02 be 0b 00 02 ba 00 |................| -00000040 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000050 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000060 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000070 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -00000080 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -00000090 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000a0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000b0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000c0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000d0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -000000e0 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -000000f0 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000100 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000110 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000120 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000130 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000140 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000150 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000160 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000170 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -00000180 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -00000190 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001a0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001b0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001c0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001d0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -000001e0 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -000001f0 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000200 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000210 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000220 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000230 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000240 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000250 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000260 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000270 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -00000280 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -00000290 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002a0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002b0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002c0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002d0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -000002e0 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -000002f0 6e 38 50 29 6c 90 a7 bd d9 16 03 02 00 04 0e 00 |n8P)l...........| -00000300 00 00 |..| ->>> Flow 3 (client to server) -00000000 16 03 02 00 86 10 00 00 82 00 80 71 2b 19 25 86 |...........q+.%.| -00000010 a0 ff ba d5 1c a6 0c 8b 6b 0a b8 e9 42 93 2f 55 |........k...B./U| -00000020 a8 ee 62 fa ed bc 6d e2 9d e3 76 a6 73 d7 99 58 |..b...m...v.s..X| -00000030 cc 0b 14 42 96 7c b6 c7 8f 21 16 cf 71 9b 2b b9 |...B.|...!..q.+.| -00000040 e0 34 57 76 22 d5 87 8a ce 1f ea 26 6e 1e e6 ca |.4Wv"......&n...| -00000050 55 3b 20 cd cf 42 26 b1 51 3e 8c 1d a2 ae c4 63 |U; ..B&.Q>.....c| -00000060 f5 ce 27 3c 1e c3 e0 e3 b1 16 c1 8a 62 bd 21 7f |..'<........b.!.| -00000070 38 b5 b7 3a 3c bb 03 37 e1 a5 ff f1 29 e2 21 0a |8..:<..7....).!.| -00000080 8c 20 02 e0 c0 82 97 9d 18 6d f8 14 03 02 00 01 |. .......m......| -00000090 01 16 03 02 00 24 bc 19 16 6e fd 0b db 9e d5 1d |.....$...n......| -000000a0 65 b6 57 1c 58 b5 6a ac f7 4f f0 cd a1 a9 0c c0 |e.W.X.j..O......| -000000b0 df e6 eb d5 00 f7 fd 43 bb 27 |.......C.'| ->>> Flow 4 (server to client) -00000000 14 03 02 00 01 01 16 03 02 00 24 cf 4f e4 27 b0 |..........$.O.'.| -00000010 3d 17 34 b1 3c 37 6e c5 2b 3d 4a c3 46 50 44 b4 |=.4.<7n.+=J.FPD.| -00000020 de 77 18 10 4f 60 b3 4e dc 06 fd 25 ec 05 15 17 |.w..O`.N...%....| -00000030 03 02 00 21 a5 c9 32 f2 21 fb 94 7e 0d 15 65 fd |...!..2.!..~..e.| -00000040 3e fe e4 c1 a5 e9 88 72 b2 f1 26 39 a6 48 59 97 |>......r..&9.HY.| -00000050 65 e3 f0 cb 46 15 03 02 00 16 4b 02 ec cd ca 30 |e...F.....K....0| -00000060 42 cf 3d a0 4a fa 8e 79 bb ed b0 59 40 9b 2c 1a |B.=.J..y...Y@.,.| diff --git a/src/pkg/crypto/tls/testdata/Server-TLSv12-ALPN b/src/pkg/crypto/tls/testdata/Server-TLSv12-ALPN deleted file mode 100644 index 106244d5a..000000000 --- a/src/pkg/crypto/tls/testdata/Server-TLSv12-ALPN +++ /dev/null @@ -1,122 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 01 8a 01 00 01 86 03 03 34 54 69 f3 d7 |...........4Ti..| -00000010 20 9d 1d 74 db 72 e9 2f 51 7c c2 82 0a 9b cb 6d | ..t.r./Q|.....m| -00000020 90 b4 8e a2 1f 2f c7 66 74 8f 33 00 00 d6 c0 30 |...../.ft.3....0| -00000030 c0 2c c0 28 c0 24 c0 14 c0 0a c0 22 c0 21 c0 20 |.,.(.$.....".!. | -00000040 00 a5 00 a3 00 a1 00 9f 00 6b 00 6a 00 69 00 68 |.........k.j.i.h| -00000050 00 39 00 38 00 37 00 36 00 88 00 87 00 86 00 85 |.9.8.7.6........| -00000060 c0 32 c0 2e c0 2a c0 26 c0 0f c0 05 00 9d 00 3d |.2...*.&.......=| -00000070 00 35 00 84 c0 2f c0 2b c0 27 c0 23 c0 13 c0 09 |.5.../.+.'.#....| -00000080 c0 1f c0 1e c0 1d 00 a4 00 a2 00 a0 00 9e 00 67 |...............g| -00000090 00 40 00 3f 00 3e 00 33 00 32 00 31 00 30 00 9a |.@.?.>.3.2.1.0..| -000000a0 00 99 00 98 00 97 00 45 00 44 00 43 00 42 c0 31 |.......E.D.C.B.1| -000000b0 c0 2d c0 29 c0 25 c0 0e c0 04 00 9c 00 3c 00 2f |.-.).%.......<./| -000000c0 00 96 00 41 00 07 c0 11 c0 07 c0 0c c0 02 00 05 |...A............| -000000d0 00 04 c0 12 c0 08 c0 1c c0 1b c0 1a 00 16 00 13 |................| -000000e0 00 10 00 0d c0 0d c0 03 00 0a 00 15 00 12 00 0f |................| -000000f0 00 0c 00 09 00 14 00 11 00 0e 00 0b 00 08 00 06 |................| -00000100 00 03 00 ff 01 00 00 87 00 0b 00 04 03 00 01 02 |................| -00000110 00 0a 00 3a 00 38 00 0e 00 0d 00 19 00 1c 00 0b |...:.8..........| -00000120 00 0c 00 1b 00 18 00 09 00 0a 00 1a 00 16 00 17 |................| -00000130 00 08 00 06 00 07 00 14 00 15 00 04 00 05 00 12 |................| -00000140 00 13 00 01 00 02 00 03 00 0f 00 10 00 11 00 23 |...............#| -00000150 00 00 00 0d 00 20 00 1e 06 01 06 02 06 03 05 01 |..... ..........| -00000160 05 02 05 03 04 01 04 02 04 03 03 01 03 02 03 03 |................| -00000170 02 01 02 02 02 03 00 0f 00 01 01 00 10 00 10 00 |................| -00000180 0e 06 70 72 6f 74 6f 32 06 70 72 6f 74 6f 31 |..proto2.proto1| ->>> Flow 2 (server to client) -00000000 16 03 03 00 42 02 00 00 3e 03 03 00 00 00 00 00 |....B...>.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 c0 14 00 00 |................| -00000030 16 00 23 00 00 ff 01 00 01 00 00 10 00 09 00 07 |..#.............| -00000040 06 70 72 6f 74 6f 31 16 03 03 02 be 0b 00 02 ba |.proto1.........| -00000050 00 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 |......0...0.....| -00000060 02 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d |..............0.| -00000070 06 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 |..*.H........0E1| -00000080 0b 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 |.0...U....AU1.0.| -00000090 06 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 |..U....Some-Stat| -000000a0 65 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 |e1!0...U....Inte| -000000b0 72 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 |rnet Widgits Pty| -000000c0 20 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 | Ltd0...10042409| -000000d0 30 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 |0938Z..110424090| -000000e0 39 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 |938Z0E1.0...U...| -000000f0 02 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f |.AU1.0...U....So| -00000100 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 |me-State1!0...U.| -00000110 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 |...Internet Widg| -00000120 69 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d |its Pty Ltd0..0.| -00000130 06 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d |..*.H...........| -00000140 00 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf |.0.......y......| -00000150 46 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a |F...i..+.CZ..-.z| -00000160 43 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 |C...R..eL,x.#...| -00000170 82 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c |.....;~b.,.3...\| -00000180 7a 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 |zV.....X{&?.....| -00000190 c9 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 |.!.J..T.Z..Bq...| -000001a0 99 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 |...~.}}..9....Q.| -000001b0 7c e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d ||..L;2f......q..| -000001c0 db db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 |...k..-y........| -000001d0 30 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad |0..0...U........| -000001e0 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -000001f0 88 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 |.90u..U.#.n0l...| -00000200 ad e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e |...Z..(.i.#i..&.| -00000210 18 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 |..9.I.G0E1.0...U| -00000220 04 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 |....AU1.0...U...| -00000230 0a 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 |.Some-State1!0..| -00000240 03 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 |.U....Internet W| -00000250 69 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 |idgits Pty Ltd..| -00000260 00 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 |.........0...U..| -00000270 04 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 |..0....0...*.H..| -00000280 0d 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b |...........lE$.k| -00000290 b1 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 |.Y..R.......zdu.| -000002a0 5a 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e |Z.f..+...f..O8.n| -000002b0 60 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 |`....A..%...z$.0| -000002c0 1d ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 |.........1Y....x| -000002d0 ea 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 |.PV\..Z-Z_3....u| -000002e0 90 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c |....R...... _...| -000002f0 a3 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b |.......W.p.&mq..| -00000300 26 6e 38 50 29 6c 90 a7 bd d9 16 03 03 00 cd 0c |&n8P)l..........| -00000310 00 00 c9 03 00 17 41 04 1e 18 37 ef 0d 19 51 88 |......A...7...Q.| -00000320 35 75 71 b5 e5 54 5b 12 2e 8f 09 67 fd a7 24 20 |5uq..T[....g..$ | -00000330 3e b2 56 1c ce 97 28 5e f8 2b 2d 4f 9e f1 07 9f |>.V...(^.+-O....| -00000340 6c 4b 5b 83 56 e2 32 42 e9 58 b6 d7 49 a6 b5 68 |lK[.V.2B.X..I..h| -00000350 1a 41 03 56 6b dc 5a 89 04 01 00 80 2d a0 6e 47 |.A.Vk.Z.....-.nG| -00000360 93 a2 19 17 32 f5 42 58 93 f6 4f d4 e9 4d a4 0f |....2.BX..O..M..| -00000370 fe 4e d7 2c 62 b6 fb 83 37 a3 09 60 4b 69 e2 4c |.N.,b...7..`Ki.L| -00000380 fc b8 4c d1 a6 9a 89 a0 c5 76 f5 62 b7 e8 eb c2 |..L......v.b....| -00000390 fa 0f 0e 61 86 bc 70 da 13 72 8d 87 94 16 9a 8d |...a..p..r......| -000003a0 5f 80 82 92 77 37 4f 9e 55 5d dc 35 42 a3 75 5c |_...w7O.U].5B.u\| -000003b0 ec a4 58 78 66 97 97 da 49 67 2e b6 7e 11 de fb |..Xxf...Ig..~...| -000003c0 e3 8f e8 bf 1d 91 1e 91 20 1b 2a df c6 58 e4 82 |........ .*..X..| -000003d0 ce 37 dd 6f a5 ac 51 3d 65 db 3f f5 16 03 03 00 |.7.o..Q=e.?.....| -000003e0 04 0e 00 00 00 |.....| ->>> Flow 3 (client to server) -00000000 16 03 03 00 46 10 00 00 42 41 04 f3 fc ea d8 50 |....F...BA.....P| -00000010 e6 15 b0 e7 11 c7 6d ee 09 ad 80 d5 54 eb 4f 62 |......m.....T.Ob| -00000020 7d bb a7 2d 28 0c 66 33 42 09 cf 2b 58 f8 58 41 |}..-(.f3B..+X.XA| -00000030 bd 46 51 0a f0 7d 8c 0c 98 9e 26 77 20 fd 5e c1 |.FQ..}....&w .^.| -00000040 a9 b3 e5 c3 6c 05 97 e3 81 fd db 14 03 03 00 01 |....l...........| -00000050 01 16 03 03 00 40 02 2a 28 41 e3 9c 5d 45 d4 45 |.....@.*(A..]E.E| -00000060 51 8c 7a c0 ba b1 8e a4 84 2c f3 83 cd c4 55 5c |Q.z......,....U\| -00000070 d6 5c 6f 72 ab 89 7a c6 d7 9c 2a 54 f0 c4 20 ee |.\or..z...*T.. .| -00000080 37 74 9b b6 8c f7 e4 37 2c eb d4 9f 5c 5e 55 a0 |7t.....7,...\^U.| -00000090 e2 5a fe 1e c8 67 |.Z...g| ->>> Flow 4 (server to client) -00000000 16 03 03 00 72 04 00 00 6e 00 00 00 00 00 68 00 |....r...n.....h.| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 65 |...............e| -00000020 ea 8b c0 ef ba 59 31 75 33 96 f1 f8 c9 e1 ef 30 |.....Y1u3......0| -00000030 00 a3 a9 1d ab c8 4b 29 94 f2 c8 c8 8d 03 57 ab |......K)......W.| -00000040 56 df 0f 4e 0d 30 13 09 c9 e4 fa 51 4e b3 26 ad |V..N.0.....QN.&.| -00000050 43 9f ae 62 d5 59 23 05 9b 69 8f 5b a8 ba 39 f1 |C..b.Y#..i.[..9.| -00000060 90 84 35 bf 8f 8d d5 39 93 98 ee b9 75 03 3f 91 |..5....9....u.?.| -00000070 e8 56 0b cb 44 a6 7a 14 03 03 00 01 01 16 03 03 |.V..D.z.........| -00000080 00 40 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |.@..............| -00000090 00 00 f9 a0 8e 23 34 f1 61 15 a8 4e ae c4 f3 2a |.....#4.a..N...*| -000000a0 a6 f8 ee 1b 65 c4 c0 ff 93 14 74 ed 82 ae 48 a8 |....e.....t...H.| -000000b0 42 fb a9 24 5d dd fd 98 b8 65 73 03 88 99 e1 ed |B..$]....es.....| -000000c0 02 95 17 03 03 00 40 00 00 00 00 00 00 00 00 00 |......@.........| -000000d0 00 00 00 00 00 00 00 b9 b3 f5 41 84 3b 2a a9 c3 |..........A.;*..| -000000e0 9c e3 d4 38 90 76 c1 8c f0 4f 10 1b 04 b5 07 fe |...8.v...O......| -000000f0 79 3d 7b 77 a4 17 0f 4e df 64 70 70 9e 34 8e b6 |y={w...N.dpp.4..| -00000100 db b2 b6 fd 41 fe b3 15 03 03 00 30 00 00 00 00 |....A......0....| -00000110 00 00 00 00 00 00 00 00 00 00 00 00 02 73 de fe |.............s..| -00000120 fa 4b 69 6d 30 69 79 96 7e 4f 2f 04 67 36 96 27 |.Kim0iy.~O/.g6.'| -00000130 67 23 2b dc 7a c4 6c 34 ea fc 79 fd |g#+.z.l4..y.| diff --git a/src/pkg/crypto/tls/testdata/Server-TLSv12-ALPN-NoMatch b/src/pkg/crypto/tls/testdata/Server-TLSv12-ALPN-NoMatch deleted file mode 100644 index db5881b76..000000000 --- a/src/pkg/crypto/tls/testdata/Server-TLSv12-ALPN-NoMatch +++ /dev/null @@ -1,121 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 01 8a 01 00 01 86 03 03 0a a8 82 53 61 |..............Sa| -00000010 68 e0 83 91 71 36 f9 c1 19 ff e8 09 fc 21 9f 03 |h...q6.......!..| -00000020 31 f3 87 4a 04 8c 3d c2 6e 00 32 00 00 d6 c0 30 |1..J..=.n.2....0| -00000030 c0 2c c0 28 c0 24 c0 14 c0 0a c0 22 c0 21 c0 20 |.,.(.$.....".!. | -00000040 00 a5 00 a3 00 a1 00 9f 00 6b 00 6a 00 69 00 68 |.........k.j.i.h| -00000050 00 39 00 38 00 37 00 36 00 88 00 87 00 86 00 85 |.9.8.7.6........| -00000060 c0 32 c0 2e c0 2a c0 26 c0 0f c0 05 00 9d 00 3d |.2...*.&.......=| -00000070 00 35 00 84 c0 2f c0 2b c0 27 c0 23 c0 13 c0 09 |.5.../.+.'.#....| -00000080 c0 1f c0 1e c0 1d 00 a4 00 a2 00 a0 00 9e 00 67 |...............g| -00000090 00 40 00 3f 00 3e 00 33 00 32 00 31 00 30 00 9a |.@.?.>.3.2.1.0..| -000000a0 00 99 00 98 00 97 00 45 00 44 00 43 00 42 c0 31 |.......E.D.C.B.1| -000000b0 c0 2d c0 29 c0 25 c0 0e c0 04 00 9c 00 3c 00 2f |.-.).%.......<./| -000000c0 00 96 00 41 00 07 c0 11 c0 07 c0 0c c0 02 00 05 |...A............| -000000d0 00 04 c0 12 c0 08 c0 1c c0 1b c0 1a 00 16 00 13 |................| -000000e0 00 10 00 0d c0 0d c0 03 00 0a 00 15 00 12 00 0f |................| -000000f0 00 0c 00 09 00 14 00 11 00 0e 00 0b 00 08 00 06 |................| -00000100 00 03 00 ff 01 00 00 87 00 0b 00 04 03 00 01 02 |................| -00000110 00 0a 00 3a 00 38 00 0e 00 0d 00 19 00 1c 00 0b |...:.8..........| -00000120 00 0c 00 1b 00 18 00 09 00 0a 00 1a 00 16 00 17 |................| -00000130 00 08 00 06 00 07 00 14 00 15 00 04 00 05 00 12 |................| -00000140 00 13 00 01 00 02 00 03 00 0f 00 10 00 11 00 23 |...............#| -00000150 00 00 00 0d 00 20 00 1e 06 01 06 02 06 03 05 01 |..... ..........| -00000160 05 02 05 03 04 01 04 02 04 03 03 01 03 02 03 03 |................| -00000170 02 01 02 02 02 03 00 0f 00 01 01 00 10 00 10 00 |................| -00000180 0e 06 70 72 6f 74 6f 32 06 70 72 6f 74 6f 31 |..proto2.proto1| ->>> Flow 2 (server to client) -00000000 16 03 03 00 35 02 00 00 31 03 03 00 00 00 00 00 |....5...1.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 c0 14 00 00 |................| -00000030 09 00 23 00 00 ff 01 00 01 00 16 03 03 02 be 0b |..#.............| -00000040 00 02 ba 00 02 b7 00 02 b4 30 82 02 b0 30 82 02 |.........0...0..| -00000050 19 a0 03 02 01 02 02 09 00 85 b0 bb a4 8a 7f b8 |................| -00000060 ca 30 0d 06 09 2a 86 48 86 f7 0d 01 01 05 05 00 |.0...*.H........| -00000070 30 45 31 0b 30 09 06 03 55 04 06 13 02 41 55 31 |0E1.0...U....AU1| -00000080 13 30 11 06 03 55 04 08 13 0a 53 6f 6d 65 2d 53 |.0...U....Some-S| -00000090 74 61 74 65 31 21 30 1f 06 03 55 04 0a 13 18 49 |tate1!0...U....I| -000000a0 6e 74 65 72 6e 65 74 20 57 69 64 67 69 74 73 20 |nternet Widgits | -000000b0 50 74 79 20 4c 74 64 30 1e 17 0d 31 30 30 34 32 |Pty Ltd0...10042| -000000c0 34 30 39 30 39 33 38 5a 17 0d 31 31 30 34 32 34 |4090938Z..110424| -000000d0 30 39 30 39 33 38 5a 30 45 31 0b 30 09 06 03 55 |090938Z0E1.0...U| -000000e0 04 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 |....AU1.0...U...| -000000f0 0a 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 |.Some-State1!0..| -00000100 03 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 |.U....Internet W| -00000110 69 64 67 69 74 73 20 50 74 79 20 4c 74 64 30 81 |idgits Pty Ltd0.| -00000120 9f 30 0d 06 09 2a 86 48 86 f7 0d 01 01 01 05 00 |.0...*.H........| -00000130 03 81 8d 00 30 81 89 02 81 81 00 bb 79 d6 f5 17 |....0.......y...| -00000140 b5 e5 bf 46 10 d0 dc 69 be e6 2b 07 43 5a d0 03 |...F...i..+.CZ..| -00000150 2d 8a 7a 43 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 |-.zC...R..eL,x.#| -00000160 8c b5 b4 82 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 |........;~b.,.3.| -00000170 fe 12 5c 7a 56 fc f5 06 bf fa 58 7b 26 3f b5 cd |..\zV.....X{&?..| -00000180 04 d3 d0 c9 21 96 4a c7 f4 54 9f 5a bf ef 42 71 |....!.J..T.Z..Bq| -00000190 00 fe 18 99 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e |......~.}}..9...| -000001a0 db 51 c9 7c e3 c0 4c 3b 32 66 01 cf af b1 1d b8 |.Q.|..L;2f......| -000001b0 71 9a 1d db db 89 6b ae da 2d 79 02 03 01 00 01 |q.....k..-y.....| -000001c0 a3 81 a7 30 81 a4 30 1d 06 03 55 1d 0e 04 16 04 |...0..0...U.....| -000001d0 14 b1 ad e2 85 5a cf cb 28 db 69 ce 23 69 de d3 |.....Z..(.i.#i..| -000001e0 26 8e 18 88 39 30 75 06 03 55 1d 23 04 6e 30 6c |&...90u..U.#.n0l| -000001f0 80 14 b1 ad e2 85 5a cf cb 28 db 69 ce 23 69 de |......Z..(.i.#i.| -00000200 d3 26 8e 18 88 39 a1 49 a4 47 30 45 31 0b 30 09 |.&...9.I.G0E1.0.| -00000210 06 03 55 04 06 13 02 41 55 31 13 30 11 06 03 55 |..U....AU1.0...U| -00000220 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 31 21 |....Some-State1!| -00000230 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 6e 65 |0...U....Interne| -00000240 74 20 57 69 64 67 69 74 73 20 50 74 79 20 4c 74 |t Widgits Pty Lt| -00000250 64 82 09 00 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 |d...........0...| -00000260 55 1d 13 04 05 30 03 01 01 ff 30 0d 06 09 2a 86 |U....0....0...*.| -00000270 48 86 f7 0d 01 01 05 05 00 03 81 81 00 08 6c 45 |H.............lE| -00000280 24 c7 6b b1 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a |$.k.Y..R.......z| -00000290 64 75 b5 5a 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f |du.Z.f..+...f..O| -000002a0 38 b3 6e 60 d3 92 fd f7 41 08 b5 25 13 b1 18 7a |8.n`....A..%...z| -000002b0 24 fb 30 1d ba ed 98 b9 17 ec e7 d7 31 59 db 95 |$.0.........1Y..| -000002c0 d3 1d 78 ea 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 |..x.PV\..Z-Z_3..| -000002d0 d8 c9 75 90 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f |..u....R...... _| -000002e0 f2 a0 1c a3 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d |..........W.p.&m| -000002f0 71 99 9b 26 6e 38 50 29 6c 90 a7 bd d9 16 03 03 |q..&n8P)l.......| -00000300 00 cd 0c 00 00 c9 03 00 17 41 04 1e 18 37 ef 0d |.........A...7..| -00000310 19 51 88 35 75 71 b5 e5 54 5b 12 2e 8f 09 67 fd |.Q.5uq..T[....g.| -00000320 a7 24 20 3e b2 56 1c ce 97 28 5e f8 2b 2d 4f 9e |.$ >.V...(^.+-O.| -00000330 f1 07 9f 6c 4b 5b 83 56 e2 32 42 e9 58 b6 d7 49 |...lK[.V.2B.X..I| -00000340 a6 b5 68 1a 41 03 56 6b dc 5a 89 04 01 00 80 b9 |..h.A.Vk.Z......| -00000350 0f 79 8a 16 f4 da 8f 27 b4 16 fc c0 51 db ae d1 |.y.....'....Q...| -00000360 af 79 77 d5 d5 a2 13 05 45 20 cc eb ac ed cb 30 |.yw.....E .....0| -00000370 32 2e 2c bd fa 1c 4d b5 32 a6 37 43 c8 5c 2d f8 |2.,...M.2.7C.\-.| -00000380 6e 85 f5 cd 54 92 29 ad 13 7d d5 9e 8c 1d b7 d0 |n...T.)..}......| -00000390 c1 c7 3d e8 ba 4a 0f 9a a6 3e 25 5f 27 62 b1 00 |..=..J...>%_'b..| -000003a0 91 d9 23 48 3f 10 fe c5 e3 07 9a 58 57 6d cc 10 |..#H?......XWm..| -000003b0 3b f8 1a d5 6e 8b 1f 03 6f 82 84 98 b5 f7 71 5d |;...n...o.....q]| -000003c0 c2 ad 60 14 c1 88 07 5a 3d 99 fd a8 c9 9a 03 16 |..`....Z=.......| -000003d0 03 03 00 04 0e 00 00 00 |........| ->>> Flow 3 (client to server) -00000000 16 03 03 00 46 10 00 00 42 41 04 76 aa 4e b9 f9 |....F...BA.v.N..| -00000010 68 85 81 74 7c d9 f9 64 7f bd 09 83 08 5b 4f 76 |h..t|..d.....[Ov| -00000020 6e be 79 b6 4e 97 17 63 e4 b5 1c 77 e5 85 76 8a |n.y.N..c...w..v.| -00000030 5d 9f f1 21 88 ec f9 a7 7c 41 af f9 c5 fe 11 81 |]..!....|A......| -00000040 11 51 8e a7 20 33 5f cf e7 90 90 14 03 03 00 01 |.Q.. 3_.........| -00000050 01 16 03 03 00 40 44 3e 32 01 71 ac 5a b5 1f 2c |.....@D>2.q.Z..,| -00000060 37 d9 4b 70 72 91 89 d4 d7 c2 c3 e7 ff dc 72 2a |7.Kpr.........r*| -00000070 ba f5 30 b0 e9 dd 48 10 3d cd 98 48 a3 e3 ca de |..0...H.=..H....| -00000080 15 0e 90 8e e5 04 14 74 42 b8 b0 12 cc 68 7b 7d |.......tB....h{}| -00000090 6c 43 72 60 05 0d |lCr`..| ->>> Flow 4 (server to client) -00000000 16 03 03 00 72 04 00 00 6e 00 00 00 00 00 68 00 |....r...n.....h.| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 65 |...............e| -00000020 ea 8b c0 ef ba 12 45 17 61 24 cd d2 4c 22 bb 3b |......E.a$..L".;| -00000030 e3 0e d0 ff 83 e9 7c b7 8f 10 3c 16 1c fc c2 44 |......|...<....D| -00000040 ef 45 f8 27 30 56 db ea eb ae f5 b6 17 b2 ef f9 |.E.'0V..........| -00000050 96 0d 2d db e4 59 23 0a fc fa e3 13 48 57 e5 b3 |..-..Y#.....HW..| -00000060 3a d1 f5 5e ca ef d7 3f 7b b5 f4 69 85 c3 bd da |:..^...?{..i....| -00000070 fd 9c 50 05 2f 86 ce 14 03 03 00 01 01 16 03 03 |..P./...........| -00000080 00 40 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |.@..............| -00000090 00 00 60 25 1c ed 6f c6 a5 bd b2 29 39 4e 09 d1 |..`%..o....)9N..| -000000a0 64 cc 75 cd df 91 a8 90 9d 03 aa 92 07 f2 d0 8a |d.u.............| -000000b0 60 bb 3e 85 21 22 fe f8 dc 52 3c 4e 82 77 14 14 |`.>.!"...R.>}t| -000000e0 0d ac c4 a9 df 67 1c 5a ad 3e 01 34 03 88 2f 39 |.....g.Z.>.4../9| -000000f0 f7 3c 06 e4 f6 81 43 66 b1 1b ed a5 e5 b6 a8 43 |.<....Cf.......C| -00000100 7f 36 2f b2 da 45 9a 15 03 03 00 30 00 00 00 00 |.6/..E.....0....| -00000110 00 00 00 00 00 00 00 00 00 00 00 00 fa 63 4e c5 |.............cN.| -00000120 77 89 71 56 e3 0a cf 98 da 2f 89 8f 74 8e 76 24 |w.qV...../..t.v$| -00000130 e2 40 a5 9f 29 1b b2 11 ef 7a 55 7f |.@..)....zU.| diff --git a/src/pkg/crypto/tls/testdata/Server-TLSv12-CipherSuiteCertPreferenceECDSA b/src/pkg/crypto/tls/testdata/Server-TLSv12-CipherSuiteCertPreferenceECDSA deleted file mode 100644 index 0ab8b8d74..000000000 --- a/src/pkg/crypto/tls/testdata/Server-TLSv12-CipherSuiteCertPreferenceECDSA +++ /dev/null @@ -1,91 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 ca 01 00 00 c6 03 03 53 04 f1 3f 5f |...........S..?_| -00000010 f4 ef 1f b3 41 0b 54 e4 4d 56 0a 31 22 b8 5c 73 |....A.T.MV.1".\s| -00000020 a3 cb b5 b2 9d 43 f1 83 bc d3 bd 00 00 32 c0 30 |.....C.......2.0| -00000030 c0 2c c0 28 c0 24 c0 14 c0 0a c0 22 c0 21 00 a3 |.,.(.$.....".!..| -00000040 00 9f 00 6b 00 6a 00 39 00 38 00 88 00 87 c0 32 |...k.j.9.8.....2| -00000050 c0 2e c0 2a c0 26 c0 0f c0 05 00 9d 00 3d 00 35 |...*.&.......=.5| -00000060 01 00 00 6b 00 0b 00 04 03 00 01 02 00 0a 00 34 |...k...........4| -00000070 00 32 00 0e 00 0d 00 19 00 0b 00 0c 00 18 00 09 |.2..............| -00000080 00 0a 00 16 00 17 00 08 00 06 00 07 00 14 00 15 |................| -00000090 00 04 00 05 00 12 00 13 00 01 00 02 00 03 00 0f |................| -000000a0 00 10 00 11 00 0d 00 22 00 20 06 01 06 02 06 03 |.......". ......| -000000b0 05 01 05 02 05 03 04 01 04 02 04 03 03 01 03 02 |................| -000000c0 03 03 02 01 02 02 02 03 01 01 00 0f 00 01 01 |...............| ->>> Flow 2 (server to client) -00000000 16 03 03 00 2a 02 00 00 26 03 03 00 00 00 00 00 |....*...&.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 c0 0a 00 16 |................| -00000030 03 03 02 0e 0b 00 02 0a 00 02 07 00 02 04 30 82 |..............0.| -00000040 02 00 30 82 01 62 02 09 00 b8 bf 2d 47 a0 d2 eb |..0..b.....-G...| -00000050 f4 30 09 06 07 2a 86 48 ce 3d 04 01 30 45 31 0b |.0...*.H.=..0E1.| -00000060 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -00000070 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -00000080 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -00000090 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000a0 4c 74 64 30 1e 17 0d 31 32 31 31 32 32 31 35 30 |Ltd0...121122150| -000000b0 36 33 32 5a 17 0d 32 32 31 31 32 30 31 35 30 36 |632Z..2211201506| -000000c0 33 32 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |32Z0E1.0...U....| -000000d0 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -000000e0 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -000000f0 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000100 74 73 20 50 74 79 20 4c 74 64 30 81 9b 30 10 06 |ts Pty Ltd0..0..| -00000110 07 2a 86 48 ce 3d 02 01 06 05 2b 81 04 00 23 03 |.*.H.=....+...#.| -00000120 81 86 00 04 00 c4 a1 ed be 98 f9 0b 48 73 36 7e |............Hs6~| -00000130 c3 16 56 11 22 f2 3d 53 c3 3b 4d 21 3d cd 6b 75 |..V.".=S.;M!=.ku| -00000140 e6 f6 b0 dc 9a df 26 c1 bc b2 87 f0 72 32 7c b3 |......&.....r2|.| -00000150 64 2f 1c 90 bc ea 68 23 10 7e fe e3 25 c0 48 3a |d/....h#.~..%.H:| -00000160 69 e0 28 6d d3 37 00 ef 04 62 dd 0d a0 9c 70 62 |i.(m.7...b....pb| -00000170 83 d8 81 d3 64 31 aa 9e 97 31 bd 96 b0 68 c0 9b |....d1...1...h..| -00000180 23 de 76 64 3f 1a 5c 7f e9 12 0e 58 58 b6 5f 70 |#.vd?.\....XX._p| -00000190 dd 9b d8 ea d5 d7 f5 d5 cc b9 b6 9f 30 66 5b 66 |............0f[f| -000001a0 9a 20 e2 27 e5 bf fe 3b 30 09 06 07 2a 86 48 ce |. .'...;0...*.H.| -000001b0 3d 04 01 03 81 8c 00 30 81 88 02 42 01 88 a2 4f |=......0...B...O| -000001c0 eb e2 45 c5 48 7d 1b ac f5 ed 98 9d ae 47 70 c0 |..E.H}.......Gp.| -000001d0 5e 1b b6 2f bd f1 b6 4d b7 61 40 d3 11 a2 ce ee |^../...M.a@.....| -000001e0 0b 7e 92 7e ff 76 9d c3 3b 7e a5 3f ce fa 10 e2 |.~.~.v..;~.?....| -000001f0 59 ec 47 2d 7c ac da 4e 97 0e 15 a0 6f d0 02 42 |Y.G-|..N....o..B| -00000200 01 4d fc be 67 13 9c 2d 05 0e bd 3f a3 8c 25 c1 |.M..g..-...?..%.| -00000210 33 13 83 0d 94 06 bb d4 37 7a f6 ec 7a c9 86 2e |3.......7z..z...| -00000220 dd d7 11 69 7f 85 7c 56 de fb 31 78 2b e4 c7 78 |...i..|V..1x+..x| -00000230 0d ae cb be 9e 4e 36 24 31 7b 6a 0f 39 95 12 07 |.....N6$1{j.9...| -00000240 8f 2a 16 03 03 00 d8 0c 00 00 d4 03 00 17 41 04 |.*............A.| -00000250 1e 18 37 ef 0d 19 51 88 35 75 71 b5 e5 54 5b 12 |..7...Q.5uq..T[.| -00000260 2e 8f 09 67 fd a7 24 20 3e b2 56 1c ce 97 28 5e |...g..$ >.V...(^| -00000270 f8 2b 2d 4f 9e f1 07 9f 6c 4b 5b 83 56 e2 32 42 |.+-O....lK[.V.2B| -00000280 e9 58 b6 d7 49 a6 b5 68 1a 41 03 56 6b dc 5a 89 |.X..I..h.A.Vk.Z.| -00000290 04 03 00 8b 30 81 88 02 42 00 c6 85 8e 06 b7 04 |....0...B.......| -000002a0 04 e9 cd 9e 3e cb 66 23 95 b4 42 9c 64 81 39 05 |....>.f#..B.d.9.| -000002b0 3f b5 21 f8 28 af 60 6b 4d 3d ba a1 4b 5e 77 ef |?.!.(.`kM=..K^w.| -000002c0 e7 59 28 fe 1d c1 27 a2 ff a8 de 33 48 b3 c1 85 |.Y(...'....3H...| -000002d0 6a 42 9b f9 7e 7e 31 c2 e5 bd 66 02 42 00 ad 7d |jB..~~1...f.B..}| -000002e0 06 35 ab ec 8d ac d4 ba 1b 49 5e 05 5f f0 97 93 |.5.......I^._...| -000002f0 82 b8 2b 8d 91 98 63 8e b4 14 62 db 1e c9 2b 64 |..+...c...b...+d| -00000300 e9 e6 bf 15 5b 67 c2 40 90 c6 1f b7 92 db 4b f6 |....[g.@......K.| -00000310 f4 db ae 82 f1 4f 02 75 52 40 38 10 ff 35 f0 16 |.....O.uR@8..5..| -00000320 03 03 00 04 0e 00 00 00 |........| ->>> Flow 3 (client to server) -00000000 16 03 03 00 46 10 00 00 42 41 04 d8 94 c4 05 26 |....F...BA.....&| -00000010 76 29 2d 0e ec 47 b6 50 d5 a3 da 2a ba 02 11 37 |v)-..G.P...*...7| -00000020 3d ef e6 2a db d0 47 47 a7 9a 5f 43 2d 98 78 26 |=..*..GG.._C-.x&| -00000030 81 e2 f1 ba fe f7 66 c6 61 cb c1 b7 60 62 34 a5 |......f.a...`b4.| -00000040 78 67 50 3d 9a 0e 4a 8c 8f d7 10 14 03 03 00 01 |xgP=..J.........| -00000050 01 16 03 03 00 40 5e 46 b0 5d 30 f6 da 8f 9e 67 |.....@^F.]0....g| -00000060 f5 3e bd fe c9 b8 53 b2 10 d5 7c 0e 34 e3 93 6d |.>....S...|.4..m| -00000070 0e 8e 8a 2b df fb 9a 0f a5 23 55 e7 0a 4b e2 d3 |...+.....#U..K..| -00000080 db 15 e8 52 74 26 78 b3 b0 56 65 63 ac ae 1e c0 |...Rt&x..Vec....| -00000090 0b f4 92 56 a9 04 |...V..| ->>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 40 00 00 00 00 00 |..........@.....| -00000010 00 00 00 00 00 00 00 00 00 00 00 16 a9 63 0a 99 |.............c..| -00000020 21 8a fc 5c b3 ee 05 71 4e 75 c0 d9 40 54 0d 3e |!..\...qNu..@T.>| -00000030 4e 5d 44 b7 4b 5d a9 e7 5a 30 ed b6 d5 08 50 b1 |N]D.K]..Z0....P.| -00000040 e8 8c 54 eb 1b 39 7a f9 3b ac 2e 17 03 03 00 40 |..T..9z.;......@| -00000050 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000060 96 03 20 2b 20 c4 c1 9a 76 7b f3 96 bd 33 ed e6 |.. + ...v{...3..| -00000070 38 48 ea 53 d5 e0 62 b5 7e 1a 36 a8 dd 9f 2d 4b |8H.S..b.~.6...-K| -00000080 06 0d ae f6 bc 99 14 b3 93 14 27 63 e2 a0 c8 76 |..........'c...v| -00000090 15 03 03 00 30 00 00 00 00 00 00 00 00 00 00 00 |....0...........| -000000a0 00 00 00 00 00 48 af e1 e4 11 e1 b7 03 19 b0 e3 |.....H..........| -000000b0 e6 a9 66 d8 ac af aa 03 f6 0d 51 df 9a 27 78 3a |..f.......Q..'x:| -000000c0 56 5a 03 1a 4c |VZ..L| diff --git a/src/pkg/crypto/tls/testdata/Server-TLSv12-CipherSuiteCertPreferenceRSA b/src/pkg/crypto/tls/testdata/Server-TLSv12-CipherSuiteCertPreferenceRSA deleted file mode 100644 index 88abb15a7..000000000 --- a/src/pkg/crypto/tls/testdata/Server-TLSv12-CipherSuiteCertPreferenceRSA +++ /dev/null @@ -1,101 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 ca 01 00 00 c6 03 03 53 04 f1 3f cc |...........S..?.| -00000010 41 74 00 07 cb ae 3b 30 79 48 51 60 41 a3 8c ab |At....;0yHQ`A...| -00000020 dc 76 f9 74 52 1e c5 fb a9 69 c2 00 00 32 c0 30 |.v.tR....i...2.0| -00000030 c0 2c c0 28 c0 24 c0 14 c0 0a c0 22 c0 21 00 a3 |.,.(.$.....".!..| -00000040 00 9f 00 6b 00 6a 00 39 00 38 00 88 00 87 c0 32 |...k.j.9.8.....2| -00000050 c0 2e c0 2a c0 26 c0 0f c0 05 00 9d 00 3d 00 35 |...*.&.......=.5| -00000060 01 00 00 6b 00 0b 00 04 03 00 01 02 00 0a 00 34 |...k...........4| -00000070 00 32 00 0e 00 0d 00 19 00 0b 00 0c 00 18 00 09 |.2..............| -00000080 00 0a 00 16 00 17 00 08 00 06 00 07 00 14 00 15 |................| -00000090 00 04 00 05 00 12 00 13 00 01 00 02 00 03 00 0f |................| -000000a0 00 10 00 11 00 0d 00 22 00 20 06 01 06 02 06 03 |.......". ......| -000000b0 05 01 05 02 05 03 04 01 04 02 04 03 03 01 03 02 |................| -000000c0 03 03 02 01 02 02 02 03 01 01 00 0f 00 01 01 |...............| ->>> Flow 2 (server to client) -00000000 16 03 03 00 2a 02 00 00 26 03 03 00 00 00 00 00 |....*...&.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 c0 14 00 16 |................| -00000030 03 03 02 be 0b 00 02 ba 00 02 b7 00 02 b4 30 82 |..............0.| -00000040 02 b0 30 82 02 19 a0 03 02 01 02 02 09 00 85 b0 |..0.............| -00000050 bb a4 8a 7f b8 ca 30 0d 06 09 2a 86 48 86 f7 0d |......0...*.H...| -00000060 01 01 05 05 00 30 45 31 0b 30 09 06 03 55 04 06 |.....0E1.0...U..| -00000070 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 |..AU1.0...U....S| -00000080 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 |ome-State1!0...U| -00000090 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 |....Internet Wid| -000000a0 67 69 74 73 20 50 74 79 20 4c 74 64 30 1e 17 0d |gits Pty Ltd0...| -000000b0 31 30 30 34 32 34 30 39 30 39 33 38 5a 17 0d 31 |100424090938Z..1| -000000c0 31 30 34 32 34 30 39 30 39 33 38 5a 30 45 31 0b |10424090938Z0E1.| -000000d0 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -000000e0 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -000000f0 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -00000100 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -00000110 4c 74 64 30 81 9f 30 0d 06 09 2a 86 48 86 f7 0d |Ltd0..0...*.H...| -00000120 01 01 01 05 00 03 81 8d 00 30 81 89 02 81 81 00 |.........0......| -00000130 bb 79 d6 f5 17 b5 e5 bf 46 10 d0 dc 69 be e6 2b |.y......F...i..+| -00000140 07 43 5a d0 03 2d 8a 7a 43 85 b7 14 52 e7 a5 65 |.CZ..-.zC...R..e| -00000150 4c 2c 78 b8 23 8c b5 b4 82 e5 de 1f 95 3b 7e 62 |L,x.#........;~b| -00000160 a5 2c a5 33 d6 fe 12 5c 7a 56 fc f5 06 bf fa 58 |.,.3...\zV.....X| -00000170 7b 26 3f b5 cd 04 d3 d0 c9 21 96 4a c7 f4 54 9f |{&?......!.J..T.| -00000180 5a bf ef 42 71 00 fe 18 99 07 7f 7e 88 7d 7d f1 |Z..Bq......~.}}.| -00000190 04 39 c4 a2 2e db 51 c9 7c e3 c0 4c 3b 32 66 01 |.9....Q.|..L;2f.| -000001a0 cf af b1 1d b8 71 9a 1d db db 89 6b ae da 2d 79 |.....q.....k..-y| -000001b0 02 03 01 00 01 a3 81 a7 30 81 a4 30 1d 06 03 55 |........0..0...U| -000001c0 1d 0e 04 16 04 14 b1 ad e2 85 5a cf cb 28 db 69 |..........Z..(.i| -000001d0 ce 23 69 de d3 26 8e 18 88 39 30 75 06 03 55 1d |.#i..&...90u..U.| -000001e0 23 04 6e 30 6c 80 14 b1 ad e2 85 5a cf cb 28 db |#.n0l......Z..(.| -000001f0 69 ce 23 69 de d3 26 8e 18 88 39 a1 49 a4 47 30 |i.#i..&...9.I.G0| -00000200 45 31 0b 30 09 06 03 55 04 06 13 02 41 55 31 13 |E1.0...U....AU1.| -00000210 30 11 06 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 |0...U....Some-St| -00000220 61 74 65 31 21 30 1f 06 03 55 04 0a 13 18 49 6e |ate1!0...U....In| -00000230 74 65 72 6e 65 74 20 57 69 64 67 69 74 73 20 50 |ternet Widgits P| -00000240 74 79 20 4c 74 64 82 09 00 85 b0 bb a4 8a 7f b8 |ty Ltd..........| -00000250 ca 30 0c 06 03 55 1d 13 04 05 30 03 01 01 ff 30 |.0...U....0....0| -00000260 0d 06 09 2a 86 48 86 f7 0d 01 01 05 05 00 03 81 |...*.H..........| -00000270 81 00 08 6c 45 24 c7 6b b1 59 ab 0c 52 cc f2 b0 |...lE$.k.Y..R...| -00000280 14 d7 87 9d 7a 64 75 b5 5a 95 66 e4 c5 2b 8e ae |....zdu.Z.f..+..| -00000290 12 66 1f eb 4f 38 b3 6e 60 d3 92 fd f7 41 08 b5 |.f..O8.n`....A..| -000002a0 25 13 b1 18 7a 24 fb 30 1d ba ed 98 b9 17 ec e7 |%...z$.0........| -000002b0 d7 31 59 db 95 d3 1d 78 ea 50 56 5c d5 82 5a 2d |.1Y....x.PV\..Z-| -000002c0 5a 5f 33 c4 b6 d8 c9 75 90 96 8c 0f 52 98 b5 cd |Z_3....u....R...| -000002d0 98 1f 89 20 5f f2 a0 1c a3 1b 96 94 dd a9 fd 57 |... _..........W| -000002e0 e9 70 e8 26 6d 71 99 9b 26 6e 38 50 29 6c 90 a7 |.p.&mq..&n8P)l..| -000002f0 bd d9 16 03 03 00 cd 0c 00 00 c9 03 00 17 41 04 |..............A.| -00000300 1e 18 37 ef 0d 19 51 88 35 75 71 b5 e5 54 5b 12 |..7...Q.5uq..T[.| -00000310 2e 8f 09 67 fd a7 24 20 3e b2 56 1c ce 97 28 5e |...g..$ >.V...(^| -00000320 f8 2b 2d 4f 9e f1 07 9f 6c 4b 5b 83 56 e2 32 42 |.+-O....lK[.V.2B| -00000330 e9 58 b6 d7 49 a6 b5 68 1a 41 03 56 6b dc 5a 89 |.X..I..h.A.Vk.Z.| -00000340 04 01 00 80 9d 84 09 35 73 fb f6 ea 94 7b 49 fb |.......5s....{I.| -00000350 c2 70 b1 11 64 5b 93 9f d9 8c f5 56 98 f6 d3 66 |.p..d[.....V...f| -00000360 a6 1d 18 56 88 87 71 3f b0 38 9d 44 1f ad 2c 0d |...V..q?.8.D..,.| -00000370 3a a7 e8 d4 3e 33 3c 41 20 f3 3f 5c e5 fb e3 23 |:...>36as.d...mP| -000003b0 33 55 c7 e1 c5 a5 4c 32 5c 95 dc 07 43 60 49 11 |3U....L2\...C`I.| -000003c0 e9 98 cc ba 16 03 03 00 04 0e 00 00 00 |.............| ->>> Flow 3 (client to server) -00000000 16 03 03 00 46 10 00 00 42 41 04 28 02 84 d5 b4 |....F...BA.(....| -00000010 58 07 47 d5 a0 d6 0b 1d 37 91 e6 34 a4 ad 0b ad |X.G.....7..4....| -00000020 22 01 82 77 a7 32 86 78 83 3a da 75 2f e5 68 7a |"..w.2.x.:.u/.hz| -00000030 de e4 05 e0 02 47 40 4e 38 d2 2c c3 7b da 53 73 |.....G@N8.,.{.Ss| -00000040 19 cb 8b 73 34 72 4d 33 71 39 c8 14 03 03 00 01 |...s4rM3q9......| -00000050 01 16 03 03 00 40 10 63 43 76 83 bd 36 e4 1e 4d |.....@.cCv..6..M| -00000060 7e 13 b0 ac aa c8 ec 90 31 df 84 46 49 68 39 5a |~.......1..FIh9Z| -00000070 05 8b 73 32 86 15 3a 18 57 d8 e2 2c 2d 05 89 93 |..s2..:.W..,-...| -00000080 37 b8 dd 73 33 92 ff a7 b2 53 27 94 b7 25 56 64 |7..s3....S'..%Vd| -00000090 a1 d3 2c f7 6b 71 |..,.kq| ->>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 40 00 00 00 00 00 |..........@.....| -00000010 00 00 00 00 00 00 00 00 00 00 00 21 5c 31 b1 4b |...........!\1.K| -00000020 96 96 30 8f 79 35 3a 3a 2d 26 67 d0 70 48 be 30 |..0.y5::-&g.pH.0| -00000030 f8 3e e8 c1 cb 1d d5 89 f6 9c 72 bb 1c f9 4d 90 |.>........r...M.| -00000040 9c d7 c6 fa 40 76 a5 61 46 61 24 17 03 03 00 40 |....@v.aFa$....@| -00000050 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000060 94 8a 14 04 06 b9 30 a0 67 fd b2 4c 84 f4 10 93 |......0.g..L....| -00000070 7d d4 2b 23 f0 e9 62 93 c2 20 a2 f2 7c 07 21 4b |}.+#..b.. ..|.!K| -00000080 94 ba 7b 7d cb 77 da 85 93 bd 53 ee ca db 9b 3e |..{}.w....S....>| -00000090 15 03 03 00 30 00 00 00 00 00 00 00 00 00 00 00 |....0...........| -000000a0 00 00 00 00 00 17 3f 53 8d b3 35 b4 84 ed bb 12 |......?S..5.....| -000000b0 cf 73 25 25 7c c3 d3 bb 1f 5a 6b 73 9a 8a b1 a2 |.s%%|....Zks....| -000000c0 ba 99 f8 0e 43 |....C| diff --git a/src/pkg/crypto/tls/testdata/Server-TLSv12-ClientAuthRequestedAndECDSAGiven b/src/pkg/crypto/tls/testdata/Server-TLSv12-ClientAuthRequestedAndECDSAGiven deleted file mode 100644 index 547f79834..000000000 --- a/src/pkg/crypto/tls/testdata/Server-TLSv12-ClientAuthRequestedAndECDSAGiven +++ /dev/null @@ -1,122 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 5c 01 00 00 58 03 03 52 cc 57 59 65 |....\...X..R.WYe| -00000010 ae b3 ec a4 7a 05 f7 ec 39 22 7d 8c 91 96 6b e0 |....z...9"}...k.| -00000020 69 81 ff 88 28 17 60 ac 94 19 ff 00 00 04 00 05 |i...(.`.........| -00000030 00 ff 01 00 00 2b 00 0d 00 22 00 20 06 01 06 02 |.....+...". ....| -00000040 06 03 05 01 05 02 05 03 04 01 04 02 04 03 03 01 |................| -00000050 03 02 03 03 02 01 02 02 02 03 01 01 00 0f 00 01 |................| -00000060 01 |.| ->>> Flow 2 (server to client) -00000000 16 03 03 00 31 02 00 00 2d 03 03 00 00 00 00 00 |....1...-.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 05 00 00 |................| -00000030 05 ff 01 00 01 00 16 03 03 02 be 0b 00 02 ba 00 |................| -00000040 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000050 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000060 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000070 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -00000080 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -00000090 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000a0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000b0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000c0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000d0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -000000e0 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -000000f0 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000100 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000110 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000120 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000130 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000140 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000150 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000160 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000170 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -00000180 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -00000190 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001a0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001b0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001c0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001d0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -000001e0 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -000001f0 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000200 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000210 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000220 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000230 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000240 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000250 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000260 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000270 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -00000280 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -00000290 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002a0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002b0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002c0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002d0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -000002e0 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -000002f0 6e 38 50 29 6c 90 a7 bd d9 16 03 03 00 0f 0d 00 |n8P)l...........| -00000300 00 0b 02 01 40 00 04 04 01 04 03 00 00 16 03 03 |....@...........| -00000310 00 04 0e 00 00 00 |......| ->>> Flow 3 (client to server) -00000000 16 03 03 02 0a 0b 00 02 06 00 02 03 00 02 00 30 |...............0| -00000010 82 01 fc 30 82 01 5e 02 09 00 9a 30 84 6c 26 35 |...0..^....0.l&5| -00000020 d9 17 30 09 06 07 2a 86 48 ce 3d 04 01 30 45 31 |..0...*.H.=..0E1| -00000030 0b 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 |.0...U....AU1.0.| -00000040 06 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 |..U....Some-Stat| -00000050 65 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 |e1!0...U....Inte| -00000060 72 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 |rnet Widgits Pty| -00000070 20 4c 74 64 30 1e 17 0d 31 32 31 31 31 34 31 33 | Ltd0...12111413| -00000080 32 35 35 33 5a 17 0d 32 32 31 31 31 32 31 33 32 |2553Z..221112132| -00000090 35 35 33 5a 30 41 31 0b 30 09 06 03 55 04 06 13 |553Z0A1.0...U...| -000000a0 02 41 55 31 0c 30 0a 06 03 55 04 08 13 03 4e 53 |.AU1.0...U....NS| -000000b0 57 31 10 30 0e 06 03 55 04 07 13 07 50 79 72 6d |W1.0...U....Pyrm| -000000c0 6f 6e 74 31 12 30 10 06 03 55 04 03 13 09 4a 6f |ont1.0...U....Jo| -000000d0 65 6c 20 53 69 6e 67 30 81 9b 30 10 06 07 2a 86 |el Sing0..0...*.| -000000e0 48 ce 3d 02 01 06 05 2b 81 04 00 23 03 81 86 00 |H.=....+...#....| -000000f0 04 00 95 8c 91 75 14 c0 5e c4 57 b4 d4 c3 6f 8d |.....u..^.W...o.| -00000100 ae 68 1e dd 6f ce 86 e1 7e 6e b2 48 3e 81 e5 4e |.h..o...~n.H>..N| -00000110 e2 c6 88 4b 64 dc f5 30 bb d3 ff 65 cc 5b f4 dd |...Kd..0...e.[..| -00000120 b5 6a 3e 3e d0 1d de 47 c3 76 ad 19 f6 45 2c 8c |.j>>...G.v...E,.| -00000130 bc d8 1d 01 4c 1f 70 90 46 76 48 8b 8f 83 cc 4a |....L.p.FvH....J| -00000140 5c 8f 40 76 da e0 89 ec 1d 2b c4 4e 30 76 28 41 |\.@v.....+.N0v(A| -00000150 b2 62 a8 fb 5b f1 f9 4e 7a 8d bd 09 b8 ae ea 8b |.b..[..Nz.......| -00000160 18 27 4f 2e 70 fe 13 96 ba c3 d3 40 16 cd 65 4e |.'O.p......@..eN| -00000170 ac 11 1e e6 f1 30 09 06 07 2a 86 48 ce 3d 04 01 |.....0...*.H.=..| -00000180 03 81 8c 00 30 81 88 02 42 00 e0 14 c4 60 60 0b |....0...B....``.| -00000190 72 68 b0 32 5d 61 4a 02 74 5c c2 81 b9 16 a8 3f |rh.2]aJ.t\.....?| -000001a0 29 c8 36 c7 81 ff 6c b6 5b d9 70 f1 38 3b 50 48 |).6...l.[.p.8;PH| -000001b0 28 94 cb 09 1a 52 f1 5d ee 8d f2 b9 f0 f0 da d9 |(....R.]........| -000001c0 15 3a f9 bd 03 7a 87 a2 23 35 ec 02 42 01 a3 d4 |.:...z..#5..B...| -000001d0 8a 78 35 1c 4a 9a 23 d2 0a be 2b 10 31 9d 9c 5f |.x5.J.#...+.1.._| -000001e0 be e8 91 b3 da 1a f5 5d a3 23 f5 26 8b 45 70 8d |.......].#.&.Ep.| -000001f0 65 62 9b 7e 01 99 3d 18 f6 10 9a 38 61 9b 2e 57 |eb.~..=....8a..W| -00000200 e4 fa cc b1 8a ce e2 23 a0 87 f0 e1 67 51 eb 16 |.......#....gQ..| -00000210 03 03 00 86 10 00 00 82 00 80 47 5a 2f b8 78 46 |..........GZ/.xF| -00000220 9f 3c fc ab 8b 35 c9 77 da c3 96 78 31 7c 2b 4f |.<...5.w...x1|+O| -00000230 56 be 0f 33 bd 17 bc 1c 86 5a ae b3 0f 8b 18 2f |V..3.....Z...../| -00000240 48 0d e0 0a 20 d3 53 96 88 d2 8a 7d b6 58 13 44 |H... .S....}.X.D| -00000250 a5 e8 19 6d 02 df a6 1b 79 c5 54 c2 ef 4d 41 4f |...m....y.T..MAO| -00000260 04 1c eb 37 55 b7 2b f4 7c 6d 37 9c f1 89 a0 2c |...7U.+.|m7....,| -00000270 0f ba 10 09 e4 a1 ee 0a 7e 9a fd 2c 32 63 1c 55 |........~..,2c.U| -00000280 85 38 de d0 7b 5f 46 03 1f cc 4d 69 51 97 d8 d7 |.8..{_F...MiQ...| -00000290 88 6f ba 43 04 b0 42 09 61 5e 16 03 03 00 92 0f |.o.C..B.a^......| -000002a0 00 00 8e 04 03 00 8a 30 81 87 02 41 14 3d 4c 71 |.......0...A.=Lq| -000002b0 c2 32 4a 20 ee b7 69 17 55 e8 99 55 11 76 51 7a |.2J ..i.U..U.vQz| -000002c0 74 55 e7 e8 c3 3b b3 70 db 1c 8e f6 8a d4 99 40 |tU...;.p.......@| -000002d0 6e da 04 fd 7a 47 41 d6 ae c0 63 ad fd 91 a8 58 |n...zGA...c....X| -000002e0 24 b9 ac 2f 7a 4c bf 5b 24 12 cb 3a f3 02 42 00 |$../zL.[$..:..B.| -000002f0 90 f9 48 97 0e d4 33 99 09 9f 1d a8 97 16 60 82 |..H...3.......`.| -00000300 85 cc 5a 5d 79 f7 2f 03 2a c0 b8 12 61 ac 9f 88 |..Z]y./.*...a...| -00000310 1d 0d 9e 0a ee 28 a8 5a e2 42 b7 94 e2 e6 0e 13 |.....(.Z.B......| -00000320 c8 64 dc 4e d3 6b 10 d6 83 41 9c dc d4 53 c3 08 |.d.N.k...A...S..| -00000330 19 14 03 03 00 01 01 16 03 03 00 24 ef bd e3 23 |...........$...#| -00000340 10 23 ae 6e b5 12 eb 9c 21 78 db 36 fd bf 7f ee |.#.n....!x.6....| -00000350 6f c8 00 2d b6 35 cc 2f 38 73 ae a4 34 cf 0d df |o..-.5./8s..4...| ->>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 24 a7 50 0f 50 b4 |..........$.P.P.| -00000010 1c c3 4d f3 7a 64 df 65 ac 35 22 13 46 cc ec 36 |..M.zd.e.5".F..6| -00000020 e6 d2 f3 67 94 6a 18 85 9f 4a 3c 44 a3 58 b0 17 |...g.j...J>> Flow 1 (client to server) -00000000 16 03 01 00 5c 01 00 00 58 03 03 52 cc 57 59 6b |....\...X..R.WYk| -00000010 11 07 04 39 77 20 c2 b4 3f cb 0a c9 53 fe 5b 3e |...9w ..?...S.[>| -00000020 5f 58 2c 7e 30 69 e1 8e 6c 9d c8 00 00 04 00 05 |_X,~0i..l.......| -00000030 00 ff 01 00 00 2b 00 0d 00 22 00 20 06 01 06 02 |.....+...". ....| -00000040 06 03 05 01 05 02 05 03 04 01 04 02 04 03 03 01 |................| -00000050 03 02 03 03 02 01 02 02 02 03 01 01 00 0f 00 01 |................| -00000060 01 |.| ->>> Flow 2 (server to client) -00000000 16 03 03 00 31 02 00 00 2d 03 03 00 00 00 00 00 |....1...-.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 05 00 00 |................| -00000030 05 ff 01 00 01 00 16 03 03 02 be 0b 00 02 ba 00 |................| -00000040 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000050 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000060 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000070 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -00000080 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -00000090 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000a0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000b0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000c0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000d0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -000000e0 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -000000f0 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000100 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000110 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000120 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000130 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000140 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000150 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000160 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000170 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -00000180 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -00000190 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001a0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001b0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001c0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001d0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -000001e0 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -000001f0 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000200 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000210 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000220 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000230 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000240 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000250 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000260 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000270 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -00000280 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -00000290 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002a0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002b0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002c0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002d0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -000002e0 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -000002f0 6e 38 50 29 6c 90 a7 bd d9 16 03 03 00 0f 0d 00 |n8P)l...........| -00000300 00 0b 02 01 40 00 04 04 01 04 03 00 00 16 03 03 |....@...........| -00000310 00 04 0e 00 00 00 |......| ->>> Flow 3 (client to server) -00000000 16 03 03 01 fb 0b 00 01 f7 00 01 f4 00 01 f1 30 |...............0| -00000010 82 01 ed 30 82 01 58 a0 03 02 01 02 02 01 00 30 |...0..X........0| -00000020 0b 06 09 2a 86 48 86 f7 0d 01 01 05 30 26 31 10 |...*.H......0&1.| -00000030 30 0e 06 03 55 04 0a 13 07 41 63 6d 65 20 43 6f |0...U....Acme Co| -00000040 31 12 30 10 06 03 55 04 03 13 09 31 32 37 2e 30 |1.0...U....127.0| -00000050 2e 30 2e 31 30 1e 17 0d 31 31 31 32 30 38 30 37 |.0.10...11120807| -00000060 35 35 31 32 5a 17 0d 31 32 31 32 30 37 30 38 30 |5512Z..121207080| -00000070 30 31 32 5a 30 26 31 10 30 0e 06 03 55 04 0a 13 |012Z0&1.0...U...| -00000080 07 41 63 6d 65 20 43 6f 31 12 30 10 06 03 55 04 |.Acme Co1.0...U.| -00000090 03 13 09 31 32 37 2e 30 2e 30 2e 31 30 81 9c 30 |...127.0.0.10..0| -000000a0 0b 06 09 2a 86 48 86 f7 0d 01 01 01 03 81 8c 00 |...*.H..........| -000000b0 30 81 88 02 81 80 4e d0 7b 31 e3 82 64 d9 59 c0 |0.....N.{1..d.Y.| -000000c0 c2 87 a4 5e 1e 8b 73 33 c7 63 53 df 66 92 06 84 |...^..s3.cS.f...| -000000d0 f6 64 d5 8f e4 36 a7 1d 2b e8 b3 20 36 45 23 b5 |.d...6..+.. 6E#.| -000000e0 e3 95 ae ed e0 f5 20 9c 8d 95 df 7f 5a 12 ef 87 |...... .....Z...| -000000f0 e4 5b 68 e4 e9 0e 74 ec 04 8a 7f de 93 27 c4 01 |.[h...t......'..| -00000100 19 7a bd f2 dc 3d 14 ab d0 54 ca 21 0c d0 4d 6e |.z...=...T.!..Mn| -00000110 87 2e 5c c5 d2 bb 4d 4b 4f ce b6 2c f7 7e 88 ec |..\...MKO..,.~..| -00000120 7c d7 02 91 74 a6 1e 0c 1a da e3 4a 5a 2e de 13 ||...t......JZ...| -00000130 9c 4c 40 88 59 93 02 03 01 00 01 a3 32 30 30 30 |.L@.Y.......2000| -00000140 0e 06 03 55 1d 0f 01 01 ff 04 04 03 02 00 a0 30 |...U...........0| -00000150 0d 06 03 55 1d 0e 04 06 04 04 01 02 03 04 30 0f |...U..........0.| -00000160 06 03 55 1d 23 04 08 30 06 80 04 01 02 03 04 30 |..U.#..0.......0| -00000170 0b 06 09 2a 86 48 86 f7 0d 01 01 05 03 81 81 00 |...*.H..........| -00000180 36 1f b3 7a 0c 75 c9 6e 37 46 61 2b d5 bd c0 a7 |6..z.u.n7Fa+....| -00000190 4b cc 46 9a 81 58 7c 85 79 29 c8 c8 c6 67 dd 32 |K.F..X|.y)...g.2| -000001a0 56 45 2b 75 b6 e9 24 a9 50 9a be 1f 5a fa 1a 15 |VE+u..$.P...Z...| -000001b0 d9 cc 55 95 72 16 83 b9 c2 b6 8f fd 88 8c 38 84 |..U.r.........8.| -000001c0 1d ab 5d 92 31 13 4f fd 83 3b c6 9d f1 11 62 b6 |..].1.O..;....b.| -000001d0 8b ec ab 67 be c8 64 b0 11 50 46 58 17 6b 99 1c |...g..d..PFX.k..| -000001e0 d3 1d fc 06 f1 0e e5 96 a8 0c f9 78 20 b7 44 18 |...........x .D.| -000001f0 51 8d 10 7e 4f 94 67 df a3 4e 70 73 8e 90 91 85 |Q..~O.g..Nps....| -00000200 16 03 03 00 86 10 00 00 82 00 80 44 89 7d aa 26 |...........D.}.&| -00000210 30 ce 6b db 25 70 b0 1e 16 fa 5b 3a dd 4a 4b bd |0.k.%p....[:.JK.| -00000220 ec ee 50 9d 21 ba 52 b5 51 4f a8 65 d8 2e 41 e2 |..P.!.R.QO.e..A.| -00000230 e1 dc f3 1a df 58 4f 87 7a d3 e1 e1 1c 13 b2 0b |.....XO.z.......| -00000240 b7 43 b7 92 f2 df 19 bb 79 71 e0 71 44 ab 19 2f |.C......yq.qD../| -00000250 37 11 ac 62 50 b6 f1 53 fe aa b4 bc 29 8e 0b 4c |7..bP..S....)..L| -00000260 0b 12 8d d5 84 a9 fa a9 ea 16 aa c3 0d da 32 c8 |..............2.| -00000270 e0 4c 9f 99 f8 69 cd a8 c3 b1 76 42 67 f3 ff 15 |.L...i....vBg...| -00000280 52 95 43 66 da 49 43 25 9d e5 eb 16 03 03 00 88 |R.Cf.IC%........| -00000290 0f 00 00 84 04 01 00 80 01 d5 0e 1c 75 97 89 52 |............u..R| -000002a0 1a f0 cc ef 93 6e 71 b2 b1 38 8c 50 11 f7 a3 02 |.....nq..8.P....| -000002b0 71 c4 d5 6f 8d 01 83 06 2e ea 5a 10 8a 0d d0 fc |q..o......Z.....| -000002c0 b6 a2 63 af 4f 99 b5 eb ab fd 01 c2 fb 26 fc fd |..c.O........&..| -000002d0 ad 2c b3 63 b3 87 a6 f5 14 ea 7d e7 fe a8 e7 7e |.,.c......}....~| -000002e0 20 ab b9 f6 c3 58 bd c0 f3 96 eb 83 dc 42 6c 0d | ....X.......Bl.| -000002f0 5e e8 09 55 c7 b8 24 05 dd e1 7c af 9f 2c 22 6c |^..U..$...|..,"l| -00000300 fa b8 94 13 3b f1 09 e1 38 59 fc a1 8c cb aa ca |....;...8Y......| -00000310 f8 e0 2a 9c 36 f9 c3 2b 14 03 03 00 01 01 16 03 |..*.6..+........| -00000320 03 00 24 d0 12 7c cc d2 3e 37 1f f4 7d b4 c0 fc |..$..|..>7..}...| -00000330 19 f6 c8 ea 62 12 e0 0d af 62 d4 69 f7 96 5a c0 |....b....b.i..Z.| -00000340 97 d3 bb b0 a3 f7 3f |......?| ->>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 24 cd 20 85 1e 74 |..........$. ..t| -00000010 18 b2 71 48 d5 10 61 c6 b0 18 26 83 c2 7f f1 b1 |..qH..a...&.....| -00000020 2f b5 35 d0 47 a8 99 9a 9a a5 62 64 fb f9 29 17 |/.5.G.....bd..).| -00000030 03 03 00 21 22 7b ed 61 e3 9b 6d 98 b9 23 98 e3 |...!"{.a..m..#..| -00000040 55 11 b8 0f 7e 2b e1 c1 d4 f1 83 79 c3 f8 03 f0 |U...~+.....y....| -00000050 02 5c 61 24 d7 15 03 03 00 16 14 2b a3 5a 56 f0 |.\a$.......+.ZV.| -00000060 92 da d0 e6 32 91 d8 30 7a b4 d0 a2 93 f5 01 ea |....2..0z.......| diff --git a/src/pkg/crypto/tls/testdata/Server-TLSv12-ClientAuthRequestedNotGiven b/src/pkg/crypto/tls/testdata/Server-TLSv12-ClientAuthRequestedNotGiven deleted file mode 100644 index 562fe1aaa..000000000 --- a/src/pkg/crypto/tls/testdata/Server-TLSv12-ClientAuthRequestedNotGiven +++ /dev/null @@ -1,81 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 5c 01 00 00 58 03 03 52 cc 57 59 1b |....\...X..R.WY.| -00000010 08 fe f7 8a bf 07 84 2b 60 a6 13 2d 15 13 f8 b6 |.......+`..-....| -00000020 d4 b6 3b f2 7a 98 ff 32 a0 68 7c 00 00 04 00 05 |..;.z..2.h|.....| -00000030 00 ff 01 00 00 2b 00 0d 00 22 00 20 06 01 06 02 |.....+...". ....| -00000040 06 03 05 01 05 02 05 03 04 01 04 02 04 03 03 01 |................| -00000050 03 02 03 03 02 01 02 02 02 03 01 01 00 0f 00 01 |................| -00000060 01 |.| ->>> Flow 2 (server to client) -00000000 16 03 03 00 31 02 00 00 2d 03 03 00 00 00 00 00 |....1...-.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 05 00 00 |................| -00000030 05 ff 01 00 01 00 16 03 03 02 be 0b 00 02 ba 00 |................| -00000040 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000050 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000060 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000070 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -00000080 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -00000090 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000a0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000b0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000c0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000d0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -000000e0 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -000000f0 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000100 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000110 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000120 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000130 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000140 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000150 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000160 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000170 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -00000180 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -00000190 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001a0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001b0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001c0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001d0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -000001e0 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -000001f0 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000200 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000210 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000220 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000230 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000240 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000250 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000260 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000270 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -00000280 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -00000290 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002a0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002b0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002c0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002d0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -000002e0 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -000002f0 6e 38 50 29 6c 90 a7 bd d9 16 03 03 00 0f 0d 00 |n8P)l...........| -00000300 00 0b 02 01 40 00 04 04 01 04 03 00 00 16 03 03 |....@...........| -00000310 00 04 0e 00 00 00 |......| ->>> Flow 3 (client to server) -00000000 16 03 03 00 07 0b 00 00 03 00 00 00 16 03 03 00 |................| -00000010 86 10 00 00 82 00 80 6b 51 48 d3 18 7d 30 e0 0c |.......kQH..}0..| -00000020 20 8d f3 e4 39 47 30 0e a5 85 79 f9 8b 11 50 9e | ...9G0...y...P.| -00000030 81 71 5c 26 c6 bb cb aa d5 00 d1 89 79 b1 77 2d |.q\&........y.w-| -00000040 eb 9b 86 7c 52 c6 f7 b7 10 b0 b6 94 22 51 b8 12 |...|R......."Q..| -00000050 3c 09 35 8e 1b cc f4 3b b7 b8 78 ab 89 59 41 49 |<.5....;..x..YAI| -00000060 21 31 eb f0 f8 94 63 3d e6 96 8f b6 63 95 05 dd |!1....c=....c...| -00000070 46 b3 00 8a d6 83 75 99 1b 5a 48 0a 23 b5 10 c1 |F.....u..ZH.#...| -00000080 95 b5 bc 15 72 b5 f5 a0 62 e2 1d c0 ff d2 87 a5 |....r...b.......| -00000090 97 5c 33 49 a7 26 35 14 03 03 00 01 01 16 03 03 |.\3I.&5.........| -000000a0 00 24 61 38 1f 9d fb d9 65 2e 02 07 fb be f9 85 |.$a8....e.......| -000000b0 8d 15 34 c0 d1 0e 4e 10 3c 25 60 2f ac 04 21 66 |..4...N.<%`/..!f| -000000c0 04 9d 9a 60 31 72 |...`1r| ->>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 24 fe 0e 3e 84 af |..........$..>..| -00000010 e5 6b 10 ed 41 9c 2b e0 ba e0 2b 53 61 36 1b 40 |.k..A.+...+Sa6.@| -00000020 35 de 3a c7 c3 5c df 74 67 f7 05 74 84 f5 e1 17 |5.:..\.tg..t....| -00000030 03 03 00 21 d3 8d 81 85 b7 1f 30 bd 89 33 f9 81 |...!......0..3..| -00000040 89 f7 af d1 be b0 c1 46 e3 df 32 f6 dc 2f 4d 82 |.......F..2../M.| -00000050 0a 84 9f 5b 03 15 03 03 00 16 13 af 37 91 82 67 |...[........7..g| -00000060 b0 7c 5e 0e ec 8e cc 31 a0 ea a5 72 a4 2b 0b 73 |.|^....1...r.+.s| diff --git a/src/pkg/crypto/tls/testdata/Server-TLSv12-ECDHE-ECDSA-AES b/src/pkg/crypto/tls/testdata/Server-TLSv12-ECDHE-ECDSA-AES deleted file mode 100644 index aacbb8670..000000000 --- a/src/pkg/crypto/tls/testdata/Server-TLSv12-ECDHE-ECDSA-AES +++ /dev/null @@ -1,89 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 9c 01 00 00 98 03 03 53 04 f0 f9 09 |...........S....| -00000010 13 56 01 37 84 b1 32 59 4c 73 b1 8e bb 02 1a 32 |.V.7..2YLs.....2| -00000020 db ab 8c e6 ed ad 7f 52 9a 59 39 00 00 04 c0 0a |.......R.Y9.....| -00000030 00 ff 01 00 00 6b 00 0b 00 04 03 00 01 02 00 0a |.....k..........| -00000040 00 34 00 32 00 0e 00 0d 00 19 00 0b 00 0c 00 18 |.4.2............| -00000050 00 09 00 0a 00 16 00 17 00 08 00 06 00 07 00 14 |................| -00000060 00 15 00 04 00 05 00 12 00 13 00 01 00 02 00 03 |................| -00000070 00 0f 00 10 00 11 00 0d 00 22 00 20 06 01 06 02 |.........". ....| -00000080 06 03 05 01 05 02 05 03 04 01 04 02 04 03 03 01 |................| -00000090 03 02 03 03 02 01 02 02 02 03 01 01 00 0f 00 01 |................| -000000a0 01 |.| ->>> Flow 2 (server to client) -00000000 16 03 03 00 31 02 00 00 2d 03 03 00 00 00 00 00 |....1...-.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 c0 0a 00 00 |................| -00000030 05 ff 01 00 01 00 16 03 03 02 0e 0b 00 02 0a 00 |................| -00000040 02 07 00 02 04 30 82 02 00 30 82 01 62 02 09 00 |.....0...0..b...| -00000050 b8 bf 2d 47 a0 d2 eb f4 30 09 06 07 2a 86 48 ce |..-G....0...*.H.| -00000060 3d 04 01 30 45 31 0b 30 09 06 03 55 04 06 13 02 |=..0E1.0...U....| -00000070 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -00000080 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000090 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -000000a0 74 73 20 50 74 79 20 4c 74 64 30 1e 17 0d 31 32 |ts Pty Ltd0...12| -000000b0 31 31 32 32 31 35 30 36 33 32 5a 17 0d 32 32 31 |1122150632Z..221| -000000c0 31 32 30 31 35 30 36 33 32 5a 30 45 31 0b 30 09 |120150632Z0E1.0.| -000000d0 06 03 55 04 06 13 02 41 55 31 13 30 11 06 03 55 |..U....AU1.0...U| -000000e0 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 31 21 |....Some-State1!| -000000f0 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 6e 65 |0...U....Interne| -00000100 74 20 57 69 64 67 69 74 73 20 50 74 79 20 4c 74 |t Widgits Pty Lt| -00000110 64 30 81 9b 30 10 06 07 2a 86 48 ce 3d 02 01 06 |d0..0...*.H.=...| -00000120 05 2b 81 04 00 23 03 81 86 00 04 00 c4 a1 ed be |.+...#..........| -00000130 98 f9 0b 48 73 36 7e c3 16 56 11 22 f2 3d 53 c3 |...Hs6~..V.".=S.| -00000140 3b 4d 21 3d cd 6b 75 e6 f6 b0 dc 9a df 26 c1 bc |;M!=.ku......&..| -00000150 b2 87 f0 72 32 7c b3 64 2f 1c 90 bc ea 68 23 10 |...r2|.d/....h#.| -00000160 7e fe e3 25 c0 48 3a 69 e0 28 6d d3 37 00 ef 04 |~..%.H:i.(m.7...| -00000170 62 dd 0d a0 9c 70 62 83 d8 81 d3 64 31 aa 9e 97 |b....pb....d1...| -00000180 31 bd 96 b0 68 c0 9b 23 de 76 64 3f 1a 5c 7f e9 |1...h..#.vd?.\..| -00000190 12 0e 58 58 b6 5f 70 dd 9b d8 ea d5 d7 f5 d5 cc |..XX._p.........| -000001a0 b9 b6 9f 30 66 5b 66 9a 20 e2 27 e5 bf fe 3b 30 |...0f[f. .'...;0| -000001b0 09 06 07 2a 86 48 ce 3d 04 01 03 81 8c 00 30 81 |...*.H.=......0.| -000001c0 88 02 42 01 88 a2 4f eb e2 45 c5 48 7d 1b ac f5 |..B...O..E.H}...| -000001d0 ed 98 9d ae 47 70 c0 5e 1b b6 2f bd f1 b6 4d b7 |....Gp.^../...M.| -000001e0 61 40 d3 11 a2 ce ee 0b 7e 92 7e ff 76 9d c3 3b |a@......~.~.v..;| -000001f0 7e a5 3f ce fa 10 e2 59 ec 47 2d 7c ac da 4e 97 |~.?....Y.G-|..N.| -00000200 0e 15 a0 6f d0 02 42 01 4d fc be 67 13 9c 2d 05 |...o..B.M..g..-.| -00000210 0e bd 3f a3 8c 25 c1 33 13 83 0d 94 06 bb d4 37 |..?..%.3.......7| -00000220 7a f6 ec 7a c9 86 2e dd d7 11 69 7f 85 7c 56 de |z..z......i..|V.| -00000230 fb 31 78 2b e4 c7 78 0d ae cb be 9e 4e 36 24 31 |.1x+..x.....N6$1| -00000240 7b 6a 0f 39 95 12 07 8f 2a 16 03 03 00 d8 0c 00 |{j.9....*.......| -00000250 00 d4 03 00 17 41 04 1e 18 37 ef 0d 19 51 88 35 |.....A...7...Q.5| -00000260 75 71 b5 e5 54 5b 12 2e 8f 09 67 fd a7 24 20 3e |uq..T[....g..$ >| -00000270 b2 56 1c ce 97 28 5e f8 2b 2d 4f 9e f1 07 9f 6c |.V...(^.+-O....l| -00000280 4b 5b 83 56 e2 32 42 e9 58 b6 d7 49 a6 b5 68 1a |K[.V.2B.X..I..h.| -00000290 41 03 56 6b dc 5a 89 04 03 00 8b 30 81 88 02 42 |A.Vk.Z.....0...B| -000002a0 00 c6 85 8e 06 b7 04 04 e9 cd 9e 3e cb 66 23 95 |...........>.f#.| -000002b0 b4 42 9c 64 81 39 05 3f b5 21 f8 28 af 60 6b 4d |.B.d.9.?.!.(.`kM| -000002c0 3d ba a1 4b 5e 77 ef e7 59 28 fe 1d c1 27 a2 ff |=..K^w..Y(...'..| -000002d0 a8 de 33 48 b3 c1 85 6a 42 9b f9 7e 7e 31 c2 e5 |..3H...jB..~~1..| -000002e0 bd 66 02 42 00 ad 7d 06 35 ab ec 8d ac d4 ba 1b |.f.B..}.5.......| -000002f0 49 5e 05 5f f0 97 93 82 b8 2b 8d 91 98 63 8e b4 |I^._.....+...c..| -00000300 14 62 db 1e c9 2c 13 ae b7 d3 17 38 23 2f f6 7f |.b...,.....8#/..| -00000310 0c 4d d3 33 d2 79 d1 77 ee cb b1 c2 fc 34 b8 69 |.M.3.y.w.....4.i| -00000320 f9 10 8b 61 89 85 16 03 03 00 04 0e 00 00 00 |...a...........| ->>> Flow 3 (client to server) -00000000 16 03 03 00 46 10 00 00 42 41 04 dd 22 68 a1 4e |....F...BA.."h.N| -00000010 04 1b 47 f9 c5 7d 04 1d d8 fe 84 fa be 31 2e a7 |..G..}.......1..| -00000020 f8 e5 b8 14 92 44 99 11 0e 34 97 fc e5 b1 91 cf |.....D...4......| -00000030 a4 d1 3f b4 71 94 c6 06 16 f0 98 c0 3e 05 f9 2f |..?.q.......>../| -00000040 0a 97 78 3d ef dc fa a2 d7 ee 7d 14 03 03 00 01 |..x=......}.....| -00000050 01 16 03 03 00 40 90 bf 7f e9 c9 6e d1 80 f5 12 |.....@.....n....| -00000060 6d c5 b7 c5 15 4b 18 a5 d3 18 1e f8 8c 4d 7e 6d |m....K.......M~m| -00000070 03 60 29 7c 45 7c b2 ca 8c 07 71 70 aa 23 fa 6e |.`)|E|....qp.#.n| -00000080 d9 0b 0a 32 4c 9e e5 00 f9 19 9b b6 8d dc d3 67 |...2L..........g| -00000090 3d 0f bb b8 4b 9e |=...K.| ->>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 40 00 00 00 00 00 |..........@.....| -00000010 00 00 00 00 00 00 00 00 00 00 00 a1 6e e5 d1 ca |............n...| -00000020 03 f4 77 dc ec ee 5d f0 22 5e 7f 55 1a 8d ad 45 |..w...]."^.U...E| -00000030 09 f1 3b b2 61 36 dc 3d 2a 1e 1f e5 a7 84 76 a9 |..;.a6.=*.....v.| -00000040 41 5b 86 03 ac 22 18 20 9b a9 29 17 03 03 00 40 |A[...". ..)....@| -00000050 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000060 f5 cb 28 1e b5 bc 82 7f 82 38 54 14 e8 b9 6d 3b |..(......8T...m;| -00000070 bc 99 d6 0e f9 00 96 99 a8 92 2e 86 9d 62 4e 90 |.............bN.| -00000080 27 52 58 45 20 93 90 a1 f3 a8 89 2b e7 21 24 16 |'RXE ......+.!$.| -00000090 15 03 03 00 30 00 00 00 00 00 00 00 00 00 00 00 |....0...........| -000000a0 00 00 00 00 00 a8 2a ab 8f b0 ce 49 8b fd a5 c9 |......*....I....| -000000b0 11 b2 04 83 18 f3 1d 6c 82 34 1d df dd 2f 45 3b |.......l.4.../E;| -000000c0 27 8a 0f 16 69 |'...i| diff --git a/src/pkg/crypto/tls/testdata/Server-TLSv12-IssueTicket b/src/pkg/crypto/tls/testdata/Server-TLSv12-IssueTicket deleted file mode 100644 index e3e62f224..000000000 --- a/src/pkg/crypto/tls/testdata/Server-TLSv12-IssueTicket +++ /dev/null @@ -1,87 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 60 01 00 00 5c 03 03 52 cc 57 59 7e |....`...\..R.WY~| -00000010 43 5c 3b fd 50 ab 61 3f 64 a4 f9 bd ba 8c 28 e1 |C\;.P.a?d.....(.| -00000020 f9 a1 45 7e 48 9e 62 af 25 de 0e 00 00 04 00 05 |..E~H.b.%.......| -00000030 00 ff 01 00 00 2f 00 23 00 00 00 0d 00 22 00 20 |...../.#.....". | -00000040 06 01 06 02 06 03 05 01 05 02 05 03 04 01 04 02 |................| -00000050 04 03 03 01 03 02 03 03 02 01 02 02 02 03 01 01 |................| -00000060 00 0f 00 01 01 |.....| ->>> Flow 2 (server to client) -00000000 16 03 03 00 35 02 00 00 31 03 03 00 00 00 00 00 |....5...1.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 05 00 00 |................| -00000030 09 00 23 00 00 ff 01 00 01 00 16 03 03 02 be 0b |..#.............| -00000040 00 02 ba 00 02 b7 00 02 b4 30 82 02 b0 30 82 02 |.........0...0..| -00000050 19 a0 03 02 01 02 02 09 00 85 b0 bb a4 8a 7f b8 |................| -00000060 ca 30 0d 06 09 2a 86 48 86 f7 0d 01 01 05 05 00 |.0...*.H........| -00000070 30 45 31 0b 30 09 06 03 55 04 06 13 02 41 55 31 |0E1.0...U....AU1| -00000080 13 30 11 06 03 55 04 08 13 0a 53 6f 6d 65 2d 53 |.0...U....Some-S| -00000090 74 61 74 65 31 21 30 1f 06 03 55 04 0a 13 18 49 |tate1!0...U....I| -000000a0 6e 74 65 72 6e 65 74 20 57 69 64 67 69 74 73 20 |nternet Widgits | -000000b0 50 74 79 20 4c 74 64 30 1e 17 0d 31 30 30 34 32 |Pty Ltd0...10042| -000000c0 34 30 39 30 39 33 38 5a 17 0d 31 31 30 34 32 34 |4090938Z..110424| -000000d0 30 39 30 39 33 38 5a 30 45 31 0b 30 09 06 03 55 |090938Z0E1.0...U| -000000e0 04 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 |....AU1.0...U...| -000000f0 0a 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 |.Some-State1!0..| -00000100 03 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 |.U....Internet W| -00000110 69 64 67 69 74 73 20 50 74 79 20 4c 74 64 30 81 |idgits Pty Ltd0.| -00000120 9f 30 0d 06 09 2a 86 48 86 f7 0d 01 01 01 05 00 |.0...*.H........| -00000130 03 81 8d 00 30 81 89 02 81 81 00 bb 79 d6 f5 17 |....0.......y...| -00000140 b5 e5 bf 46 10 d0 dc 69 be e6 2b 07 43 5a d0 03 |...F...i..+.CZ..| -00000150 2d 8a 7a 43 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 |-.zC...R..eL,x.#| -00000160 8c b5 b4 82 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 |........;~b.,.3.| -00000170 fe 12 5c 7a 56 fc f5 06 bf fa 58 7b 26 3f b5 cd |..\zV.....X{&?..| -00000180 04 d3 d0 c9 21 96 4a c7 f4 54 9f 5a bf ef 42 71 |....!.J..T.Z..Bq| -00000190 00 fe 18 99 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e |......~.}}..9...| -000001a0 db 51 c9 7c e3 c0 4c 3b 32 66 01 cf af b1 1d b8 |.Q.|..L;2f......| -000001b0 71 9a 1d db db 89 6b ae da 2d 79 02 03 01 00 01 |q.....k..-y.....| -000001c0 a3 81 a7 30 81 a4 30 1d 06 03 55 1d 0e 04 16 04 |...0..0...U.....| -000001d0 14 b1 ad e2 85 5a cf cb 28 db 69 ce 23 69 de d3 |.....Z..(.i.#i..| -000001e0 26 8e 18 88 39 30 75 06 03 55 1d 23 04 6e 30 6c |&...90u..U.#.n0l| -000001f0 80 14 b1 ad e2 85 5a cf cb 28 db 69 ce 23 69 de |......Z..(.i.#i.| -00000200 d3 26 8e 18 88 39 a1 49 a4 47 30 45 31 0b 30 09 |.&...9.I.G0E1.0.| -00000210 06 03 55 04 06 13 02 41 55 31 13 30 11 06 03 55 |..U....AU1.0...U| -00000220 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 31 21 |....Some-State1!| -00000230 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 6e 65 |0...U....Interne| -00000240 74 20 57 69 64 67 69 74 73 20 50 74 79 20 4c 74 |t Widgits Pty Lt| -00000250 64 82 09 00 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 |d...........0...| -00000260 55 1d 13 04 05 30 03 01 01 ff 30 0d 06 09 2a 86 |U....0....0...*.| -00000270 48 86 f7 0d 01 01 05 05 00 03 81 81 00 08 6c 45 |H.............lE| -00000280 24 c7 6b b1 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a |$.k.Y..R.......z| -00000290 64 75 b5 5a 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f |du.Z.f..+...f..O| -000002a0 38 b3 6e 60 d3 92 fd f7 41 08 b5 25 13 b1 18 7a |8.n`....A..%...z| -000002b0 24 fb 30 1d ba ed 98 b9 17 ec e7 d7 31 59 db 95 |$.0.........1Y..| -000002c0 d3 1d 78 ea 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 |..x.PV\..Z-Z_3..| -000002d0 d8 c9 75 90 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f |..u....R...... _| -000002e0 f2 a0 1c a3 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d |..........W.p.&m| -000002f0 71 99 9b 26 6e 38 50 29 6c 90 a7 bd d9 16 03 03 |q..&n8P)l.......| -00000300 00 04 0e 00 00 00 |......| ->>> Flow 3 (client to server) -00000000 16 03 03 00 86 10 00 00 82 00 80 6e 2e 79 82 3a |...........n.y.:| -00000010 c4 68 72 f5 a2 42 3d 71 f9 ec 22 8c 0b fa f0 82 |.hr..B=q..".....| -00000020 82 c0 cb fc 52 0a 51 03 04 8c eb 4a 4e 4f b6 49 |....R.Q....JNO.I| -00000030 ef 94 65 21 3c f7 9d 46 85 6e 35 d5 17 6b ff a3 |..e!<..F.n5..k..| -00000040 5e 4d c1 36 1a 2f 68 f5 06 d4 2d 73 4f 1c 3b 7b |^M.6./h...-sO.;{| -00000050 c1 fa 4e 7e 7c f9 6c 13 a6 f4 3a 43 e9 aa be 22 |..N~|.l...:C..."| -00000060 85 6f 2f 7c 5b b0 08 e2 86 b2 ae cb a9 12 d8 32 |.o/|[..........2| -00000070 80 1d e4 2e 5d c3 66 d1 19 e5 89 33 2a 88 24 40 |....].f....3*.$@| -00000080 2a 6d 6b b5 f1 92 4b 66 06 b8 49 14 03 03 00 01 |*mk...Kf..I.....| -00000090 01 16 03 03 00 24 16 49 e2 a0 67 31 cf 0d 72 cb |.....$.I..g1..r.| -000000a0 ac 16 2c 80 37 71 69 f7 5f c4 d3 00 19 b7 4b fb |..,.7qi._.....K.| -000000b0 e5 e9 74 8e 30 b3 1c c5 ae e6 |..t.0.....| ->>> Flow 4 (server to client) -00000000 16 03 03 00 72 04 00 00 6e 00 00 00 00 00 68 00 |....r...n.....h.| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 65 |...............e| -00000020 ea 4b d1 ef ba 06 38 1e e1 88 82 3a cd 03 ac 3b |.K....8....:...;| -00000030 39 0a e0 19 fd af 6c 57 30 df 31 6e f7 92 38 4b |9.....lW0.1n..8K| -00000040 5d 77 90 39 ff 32 51 f5 ed 12 d7 b0 7c 4d 6c c5 |]w.9.2Q.....|Ml.| -00000050 76 e4 72 48 3e 59 23 fe 0d 15 df f4 ba ea b9 67 |v.rH>Y#........g| -00000060 16 23 8f 7d 15 b6 11 f1 ab d7 d4 cd a3 21 82 92 |.#.}.........!..| -00000070 2a 12 cf 95 f3 60 b2 14 03 03 00 01 01 16 03 03 |*....`..........| -00000080 00 24 89 ad 87 04 4f 08 dc 2a 71 37 fb f1 95 d1 |.$....O..*q7....| -00000090 2e 3c c2 6e 0f 38 5d e4 0e c3 f7 27 d0 46 a3 c1 |.<.n.8]....'.F..| -000000a0 a8 3b 06 ed 96 ec 17 03 03 00 21 30 d4 9f 0b 49 |.;........!0...I| -000000b0 9f a2 a8 a1 2c 0a 79 93 56 2d 8a ee 85 ed 62 42 |....,.y.V-....bB| -000000c0 8c 18 fe 7a 09 3a 24 c4 5e ed 7d 2a 15 03 03 00 |...z.:$.^.}*....| -000000d0 16 a0 24 0a 8b 90 4c fc 99 ba 67 bb 04 1e 59 69 |..$...L...g...Yi| -000000e0 c2 98 49 b5 00 0b e0 |..I....| diff --git a/src/pkg/crypto/tls/testdata/Server-TLSv12-RSA-3DES b/src/pkg/crypto/tls/testdata/Server-TLSv12-RSA-3DES deleted file mode 100644 index 5995b3314..000000000 --- a/src/pkg/crypto/tls/testdata/Server-TLSv12-RSA-3DES +++ /dev/null @@ -1,83 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 5c 01 00 00 58 03 03 52 cc 57 59 68 |....\...X..R.WYh| -00000010 11 72 a6 ec 6b 0a 47 1d 10 06 ec 75 af 07 38 a0 |.r..k.G....u..8.| -00000020 30 9e 91 12 e1 9b 19 46 0d d4 45 00 00 04 00 0a |0......F..E.....| -00000030 00 ff 01 00 00 2b 00 0d 00 22 00 20 06 01 06 02 |.....+...". ....| -00000040 06 03 05 01 05 02 05 03 04 01 04 02 04 03 03 01 |................| -00000050 03 02 03 03 02 01 02 02 02 03 01 01 00 0f 00 01 |................| -00000060 01 |.| ->>> Flow 2 (server to client) -00000000 16 03 03 00 31 02 00 00 2d 03 03 00 00 00 00 00 |....1...-.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 0a 00 00 |................| -00000030 05 ff 01 00 01 00 16 03 03 02 be 0b 00 02 ba 00 |................| -00000040 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000050 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000060 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000070 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -00000080 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -00000090 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000a0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000b0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000c0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000d0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -000000e0 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -000000f0 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000100 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000110 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000120 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000130 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000140 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000150 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000160 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000170 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -00000180 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -00000190 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001a0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001b0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001c0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001d0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -000001e0 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -000001f0 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000200 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000210 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000220 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000230 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000240 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000250 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000260 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000270 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -00000280 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -00000290 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002a0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002b0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002c0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002d0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -000002e0 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -000002f0 6e 38 50 29 6c 90 a7 bd d9 16 03 03 00 04 0e 00 |n8P)l...........| -00000300 00 00 |..| ->>> Flow 3 (client to server) -00000000 16 03 03 00 86 10 00 00 82 00 80 7a c0 73 ec cb |...........z.s..| -00000010 cf c2 a8 86 c0 7e 03 63 57 a1 ce 42 37 6d 78 54 |.....~.cW..B7mxT| -00000020 29 f5 3e cc 57 c7 0d d9 69 e1 52 5c 3b 6b c4 c7 |).>.W...i.R\;k..| -00000030 20 6d 59 ee c0 07 81 74 74 9f 62 41 64 f0 4d c8 | mY....tt.bAd.M.| -00000040 9b aa 1a b9 da 56 07 f5 6c 1c 59 8c d3 f9 08 d9 |.....V..l.Y.....| -00000050 08 f4 16 93 5d 9a e5 6f fb 9f ba 3d 3c d6 81 ad |....]..o...=<...| -00000060 02 12 a7 28 b6 81 6a 77 c3 e9 d7 c7 54 d6 77 83 |...(..jw....T.w.| -00000070 77 de 71 fb b3 f3 2d c4 a5 b1 e5 de aa 0e 21 bd |w.q...-.......!.| -00000080 91 a2 dc 7f f7 6f 90 82 54 b1 e7 14 03 03 00 01 |.....o..T.......| -00000090 01 16 03 03 00 30 8f ee bf fb c8 5c 54 f5 29 23 |.....0.....\T.)#| -000000a0 d4 55 f6 98 a1 6e d5 43 e7 81 b2 36 f2 98 d8 1b |.U...n.C...6....| -000000b0 0d 76 cb 14 ba 32 d7 36 30 e6 ab 42 80 95 f6 8a |.v...2.60..B....| -000000c0 60 64 a0 6b 90 81 |`d.k..| ->>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 30 00 00 00 00 00 |..........0.....| -00000010 00 00 00 2c 21 52 34 63 ac e3 a3 66 45 00 41 0c |...,!R4c...fE.A.| -00000020 93 5d 6a 74 5a 25 dc 69 1d 76 73 0c f4 42 6a 18 |.]jtZ%.i.vs..Bj.| -00000030 5b 62 23 e7 fe 41 cf d4 9b 86 35 17 03 03 00 30 |[b#..A....5....0| -00000040 00 00 00 00 00 00 00 00 7d 5d ce 43 85 5c 6b 89 |........}].C.\k.| -00000050 c9 a5 0e 22 69 8e b9 4a 77 4c c0 4e cc 79 d9 7e |..."i..JwL.N.y.~| -00000060 a3 c8 d3 db 5c 53 f8 92 4d c4 5a 88 72 58 05 11 |....\S..M.Z.rX..| -00000070 15 03 03 00 20 00 00 00 00 00 00 00 00 1d 63 8b |.... .........c.| -00000080 a7 74 fb 76 1d 47 31 93 1f ec 8c e2 18 8e 21 dd |.t.v.G1.......!.| -00000090 87 97 9f 1c ca |.....| diff --git a/src/pkg/crypto/tls/testdata/Server-TLSv12-RSA-AES b/src/pkg/crypto/tls/testdata/Server-TLSv12-RSA-AES deleted file mode 100644 index a152a96a8..000000000 --- a/src/pkg/crypto/tls/testdata/Server-TLSv12-RSA-AES +++ /dev/null @@ -1,87 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 5c 01 00 00 58 03 03 52 cc 57 59 d0 |....\...X..R.WY.| -00000010 38 05 36 7e e3 1e 93 2a 5a bf dc c2 f8 0a 03 6f |8.6~...*Z......o| -00000020 1a fc 21 74 e5 8b 2a c3 9e 2c 26 00 00 04 00 2f |..!t..*..,&..../| -00000030 00 ff 01 00 00 2b 00 0d 00 22 00 20 06 01 06 02 |.....+...". ....| -00000040 06 03 05 01 05 02 05 03 04 01 04 02 04 03 03 01 |................| -00000050 03 02 03 03 02 01 02 02 02 03 01 01 00 0f 00 01 |................| -00000060 01 |.| ->>> Flow 2 (server to client) -00000000 16 03 03 00 31 02 00 00 2d 03 03 00 00 00 00 00 |....1...-.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 2f 00 00 |............./..| -00000030 05 ff 01 00 01 00 16 03 03 02 be 0b 00 02 ba 00 |................| -00000040 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000050 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000060 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000070 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -00000080 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -00000090 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000a0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000b0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000c0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000d0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -000000e0 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -000000f0 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000100 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000110 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000120 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000130 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000140 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000150 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000160 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000170 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -00000180 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -00000190 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001a0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001b0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001c0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001d0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -000001e0 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -000001f0 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000200 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000210 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000220 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000230 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000240 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000250 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000260 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000270 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -00000280 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -00000290 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002a0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002b0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002c0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002d0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -000002e0 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -000002f0 6e 38 50 29 6c 90 a7 bd d9 16 03 03 00 04 0e 00 |n8P)l...........| -00000300 00 00 |..| ->>> Flow 3 (client to server) -00000000 16 03 03 00 86 10 00 00 82 00 80 4b b4 28 bc 78 |...........K.(.x| -00000010 41 34 f3 49 e8 74 07 74 42 ae 2e 55 9e 9a ce e5 |A4.I.t.tB..U....| -00000020 4a 1b e7 55 c7 64 c4 9c b3 dd 20 d6 f8 8e 67 b3 |J..U.d.... ...g.| -00000030 7a 5c 3b 34 e4 1a f6 bd 65 fc 21 cd 9a de 64 77 |z\;4....e.!...dw| -00000040 09 a5 92 e5 a4 f5 18 7b 23 5b 8b c1 95 23 97 6f |.......{#[...#.o| -00000050 76 55 04 34 22 7d 43 71 db cd eb f8 36 36 44 4b |vU.4"}Cq....66DK| -00000060 ae e3 cc ec 64 88 7b e1 ea d6 ab 49 35 94 a5 04 |....d.{....I5...| -00000070 1e 83 c5 cf 21 bb ca 33 5f d4 bf 1d d3 4d 07 59 |....!..3_....M.Y| -00000080 b4 39 b2 4b 7b 05 43 70 0d ba 7a 14 03 03 00 01 |.9.K{.Cp..z.....| -00000090 01 16 03 03 00 40 74 4b 7d b2 53 49 ea 86 90 c3 |.....@tK}.SI....| -000000a0 64 6b 64 31 1a 2a 3f 1a 37 1e 56 b8 dd 12 6d 56 |dkd1.*?.7.V...mV| -000000b0 2a 61 92 5b 39 e7 e1 be 71 70 4b 9b b3 f0 71 e7 |*a.[9...qpK...q.| -000000c0 47 2e 2e 17 c3 0a 66 9f 69 74 30 2d f0 a0 7f 84 |G.....f.it0-....| -000000d0 25 db c1 81 ee cf |%.....| ->>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 40 00 00 00 00 00 |..........@.....| -00000010 00 00 00 00 00 00 00 00 00 00 00 f3 4d 5a fc 21 |............MZ.!| -00000020 30 b5 a1 86 9d e2 ea 38 ac 54 57 fa 5a 54 97 b8 |0......8.TW.ZT..| -00000030 bb 4d 64 09 ef ce a1 75 0c 50 8d ff 5c c2 e9 47 |.Md....u.P..\..G| -00000040 95 93 53 c0 bd dc c5 9c e0 59 17 17 03 03 00 40 |..S......Y.....@| -00000050 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000060 69 c5 48 6e 45 cf 98 1b 2c 23 40 d1 ab a3 c2 e2 |i.HnE...,#@.....| -00000070 10 7b b1 c8 21 3c f0 eb 96 bd 4f 78 b2 4a 7b 18 |.{..!<....Ox.J{.| -00000080 4c b1 a6 67 bf 06 40 01 d0 8d 91 be 17 d8 0c 71 |L..g..@........q| -00000090 15 03 03 00 30 00 00 00 00 00 00 00 00 00 00 00 |....0...........| -000000a0 00 00 00 00 00 20 84 80 3d 70 fe ae ee d7 2f e9 |..... ..=p..../.| -000000b0 bf 65 30 bf 0b dd 98 ea bb ba 12 14 98 53 7f d5 |.e0..........S..| -000000c0 56 ce 06 3c d0 |V..<.| diff --git a/src/pkg/crypto/tls/testdata/Server-TLSv12-RSA-AES-GCM b/src/pkg/crypto/tls/testdata/Server-TLSv12-RSA-AES-GCM deleted file mode 100644 index 0ddfe022f..000000000 --- a/src/pkg/crypto/tls/testdata/Server-TLSv12-RSA-AES-GCM +++ /dev/null @@ -1,93 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 9c 01 00 00 98 03 03 53 04 f1 30 73 |...........S..0s| -00000010 a1 ea 8c d2 90 1c c6 d6 0d 3c af 58 21 65 90 25 |.........<.X!e.%| -00000020 5e fa f4 27 22 65 c9 68 90 b9 04 00 00 04 c0 2f |^..'"e.h......./| -00000030 00 ff 01 00 00 6b 00 0b 00 04 03 00 01 02 00 0a |.....k..........| -00000040 00 34 00 32 00 0e 00 0d 00 19 00 0b 00 0c 00 18 |.4.2............| -00000050 00 09 00 0a 00 16 00 17 00 08 00 06 00 07 00 14 |................| -00000060 00 15 00 04 00 05 00 12 00 13 00 01 00 02 00 03 |................| -00000070 00 0f 00 10 00 11 00 0d 00 22 00 20 06 01 06 02 |.........". ....| -00000080 06 03 05 01 05 02 05 03 04 01 04 02 04 03 03 01 |................| -00000090 03 02 03 03 02 01 02 02 02 03 01 01 00 0f 00 01 |................| -000000a0 01 |.| ->>> Flow 2 (server to client) -00000000 16 03 03 00 31 02 00 00 2d 03 03 00 00 00 00 00 |....1...-.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 c0 2f 00 00 |............./..| -00000030 05 ff 01 00 01 00 16 03 03 02 be 0b 00 02 ba 00 |................| -00000040 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000050 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000060 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000070 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -00000080 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -00000090 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000a0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000b0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000c0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000d0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -000000e0 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -000000f0 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000100 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000110 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000120 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000130 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000140 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000150 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000160 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000170 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -00000180 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -00000190 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001a0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001b0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001c0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001d0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -000001e0 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -000001f0 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000200 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000210 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000220 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000230 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000240 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000250 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000260 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000270 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -00000280 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -00000290 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002a0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002b0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002c0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002d0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -000002e0 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -000002f0 6e 38 50 29 6c 90 a7 bd d9 16 03 03 00 cd 0c 00 |n8P)l...........| -00000300 00 c9 03 00 17 41 04 1e 18 37 ef 0d 19 51 88 35 |.....A...7...Q.5| -00000310 75 71 b5 e5 54 5b 12 2e 8f 09 67 fd a7 24 20 3e |uq..T[....g..$ >| -00000320 b2 56 1c ce 97 28 5e f8 2b 2d 4f 9e f1 07 9f 6c |.V...(^.+-O....l| -00000330 4b 5b 83 56 e2 32 42 e9 58 b6 d7 49 a6 b5 68 1a |K[.V.2B.X..I..h.| -00000340 41 03 56 6b dc 5a 89 04 01 00 80 a2 54 61 84 29 |A.Vk.Z......Ta.)| -00000350 3e 97 4b 97 9a 9f 5c c0 49 6d 86 d2 79 8e 95 a1 |>.K...\.Im..y...| -00000360 0a 5a 36 73 34 bb 05 73 35 47 e1 2b 5d f3 ef 36 |.Z6s4..s5G.+]..6| -00000370 a8 32 e2 7e ef aa 3f 1f b3 64 60 d4 06 2e 98 e3 |.2.~..?..d`.....| -00000380 11 e2 60 3c d6 20 17 63 b2 6f a0 cd 21 01 2b 4e |..`<. .c.o..!.+N| -00000390 b2 a8 55 04 39 37 5c 6c 71 66 4d a3 eb 1b 83 67 |..U.97\lqfM....g| -000003a0 6b 15 a0 56 9a f1 a2 79 92 29 ce 58 3c 10 4d 65 |k..V...y.).X<.Me| -000003b0 1f 22 e3 ea d8 74 aa 01 7e ca f3 89 23 41 4d bd |."...t..~...#AM.| -000003c0 df 77 4e 59 54 97 74 ad 07 ea c0 16 03 03 00 04 |.wNYT.t.........| -000003d0 0e 00 00 00 |....| ->>> Flow 3 (client to server) -00000000 16 03 03 00 46 10 00 00 42 41 04 45 65 ce f7 b9 |....F...BA.Ee...| -00000010 52 e3 fb 13 db 91 f2 65 43 84 57 f5 1a 19 a0 e6 |R......eC.W.....| -00000020 89 2d bb 2c 83 6b 62 f6 6f 1f 26 ae 59 67 bd dc |.-.,.kb.o.&.Yg..| -00000030 c4 9e 0b dc 7d 6e f8 6b 95 8c 61 47 3d cd d1 df |....}n.k..aG=...| -00000040 82 45 30 81 c3 a3 49 5d 85 59 70 14 03 03 00 01 |.E0...I].Yp.....| -00000050 01 16 03 03 00 28 3f aa 85 33 f9 c6 95 a0 56 ff |.....(?..3....V.| -00000060 1c f1 5a ba 6e 41 50 0c ab 92 e1 e2 8e 89 1c f1 |..Z.nAP.........| -00000070 fa 54 1b f1 f5 00 01 12 6d c4 96 78 b6 87 |.T......m..x..| ->>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 28 00 00 00 00 00 |..........(.....| -00000010 00 00 00 94 5c be 46 05 d6 d0 b0 3a 56 dc 2c 10 |....\.F....:V.,.| -00000020 0f 6f 5d 33 33 7f a5 4e 74 84 bf 63 87 c4 f4 49 |.o]33..Nt..c...I| -00000030 bc 6b ab 17 03 03 00 25 00 00 00 00 00 00 00 01 |.k.....%........| -00000040 7e 4f f9 ae ae fe 6b a0 4a f8 0f 0b b4 b6 65 b6 |~O....k.J.....e.| -00000050 be 24 5f 94 6d d1 db 54 11 07 b9 ce 01 15 03 03 |.$_.m..T........| -00000060 00 1a 00 00 00 00 00 00 00 02 a8 1c d6 62 ac fd |.............b..| -00000070 77 ba 23 92 5d 34 f1 17 c7 e1 1c 99 |w.#.]4......| diff --git a/src/pkg/crypto/tls/testdata/Server-TLSv12-RSA-RC4 b/src/pkg/crypto/tls/testdata/Server-TLSv12-RSA-RC4 deleted file mode 100644 index b703a8f76..000000000 --- a/src/pkg/crypto/tls/testdata/Server-TLSv12-RSA-RC4 +++ /dev/null @@ -1,79 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 5c 01 00 00 58 03 03 52 cc 57 59 c9 |....\...X..R.WY.| -00000010 c3 13 fc 18 8a ee c2 0e 88 ff fb 4a 16 f2 eb eb |...........J....| -00000020 d4 f8 b3 5b cd bb 25 0e 0b cb 48 00 00 04 00 05 |...[..%...H.....| -00000030 00 ff 01 00 00 2b 00 0d 00 22 00 20 06 01 06 02 |.....+...". ....| -00000040 06 03 05 01 05 02 05 03 04 01 04 02 04 03 03 01 |................| -00000050 03 02 03 03 02 01 02 02 02 03 01 01 00 0f 00 01 |................| -00000060 01 |.| ->>> Flow 2 (server to client) -00000000 16 03 03 00 31 02 00 00 2d 03 03 00 00 00 00 00 |....1...-.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 05 00 00 |................| -00000030 05 ff 01 00 01 00 16 03 03 02 be 0b 00 02 ba 00 |................| -00000040 02 b7 00 02 b4 30 82 02 b0 30 82 02 19 a0 03 02 |.....0...0......| -00000050 01 02 02 09 00 85 b0 bb a4 8a 7f b8 ca 30 0d 06 |.............0..| -00000060 09 2a 86 48 86 f7 0d 01 01 05 05 00 30 45 31 0b |.*.H........0E1.| -00000070 30 09 06 03 55 04 06 13 02 41 55 31 13 30 11 06 |0...U....AU1.0..| -00000080 03 55 04 08 13 0a 53 6f 6d 65 2d 53 74 61 74 65 |.U....Some-State| -00000090 31 21 30 1f 06 03 55 04 0a 13 18 49 6e 74 65 72 |1!0...U....Inter| -000000a0 6e 65 74 20 57 69 64 67 69 74 73 20 50 74 79 20 |net Widgits Pty | -000000b0 4c 74 64 30 1e 17 0d 31 30 30 34 32 34 30 39 30 |Ltd0...100424090| -000000c0 39 33 38 5a 17 0d 31 31 30 34 32 34 30 39 30 39 |938Z..1104240909| -000000d0 33 38 5a 30 45 31 0b 30 09 06 03 55 04 06 13 02 |38Z0E1.0...U....| -000000e0 41 55 31 13 30 11 06 03 55 04 08 13 0a 53 6f 6d |AU1.0...U....Som| -000000f0 65 2d 53 74 61 74 65 31 21 30 1f 06 03 55 04 0a |e-State1!0...U..| -00000100 13 18 49 6e 74 65 72 6e 65 74 20 57 69 64 67 69 |..Internet Widgi| -00000110 74 73 20 50 74 79 20 4c 74 64 30 81 9f 30 0d 06 |ts Pty Ltd0..0..| -00000120 09 2a 86 48 86 f7 0d 01 01 01 05 00 03 81 8d 00 |.*.H............| -00000130 30 81 89 02 81 81 00 bb 79 d6 f5 17 b5 e5 bf 46 |0.......y......F| -00000140 10 d0 dc 69 be e6 2b 07 43 5a d0 03 2d 8a 7a 43 |...i..+.CZ..-.zC| -00000150 85 b7 14 52 e7 a5 65 4c 2c 78 b8 23 8c b5 b4 82 |...R..eL,x.#....| -00000160 e5 de 1f 95 3b 7e 62 a5 2c a5 33 d6 fe 12 5c 7a |....;~b.,.3...\z| -00000170 56 fc f5 06 bf fa 58 7b 26 3f b5 cd 04 d3 d0 c9 |V.....X{&?......| -00000180 21 96 4a c7 f4 54 9f 5a bf ef 42 71 00 fe 18 99 |!.J..T.Z..Bq....| -00000190 07 7f 7e 88 7d 7d f1 04 39 c4 a2 2e db 51 c9 7c |..~.}}..9....Q.|| -000001a0 e3 c0 4c 3b 32 66 01 cf af b1 1d b8 71 9a 1d db |..L;2f......q...| -000001b0 db 89 6b ae da 2d 79 02 03 01 00 01 a3 81 a7 30 |..k..-y........0| -000001c0 81 a4 30 1d 06 03 55 1d 0e 04 16 04 14 b1 ad e2 |..0...U.........| -000001d0 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 88 |.Z..(.i.#i..&...| -000001e0 39 30 75 06 03 55 1d 23 04 6e 30 6c 80 14 b1 ad |90u..U.#.n0l....| -000001f0 e2 85 5a cf cb 28 db 69 ce 23 69 de d3 26 8e 18 |..Z..(.i.#i..&..| -00000200 88 39 a1 49 a4 47 30 45 31 0b 30 09 06 03 55 04 |.9.I.G0E1.0...U.| -00000210 06 13 02 41 55 31 13 30 11 06 03 55 04 08 13 0a |...AU1.0...U....| -00000220 53 6f 6d 65 2d 53 74 61 74 65 31 21 30 1f 06 03 |Some-State1!0...| -00000230 55 04 0a 13 18 49 6e 74 65 72 6e 65 74 20 57 69 |U....Internet Wi| -00000240 64 67 69 74 73 20 50 74 79 20 4c 74 64 82 09 00 |dgits Pty Ltd...| -00000250 85 b0 bb a4 8a 7f b8 ca 30 0c 06 03 55 1d 13 04 |........0...U...| -00000260 05 30 03 01 01 ff 30 0d 06 09 2a 86 48 86 f7 0d |.0....0...*.H...| -00000270 01 01 05 05 00 03 81 81 00 08 6c 45 24 c7 6b b1 |..........lE$.k.| -00000280 59 ab 0c 52 cc f2 b0 14 d7 87 9d 7a 64 75 b5 5a |Y..R.......zdu.Z| -00000290 95 66 e4 c5 2b 8e ae 12 66 1f eb 4f 38 b3 6e 60 |.f..+...f..O8.n`| -000002a0 d3 92 fd f7 41 08 b5 25 13 b1 18 7a 24 fb 30 1d |....A..%...z$.0.| -000002b0 ba ed 98 b9 17 ec e7 d7 31 59 db 95 d3 1d 78 ea |........1Y....x.| -000002c0 50 56 5c d5 82 5a 2d 5a 5f 33 c4 b6 d8 c9 75 90 |PV\..Z-Z_3....u.| -000002d0 96 8c 0f 52 98 b5 cd 98 1f 89 20 5f f2 a0 1c a3 |...R...... _....| -000002e0 1b 96 94 dd a9 fd 57 e9 70 e8 26 6d 71 99 9b 26 |......W.p.&mq..&| -000002f0 6e 38 50 29 6c 90 a7 bd d9 16 03 03 00 04 0e 00 |n8P)l...........| -00000300 00 00 |..| ->>> Flow 3 (client to server) -00000000 16 03 03 00 86 10 00 00 82 00 80 35 b3 60 ba 14 |...........5.`..| -00000010 5f 19 24 a0 24 de 4e 85 a9 64 78 3a 51 24 64 70 |_.$.$.N..dx:Q$dp| -00000020 88 55 6d c3 11 b8 d3 9f bc 7a 33 f8 3c 48 93 2f |.Um......z3..|.| -00000070 44 82 f4 24 03 22 40 00 64 27 53 15 41 8c 01 e9 |D..$."@.d'S.A...| -00000080 39 32 fa 8e 2d f9 b4 89 34 15 d6 14 03 03 00 01 |92..-...4.......| -00000090 01 16 03 03 00 24 f5 61 8b 24 bf b4 82 3a cf 49 |.....$.a.$...:.I| -000000a0 99 a0 b1 1b a7 a7 a3 92 7c 84 85 e0 64 a3 3d bd |........|...d.=.| -000000b0 38 98 7d 97 a8 b9 2a 35 a9 09 |8.}...*5..| ->>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 24 c9 0b 84 e6 39 |..........$....9| -00000010 f2 e0 f3 ac 9f 0f 17 92 5f 6d de 94 18 c4 60 d9 |........_m....`.| -00000020 66 c3 0d 1a ae c2 8f 46 8f 7f f0 58 0e 4a 9b 17 |f......F...X.J..| -00000030 03 03 00 21 8b 73 a1 6a 7e d9 7e 4f 1d cc b2 7d |...!.s.j~.~O...}| -00000040 3c 83 3f 52 f8 08 77 01 4c 65 11 6d 50 25 9a cc |<.?R..w.Le.mP%..| -00000050 e3 54 27 72 59 15 03 03 00 16 3d c8 ab 14 51 fa |.T'rY.....=...Q.| -00000060 97 f1 ef 5f b4 4f 44 58 d4 93 3b ae e5 61 1f a3 |..._.ODX..;..a..| diff --git a/src/pkg/crypto/tls/testdata/Server-TLSv12-Resume b/src/pkg/crypto/tls/testdata/Server-TLSv12-Resume deleted file mode 100644 index c495d4adc..000000000 --- a/src/pkg/crypto/tls/testdata/Server-TLSv12-Resume +++ /dev/null @@ -1,36 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 e8 01 00 00 e4 03 03 52 cc 57 59 c3 |...........R.WY.| -00000010 8b df 97 05 d8 5f 16 22 b4 b1 e7 cb 7d 2f 9b 58 |....._."....}/.X| -00000020 a3 f4 d7 2c a4 c1 9d 49 ed 4b ba 20 90 da 90 3e |...,...I.K. ...>| -00000030 36 19 7a db 56 43 26 f7 dc 42 57 33 22 ed 9d a4 |6.z.VC&..BW3"...| -00000040 9d 53 da f8 9d 4e 60 66 71 a0 2e 2e 00 04 00 05 |.S...N`fq.......| -00000050 00 ff 01 00 00 97 00 23 00 68 00 00 00 00 00 00 |.......#.h......| -00000060 00 00 00 00 00 00 00 00 00 00 65 ea 4b d1 ef ba |..........e.K...| -00000070 06 38 1e e1 88 82 3a cd 03 ac 3b 39 0a e0 19 fd |.8....:...;9....| -00000080 af 6c 57 30 df 31 6e f7 92 38 4b 5d 77 90 39 ff |.lW0.1n..8K]w.9.| -00000090 32 51 f5 ed 12 d7 b0 7c 4d 6c c5 76 e4 72 48 3e |2Q.....|Ml.v.rH>| -000000a0 59 23 fe 0d 15 df f4 ba ea b9 67 16 23 8f 7d 15 |Y#........g.#.}.| -000000b0 b6 11 f1 ab d7 d4 cd a3 21 82 92 2a 12 cf 95 f3 |........!..*....| -000000c0 60 b2 00 0d 00 22 00 20 06 01 06 02 06 03 05 01 |`....". ........| -000000d0 05 02 05 03 04 01 04 02 04 03 03 01 03 02 03 03 |................| -000000e0 02 01 02 02 02 03 01 01 00 0f 00 01 01 |.............| ->>> Flow 2 (server to client) -00000000 16 03 03 00 51 02 00 00 4d 03 03 00 00 00 00 00 |....Q...M.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 20 90 da 90 3e |........... ...>| -00000030 36 19 7a db 56 43 26 f7 dc 42 57 33 22 ed 9d a4 |6.z.VC&..BW3"...| -00000040 9d 53 da f8 9d 4e 60 66 71 a0 2e 2e 00 05 00 00 |.S...N`fq.......| -00000050 05 ff 01 00 01 00 14 03 03 00 01 01 16 03 03 00 |................| -00000060 24 11 12 ff 28 10 14 4c e5 0e ad a7 fa f3 92 fb |$...(..L........| -00000070 13 7d ae f2 b2 4a 6b a1 9e 67 cf a8 f7 8c 6f a0 |.}...Jk..g....o.| -00000080 6c 30 0e 18 55 |l0..U| ->>> Flow 3 (client to server) -00000000 14 03 03 00 01 01 16 03 03 00 24 0d 46 41 8b 24 |..........$.FA.$| -00000010 36 01 a9 fd 8b ec fc e6 b1 83 96 df 0d 3e 53 54 |6............>ST| -00000020 58 b8 43 f2 a6 25 5e 1a ae 19 9e d2 28 44 92 |X.C..%^.....(D.| ->>> Flow 4 (server to client) -00000000 17 03 03 00 21 c4 fb f6 53 bb 3e 04 cc 0b a0 03 |....!...S.>.....| -00000010 fa 49 96 da b5 8d b2 f2 e5 d8 f3 5c 27 57 4f 9c |.I.........\'WO.| -00000020 30 00 34 fc 52 92 15 03 03 00 16 a3 02 7a 50 d2 |0.4.R........zP.| -00000030 c6 b3 fc 69 8f e4 94 ae ab 22 ad 05 1d 15 69 b9 |...i....."....i.| -00000040 a5 |.| diff --git a/src/pkg/crypto/tls/testdata/Server-TLSv12-SNI b/src/pkg/crypto/tls/testdata/Server-TLSv12-SNI deleted file mode 100644 index 61b17a11d..000000000 --- a/src/pkg/crypto/tls/testdata/Server-TLSv12-SNI +++ /dev/null @@ -1,76 +0,0 @@ ->>> Flow 1 (client to server) -00000000 16 03 01 00 70 01 00 00 6c 03 03 52 cc 57 59 2d |....p...l..R.WY-| -00000010 77 aa 75 35 fa ff 2a a2 bf 91 5e e3 7f 38 7d 7a |w.u5..*...^..8}z| -00000020 e3 93 d3 e8 8b 09 bb 06 c8 6d 91 00 00 04 00 2f |.........m...../| -00000030 00 ff 01 00 00 3f 00 00 00 10 00 0e 00 00 0b 73 |.....?.........s| -00000040 6e 69 74 65 73 74 2e 63 6f 6d 00 0d 00 22 00 20 |nitest.com...". | -00000050 06 01 06 02 06 03 05 01 05 02 05 03 04 01 04 02 |................| -00000060 04 03 03 01 03 02 03 03 02 01 02 02 02 03 01 01 |................| -00000070 00 0f 00 01 01 |.....| ->>> Flow 2 (server to client) -00000000 16 03 03 00 31 02 00 00 2d 03 03 00 00 00 00 00 |....1...-.......| -00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000020 00 00 00 00 00 00 00 00 00 00 00 00 00 2f 00 00 |............./..| -00000030 05 ff 01 00 01 00 16 03 03 02 00 0b 00 01 fc 00 |................| -00000040 01 f9 00 01 f6 30 82 01 f2 30 82 01 5d a0 03 02 |.....0...0..]...| -00000050 01 02 02 01 00 30 0b 06 09 2a 86 48 86 f7 0d 01 |.....0...*.H....| -00000060 01 05 30 28 31 10 30 0e 06 03 55 04 0a 13 07 41 |..0(1.0...U....A| -00000070 63 6d 65 20 43 6f 31 14 30 12 06 03 55 04 03 13 |cme Co1.0...U...| -00000080 0b 73 6e 69 74 65 73 74 2e 63 6f 6d 30 1e 17 0d |.snitest.com0...| -00000090 31 32 30 34 31 31 31 37 34 30 33 35 5a 17 0d 31 |120411174035Z..1| -000000a0 33 30 34 31 31 31 37 34 35 33 35 5a 30 28 31 10 |30411174535Z0(1.| -000000b0 30 0e 06 03 55 04 0a 13 07 41 63 6d 65 20 43 6f |0...U....Acme Co| -000000c0 31 14 30 12 06 03 55 04 03 13 0b 73 6e 69 74 65 |1.0...U....snite| -000000d0 73 74 2e 63 6f 6d 30 81 9d 30 0b 06 09 2a 86 48 |st.com0..0...*.H| -000000e0 86 f7 0d 01 01 01 03 81 8d 00 30 81 89 02 81 81 |..........0.....| -000000f0 00 bb 79 d6 f5 17 b5 e5 bf 46 10 d0 dc 69 be e6 |..y......F...i..| -00000100 2b 07 43 5a d0 03 2d 8a 7a 43 85 b7 14 52 e7 a5 |+.CZ..-.zC...R..| -00000110 65 4c 2c 78 b8 23 8c b5 b4 82 e5 de 1f 95 3b 7e |eL,x.#........;~| -00000120 62 a5 2c a5 33 d6 fe 12 5c 7a 56 fc f5 06 bf fa |b.,.3...\zV.....| -00000130 58 7b 26 3f b5 cd 04 d3 d0 c9 21 96 4a c7 f4 54 |X{&?......!.J..T| -00000140 9f 5a bf ef 42 71 00 fe 18 99 07 7f 7e 88 7d 7d |.Z..Bq......~.}}| -00000150 f1 04 39 c4 a2 2e db 51 c9 7c e3 c0 4c 3b 32 66 |..9....Q.|..L;2f| -00000160 01 cf af b1 1d b8 71 9a 1d db db 89 6b ae da 2d |......q.....k..-| -00000170 79 02 03 01 00 01 a3 32 30 30 30 0e 06 03 55 1d |y......2000...U.| -00000180 0f 01 01 ff 04 04 03 02 00 a0 30 0d 06 03 55 1d |..........0...U.| -00000190 0e 04 06 04 04 01 02 03 04 30 0f 06 03 55 1d 23 |.........0...U.#| -000001a0 04 08 30 06 80 04 01 02 03 04 30 0b 06 09 2a 86 |..0.......0...*.| -000001b0 48 86 f7 0d 01 01 05 03 81 81 00 89 c6 45 5f 1c |H............E_.| -000001c0 1f 5e f8 eb 1a b1 74 ee 24 39 05 9f 5c 42 59 bb |.^....t.$9..\BY.| -000001d0 1a 8d 86 cd b1 d0 56 f5 6a 71 7d a4 0e 95 ab 90 |......V.jq}.....| -000001e0 f5 9e 8d ea f6 27 c1 57 99 50 94 db 08 02 26 6e |.....'.W.P....&n| -000001f0 b3 4f c6 84 2d ea 8a 4b 68 d9 c1 38 91 03 ab 84 |.O..-..Kh..8....| -00000200 fb 9e 1f 85 d9 b5 d2 3f f2 31 2c 86 70 fb b5 40 |.......?.1,.p..@| -00000210 14 82 45 a4 eb af e2 64 d9 0c 8a 4c f4 f8 5b 0f |..E....d...L..[.| -00000220 ac 12 ac 2f c4 a3 15 4b ad 52 46 28 68 af 96 c6 |.../...K.RF(h...| -00000230 2c 65 25 d6 52 b6 e3 18 45 bd cc 16 03 03 00 04 |,e%.R...E.......| -00000240 0e 00 00 00 |....| ->>> Flow 3 (client to server) -00000000 16 03 03 00 86 10 00 00 82 00 80 0d f2 bf 75 a9 |..............u.| -00000010 aa db f3 25 55 d4 20 59 63 54 d1 70 82 f9 61 c5 |...%U. YcT.p..a.| -00000020 b7 ae 3f 75 71 75 9d c5 01 a1 ed b1 07 66 9f 3f |..?uqu.......f.?| -00000030 cf c6 e6 ad 44 03 fd 18 6f 53 24 ce 76 01 bd fe |....D...oS$.v...| -00000040 e2 51 f7 df 8a 23 3a 21 c4 00 15 ff d0 e0 ff c8 |.Q...#:!........| -00000050 8b 89 33 c6 8e e0 ce 97 ef b4 c6 f9 b0 ea 38 89 |..3...........8.| -00000060 79 98 34 9e f7 bc c6 fd d2 5d 56 84 5c d2 9a ce |y.4......]V.\...| -00000070 ae de 09 bc 24 25 fc 09 0c bc 0e 91 0d 6b 36 ae |....$%.......k6.| -00000080 ce 6b cd 14 ec b6 3c fa d6 df fc 14 03 03 00 01 |.k....<.........| -00000090 01 16 03 03 00 40 ad 21 13 2b 33 7a 4a 0d fb 0f |.....@.!.+3zJ...| -000000a0 eb d2 b6 85 29 1f 59 79 ba 86 53 5c 68 b4 c7 e3 |....).Yy..S\h...| -000000b0 8a 6c 5c 18 04 4d e4 76 19 30 ba 92 b4 79 8c 64 |.l\..M.v.0...y.d| -000000c0 00 a0 2e 13 96 45 9f e7 a9 e4 23 9e 9f 89 23 26 |.....E....#...#&| -000000d0 36 20 82 fc 75 fe |6 ..u.| ->>> Flow 4 (server to client) -00000000 14 03 03 00 01 01 16 03 03 00 40 00 00 00 00 00 |..........@.....| -00000010 00 00 00 00 00 00 00 00 00 00 00 b7 87 61 10 03 |.............a..| -00000020 b8 a4 42 d4 8b 49 bc 40 80 70 92 c8 25 b0 c6 7f |..B..I.@.p..%...| -00000030 b3 87 76 50 5a 59 b3 3c d8 3e 23 24 aa 1a f3 36 |..vPZY.<.>#$...6| -00000040 c9 2c 87 c1 22 d2 94 f8 2c fd ef 17 03 03 00 40 |.,.."...,......@| -00000050 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................| -00000060 e5 7f bd 3e ff 9f d4 1b 91 02 f8 69 6f 70 9d 51 |...>.......iop.Q| -00000070 a5 ec ef 5b 10 3f 4e 3f 44 e5 9a 39 68 7c 3a b9 |...[.?N?D..9h|:.| -00000080 69 38 31 ec 9c 45 bf 19 d1 5c 5e 2e 06 00 ca 19 |i81..E...\^.....| -00000090 15 03 03 00 30 00 00 00 00 00 00 00 00 00 00 00 |....0...........| -000000a0 00 00 00 00 00 63 5e 79 2c f2 05 dc 2b d7 5b ac |.....c^y,...+.[.| -000000b0 9d fc 75 94 03 16 ca 1f b2 75 58 2d f1 2f f1 1e |..u......uX-./..| -000000c0 d2 f6 84 8f 2e |.....| diff --git a/src/pkg/crypto/tls/ticket.go b/src/pkg/crypto/tls/ticket.go deleted file mode 100644 index 4cfc5a53f..000000000 --- a/src/pkg/crypto/tls/ticket.go +++ /dev/null @@ -1,182 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tls - -import ( - "bytes" - "crypto/aes" - "crypto/cipher" - "crypto/hmac" - "crypto/sha256" - "crypto/subtle" - "errors" - "io" -) - -// sessionState contains the information that is serialized into a session -// ticket in order to later resume a connection. -type sessionState struct { - vers uint16 - cipherSuite uint16 - masterSecret []byte - certificates [][]byte -} - -func (s *sessionState) equal(i interface{}) bool { - s1, ok := i.(*sessionState) - if !ok { - return false - } - - if s.vers != s1.vers || - s.cipherSuite != s1.cipherSuite || - !bytes.Equal(s.masterSecret, s1.masterSecret) { - return false - } - - if len(s.certificates) != len(s1.certificates) { - return false - } - - for i := range s.certificates { - if !bytes.Equal(s.certificates[i], s1.certificates[i]) { - return false - } - } - - return true -} - -func (s *sessionState) marshal() []byte { - length := 2 + 2 + 2 + len(s.masterSecret) + 2 - for _, cert := range s.certificates { - length += 4 + len(cert) - } - - ret := make([]byte, length) - x := ret - x[0] = byte(s.vers >> 8) - x[1] = byte(s.vers) - x[2] = byte(s.cipherSuite >> 8) - x[3] = byte(s.cipherSuite) - x[4] = byte(len(s.masterSecret) >> 8) - x[5] = byte(len(s.masterSecret)) - x = x[6:] - copy(x, s.masterSecret) - x = x[len(s.masterSecret):] - - x[0] = byte(len(s.certificates) >> 8) - x[1] = byte(len(s.certificates)) - x = x[2:] - - for _, cert := range s.certificates { - x[0] = byte(len(cert) >> 24) - x[1] = byte(len(cert) >> 16) - x[2] = byte(len(cert) >> 8) - x[3] = byte(len(cert)) - copy(x[4:], cert) - x = x[4+len(cert):] - } - - return ret -} - -func (s *sessionState) unmarshal(data []byte) bool { - if len(data) < 8 { - return false - } - - s.vers = uint16(data[0])<<8 | uint16(data[1]) - s.cipherSuite = uint16(data[2])<<8 | uint16(data[3]) - masterSecretLen := int(data[4])<<8 | int(data[5]) - data = data[6:] - if len(data) < masterSecretLen { - return false - } - - s.masterSecret = data[:masterSecretLen] - data = data[masterSecretLen:] - - if len(data) < 2 { - return false - } - - numCerts := int(data[0])<<8 | int(data[1]) - data = data[2:] - - s.certificates = make([][]byte, numCerts) - for i := range s.certificates { - if len(data) < 4 { - return false - } - certLen := int(data[0])<<24 | int(data[1])<<16 | int(data[2])<<8 | int(data[3]) - data = data[4:] - if certLen < 0 { - return false - } - if len(data) < certLen { - return false - } - s.certificates[i] = data[:certLen] - data = data[certLen:] - } - - if len(data) > 0 { - return false - } - - return true -} - -func (c *Conn) encryptTicket(state *sessionState) ([]byte, error) { - serialized := state.marshal() - encrypted := make([]byte, aes.BlockSize+len(serialized)+sha256.Size) - iv := encrypted[:aes.BlockSize] - macBytes := encrypted[len(encrypted)-sha256.Size:] - - if _, err := io.ReadFull(c.config.rand(), iv); err != nil { - return nil, err - } - block, err := aes.NewCipher(c.config.SessionTicketKey[:16]) - if err != nil { - return nil, errors.New("tls: failed to create cipher while encrypting ticket: " + err.Error()) - } - cipher.NewCTR(block, iv).XORKeyStream(encrypted[aes.BlockSize:], serialized) - - mac := hmac.New(sha256.New, c.config.SessionTicketKey[16:32]) - mac.Write(encrypted[:len(encrypted)-sha256.Size]) - mac.Sum(macBytes[:0]) - - return encrypted, nil -} - -func (c *Conn) decryptTicket(encrypted []byte) (*sessionState, bool) { - if len(encrypted) < aes.BlockSize+sha256.Size { - return nil, false - } - - iv := encrypted[:aes.BlockSize] - macBytes := encrypted[len(encrypted)-sha256.Size:] - - mac := hmac.New(sha256.New, c.config.SessionTicketKey[16:32]) - mac.Write(encrypted[:len(encrypted)-sha256.Size]) - expected := mac.Sum(nil) - - if subtle.ConstantTimeCompare(macBytes, expected) != 1 { - return nil, false - } - - block, err := aes.NewCipher(c.config.SessionTicketKey[:16]) - if err != nil { - return nil, false - } - ciphertext := encrypted[aes.BlockSize : len(encrypted)-sha256.Size] - plaintext := ciphertext - cipher.NewCTR(block, iv).XORKeyStream(plaintext, ciphertext) - - state := new(sessionState) - ok := state.unmarshal(plaintext) - return state, ok -} diff --git a/src/pkg/crypto/tls/tls.go b/src/pkg/crypto/tls/tls.go deleted file mode 100644 index d50e12029..000000000 --- a/src/pkg/crypto/tls/tls.go +++ /dev/null @@ -1,275 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package tls partially implements TLS 1.2, as specified in RFC 5246. -package tls - -import ( - "crypto" - "crypto/ecdsa" - "crypto/rsa" - "crypto/x509" - "encoding/pem" - "errors" - "io/ioutil" - "net" - "strings" - "time" -) - -// Server returns a new TLS server side connection -// using conn as the underlying transport. -// The configuration config must be non-nil and must have -// at least one certificate. -func Server(conn net.Conn, config *Config) *Conn { - return &Conn{conn: conn, config: config} -} - -// Client returns a new TLS client side connection -// using conn as the underlying transport. -// The config cannot be nil: users must set either ServerName or -// InsecureSkipVerify in the config. -func Client(conn net.Conn, config *Config) *Conn { - return &Conn{conn: conn, config: config, isClient: true} -} - -// A listener implements a network listener (net.Listener) for TLS connections. -type listener struct { - net.Listener - config *Config -} - -// Accept waits for and returns the next incoming TLS connection. -// The returned connection c is a *tls.Conn. -func (l *listener) Accept() (c net.Conn, err error) { - c, err = l.Listener.Accept() - if err != nil { - return - } - c = Server(c, l.config) - return -} - -// NewListener creates a Listener which accepts connections from an inner -// Listener and wraps each connection with Server. -// The configuration config must be non-nil and must have -// at least one certificate. -func NewListener(inner net.Listener, config *Config) net.Listener { - l := new(listener) - l.Listener = inner - l.config = config - return l -} - -// Listen creates a TLS listener accepting connections on the -// given network address using net.Listen. -// The configuration config must be non-nil and must have -// at least one certificate. -func Listen(network, laddr string, config *Config) (net.Listener, error) { - if config == nil || len(config.Certificates) == 0 { - return nil, errors.New("tls.Listen: no certificates in configuration") - } - l, err := net.Listen(network, laddr) - if err != nil { - return nil, err - } - return NewListener(l, config), nil -} - -type timeoutError struct{} - -func (timeoutError) Error() string { return "tls: DialWithDialer timed out" } -func (timeoutError) Timeout() bool { return true } -func (timeoutError) Temporary() bool { return true } - -// DialWithDialer connects to the given network address using dialer.Dial and -// then initiates a TLS handshake, returning the resulting TLS connection. Any -// timeout or deadline given in the dialer apply to connection and TLS -// handshake as a whole. -// -// DialWithDialer interprets a nil configuration as equivalent to the zero -// configuration; see the documentation of Config for the defaults. -func DialWithDialer(dialer *net.Dialer, network, addr string, config *Config) (*Conn, error) { - // We want the Timeout and Deadline values from dialer to cover the - // whole process: TCP connection and TLS handshake. This means that we - // also need to start our own timers now. - timeout := dialer.Timeout - - if !dialer.Deadline.IsZero() { - deadlineTimeout := dialer.Deadline.Sub(time.Now()) - if timeout == 0 || deadlineTimeout < timeout { - timeout = deadlineTimeout - } - } - - var errChannel chan error - - if timeout != 0 { - errChannel = make(chan error, 2) - time.AfterFunc(timeout, func() { - errChannel <- timeoutError{} - }) - } - - rawConn, err := dialer.Dial(network, addr) - if err != nil { - return nil, err - } - - colonPos := strings.LastIndex(addr, ":") - if colonPos == -1 { - colonPos = len(addr) - } - hostname := addr[:colonPos] - - if config == nil { - config = defaultConfig() - } - // If no ServerName is set, infer the ServerName - // from the hostname we're connecting to. - if config.ServerName == "" { - // Make a copy to avoid polluting argument or default. - c := *config - c.ServerName = hostname - config = &c - } - - conn := Client(rawConn, config) - - if timeout == 0 { - err = conn.Handshake() - } else { - go func() { - errChannel <- conn.Handshake() - }() - - err = <-errChannel - } - - if err != nil { - rawConn.Close() - return nil, err - } - - return conn, nil -} - -// Dial connects to the given network address using net.Dial -// and then initiates a TLS handshake, returning the resulting -// TLS connection. -// Dial interprets a nil configuration as equivalent to -// the zero configuration; see the documentation of Config -// for the defaults. -func Dial(network, addr string, config *Config) (*Conn, error) { - return DialWithDialer(new(net.Dialer), network, addr, config) -} - -// LoadX509KeyPair reads and parses a public/private key pair from a pair of -// files. The files must contain PEM encoded data. -func LoadX509KeyPair(certFile, keyFile string) (cert Certificate, err error) { - certPEMBlock, err := ioutil.ReadFile(certFile) - if err != nil { - return - } - keyPEMBlock, err := ioutil.ReadFile(keyFile) - if err != nil { - return - } - return X509KeyPair(certPEMBlock, keyPEMBlock) -} - -// X509KeyPair parses a public/private key pair from a pair of -// PEM encoded data. -func X509KeyPair(certPEMBlock, keyPEMBlock []byte) (cert Certificate, err error) { - var certDERBlock *pem.Block - for { - certDERBlock, certPEMBlock = pem.Decode(certPEMBlock) - if certDERBlock == nil { - break - } - if certDERBlock.Type == "CERTIFICATE" { - cert.Certificate = append(cert.Certificate, certDERBlock.Bytes) - } - } - - if len(cert.Certificate) == 0 { - err = errors.New("crypto/tls: failed to parse certificate PEM data") - return - } - - var keyDERBlock *pem.Block - for { - keyDERBlock, keyPEMBlock = pem.Decode(keyPEMBlock) - if keyDERBlock == nil { - err = errors.New("crypto/tls: failed to parse key PEM data") - return - } - if keyDERBlock.Type == "PRIVATE KEY" || strings.HasSuffix(keyDERBlock.Type, " PRIVATE KEY") { - break - } - } - - cert.PrivateKey, err = parsePrivateKey(keyDERBlock.Bytes) - if err != nil { - return - } - - // We don't need to parse the public key for TLS, but we so do anyway - // to check that it looks sane and matches the private key. - x509Cert, err := x509.ParseCertificate(cert.Certificate[0]) - if err != nil { - return - } - - switch pub := x509Cert.PublicKey.(type) { - case *rsa.PublicKey: - priv, ok := cert.PrivateKey.(*rsa.PrivateKey) - if !ok { - err = errors.New("crypto/tls: private key type does not match public key type") - return - } - if pub.N.Cmp(priv.N) != 0 { - err = errors.New("crypto/tls: private key does not match public key") - return - } - case *ecdsa.PublicKey: - priv, ok := cert.PrivateKey.(*ecdsa.PrivateKey) - if !ok { - err = errors.New("crypto/tls: private key type does not match public key type") - return - - } - if pub.X.Cmp(priv.X) != 0 || pub.Y.Cmp(priv.Y) != 0 { - err = errors.New("crypto/tls: private key does not match public key") - return - } - default: - err = errors.New("crypto/tls: unknown public key algorithm") - return - } - - return -} - -// Attempt to parse the given private key DER block. OpenSSL 0.9.8 generates -// PKCS#1 private keys by default, while OpenSSL 1.0.0 generates PKCS#8 keys. -// OpenSSL ecparam generates SEC1 EC private keys for ECDSA. We try all three. -func parsePrivateKey(der []byte) (crypto.PrivateKey, error) { - if key, err := x509.ParsePKCS1PrivateKey(der); err == nil { - return key, nil - } - if key, err := x509.ParsePKCS8PrivateKey(der); err == nil { - switch key := key.(type) { - case *rsa.PrivateKey, *ecdsa.PrivateKey: - return key, nil - default: - return nil, errors.New("crypto/tls: found unknown private key type in PKCS#8 wrapping") - } - } - if key, err := x509.ParseECPrivateKey(der); err == nil { - return key, nil - } - - return nil, errors.New("crypto/tls: failed to parse private key") -} diff --git a/src/pkg/crypto/tls/tls_test.go b/src/pkg/crypto/tls/tls_test.go deleted file mode 100644 index e82579eee..000000000 --- a/src/pkg/crypto/tls/tls_test.go +++ /dev/null @@ -1,282 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package tls - -import ( - "bytes" - "fmt" - "io" - "net" - "strings" - "testing" - "time" -) - -var rsaCertPEM = `-----BEGIN CERTIFICATE----- -MIIB0zCCAX2gAwIBAgIJAI/M7BYjwB+uMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV -BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX -aWRnaXRzIFB0eSBMdGQwHhcNMTIwOTEyMjE1MjAyWhcNMTUwOTEyMjE1MjAyWjBF -MQswCQYDVQQGEwJBVTETMBEGA1UECAwKU29tZS1TdGF0ZTEhMB8GA1UECgwYSW50 -ZXJuZXQgV2lkZ2l0cyBQdHkgTHRkMFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBANLJ -hPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wok/4xIA+ui35/MmNa -rtNuC+BdZ1tMuVCPFZcCAwEAAaNQME4wHQYDVR0OBBYEFJvKs8RfJaXTH08W+SGv -zQyKn0H8MB8GA1UdIwQYMBaAFJvKs8RfJaXTH08W+SGvzQyKn0H8MAwGA1UdEwQF -MAMBAf8wDQYJKoZIhvcNAQEFBQADQQBJlffJHybjDGxRMqaRmDhX0+6v02TUKZsW -r5QuVbpQhH6u+0UgcW0jp9QwpxoPTLTWGXEWBBBurxFwiCBhkQ+V ------END CERTIFICATE----- -` - -var rsaKeyPEM = `-----BEGIN RSA PRIVATE KEY----- -MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo -k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G -6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N -MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW -SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T -xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi -D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g== ------END RSA PRIVATE KEY----- -` - -// keyPEM is the same as rsaKeyPEM, but declares itself as just -// "PRIVATE KEY", not "RSA PRIVATE KEY". http://golang.org/issue/4477 -var keyPEM = `-----BEGIN PRIVATE KEY----- -MIIBOwIBAAJBANLJhPHhITqQbPklG3ibCVxwGMRfp/v4XqhfdQHdcVfHap6NQ5Wo -k/4xIA+ui35/MmNartNuC+BdZ1tMuVCPFZcCAwEAAQJAEJ2N+zsR0Xn8/Q6twa4G -6OB1M1WO+k+ztnX/1SvNeWu8D6GImtupLTYgjZcHufykj09jiHmjHx8u8ZZB/o1N -MQIhAPW+eyZo7ay3lMz1V01WVjNKK9QSn1MJlb06h/LuYv9FAiEA25WPedKgVyCW -SmUwbPw8fnTcpqDWE3yTO3vKcebqMSsCIBF3UmVue8YU3jybC3NxuXq3wNm34R8T -xVLHwDXh/6NJAiEAl2oHGGLz64BuAfjKrqwz7qMYr9HCLIe/YsoWq/olzScCIQDi -D2lWusoe2/nEqfDVVWGWlyJ7yOmqaVm/iNUN9B2N2g== ------END PRIVATE KEY----- -` - -var ecdsaCertPEM = `-----BEGIN CERTIFICATE----- -MIIB/jCCAWICCQDscdUxw16XFDAJBgcqhkjOPQQBMEUxCzAJBgNVBAYTAkFVMRMw -EQYDVQQIEwpTb21lLVN0YXRlMSEwHwYDVQQKExhJbnRlcm5ldCBXaWRnaXRzIFB0 -eSBMdGQwHhcNMTIxMTE0MTI0MDQ4WhcNMTUxMTE0MTI0MDQ4WjBFMQswCQYDVQQG -EwJBVTETMBEGA1UECBMKU29tZS1TdGF0ZTEhMB8GA1UEChMYSW50ZXJuZXQgV2lk -Z2l0cyBQdHkgTHRkMIGbMBAGByqGSM49AgEGBSuBBAAjA4GGAAQBY9+my9OoeSUR -lDQdV/x8LsOuLilthhiS1Tz4aGDHIPwC1mlvnf7fg5lecYpMCrLLhauAc1UJXcgl -01xoLuzgtAEAgv2P/jgytzRSpUYvgLBt1UA0leLYBy6mQQbrNEuqT3INapKIcUv8 -XxYP0xMEUksLPq6Ca+CRSqTtrd/23uTnapkwCQYHKoZIzj0EAQOBigAwgYYCQXJo -A7Sl2nLVf+4Iu/tAX/IF4MavARKC4PPHK3zfuGfPR3oCCcsAoz3kAzOeijvd0iXb -H5jBImIxPL4WxQNiBTexAkF8D1EtpYuWdlVQ80/h/f4pBcGiXPqX5h2PQSQY7hP1 -+jwM1FGS4fREIOvlBYr/SzzQRtwrvrzGYxDEDbsC0ZGRnA== ------END CERTIFICATE----- -` - -var ecdsaKeyPEM = `-----BEGIN EC PARAMETERS----- -BgUrgQQAIw== ------END EC PARAMETERS----- ------BEGIN EC PRIVATE KEY----- -MIHcAgEBBEIBrsoKp0oqcv6/JovJJDoDVSGWdirrkgCWxrprGlzB9o0X8fV675X0 -NwuBenXFfeZvVcwluO7/Q9wkYoPd/t3jGImgBwYFK4EEACOhgYkDgYYABAFj36bL -06h5JRGUNB1X/Hwuw64uKW2GGJLVPPhoYMcg/ALWaW+d/t+DmV5xikwKssuFq4Bz -VQldyCXTXGgu7OC0AQCC/Y/+ODK3NFKlRi+AsG3VQDSV4tgHLqZBBus0S6pPcg1q -kohxS/xfFg/TEwRSSws+roJr4JFKpO2t3/be5OdqmQ== ------END EC PRIVATE KEY----- -` - -var keyPairTests = []struct { - algo string - cert string - key string -}{ - {"ECDSA", ecdsaCertPEM, ecdsaKeyPEM}, - {"RSA", rsaCertPEM, rsaKeyPEM}, - {"RSA-untyped", rsaCertPEM, keyPEM}, // golang.org/issue/4477 -} - -func TestX509KeyPair(t *testing.T) { - var pem []byte - for _, test := range keyPairTests { - pem = []byte(test.cert + test.key) - if _, err := X509KeyPair(pem, pem); err != nil { - t.Errorf("Failed to load %s cert followed by %s key: %s", test.algo, test.algo, err) - } - pem = []byte(test.key + test.cert) - if _, err := X509KeyPair(pem, pem); err != nil { - t.Errorf("Failed to load %s key followed by %s cert: %s", test.algo, test.algo, err) - } - } -} - -func TestX509MixedKeyPair(t *testing.T) { - if _, err := X509KeyPair([]byte(rsaCertPEM), []byte(ecdsaKeyPEM)); err == nil { - t.Error("Load of RSA certificate succeeded with ECDSA private key") - } - if _, err := X509KeyPair([]byte(ecdsaCertPEM), []byte(rsaKeyPEM)); err == nil { - t.Error("Load of ECDSA certificate succeeded with RSA private key") - } -} - -func newLocalListener(t *testing.T) net.Listener { - ln, err := net.Listen("tcp", "127.0.0.1:0") - if err != nil { - ln, err = net.Listen("tcp6", "[::1]:0") - } - if err != nil { - t.Fatal(err) - } - return ln -} - -func TestDialTimeout(t *testing.T) { - if testing.Short() { - t.Skip("skipping in short mode") - } - listener := newLocalListener(t) - - addr := listener.Addr().String() - defer listener.Close() - - complete := make(chan bool) - defer close(complete) - - go func() { - conn, err := listener.Accept() - if err != nil { - t.Error(err) - return - } - <-complete - conn.Close() - }() - - dialer := &net.Dialer{ - Timeout: 10 * time.Millisecond, - } - - var err error - if _, err = DialWithDialer(dialer, "tcp", addr, nil); err == nil { - t.Fatal("DialWithTimeout completed successfully") - } - - if !strings.Contains(err.Error(), "timed out") { - t.Errorf("resulting error not a timeout: %s", err) - } -} - -// tests that Conn.Read returns (non-zero, io.EOF) instead of -// (non-zero, nil) when a Close (alertCloseNotify) is sitting right -// behind the application data in the buffer. -func TestConnReadNonzeroAndEOF(t *testing.T) { - // This test is racy: it assumes that after a write to a - // localhost TCP connection, the peer TCP connection can - // immediately read it. Because it's racy, we skip this test - // in short mode, and then retry it several times with an - // increasing sleep in between our final write (via srv.Close - // below) and the following read. - if testing.Short() { - t.Skip("skipping in short mode") - } - var err error - for delay := time.Millisecond; delay <= 64*time.Millisecond; delay *= 2 { - if err = testConnReadNonzeroAndEOF(t, delay); err == nil { - return - } - } - t.Error(err) -} - -func testConnReadNonzeroAndEOF(t *testing.T, delay time.Duration) error { - ln := newLocalListener(t) - defer ln.Close() - - srvCh := make(chan *Conn, 1) - var serr error - go func() { - sconn, err := ln.Accept() - if err != nil { - serr = err - srvCh <- nil - return - } - serverConfig := *testConfig - srv := Server(sconn, &serverConfig) - if err := srv.Handshake(); err != nil { - serr = fmt.Errorf("handshake: %v", err) - srvCh <- nil - return - } - srvCh <- srv - }() - - clientConfig := *testConfig - conn, err := Dial("tcp", ln.Addr().String(), &clientConfig) - if err != nil { - t.Fatal(err) - } - defer conn.Close() - - srv := <-srvCh - if srv == nil { - return serr - } - - buf := make([]byte, 6) - - srv.Write([]byte("foobar")) - n, err := conn.Read(buf) - if n != 6 || err != nil || string(buf) != "foobar" { - return fmt.Errorf("Read = %d, %v, data %q; want 6, nil, foobar", n, err, buf) - } - - srv.Write([]byte("abcdef")) - srv.Close() - time.Sleep(delay) - n, err = conn.Read(buf) - if n != 6 || string(buf) != "abcdef" { - return fmt.Errorf("Read = %d, buf= %q; want 6, abcdef", n, buf) - } - if err != io.EOF { - return fmt.Errorf("Second Read error = %v; want io.EOF", err) - } - return nil -} - -func TestTLSUniqueMatches(t *testing.T) { - ln := newLocalListener(t) - defer ln.Close() - - serverTLSUniques := make(chan []byte) - go func() { - for i := 0; i < 2; i++ { - sconn, err := ln.Accept() - if err != nil { - t.Fatal(err) - } - serverConfig := *testConfig - srv := Server(sconn, &serverConfig) - if err := srv.Handshake(); err != nil { - t.Fatal(err) - } - serverTLSUniques <- srv.ConnectionState().TLSUnique - } - }() - - clientConfig := *testConfig - clientConfig.ClientSessionCache = NewLRUClientSessionCache(1) - conn, err := Dial("tcp", ln.Addr().String(), &clientConfig) - if err != nil { - t.Fatal(err) - } - if !bytes.Equal(conn.ConnectionState().TLSUnique, <-serverTLSUniques) { - t.Error("client and server channel bindings differ") - } - conn.Close() - - conn, err = Dial("tcp", ln.Addr().String(), &clientConfig) - if err != nil { - t.Fatal(err) - } - defer conn.Close() - if !conn.ConnectionState().DidResume { - t.Error("second session did not use resumption") - } - if !bytes.Equal(conn.ConnectionState().TLSUnique, <-serverTLSUniques) { - t.Error("client and server channel bindings differ when session resumption is used") - } -} diff --git a/src/pkg/crypto/x509/cert_pool.go b/src/pkg/crypto/x509/cert_pool.go deleted file mode 100644 index babe94d41..000000000 --- a/src/pkg/crypto/x509/cert_pool.go +++ /dev/null @@ -1,116 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package x509 - -import ( - "encoding/pem" -) - -// CertPool is a set of certificates. -type CertPool struct { - bySubjectKeyId map[string][]int - byName map[string][]int - certs []*Certificate -} - -// NewCertPool returns a new, empty CertPool. -func NewCertPool() *CertPool { - return &CertPool{ - make(map[string][]int), - make(map[string][]int), - nil, - } -} - -// findVerifiedParents attempts to find certificates in s which have signed the -// given certificate. If any candidates were rejected then errCert will be set -// to one of them, arbitrarily, and err will contain the reason that it was -// rejected. -func (s *CertPool) findVerifiedParents(cert *Certificate) (parents []int, errCert *Certificate, err error) { - if s == nil { - return - } - var candidates []int - - if len(cert.AuthorityKeyId) > 0 { - candidates = s.bySubjectKeyId[string(cert.AuthorityKeyId)] - } - if len(candidates) == 0 { - candidates = s.byName[string(cert.RawIssuer)] - } - - for _, c := range candidates { - if err = cert.CheckSignatureFrom(s.certs[c]); err == nil { - parents = append(parents, c) - } else { - errCert = s.certs[c] - } - } - - return -} - -// AddCert adds a certificate to a pool. -func (s *CertPool) AddCert(cert *Certificate) { - if cert == nil { - panic("adding nil Certificate to CertPool") - } - - // Check that the certificate isn't being added twice. - for _, c := range s.certs { - if c.Equal(cert) { - return - } - } - - n := len(s.certs) - s.certs = append(s.certs, cert) - - if len(cert.SubjectKeyId) > 0 { - keyId := string(cert.SubjectKeyId) - s.bySubjectKeyId[keyId] = append(s.bySubjectKeyId[keyId], n) - } - name := string(cert.RawSubject) - s.byName[name] = append(s.byName[name], n) -} - -// AppendCertsFromPEM attempts to parse a series of PEM encoded certificates. -// It appends any certificates found to s and returns true if any certificates -// were successfully parsed. -// -// On many Linux systems, /etc/ssl/cert.pem will contain the system wide set -// of root CAs in a format suitable for this function. -func (s *CertPool) AppendCertsFromPEM(pemCerts []byte) (ok bool) { - for len(pemCerts) > 0 { - var block *pem.Block - block, pemCerts = pem.Decode(pemCerts) - if block == nil { - break - } - if block.Type != "CERTIFICATE" || len(block.Headers) != 0 { - continue - } - - cert, err := ParseCertificate(block.Bytes) - if err != nil { - continue - } - - s.AddCert(cert) - ok = true - } - - return -} - -// Subjects returns a list of the DER-encoded subjects of -// all of the certificates in the pool. -func (s *CertPool) Subjects() (res [][]byte) { - res = make([][]byte, len(s.certs)) - for i, c := range s.certs { - res[i] = c.RawSubject - } - return -} diff --git a/src/pkg/crypto/x509/example_test.go b/src/pkg/crypto/x509/example_test.go deleted file mode 100644 index 29e7c2139..000000000 --- a/src/pkg/crypto/x509/example_test.go +++ /dev/null @@ -1,91 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package x509_test - -import ( - "crypto/x509" - "encoding/pem" -) - -func ExampleCertificate_Verify() { - // Verifying with a custom list of root certificates. - - const rootPEM = ` ------BEGIN CERTIFICATE----- -MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT -MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i -YWwgQ0EwHhcNMTMwNDA1MTUxNTU1WhcNMTUwNDA0MTUxNTU1WjBJMQswCQYDVQQG -EwJVUzETMBEGA1UEChMKR29vZ2xlIEluYzElMCMGA1UEAxMcR29vZ2xlIEludGVy -bmV0IEF1dGhvcml0eSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB -AJwqBHdc2FCROgajguDYUEi8iT/xGXAaiEZ+4I/F8YnOIe5a/mENtzJEiaB0C1NP -VaTOgmKV7utZX8bhBYASxF6UP7xbSDj0U/ck5vuR6RXEz/RTDfRK/J9U3n2+oGtv -h8DQUB8oMANA2ghzUWx//zo8pzcGjr1LEQTrfSTe5vn8MXH7lNVg8y5Kr0LSy+rE -ahqyzFPdFUuLH8gZYR/Nnag+YyuENWllhMgZxUYi+FOVvuOAShDGKuy6lyARxzmZ -EASg8GF6lSWMTlJ14rbtCMoU/M4iarNOz0YDl5cDfsCx3nuvRTPPuj5xt970JSXC -DTWJnZ37DhF5iR43xa+OcmkCAwEAAaOB+zCB+DAfBgNVHSMEGDAWgBTAephojYn7 -qwVkDBF9qn1luMrMTjAdBgNVHQ4EFgQUSt0GFhu89mi1dvWBtrtiGrpagS8wEgYD -VR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAQYwOgYDVR0fBDMwMTAvoC2g -K4YpaHR0cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9ndGdsb2JhbC5jcmwwPQYI -KwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwOi8vZ3RnbG9iYWwtb2NzcC5n -ZW90cnVzdC5jb20wFwYDVR0gBBAwDjAMBgorBgEEAdZ5AgUBMA0GCSqGSIb3DQEB -BQUAA4IBAQA21waAESetKhSbOHezI6B1WLuxfoNCunLaHtiONgaX4PCVOzf9G0JY -/iLIa704XtE7JW4S615ndkZAkNoUyHgN7ZVm2o6Gb4ChulYylYbc3GrKBIxbf/a/ -zG+FA1jDaFETzf3I93k9mTXwVqO94FntT0QJo544evZG0R0SnU++0ED8Vf4GXjza -HFa9llF7b1cq26KqltyMdMKVvvBulRP/F/A8rLIQjcxz++iPAsbw+zOzlTvjwsto -WHPbqCRiOwY1nQ2pM714A5AuTHhdUDqB1O6gyHA43LL5Z/qHQF1hwFGPa4NrzQU6 -yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx ------END CERTIFICATE-----` - - const certPEM = ` ------BEGIN CERTIFICATE----- -MIIDujCCAqKgAwIBAgIIE31FZVaPXTUwDQYJKoZIhvcNAQEFBQAwSTELMAkGA1UE -BhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMxJTAjBgNVBAMTHEdvb2dsZSBJbnRl -cm5ldCBBdXRob3JpdHkgRzIwHhcNMTQwMTI5MTMyNzQzWhcNMTQwNTI5MDAwMDAw -WjBpMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwN -TW91bnRhaW4gVmlldzETMBEGA1UECgwKR29vZ2xlIEluYzEYMBYGA1UEAwwPbWFp -bC5nb29nbGUuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEfRrObuSW5T7q -5CnSEqefEmtH4CCv6+5EckuriNr1CjfVvqzwfAhopXkLrq45EQm8vkmf7W96XJhC -7ZM0dYi1/qOCAU8wggFLMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAa -BgNVHREEEzARgg9tYWlsLmdvb2dsZS5jb20wCwYDVR0PBAQDAgeAMGgGCCsGAQUF -BwEBBFwwWjArBggrBgEFBQcwAoYfaHR0cDovL3BraS5nb29nbGUuY29tL0dJQUcy -LmNydDArBggrBgEFBQcwAYYfaHR0cDovL2NsaWVudHMxLmdvb2dsZS5jb20vb2Nz -cDAdBgNVHQ4EFgQUiJxtimAuTfwb+aUtBn5UYKreKvMwDAYDVR0TAQH/BAIwADAf -BgNVHSMEGDAWgBRK3QYWG7z2aLV29YG2u2IaulqBLzAXBgNVHSAEEDAOMAwGCisG -AQQB1nkCBQEwMAYDVR0fBCkwJzAloCOgIYYfaHR0cDovL3BraS5nb29nbGUuY29t -L0dJQUcyLmNybDANBgkqhkiG9w0BAQUFAAOCAQEAH6RYHxHdcGpMpFE3oxDoFnP+ -gtuBCHan2yE2GRbJ2Cw8Lw0MmuKqHlf9RSeYfd3BXeKkj1qO6TVKwCh+0HdZk283 -TZZyzmEOyclm3UGFYe82P/iDFt+CeQ3NpmBg+GoaVCuWAARJN/KfglbLyyYygcQq -0SgeDh8dRKUiaW3HQSoYvTvdTuqzwK4CXsr3b5/dAOY8uMuG/IAR3FgwTbZ1dtoW -RvOTa8hYiU6A475WuZKyEHcwnGYe57u2I2KbMgcKjPniocj4QzgYsVAVKW3IwaOh -yE+vPxsiUkvQHdO2fojCkY8jg70jxM+gu59tPDNbw3Uh/2Ij310FgTHsnGQMyA== ------END CERTIFICATE-----` - - // First, create the set of root certificates. For this example we only - // have one. It's also possible to omit this in order to use the - // default root set of the current operating system. - roots := x509.NewCertPool() - ok := roots.AppendCertsFromPEM([]byte(rootPEM)) - if !ok { - panic("failed to parse root certificate") - } - - block, _ := pem.Decode([]byte(certPEM)) - if block == nil { - panic("failed to parse certificate PEM") - } - cert, err := x509.ParseCertificate(block.Bytes) - if err != nil { - panic("failed to parse certificate: " + err.Error()) - } - - opts := x509.VerifyOptions{ - DNSName: "mail.google.com", - Roots: roots, - } - - if _, err := cert.Verify(opts); err != nil { - panic("failed to verify certificate: " + err.Error()) - } -} diff --git a/src/pkg/crypto/x509/pem_decrypt.go b/src/pkg/crypto/x509/pem_decrypt.go deleted file mode 100644 index 194c81bf6..000000000 --- a/src/pkg/crypto/x509/pem_decrypt.go +++ /dev/null @@ -1,233 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package x509 - -// RFC 1423 describes the encryption of PEM blocks. The algorithm used to -// generate a key from the password was derived by looking at the OpenSSL -// implementation. - -import ( - "crypto/aes" - "crypto/cipher" - "crypto/des" - "crypto/md5" - "encoding/hex" - "encoding/pem" - "errors" - "io" - "strings" -) - -type PEMCipher int - -// Possible values for the EncryptPEMBlock encryption algorithm. -const ( - _ PEMCipher = iota - PEMCipherDES - PEMCipher3DES - PEMCipherAES128 - PEMCipherAES192 - PEMCipherAES256 -) - -// rfc1423Algo holds a method for enciphering a PEM block. -type rfc1423Algo struct { - cipher PEMCipher - name string - cipherFunc func(key []byte) (cipher.Block, error) - keySize int - blockSize int -} - -// rfc1423Algos holds a slice of the possible ways to encrypt a PEM -// block. The ivSize numbers were taken from the OpenSSL source. -var rfc1423Algos = []rfc1423Algo{{ - cipher: PEMCipherDES, - name: "DES-CBC", - cipherFunc: des.NewCipher, - keySize: 8, - blockSize: des.BlockSize, -}, { - cipher: PEMCipher3DES, - name: "DES-EDE3-CBC", - cipherFunc: des.NewTripleDESCipher, - keySize: 24, - blockSize: des.BlockSize, -}, { - cipher: PEMCipherAES128, - name: "AES-128-CBC", - cipherFunc: aes.NewCipher, - keySize: 16, - blockSize: aes.BlockSize, -}, { - cipher: PEMCipherAES192, - name: "AES-192-CBC", - cipherFunc: aes.NewCipher, - keySize: 24, - blockSize: aes.BlockSize, -}, { - cipher: PEMCipherAES256, - name: "AES-256-CBC", - cipherFunc: aes.NewCipher, - keySize: 32, - blockSize: aes.BlockSize, -}, -} - -// deriveKey uses a key derivation function to stretch the password into a key -// with the number of bits our cipher requires. This algorithm was derived from -// the OpenSSL source. -func (c rfc1423Algo) deriveKey(password, salt []byte) []byte { - hash := md5.New() - out := make([]byte, c.keySize) - var digest []byte - - for i := 0; i < len(out); i += len(digest) { - hash.Reset() - hash.Write(digest) - hash.Write(password) - hash.Write(salt) - digest = hash.Sum(digest[:0]) - copy(out[i:], digest) - } - return out -} - -// IsEncryptedPEMBlock returns if the PEM block is password encrypted. -func IsEncryptedPEMBlock(b *pem.Block) bool { - _, ok := b.Headers["DEK-Info"] - return ok -} - -// IncorrectPasswordError is returned when an incorrect password is detected. -var IncorrectPasswordError = errors.New("x509: decryption password incorrect") - -// DecryptPEMBlock takes a password encrypted PEM block and the password used to -// encrypt it and returns a slice of decrypted DER encoded bytes. It inspects -// the DEK-Info header to determine the algorithm used for decryption. If no -// DEK-Info header is present, an error is returned. If an incorrect password -// is detected an IncorrectPasswordError is returned. -func DecryptPEMBlock(b *pem.Block, password []byte) ([]byte, error) { - dek, ok := b.Headers["DEK-Info"] - if !ok { - return nil, errors.New("x509: no DEK-Info header in block") - } - - idx := strings.Index(dek, ",") - if idx == -1 { - return nil, errors.New("x509: malformed DEK-Info header") - } - - mode, hexIV := dek[:idx], dek[idx+1:] - ciph := cipherByName(mode) - if ciph == nil { - return nil, errors.New("x509: unknown encryption mode") - } - iv, err := hex.DecodeString(hexIV) - if err != nil { - return nil, err - } - if len(iv) != ciph.blockSize { - return nil, errors.New("x509: incorrect IV size") - } - - // Based on the OpenSSL implementation. The salt is the first 8 bytes - // of the initialization vector. - key := ciph.deriveKey(password, iv[:8]) - block, err := ciph.cipherFunc(key) - if err != nil { - return nil, err - } - - data := make([]byte, len(b.Bytes)) - dec := cipher.NewCBCDecrypter(block, iv) - dec.CryptBlocks(data, b.Bytes) - - // Blocks are padded using a scheme where the last n bytes of padding are all - // equal to n. It can pad from 1 to blocksize bytes inclusive. See RFC 1423. - // For example: - // [x y z 2 2] - // [x y 7 7 7 7 7 7 7] - // If we detect a bad padding, we assume it is an invalid password. - dlen := len(data) - if dlen == 0 || dlen%ciph.blockSize != 0 { - return nil, errors.New("x509: invalid padding") - } - last := int(data[dlen-1]) - if dlen < last { - return nil, IncorrectPasswordError - } - if last == 0 || last > ciph.blockSize { - return nil, IncorrectPasswordError - } - for _, val := range data[dlen-last:] { - if int(val) != last { - return nil, IncorrectPasswordError - } - } - return data[:dlen-last], nil -} - -// EncryptPEMBlock returns a PEM block of the specified type holding the -// given DER-encoded data encrypted with the specified algorithm and -// password. -func EncryptPEMBlock(rand io.Reader, blockType string, data, password []byte, alg PEMCipher) (*pem.Block, error) { - ciph := cipherByKey(alg) - if ciph == nil { - return nil, errors.New("x509: unknown encryption mode") - } - iv := make([]byte, ciph.blockSize) - if _, err := io.ReadFull(rand, iv); err != nil { - return nil, errors.New("x509: cannot generate IV: " + err.Error()) - } - // The salt is the first 8 bytes of the initialization vector, - // matching the key derivation in DecryptPEMBlock. - key := ciph.deriveKey(password, iv[:8]) - block, err := ciph.cipherFunc(key) - if err != nil { - return nil, err - } - enc := cipher.NewCBCEncrypter(block, iv) - pad := ciph.blockSize - len(data)%ciph.blockSize - encrypted := make([]byte, len(data), len(data)+pad) - // We could save this copy by encrypting all the whole blocks in - // the data separately, but it doesn't seem worth the additional - // code. - copy(encrypted, data) - // See RFC 1423, section 1.1 - for i := 0; i < pad; i++ { - encrypted = append(encrypted, byte(pad)) - } - enc.CryptBlocks(encrypted, encrypted) - - return &pem.Block{ - Type: blockType, - Headers: map[string]string{ - "Proc-Type": "4,ENCRYPTED", - "DEK-Info": ciph.name + "," + hex.EncodeToString(iv), - }, - Bytes: encrypted, - }, nil -} - -func cipherByName(name string) *rfc1423Algo { - for i := range rfc1423Algos { - alg := &rfc1423Algos[i] - if alg.name == name { - return alg - } - } - return nil -} - -func cipherByKey(key PEMCipher) *rfc1423Algo { - for i := range rfc1423Algos { - alg := &rfc1423Algos[i] - if alg.cipher == key { - return alg - } - } - return nil -} diff --git a/src/pkg/crypto/x509/pem_decrypt_test.go b/src/pkg/crypto/x509/pem_decrypt_test.go deleted file mode 100644 index 13e4700bd..000000000 --- a/src/pkg/crypto/x509/pem_decrypt_test.go +++ /dev/null @@ -1,223 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package x509 - -import ( - "bytes" - "crypto/rand" - "encoding/base64" - "encoding/pem" - "testing" -) - -func TestDecrypt(t *testing.T) { - for i, data := range testData { - t.Logf("test %v. %v", i, data.kind) - block, rest := pem.Decode(data.pemData) - if len(rest) > 0 { - t.Error("extra data") - } - der, err := DecryptPEMBlock(block, data.password) - if err != nil { - t.Error("decrypt failed: ", err) - continue - } - if _, err := ParsePKCS1PrivateKey(der); err != nil { - t.Error("invalid private key: ", err) - } - plainDER, err := base64.StdEncoding.DecodeString(data.plainDER) - if err != nil { - t.Fatal("cannot decode test DER data: ", err) - } - if !bytes.Equal(der, plainDER) { - t.Error("data mismatch") - } - } -} - -func TestEncrypt(t *testing.T) { - for i, data := range testData { - t.Logf("test %v. %v", i, data.kind) - plainDER, err := base64.StdEncoding.DecodeString(data.plainDER) - if err != nil { - t.Fatal("cannot decode test DER data: ", err) - } - password := []byte("kremvax1") - block, err := EncryptPEMBlock(rand.Reader, "RSA PRIVATE KEY", plainDER, password, data.kind) - if err != nil { - t.Error("encrypt: ", err) - continue - } - if !IsEncryptedPEMBlock(block) { - t.Error("PEM block does not appear to be encrypted") - } - if block.Type != "RSA PRIVATE KEY" { - t.Errorf("unexpected block type; got %q want %q", block.Type, "RSA PRIVATE KEY") - } - if block.Headers["Proc-Type"] != "4,ENCRYPTED" { - t.Errorf("block does not have correct Proc-Type header") - } - der, err := DecryptPEMBlock(block, password) - if err != nil { - t.Error("decrypt: ", err) - continue - } - if !bytes.Equal(der, plainDER) { - t.Errorf("data mismatch") - } - } -} - -var testData = []struct { - kind PEMCipher - password []byte - pemData []byte - plainDER string -}{ - { - kind: PEMCipherDES, - password: []byte("asdf"), - pemData: []byte(` ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: DES-CBC,34F09A4FC8DE22B5 - -WXxy8kbZdiZvANtKvhmPBLV7eVFj2A5z6oAxvI9KGyhG0ZK0skfnt00C24vfU7m5 -ICXeoqP67lzJ18xCzQfHjDaBNs53DSDT+Iz4e8QUep1xQ30+8QKX2NA2coee3nwc -6oM1cuvhNUDemBH2i3dKgMVkfaga0zQiiOq6HJyGSncCMSruQ7F9iWEfRbFcxFCx -qtHb1kirfGKEtgWTF+ynyco6+2gMXNu70L7nJcnxnV/RLFkHt7AUU1yrclxz7eZz -XOH9VfTjb52q/I8Suozq9coVQwg4tXfIoYUdT//O+mB7zJb9HI9Ps77b9TxDE6Gm -4C9brwZ3zg2vqXcwwV6QRZMtyll9rOpxkbw6NPlpfBqkc3xS51bbxivbO/Nve4KD -r12ymjFNF4stXCfJnNqKoZ50BHmEEUDu5Wb0fpVn82XrGw7CYc4iug== ------END RSA PRIVATE KEY-----`), - plainDER: ` -MIIBPAIBAAJBAPASZe+tCPU6p80AjHhDkVsLYa51D35e/YGa8QcZyooeZM8EHozo -KD0fNiKI+53bHdy07N+81VQ8/ejPcRoXPlsCAwEAAQJBAMTxIuSq27VpR+zZ7WJf -c6fvv1OBvpMZ0/d1pxL/KnOAgq2rD5hDtk9b0LGhTPgQAmrrMTKuSeGoIuYE+gKQ -QvkCIQD+GC1m+/do+QRurr0uo46Kx1LzLeSCrjBk34wiOp2+dwIhAPHfTLRXS2fv -7rljm0bYa4+eDZpz+E8RcXEgzhhvcQQ9AiAI5eHZJGOyml3MXnQjiPi55WcDOw0w -glcRgT6QCEtz2wIhANSyqaFtosIkHKqrDUGfz/bb5tqMYTAnBruVPaf/WEOBAiEA -9xORWeRG1tRpso4+dYy4KdDkuLPIO01KY6neYGm3BCM=`, - }, - { - kind: PEMCipher3DES, - password: []byte("asdf"), - pemData: []byte(` ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: DES-EDE3-CBC,C1F4A6A03682C2C7 - -0JqVdBEH6iqM7drTkj+e2W/bE3LqakaiWhb9WUVonFkhyu8ca/QzebY3b5gCvAZQ -YwBvDcT/GHospKqPx+cxDHJNsUASDZws6bz8ZXWJGwZGExKzr0+Qx5fgXn44Ms3x -8g1ENFuTXtxo+KoNK0zuAMAqp66Llcds3Fjl4XR18QaD0CrVNAfOdgATWZm5GJxk -Fgx5f84nT+/ovvreG+xeOzWgvtKo0UUZVrhGOgfKLpa57adumcJ6SkUuBtEFpZFB -ldw5w7WC7d13x2LsRkwo8ZrDKgIV+Y9GNvhuCCkTzNP0V3gNeJpd201HZHR+9n3w -3z0VjR/MGqsfcy1ziEWMNOO53At3zlG6zP05aHMnMcZoVXadEK6L1gz++inSSDCq -gI0UJP4e3JVB7AkgYymYAwiYALAkoEIuanxoc50njJk= ------END RSA PRIVATE KEY-----`), - plainDER: ` -MIIBOwIBAAJBANOCXKdoNS/iP/MAbl9cf1/SF3P+Ns7ZeNL27CfmDh0O6Zduaax5 -NBiumd2PmjkaCu7lQ5JOibHfWn+xJsc3kw0CAwEAAQJANX/W8d1Q/sCqzkuAn4xl -B5a7qfJWaLHndu1QRLNTRJPn0Ee7OKJ4H0QKOhQM6vpjRrz+P2u9thn6wUxoPsef -QQIhAP/jCkfejFcy4v15beqKzwz08/tslVjF+Yq41eJGejmxAiEA05pMoqfkyjcx -fyvGhpoOyoCp71vSGUfR2I9CR65oKh0CIC1Msjs66LlfJtQctRq6bCEtFCxEcsP+ -eEjYo/Sk6WphAiEAxpgWPMJeU/shFT28gS+tmhjPZLpEoT1qkVlC14u0b3ECIQDX -tZZZxCtPAm7shftEib0VU77Lk8MsXJcx2C4voRsjEw==`, - }, - { - kind: PEMCipherAES128, - password: []byte("asdf"), - pemData: []byte(` ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: AES-128-CBC,D4492E793FC835CC038A728ED174F78A - -EyfQSzXSjv6BaNH+NHdXRlkHdimpF9izWlugVJAPApgXrq5YldPe2aGIOFXyJ+QE -ZIG20DYqaPzJRjTEbPNZ6Es0S2JJ5yCpKxwJuDkgJZKtF39Q2i36JeGbSZQIuWJE -GZbBpf1jDH/pr0iGonuAdl2PCCZUiy+8eLsD2tyviHUkFLOB+ykYoJ5t8ngZ/B6D -33U43LLb7+9zD4y3Q9OVHqBFGyHcxCY9+9Qh4ZnFp7DTf6RY5TNEvE3s4g6aDpBs -3NbvRVvYTgs8K9EPk4K+5R+P2kD8J8KvEIGxVa1vz8QoCJ/jr7Ka2rvNgPCex5/E -080LzLHPCrXKdlr/f50yhNWq08ZxMWQFkui+FDHPDUaEELKAXV8/5PDxw80Rtybo -AVYoCVIbZXZCuCO81op8UcOgEpTtyU5Lgh3Mw5scQL0= ------END RSA PRIVATE KEY-----`), - plainDER: ` -MIIBOgIBAAJBAMBlj5FxYtqbcy8wY89d/S7n0+r5MzD9F63BA/Lpl78vQKtdJ5dT -cDGh/rBt1ufRrNp0WihcmZi7Mpl/3jHjiWECAwEAAQJABNOHYnKhtDIqFYj1OAJ3 -k3GlU0OlERmIOoeY/cL2V4lgwllPBEs7r134AY4wMmZSBUj8UR/O4SNO668ElKPE -cQIhAOuqY7/115x5KCdGDMWi+jNaMxIvI4ETGwV40ykGzqlzAiEA0P9oEC3m9tHB -kbpjSTxaNkrXxDgdEOZz8X0uOUUwHNsCIAwzcSCiGLyYJTULUmP1ESERfW1mlV78 -XzzESaJpIM/zAiBQkSTcl9VhcJreQqvjn5BnPZLP4ZHS4gPwJAGdsj5J4QIhAOVR -B3WlRNTXR2WsJ5JdByezg9xzdXzULqmga0OE339a`, - }, - { - kind: PEMCipherAES192, - password: []byte("asdf"), - pemData: []byte(` ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: AES-192-CBC,E2C9FB02BCA23ADE1829F8D8BC5F5369 - -cqVslvHqDDM6qwU6YjezCRifXmKsrgEev7ng6Qs7UmDJOpHDgJQZI9fwMFUhIyn5 -FbCu1SHkLMW52Ld3CuEqMnzWMlhPrW8tFvUOrMWPYSisv7nNq88HobZEJcUNL2MM -Y15XmHW6IJwPqhKyLHpWXyOCVEh4ODND2nV15PCoi18oTa475baxSk7+1qH7GuIs -Rb7tshNTMqHbCpyo9Rn3UxeFIf9efdl8YLiMoIqc7J8E5e9VlbeQSdLMQOgDAQJG -ReUtTw8exmKsY4gsSjhkg5uiw7/ZB1Ihto0qnfQJgjGc680qGkT1d6JfvOfeYAk6 -xn5RqS/h8rYAYm64KnepfC9vIujo4NqpaREDmaLdX5MJPQ+SlytITQvgUsUq3q/t -Ss85xjQEZH3hzwjQqdJvmA4hYP6SUjxYpBM+02xZ1Xw= ------END RSA PRIVATE KEY-----`), - plainDER: ` -MIIBOwIBAAJBAMGcRrZiNNmtF20zyS6MQ7pdGx17aFDl+lTl+qnLuJRUCMUG05xs -OmxmL/O1Qlf+bnqR8Bgg65SfKg21SYuLhiMCAwEAAQJBAL94uuHyO4wux2VC+qpj -IzPykjdU7XRcDHbbvksf4xokSeUFjjD3PB0Qa83M94y89ZfdILIqS9x5EgSB4/lX -qNkCIQD6cCIqLfzq/lYbZbQgAAjpBXeQVYsbvVtJrPrXJAlVVQIhAMXpDKMeFPMn -J0g2rbx1gngx0qOa5r5iMU5w/noN4W2XAiBjf+WzCG5yFvazD+dOx3TC0A8+4x3P -uZ3pWbaXf5PNuQIgAcdXarvhelH2w2piY1g3BPeFqhzBSCK/yLGxR82KIh8CIQDD -+qGKsd09NhQ/G27y/DARzOYtml1NvdmCQAgsDIIOLA==`, - }, - { - kind: PEMCipherAES256, - password: []byte("asdf"), - pemData: []byte(` ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: AES-256-CBC,8E7ED5CD731902CE938957A886A5FFBD - -4Mxr+KIzRVwoOP0wwq6caSkvW0iS+GE2h2Ov/u+n9ZTMwL83PRnmjfjzBgfRZLVf -JFPXxUK26kMNpIdssNnqGOds+DhB+oSrsNKoxgxSl5OBoYv9eJTVYm7qOyAFIsjr -DRKAcjYCmzfesr7PVTowwy0RtHmYwyXMGDlAzzZrEvaiySFFmMyKKvtoavwaFoc7 -Pz3RZScwIuubzTGJ1x8EzdffYOsdCa9Mtgpp3L136+23dOd6L/qK2EG2fzrJSHs/ -2XugkleBFSMKzEp9mxXKRfa++uidQvMZTFLDK9w5YjrRvMBo/l2BoZIsq0jAIE1N -sv5Z/KwlX+3MDEpPQpUwGPlGGdLnjI3UZ+cjgqBcoMiNc6HfgbBgYJSU6aDSHuCk -clCwByxWkBNgJ2GrkwNrF26v+bGJJJNR4SKouY1jQf0= ------END RSA PRIVATE KEY-----`), - plainDER: ` -MIIBOgIBAAJBAKy3GFkstoCHIEeUU/qO8207m8WSrjksR+p9B4tf1w5k+2O1V/GY -AQ5WFCApItcOkQe/I0yZZJk/PmCqMzSxrc8CAwEAAQJAOCAz0F7AW9oNelVQSP8F -Sfzx7O1yom+qWyAQQJF/gFR11gpf9xpVnnyu1WxIRnDUh1LZwUsjwlDYb7MB74id -oQIhANPcOiLwOPT4sIUpRM5HG6BF1BI7L77VpyGVk8xNP7X/AiEA0LMHZtk4I+lJ -nClgYp4Yh2JZ1Znbu7IoQMCEJCjwKDECIGd8Dzm5tViTkUW6Hs3Tlf73nNs65duF -aRnSglss8I3pAiEAonEnKruawgD8RavDFR+fUgmQiPz4FnGGeVgfwpGG1JECIBYq -PXHYtPqxQIbD2pScR5qum7iGUh11lEUPkmt+2uqS`, - }, - { - // generated with: - // openssl genrsa -aes128 -passout pass:asdf -out server.orig.key 128 - kind: PEMCipherAES128, - password: []byte("asdf"), - pemData: []byte(` ------BEGIN RSA PRIVATE KEY----- -Proc-Type: 4,ENCRYPTED -DEK-Info: AES-128-CBC,74611ABC2571AF11B1BF9B69E62C89E7 - -6ei/MlytjE0FFgZOGQ+jrwomKfpl8kdefeE0NSt/DMRrw8OacHAzBNi3pPEa0eX3 -eND9l7C9meCirWovjj9QWVHrXyugFuDIqgdhQ8iHTgCfF3lrmcttVrbIfMDw+smD -hTP8O1mS/MHl92NE0nhv0w== ------END RSA PRIVATE KEY-----`), - plainDER: ` -MGMCAQACEQC6ssxmYuauuHGOCDAI54RdAgMBAAECEQCWIn6Yv2O+kBcDF7STctKB -AgkA8SEfu/2i3g0CCQDGNlXbBHX7kQIIK3Ww5o0cYbECCQDCimPb0dYGsQIIeQ7A -jryIst8=`, - }, -} diff --git a/src/pkg/crypto/x509/pkcs1.go b/src/pkg/crypto/x509/pkcs1.go deleted file mode 100644 index acebe3513..000000000 --- a/src/pkg/crypto/x509/pkcs1.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package x509 - -import ( - "crypto/rsa" - "encoding/asn1" - "errors" - "math/big" -) - -// pkcs1PrivateKey is a structure which mirrors the PKCS#1 ASN.1 for an RSA private key. -type pkcs1PrivateKey struct { - Version int - N *big.Int - E int - D *big.Int - P *big.Int - Q *big.Int - // We ignore these values, if present, because rsa will calculate them. - Dp *big.Int `asn1:"optional"` - Dq *big.Int `asn1:"optional"` - Qinv *big.Int `asn1:"optional"` - - AdditionalPrimes []pkcs1AdditionalRSAPrime `asn1:"optional,omitempty"` -} - -type pkcs1AdditionalRSAPrime struct { - Prime *big.Int - - // We ignore these values because rsa will calculate them. - Exp *big.Int - Coeff *big.Int -} - -// ParsePKCS1PrivateKey returns an RSA private key from its ASN.1 PKCS#1 DER encoded form. -func ParsePKCS1PrivateKey(der []byte) (key *rsa.PrivateKey, err error) { - var priv pkcs1PrivateKey - rest, err := asn1.Unmarshal(der, &priv) - if len(rest) > 0 { - err = asn1.SyntaxError{Msg: "trailing data"} - return - } - if err != nil { - return - } - - if priv.Version > 1 { - return nil, errors.New("x509: unsupported private key version") - } - - if priv.N.Sign() <= 0 || priv.D.Sign() <= 0 || priv.P.Sign() <= 0 || priv.Q.Sign() <= 0 { - return nil, errors.New("x509: private key contains zero or negative value") - } - - key = new(rsa.PrivateKey) - key.PublicKey = rsa.PublicKey{ - E: priv.E, - N: priv.N, - } - - key.D = priv.D - key.Primes = make([]*big.Int, 2+len(priv.AdditionalPrimes)) - key.Primes[0] = priv.P - key.Primes[1] = priv.Q - for i, a := range priv.AdditionalPrimes { - if a.Prime.Sign() <= 0 { - return nil, errors.New("x509: private key contains zero or negative prime") - } - key.Primes[i+2] = a.Prime - // We ignore the other two values because rsa will calculate - // them as needed. - } - - err = key.Validate() - if err != nil { - return nil, err - } - key.Precompute() - - return -} - -// MarshalPKCS1PrivateKey converts a private key to ASN.1 DER encoded form. -func MarshalPKCS1PrivateKey(key *rsa.PrivateKey) []byte { - key.Precompute() - - version := 0 - if len(key.Primes) > 2 { - version = 1 - } - - priv := pkcs1PrivateKey{ - Version: version, - N: key.N, - E: key.PublicKey.E, - D: key.D, - P: key.Primes[0], - Q: key.Primes[1], - Dp: key.Precomputed.Dp, - Dq: key.Precomputed.Dq, - Qinv: key.Precomputed.Qinv, - } - - priv.AdditionalPrimes = make([]pkcs1AdditionalRSAPrime, len(key.Precomputed.CRTValues)) - for i, values := range key.Precomputed.CRTValues { - priv.AdditionalPrimes[i].Prime = key.Primes[2+i] - priv.AdditionalPrimes[i].Exp = values.Exp - priv.AdditionalPrimes[i].Coeff = values.Coeff - } - - b, _ := asn1.Marshal(priv) - return b -} - -// rsaPublicKey reflects the ASN.1 structure of a PKCS#1 public key. -type rsaPublicKey struct { - N *big.Int - E int -} diff --git a/src/pkg/crypto/x509/pkcs8.go b/src/pkg/crypto/x509/pkcs8.go deleted file mode 100644 index ba19989cb..000000000 --- a/src/pkg/crypto/x509/pkcs8.go +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package x509 - -import ( - "crypto/x509/pkix" - "encoding/asn1" - "errors" - "fmt" -) - -// pkcs8 reflects an ASN.1, PKCS#8 PrivateKey. See -// ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-8/pkcs-8v1_2.asn -// and RFC5208. -type pkcs8 struct { - Version int - Algo pkix.AlgorithmIdentifier - PrivateKey []byte - // optional attributes omitted. -} - -// ParsePKCS8PrivateKey parses an unencrypted, PKCS#8 private key. See -// http://www.rsa.com/rsalabs/node.asp?id=2130 and RFC5208. -func ParsePKCS8PrivateKey(der []byte) (key interface{}, err error) { - var privKey pkcs8 - if _, err := asn1.Unmarshal(der, &privKey); err != nil { - return nil, err - } - switch { - case privKey.Algo.Algorithm.Equal(oidPublicKeyRSA): - key, err = ParsePKCS1PrivateKey(privKey.PrivateKey) - if err != nil { - return nil, errors.New("x509: failed to parse RSA private key embedded in PKCS#8: " + err.Error()) - } - return key, nil - - case privKey.Algo.Algorithm.Equal(oidPublicKeyECDSA): - bytes := privKey.Algo.Parameters.FullBytes - namedCurveOID := new(asn1.ObjectIdentifier) - if _, err := asn1.Unmarshal(bytes, namedCurveOID); err != nil { - namedCurveOID = nil - } - key, err = parseECPrivateKey(namedCurveOID, privKey.PrivateKey) - if err != nil { - return nil, errors.New("x509: failed to parse EC private key embedded in PKCS#8: " + err.Error()) - } - return key, nil - - default: - return nil, fmt.Errorf("x509: PKCS#8 wrapping contained private key with unknown algorithm: %v", privKey.Algo.Algorithm) - } -} diff --git a/src/pkg/crypto/x509/pkcs8_test.go b/src/pkg/crypto/x509/pkcs8_test.go deleted file mode 100644 index 4114efd0e..000000000 --- a/src/pkg/crypto/x509/pkcs8_test.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package x509 - -import ( - "encoding/hex" - "testing" -) - -var pkcs8RSAPrivateKeyHex = `30820278020100300d06092a864886f70d0101010500048202623082025e02010002818100cfb1b5bf9685ffa97b4f99df4ff122b70e59ac9b992f3bc2b3dde17d53c1a34928719b02e8fd17839499bfbd515bd6ef99c7a1c47a239718fe36bfd824c0d96060084b5f67f0273443007a24dfaf5634f7772c9346e10eb294c2306671a5a5e719ae24b4de467291bc571014b0e02dec04534d66a9bb171d644b66b091780e8d020301000102818100b595778383c4afdbab95d2bfed12b3f93bb0a73a7ad952f44d7185fd9ec6c34de8f03a48770f2009c8580bcd275e9632714e9a5e3f32f29dc55474b2329ff0ebc08b3ffcb35bc96e6516b483df80a4a59cceb71918cbabf91564e64a39d7e35dce21cb3031824fdbc845dba6458852ec16af5dddf51a8397a8797ae0337b1439024100ea0eb1b914158c70db39031dd8904d6f18f408c85fbbc592d7d20dee7986969efbda081fdf8bc40e1b1336d6b638110c836bfdc3f314560d2e49cd4fbde1e20b024100e32a4e793b574c9c4a94c8803db5152141e72d03de64e54ef2c8ed104988ca780cd11397bc359630d01b97ebd87067c5451ba777cf045ca23f5912f1031308c702406dfcdbbd5a57c9f85abc4edf9e9e29153507b07ce0a7ef6f52e60dcfebe1b8341babd8b789a837485da6c8d55b29bbb142ace3c24a1f5b54b454d01b51e2ad03024100bd6a2b60dee01e1b3bfcef6a2f09ed027c273cdbbaf6ba55a80f6dcc64e4509ee560f84b4f3e076bd03b11e42fe71a3fdd2dffe7e0902c8584f8cad877cdc945024100aa512fa4ada69881f1d8bb8ad6614f192b83200aef5edf4811313d5ef30a86cbd0a90f7b025c71ea06ec6b34db6306c86b1040670fd8654ad7291d066d06d031` - -// Generated using: -// openssl ecparam -genkey -name secp521r1 | openssl pkcs8 -topk8 -nocrypt -var pkcs8ECPrivateKeyHex = `3081ed020100301006072a8648ce3d020106052b810400230481d53081d20201010441850d81618c5da1aec74c2eed608ba816038506975e6427237c2def150c96a3b13efbfa1f89f1be15cdf4d0ac26422e680e65a0ddd4ad3541ad76165fbf54d6e34ba18189038186000400da97bcedba1eb6d30aeb93c9f9a1454598fa47278df27d6f60ea73eb672d8dc528a9b67885b5b5dcef93c9824f7449ab512ee6a27e76142f56b94b474cfd697e810046c8ca70419365245c1d7d44d0db82c334073835d002232714548abbae6e5700f5ef315ee08b929d8581383dcf2d1c98c2f8a9fccbf79c9579f7b2fd8a90115ac2` - -func TestPKCS8(t *testing.T) { - derBytes, _ := hex.DecodeString(pkcs8RSAPrivateKeyHex) - if _, err := ParsePKCS8PrivateKey(derBytes); err != nil { - t.Errorf("failed to decode PKCS8 with RSA private key: %s", err) - } - - derBytes, _ = hex.DecodeString(pkcs8ECPrivateKeyHex) - if _, err := ParsePKCS8PrivateKey(derBytes); err != nil { - t.Errorf("failed to decode PKCS8 with EC private key: %s", err) - } -} diff --git a/src/pkg/crypto/x509/pkix/pkix.go b/src/pkg/crypto/x509/pkix/pkix.go deleted file mode 100644 index 58c1e54d1..000000000 --- a/src/pkg/crypto/x509/pkix/pkix.go +++ /dev/null @@ -1,178 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package pkix contains shared, low level structures used for ASN.1 parsing -// and serialization of X.509 certificates, CRL and OCSP. -package pkix - -import ( - "encoding/asn1" - "math/big" - "time" -) - -// AlgorithmIdentifier represents the ASN.1 structure of the same name. See RFC -// 5280, section 4.1.1.2. -type AlgorithmIdentifier struct { - Algorithm asn1.ObjectIdentifier - Parameters asn1.RawValue `asn1:"optional"` -} - -type RDNSequence []RelativeDistinguishedNameSET - -type RelativeDistinguishedNameSET []AttributeTypeAndValue - -// AttributeTypeAndValue mirrors the ASN.1 structure of the same name in -// http://tools.ietf.org/html/rfc5280#section-4.1.2.4 -type AttributeTypeAndValue struct { - Type asn1.ObjectIdentifier - Value interface{} -} - -// AttributeTypeAndValueSET represents a set of ASN.1 sequences of -// AttributeTypeAndValue sequences from RFC 2986 (PKCS #10). -type AttributeTypeAndValueSET struct { - Type asn1.ObjectIdentifier - Value [][]AttributeTypeAndValue `asn1:"set"` -} - -// Extension represents the ASN.1 structure of the same name. See RFC -// 5280, section 4.2. -type Extension struct { - Id asn1.ObjectIdentifier - Critical bool `asn1:"optional"` - Value []byte -} - -// Name represents an X.509 distinguished name. This only includes the common -// elements of a DN. Additional elements in the name are ignored. -type Name struct { - Country, Organization, OrganizationalUnit []string - Locality, Province []string - StreetAddress, PostalCode []string - SerialNumber, CommonName string - - Names []AttributeTypeAndValue -} - -func (n *Name) FillFromRDNSequence(rdns *RDNSequence) { - for _, rdn := range *rdns { - if len(rdn) == 0 { - continue - } - atv := rdn[0] - n.Names = append(n.Names, atv) - value, ok := atv.Value.(string) - if !ok { - continue - } - - t := atv.Type - if len(t) == 4 && t[0] == 2 && t[1] == 5 && t[2] == 4 { - switch t[3] { - case 3: - n.CommonName = value - case 5: - n.SerialNumber = value - case 6: - n.Country = append(n.Country, value) - case 7: - n.Locality = append(n.Locality, value) - case 8: - n.Province = append(n.Province, value) - case 9: - n.StreetAddress = append(n.StreetAddress, value) - case 10: - n.Organization = append(n.Organization, value) - case 11: - n.OrganizationalUnit = append(n.OrganizationalUnit, value) - case 17: - n.PostalCode = append(n.PostalCode, value) - } - } - } -} - -var ( - oidCountry = []int{2, 5, 4, 6} - oidOrganization = []int{2, 5, 4, 10} - oidOrganizationalUnit = []int{2, 5, 4, 11} - oidCommonName = []int{2, 5, 4, 3} - oidSerialNumber = []int{2, 5, 4, 5} - oidLocality = []int{2, 5, 4, 7} - oidProvince = []int{2, 5, 4, 8} - oidStreetAddress = []int{2, 5, 4, 9} - oidPostalCode = []int{2, 5, 4, 17} -) - -// appendRDNs appends a relativeDistinguishedNameSET to the given RDNSequence -// and returns the new value. The relativeDistinguishedNameSET contains an -// attributeTypeAndValue for each of the given values. See RFC 5280, A.1, and -// search for AttributeTypeAndValue. -func appendRDNs(in RDNSequence, values []string, oid asn1.ObjectIdentifier) RDNSequence { - if len(values) == 0 { - return in - } - - s := make([]AttributeTypeAndValue, len(values)) - for i, value := range values { - s[i].Type = oid - s[i].Value = value - } - - return append(in, s) -} - -func (n Name) ToRDNSequence() (ret RDNSequence) { - ret = appendRDNs(ret, n.Country, oidCountry) - ret = appendRDNs(ret, n.Organization, oidOrganization) - ret = appendRDNs(ret, n.OrganizationalUnit, oidOrganizationalUnit) - ret = appendRDNs(ret, n.Locality, oidLocality) - ret = appendRDNs(ret, n.Province, oidProvince) - ret = appendRDNs(ret, n.StreetAddress, oidStreetAddress) - ret = appendRDNs(ret, n.PostalCode, oidPostalCode) - if len(n.CommonName) > 0 { - ret = appendRDNs(ret, []string{n.CommonName}, oidCommonName) - } - if len(n.SerialNumber) > 0 { - ret = appendRDNs(ret, []string{n.SerialNumber}, oidSerialNumber) - } - - return ret -} - -// CertificateList represents the ASN.1 structure of the same name. See RFC -// 5280, section 5.1. Use Certificate.CheckCRLSignature to verify the -// signature. -type CertificateList struct { - TBSCertList TBSCertificateList - SignatureAlgorithm AlgorithmIdentifier - SignatureValue asn1.BitString -} - -// HasExpired reports whether now is past the expiry time of certList. -func (certList *CertificateList) HasExpired(now time.Time) bool { - return now.After(certList.TBSCertList.NextUpdate) -} - -// TBSCertificateList represents the ASN.1 structure of the same name. See RFC -// 5280, section 5.1. -type TBSCertificateList struct { - Raw asn1.RawContent - Version int `asn1:"optional,default:2"` - Signature AlgorithmIdentifier - Issuer RDNSequence - ThisUpdate time.Time - NextUpdate time.Time - RevokedCertificates []RevokedCertificate `asn1:"optional"` - Extensions []Extension `asn1:"tag:0,optional,explicit"` -} - -// RevokedCertificate represents the ASN.1 structure of the same name. See RFC -// 5280, section 5.1. -type RevokedCertificate struct { - SerialNumber *big.Int - RevocationTime time.Time - Extensions []Extension `asn1:"optional"` -} diff --git a/src/pkg/crypto/x509/root.go b/src/pkg/crypto/x509/root.go deleted file mode 100644 index 8aae14e09..000000000 --- a/src/pkg/crypto/x509/root.go +++ /dev/null @@ -1,17 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package x509 - -import "sync" - -var ( - once sync.Once - systemRoots *CertPool -) - -func systemRootsPool() *CertPool { - once.Do(initSystemRoots) - return systemRoots -} diff --git a/src/pkg/crypto/x509/root_cgo_darwin.go b/src/pkg/crypto/x509/root_cgo_darwin.go deleted file mode 100644 index bdcc2c170..000000000 --- a/src/pkg/crypto/x509/root_cgo_darwin.go +++ /dev/null @@ -1,79 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build cgo - -package x509 - -/* -#cgo CFLAGS: -mmacosx-version-min=10.6 -D__MAC_OS_X_VERSION_MAX_ALLOWED=1060 -#cgo LDFLAGS: -framework CoreFoundation -framework Security - -#include -#include - -// FetchPEMRoots fetches the system's list of trusted X.509 root certificates. -// -// On success it returns 0 and fills pemRoots with a CFDataRef that contains the extracted root -// certificates of the system. On failure, the function returns -1. -// -// Note: The CFDataRef returned in pemRoots must be released (using CFRelease) after -// we've consumed its content. -int FetchPEMRoots(CFDataRef *pemRoots) { - if (pemRoots == NULL) { - return -1; - } - - CFArrayRef certs = NULL; - OSStatus err = SecTrustCopyAnchorCertificates(&certs); - if (err != noErr) { - return -1; - } - - CFMutableDataRef combinedData = CFDataCreateMutable(kCFAllocatorDefault, 0); - int i, ncerts = CFArrayGetCount(certs); - for (i = 0; i < ncerts; i++) { - CFDataRef data = NULL; - SecCertificateRef cert = (SecCertificateRef)CFArrayGetValueAtIndex(certs, i); - if (cert == NULL) { - continue; - } - - // Note: SecKeychainItemExport is deprecated as of 10.7 in favor of SecItemExport. - // Once we support weak imports via cgo we should prefer that, and fall back to this - // for older systems. - err = SecKeychainItemExport(cert, kSecFormatX509Cert, kSecItemPemArmour, NULL, &data); - if (err != noErr) { - continue; - } - - if (data != NULL) { - CFDataAppendBytes(combinedData, CFDataGetBytePtr(data), CFDataGetLength(data)); - CFRelease(data); - } - } - - CFRelease(certs); - - *pemRoots = combinedData; - return 0; -} -*/ -import "C" -import "unsafe" - -func initSystemRoots() { - roots := NewCertPool() - - var data C.CFDataRef = nil - err := C.FetchPEMRoots(&data) - if err == -1 { - return - } - - defer C.CFRelease(C.CFTypeRef(data)) - buf := C.GoBytes(unsafe.Pointer(C.CFDataGetBytePtr(data)), C.int(C.CFDataGetLength(data))) - roots.AppendCertsFromPEM(buf) - systemRoots = roots -} diff --git a/src/pkg/crypto/x509/root_darwin.go b/src/pkg/crypto/x509/root_darwin.go deleted file mode 100644 index 2a61d36ea..000000000 --- a/src/pkg/crypto/x509/root_darwin.go +++ /dev/null @@ -1,23 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package x509 - -import "os/exec" - -func (c *Certificate) systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error) { - return nil, nil -} - -func execSecurityRoots() (*CertPool, error) { - cmd := exec.Command("/usr/bin/security", "find-certificate", "-a", "-p", "/System/Library/Keychains/SystemRootCertificates.keychain") - data, err := cmd.Output() - if err != nil { - return nil, err - } - - roots := NewCertPool() - roots.AppendCertsFromPEM(data) - return roots, nil -} diff --git a/src/pkg/crypto/x509/root_darwin_test.go b/src/pkg/crypto/x509/root_darwin_test.go deleted file mode 100644 index 87ea4e344..000000000 --- a/src/pkg/crypto/x509/root_darwin_test.go +++ /dev/null @@ -1,50 +0,0 @@ -package x509 - -import "testing" - -func TestSystemRoots(t *testing.T) { - sysRoots := systemRootsPool() // actual system roots - execRoots, err := execSecurityRoots() // non-cgo roots - - if err != nil { - t.Fatalf("failed to read system roots: %v", err) - } - - for _, tt := range []*CertPool{sysRoots, execRoots} { - if tt == nil { - t.Fatal("no system roots") - } - // On Mavericks, there are 212 bundled certs; require only - // 150 here, since this is just a sanity check, and the - // exact number will vary over time. - if want, have := 150, len(tt.certs); have < want { - t.Fatalf("want at least %d system roots, have %d", want, have) - } - } - - // Check that the two cert pools are roughly the same; - // |A∩B| > max(|A|, |B|) / 2 should be a reasonably robust check. - - isect := make(map[string]bool, len(sysRoots.certs)) - for _, c := range sysRoots.certs { - isect[string(c.Raw)] = true - } - - have := 0 - for _, c := range execRoots.certs { - if isect[string(c.Raw)] { - have++ - } - } - - var want int - if nsys, nexec := len(sysRoots.certs), len(execRoots.certs); nsys > nexec { - want = nsys / 2 - } else { - want = nexec / 2 - } - - if have < want { - t.Errorf("insufficent overlap between cgo and non-cgo roots; want at least %d, have %d", want, have) - } -} diff --git a/src/pkg/crypto/x509/root_nocgo_darwin.go b/src/pkg/crypto/x509/root_nocgo_darwin.go deleted file mode 100644 index d00e25766..000000000 --- a/src/pkg/crypto/x509/root_nocgo_darwin.go +++ /dev/null @@ -1,11 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build !cgo - -package x509 - -func initSystemRoots() { - systemRoots, _ = execSecurityRoots() -} diff --git a/src/pkg/crypto/x509/root_plan9.go b/src/pkg/crypto/x509/root_plan9.go deleted file mode 100644 index 9965caade..000000000 --- a/src/pkg/crypto/x509/root_plan9.go +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build plan9 - -package x509 - -import "io/ioutil" - -// Possible certificate files; stop after finding one. -var certFiles = []string{ - "/sys/lib/tls/ca.pem", -} - -func (c *Certificate) systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error) { - return nil, nil -} - -func initSystemRoots() { - roots := NewCertPool() - for _, file := range certFiles { - data, err := ioutil.ReadFile(file) - if err == nil { - roots.AppendCertsFromPEM(data) - systemRoots = roots - return - } - } - - // All of the files failed to load. systemRoots will be nil which will - // trigger a specific error at verification time. -} diff --git a/src/pkg/crypto/x509/root_unix.go b/src/pkg/crypto/x509/root_unix.go deleted file mode 100644 index 11ad3c440..000000000 --- a/src/pkg/crypto/x509/root_unix.go +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build dragonfly freebsd linux nacl netbsd openbsd solaris - -package x509 - -import "io/ioutil" - -// Possible certificate files; stop after finding one. -var certFiles = []string{ - "/etc/ssl/certs/ca-certificates.crt", // Debian/Ubuntu/Gentoo etc. - "/etc/pki/tls/certs/ca-bundle.crt", // Fedora/RHEL - "/etc/ssl/ca-bundle.pem", // OpenSUSE - "/etc/ssl/cert.pem", // OpenBSD - "/usr/local/share/certs/ca-root-nss.crt", // FreeBSD/DragonFly -} - -func (c *Certificate) systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error) { - return nil, nil -} - -func initSystemRoots() { - roots := NewCertPool() - for _, file := range certFiles { - data, err := ioutil.ReadFile(file) - if err == nil { - roots.AppendCertsFromPEM(data) - systemRoots = roots - return - } - } - - // All of the files failed to load. systemRoots will be nil which will - // trigger a specific error at verification time. -} diff --git a/src/pkg/crypto/x509/root_windows.go b/src/pkg/crypto/x509/root_windows.go deleted file mode 100644 index 81018b78f..000000000 --- a/src/pkg/crypto/x509/root_windows.go +++ /dev/null @@ -1,229 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package x509 - -import ( - "errors" - "syscall" - "unsafe" -) - -// Creates a new *syscall.CertContext representing the leaf certificate in an in-memory -// certificate store containing itself and all of the intermediate certificates specified -// in the opts.Intermediates CertPool. -// -// A pointer to the in-memory store is available in the returned CertContext's Store field. -// The store is automatically freed when the CertContext is freed using -// syscall.CertFreeCertificateContext. -func createStoreContext(leaf *Certificate, opts *VerifyOptions) (*syscall.CertContext, error) { - var storeCtx *syscall.CertContext - - leafCtx, err := syscall.CertCreateCertificateContext(syscall.X509_ASN_ENCODING|syscall.PKCS_7_ASN_ENCODING, &leaf.Raw[0], uint32(len(leaf.Raw))) - if err != nil { - return nil, err - } - defer syscall.CertFreeCertificateContext(leafCtx) - - handle, err := syscall.CertOpenStore(syscall.CERT_STORE_PROV_MEMORY, 0, 0, syscall.CERT_STORE_DEFER_CLOSE_UNTIL_LAST_FREE_FLAG, 0) - if err != nil { - return nil, err - } - defer syscall.CertCloseStore(handle, 0) - - err = syscall.CertAddCertificateContextToStore(handle, leafCtx, syscall.CERT_STORE_ADD_ALWAYS, &storeCtx) - if err != nil { - return nil, err - } - - if opts.Intermediates != nil { - for _, intermediate := range opts.Intermediates.certs { - ctx, err := syscall.CertCreateCertificateContext(syscall.X509_ASN_ENCODING|syscall.PKCS_7_ASN_ENCODING, &intermediate.Raw[0], uint32(len(intermediate.Raw))) - if err != nil { - return nil, err - } - - err = syscall.CertAddCertificateContextToStore(handle, ctx, syscall.CERT_STORE_ADD_ALWAYS, nil) - syscall.CertFreeCertificateContext(ctx) - if err != nil { - return nil, err - } - } - } - - return storeCtx, nil -} - -// extractSimpleChain extracts the final certificate chain from a CertSimpleChain. -func extractSimpleChain(simpleChain **syscall.CertSimpleChain, count int) (chain []*Certificate, err error) { - if simpleChain == nil || count == 0 { - return nil, errors.New("x509: invalid simple chain") - } - - simpleChains := (*[1 << 20]*syscall.CertSimpleChain)(unsafe.Pointer(simpleChain))[:] - lastChain := simpleChains[count-1] - elements := (*[1 << 20]*syscall.CertChainElement)(unsafe.Pointer(lastChain.Elements))[:] - for i := 0; i < int(lastChain.NumElements); i++ { - // Copy the buf, since ParseCertificate does not create its own copy. - cert := elements[i].CertContext - encodedCert := (*[1 << 20]byte)(unsafe.Pointer(cert.EncodedCert))[:] - buf := make([]byte, cert.Length) - copy(buf, encodedCert[:]) - parsedCert, err := ParseCertificate(buf) - if err != nil { - return nil, err - } - chain = append(chain, parsedCert) - } - - return chain, nil -} - -// checkChainTrustStatus checks the trust status of the certificate chain, translating -// any errors it finds into Go errors in the process. -func checkChainTrustStatus(c *Certificate, chainCtx *syscall.CertChainContext) error { - if chainCtx.TrustStatus.ErrorStatus != syscall.CERT_TRUST_NO_ERROR { - status := chainCtx.TrustStatus.ErrorStatus - switch status { - case syscall.CERT_TRUST_IS_NOT_TIME_VALID: - return CertificateInvalidError{c, Expired} - default: - return UnknownAuthorityError{c, nil, nil} - } - } - return nil -} - -// checkChainSSLServerPolicy checks that the certificate chain in chainCtx is valid for -// use as a certificate chain for a SSL/TLS server. -func checkChainSSLServerPolicy(c *Certificate, chainCtx *syscall.CertChainContext, opts *VerifyOptions) error { - servernamep, err := syscall.UTF16PtrFromString(opts.DNSName) - if err != nil { - return err - } - sslPara := &syscall.SSLExtraCertChainPolicyPara{ - AuthType: syscall.AUTHTYPE_SERVER, - ServerName: servernamep, - } - sslPara.Size = uint32(unsafe.Sizeof(*sslPara)) - - para := &syscall.CertChainPolicyPara{ - ExtraPolicyPara: uintptr(unsafe.Pointer(sslPara)), - } - para.Size = uint32(unsafe.Sizeof(*para)) - - status := syscall.CertChainPolicyStatus{} - err = syscall.CertVerifyCertificateChainPolicy(syscall.CERT_CHAIN_POLICY_SSL, chainCtx, para, &status) - if err != nil { - return err - } - - // TODO(mkrautz): use the lChainIndex and lElementIndex fields - // of the CertChainPolicyStatus to provide proper context, instead - // using c. - if status.Error != 0 { - switch status.Error { - case syscall.CERT_E_EXPIRED: - return CertificateInvalidError{c, Expired} - case syscall.CERT_E_CN_NO_MATCH: - return HostnameError{c, opts.DNSName} - case syscall.CERT_E_UNTRUSTEDROOT: - return UnknownAuthorityError{c, nil, nil} - default: - return UnknownAuthorityError{c, nil, nil} - } - } - - return nil -} - -// systemVerify is like Verify, except that it uses CryptoAPI calls -// to build certificate chains and verify them. -func (c *Certificate) systemVerify(opts *VerifyOptions) (chains [][]*Certificate, err error) { - hasDNSName := opts != nil && len(opts.DNSName) > 0 - - storeCtx, err := createStoreContext(c, opts) - if err != nil { - return nil, err - } - defer syscall.CertFreeCertificateContext(storeCtx) - - para := new(syscall.CertChainPara) - para.Size = uint32(unsafe.Sizeof(*para)) - - // If there's a DNSName set in opts, assume we're verifying - // a certificate from a TLS server. - if hasDNSName { - oids := []*byte{ - &syscall.OID_PKIX_KP_SERVER_AUTH[0], - // Both IE and Chrome allow certificates with - // Server Gated Crypto as well. Some certificates - // in the wild require them. - &syscall.OID_SERVER_GATED_CRYPTO[0], - &syscall.OID_SGC_NETSCAPE[0], - } - para.RequestedUsage.Type = syscall.USAGE_MATCH_TYPE_OR - para.RequestedUsage.Usage.Length = uint32(len(oids)) - para.RequestedUsage.Usage.UsageIdentifiers = &oids[0] - } else { - para.RequestedUsage.Type = syscall.USAGE_MATCH_TYPE_AND - para.RequestedUsage.Usage.Length = 0 - para.RequestedUsage.Usage.UsageIdentifiers = nil - } - - var verifyTime *syscall.Filetime - if opts != nil && !opts.CurrentTime.IsZero() { - ft := syscall.NsecToFiletime(opts.CurrentTime.UnixNano()) - verifyTime = &ft - } - - // CertGetCertificateChain will traverse Windows's root stores - // in an attempt to build a verified certificate chain. Once - // it has found a verified chain, it stops. MSDN docs on - // CERT_CHAIN_CONTEXT: - // - // When a CERT_CHAIN_CONTEXT is built, the first simple chain - // begins with an end certificate and ends with a self-signed - // certificate. If that self-signed certificate is not a root - // or otherwise trusted certificate, an attempt is made to - // build a new chain. CTLs are used to create the new chain - // beginning with the self-signed certificate from the original - // chain as the end certificate of the new chain. This process - // continues building additional simple chains until the first - // self-signed certificate is a trusted certificate or until - // an additional simple chain cannot be built. - // - // The result is that we'll only get a single trusted chain to - // return to our caller. - var chainCtx *syscall.CertChainContext - err = syscall.CertGetCertificateChain(syscall.Handle(0), storeCtx, verifyTime, storeCtx.Store, para, 0, 0, &chainCtx) - if err != nil { - return nil, err - } - defer syscall.CertFreeCertificateChain(chainCtx) - - err = checkChainTrustStatus(c, chainCtx) - if err != nil { - return nil, err - } - - if hasDNSName { - err = checkChainSSLServerPolicy(c, chainCtx, opts) - if err != nil { - return nil, err - } - } - - chain, err := extractSimpleChain(chainCtx.Chains, int(chainCtx.ChainCount)) - if err != nil { - return nil, err - } - - chains = append(chains, chain) - - return chains, nil -} - -func initSystemRoots() { -} diff --git a/src/pkg/crypto/x509/sec1.go b/src/pkg/crypto/x509/sec1.go deleted file mode 100644 index 7de66754e..000000000 --- a/src/pkg/crypto/x509/sec1.go +++ /dev/null @@ -1,83 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package x509 - -import ( - "crypto/ecdsa" - "crypto/elliptic" - "encoding/asn1" - "errors" - "fmt" - "math/big" -) - -const ecPrivKeyVersion = 1 - -// ecPrivateKey reflects an ASN.1 Elliptic Curve Private Key Structure. -// References: -// RFC5915 -// SEC1 - http://www.secg.org/download/aid-780/sec1-v2.pdf -// Per RFC5915 the NamedCurveOID is marked as ASN.1 OPTIONAL, however in -// most cases it is not. -type ecPrivateKey struct { - Version int - PrivateKey []byte - NamedCurveOID asn1.ObjectIdentifier `asn1:"optional,explicit,tag:0"` - PublicKey asn1.BitString `asn1:"optional,explicit,tag:1"` -} - -// ParseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure. -func ParseECPrivateKey(der []byte) (key *ecdsa.PrivateKey, err error) { - return parseECPrivateKey(nil, der) -} - -// MarshalECPrivateKey marshals an EC private key into ASN.1, DER format. -func MarshalECPrivateKey(key *ecdsa.PrivateKey) ([]byte, error) { - oid, ok := oidFromNamedCurve(key.Curve) - if !ok { - return nil, errors.New("x509: unknown elliptic curve") - } - return asn1.Marshal(ecPrivateKey{ - Version: 1, - PrivateKey: key.D.Bytes(), - NamedCurveOID: oid, - PublicKey: asn1.BitString{Bytes: elliptic.Marshal(key.Curve, key.X, key.Y)}, - }) -} - -// parseECPrivateKey parses an ASN.1 Elliptic Curve Private Key Structure. -// The OID for the named curve may be provided from another source (such as -// the PKCS8 container) - if it is provided then use this instead of the OID -// that may exist in the EC private key structure. -func parseECPrivateKey(namedCurveOID *asn1.ObjectIdentifier, der []byte) (key *ecdsa.PrivateKey, err error) { - var privKey ecPrivateKey - if _, err := asn1.Unmarshal(der, &privKey); err != nil { - return nil, errors.New("x509: failed to parse EC private key: " + err.Error()) - } - if privKey.Version != ecPrivKeyVersion { - return nil, fmt.Errorf("x509: unknown EC private key version %d", privKey.Version) - } - - var curve elliptic.Curve - if namedCurveOID != nil { - curve = namedCurveFromOID(*namedCurveOID) - } else { - curve = namedCurveFromOID(privKey.NamedCurveOID) - } - if curve == nil { - return nil, errors.New("x509: unknown elliptic curve") - } - - k := new(big.Int).SetBytes(privKey.PrivateKey) - if k.Cmp(curve.Params().N) >= 0 { - return nil, errors.New("x509: invalid elliptic curve private key value") - } - priv := new(ecdsa.PrivateKey) - priv.Curve = curve - priv.D = k - priv.X, priv.Y = curve.ScalarBaseMult(privKey.PrivateKey) - - return priv, nil -} diff --git a/src/pkg/crypto/x509/sec1_test.go b/src/pkg/crypto/x509/sec1_test.go deleted file mode 100644 index 95f18e77d..000000000 --- a/src/pkg/crypto/x509/sec1_test.go +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package x509 - -import ( - "bytes" - "encoding/hex" - "testing" -) - -// Generated using: -// openssl ecparam -genkey -name secp384r1 -outform PEM -var ecPrivateKeyHex = `3081a40201010430bdb9839c08ee793d1157886a7a758a3c8b2a17a4df48f17ace57c72c56b4723cf21dcda21d4e1ad57ff034f19fcfd98ea00706052b81040022a16403620004feea808b5ee2429cfcce13c32160e1c960990bd050bb0fdf7222f3decd0a55008e32a6aa3c9062051c4cba92a7a3b178b24567412d43cdd2f882fa5addddd726fe3e208d2c26d733a773a597abb749714df7256ead5105fa6e7b3650de236b50` - -func TestParseECPrivateKey(t *testing.T) { - derBytes, _ := hex.DecodeString(ecPrivateKeyHex) - key, err := ParseECPrivateKey(derBytes) - if err != nil { - t.Errorf("failed to decode EC private key: %s", err) - } - serialized, err := MarshalECPrivateKey(key) - if err != nil { - t.Fatalf("failed to encode EC private key: %s", err) - } - if !bytes.Equal(serialized, derBytes) { - t.Fatalf("serialized key differs: got %x, want %x", serialized, derBytes) - } -} diff --git a/src/pkg/crypto/x509/verify.go b/src/pkg/crypto/x509/verify.go deleted file mode 100644 index ec1981423..000000000 --- a/src/pkg/crypto/x509/verify.go +++ /dev/null @@ -1,476 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package x509 - -import ( - "fmt" - "net" - "runtime" - "strings" - "time" - "unicode/utf8" -) - -type InvalidReason int - -const ( - // NotAuthorizedToSign results when a certificate is signed by another - // which isn't marked as a CA certificate. - NotAuthorizedToSign InvalidReason = iota - // Expired results when a certificate has expired, based on the time - // given in the VerifyOptions. - Expired - // CANotAuthorizedForThisName results when an intermediate or root - // certificate has a name constraint which doesn't include the name - // being checked. - CANotAuthorizedForThisName - // TooManyIntermediates results when a path length constraint is - // violated. - TooManyIntermediates - // IncompatibleUsage results when the certificate's key usage indicates - // that it may only be used for a different purpose. - IncompatibleUsage -) - -// CertificateInvalidError results when an odd error occurs. Users of this -// library probably want to handle all these errors uniformly. -type CertificateInvalidError struct { - Cert *Certificate - Reason InvalidReason -} - -func (e CertificateInvalidError) Error() string { - switch e.Reason { - case NotAuthorizedToSign: - return "x509: certificate is not authorized to sign other certificates" - case Expired: - return "x509: certificate has expired or is not yet valid" - case CANotAuthorizedForThisName: - return "x509: a root or intermediate certificate is not authorized to sign in this domain" - case TooManyIntermediates: - return "x509: too many intermediates for path length constraint" - case IncompatibleUsage: - return "x509: certificate specifies an incompatible key usage" - } - return "x509: unknown error" -} - -// HostnameError results when the set of authorized names doesn't match the -// requested name. -type HostnameError struct { - Certificate *Certificate - Host string -} - -func (h HostnameError) Error() string { - c := h.Certificate - - var valid string - if ip := net.ParseIP(h.Host); ip != nil { - // Trying to validate an IP - if len(c.IPAddresses) == 0 { - return "x509: cannot validate certificate for " + h.Host + " because it doesn't contain any IP SANs" - } - for _, san := range c.IPAddresses { - if len(valid) > 0 { - valid += ", " - } - valid += san.String() - } - } else { - if len(c.DNSNames) > 0 { - valid = strings.Join(c.DNSNames, ", ") - } else { - valid = c.Subject.CommonName - } - } - return "x509: certificate is valid for " + valid + ", not " + h.Host -} - -// UnknownAuthorityError results when the certificate issuer is unknown -type UnknownAuthorityError struct { - cert *Certificate - // hintErr contains an error that may be helpful in determining why an - // authority wasn't found. - hintErr error - // hintCert contains a possible authority certificate that was rejected - // because of the error in hintErr. - hintCert *Certificate -} - -func (e UnknownAuthorityError) Error() string { - s := "x509: certificate signed by unknown authority" - if e.hintErr != nil { - certName := e.hintCert.Subject.CommonName - if len(certName) == 0 { - if len(e.hintCert.Subject.Organization) > 0 { - certName = e.hintCert.Subject.Organization[0] - } - certName = "serial:" + e.hintCert.SerialNumber.String() - } - s += fmt.Sprintf(" (possibly because of %q while trying to verify candidate authority certificate %q)", e.hintErr, certName) - } - return s -} - -// SystemRootsError results when we fail to load the system root certificates. -type SystemRootsError struct{} - -func (SystemRootsError) Error() string { - return "x509: failed to load system roots and no roots provided" -} - -// VerifyOptions contains parameters for Certificate.Verify. It's a structure -// because other PKIX verification APIs have ended up needing many options. -type VerifyOptions struct { - DNSName string - Intermediates *CertPool - Roots *CertPool // if nil, the system roots are used - CurrentTime time.Time // if zero, the current time is used - // KeyUsage specifies which Extended Key Usage values are acceptable. - // An empty list means ExtKeyUsageServerAuth. Key usage is considered a - // constraint down the chain which mirrors Windows CryptoAPI behaviour, - // but not the spec. To accept any key usage, include ExtKeyUsageAny. - KeyUsages []ExtKeyUsage -} - -const ( - leafCertificate = iota - intermediateCertificate - rootCertificate -) - -// isValid performs validity checks on the c. -func (c *Certificate) isValid(certType int, currentChain []*Certificate, opts *VerifyOptions) error { - now := opts.CurrentTime - if now.IsZero() { - now = time.Now() - } - if now.Before(c.NotBefore) || now.After(c.NotAfter) { - return CertificateInvalidError{c, Expired} - } - - if len(c.PermittedDNSDomains) > 0 { - ok := false - for _, domain := range c.PermittedDNSDomains { - if opts.DNSName == domain || - (strings.HasSuffix(opts.DNSName, domain) && - len(opts.DNSName) >= 1+len(domain) && - opts.DNSName[len(opts.DNSName)-len(domain)-1] == '.') { - ok = true - break - } - } - - if !ok { - return CertificateInvalidError{c, CANotAuthorizedForThisName} - } - } - - // KeyUsage status flags are ignored. From Engineering Security, Peter - // Gutmann: A European government CA marked its signing certificates as - // being valid for encryption only, but no-one noticed. Another - // European CA marked its signature keys as not being valid for - // signatures. A different CA marked its own trusted root certificate - // as being invalid for certificate signing. Another national CA - // distributed a certificate to be used to encrypt data for the - // country’s tax authority that was marked as only being usable for - // digital signatures but not for encryption. Yet another CA reversed - // the order of the bit flags in the keyUsage due to confusion over - // encoding endianness, essentially setting a random keyUsage in - // certificates that it issued. Another CA created a self-invalidating - // certificate by adding a certificate policy statement stipulating - // that the certificate had to be used strictly as specified in the - // keyUsage, and a keyUsage containing a flag indicating that the RSA - // encryption key could only be used for Diffie-Hellman key agreement. - - if certType == intermediateCertificate && (!c.BasicConstraintsValid || !c.IsCA) { - return CertificateInvalidError{c, NotAuthorizedToSign} - } - - if c.BasicConstraintsValid && c.MaxPathLen >= 0 { - numIntermediates := len(currentChain) - 1 - if numIntermediates > c.MaxPathLen { - return CertificateInvalidError{c, TooManyIntermediates} - } - } - - return nil -} - -// Verify attempts to verify c by building one or more chains from c to a -// certificate in opts.Roots, using certificates in opts.Intermediates if -// needed. If successful, it returns one or more chains where the first -// element of the chain is c and the last element is from opts.Roots. -// -// If opts.Roots is nil and system roots are unavailable the returned error -// will be of type SystemRootsError. -// -// WARNING: this doesn't do any revocation checking. -func (c *Certificate) Verify(opts VerifyOptions) (chains [][]*Certificate, err error) { - // Use Windows's own verification and chain building. - if opts.Roots == nil && runtime.GOOS == "windows" { - return c.systemVerify(&opts) - } - - if opts.Roots == nil { - opts.Roots = systemRootsPool() - if opts.Roots == nil { - return nil, SystemRootsError{} - } - } - - err = c.isValid(leafCertificate, nil, &opts) - if err != nil { - return - } - - if len(opts.DNSName) > 0 { - err = c.VerifyHostname(opts.DNSName) - if err != nil { - return - } - } - - candidateChains, err := c.buildChains(make(map[int][][]*Certificate), []*Certificate{c}, &opts) - if err != nil { - return - } - - keyUsages := opts.KeyUsages - if len(keyUsages) == 0 { - keyUsages = []ExtKeyUsage{ExtKeyUsageServerAuth} - } - - // If any key usage is acceptable then we're done. - for _, usage := range keyUsages { - if usage == ExtKeyUsageAny { - chains = candidateChains - return - } - } - - for _, candidate := range candidateChains { - if checkChainForKeyUsage(candidate, keyUsages) { - chains = append(chains, candidate) - } - } - - if len(chains) == 0 { - err = CertificateInvalidError{c, IncompatibleUsage} - } - - return -} - -func appendToFreshChain(chain []*Certificate, cert *Certificate) []*Certificate { - n := make([]*Certificate, len(chain)+1) - copy(n, chain) - n[len(chain)] = cert - return n -} - -func (c *Certificate) buildChains(cache map[int][][]*Certificate, currentChain []*Certificate, opts *VerifyOptions) (chains [][]*Certificate, err error) { - possibleRoots, failedRoot, rootErr := opts.Roots.findVerifiedParents(c) - for _, rootNum := range possibleRoots { - root := opts.Roots.certs[rootNum] - err = root.isValid(rootCertificate, currentChain, opts) - if err != nil { - continue - } - chains = append(chains, appendToFreshChain(currentChain, root)) - } - - possibleIntermediates, failedIntermediate, intermediateErr := opts.Intermediates.findVerifiedParents(c) -nextIntermediate: - for _, intermediateNum := range possibleIntermediates { - intermediate := opts.Intermediates.certs[intermediateNum] - for _, cert := range currentChain { - if cert == intermediate { - continue nextIntermediate - } - } - err = intermediate.isValid(intermediateCertificate, currentChain, opts) - if err != nil { - continue - } - var childChains [][]*Certificate - childChains, ok := cache[intermediateNum] - if !ok { - childChains, err = intermediate.buildChains(cache, appendToFreshChain(currentChain, intermediate), opts) - cache[intermediateNum] = childChains - } - chains = append(chains, childChains...) - } - - if len(chains) > 0 { - err = nil - } - - if len(chains) == 0 && err == nil { - hintErr := rootErr - hintCert := failedRoot - if hintErr == nil { - hintErr = intermediateErr - hintCert = failedIntermediate - } - err = UnknownAuthorityError{c, hintErr, hintCert} - } - - return -} - -func matchHostnames(pattern, host string) bool { - if len(pattern) == 0 || len(host) == 0 { - return false - } - - patternParts := strings.Split(pattern, ".") - hostParts := strings.Split(host, ".") - - if len(patternParts) != len(hostParts) { - return false - } - - for i, patternPart := range patternParts { - if patternPart == "*" { - continue - } - if patternPart != hostParts[i] { - return false - } - } - - return true -} - -// toLowerCaseASCII returns a lower-case version of in. See RFC 6125 6.4.1. We use -// an explicitly ASCII function to avoid any sharp corners resulting from -// performing Unicode operations on DNS labels. -func toLowerCaseASCII(in string) string { - // If the string is already lower-case then there's nothing to do. - isAlreadyLowerCase := true - for _, c := range in { - if c == utf8.RuneError { - // If we get a UTF-8 error then there might be - // upper-case ASCII bytes in the invalid sequence. - isAlreadyLowerCase = false - break - } - if 'A' <= c && c <= 'Z' { - isAlreadyLowerCase = false - break - } - } - - if isAlreadyLowerCase { - return in - } - - out := []byte(in) - for i, c := range out { - if 'A' <= c && c <= 'Z' { - out[i] += 'a' - 'A' - } - } - return string(out) -} - -// VerifyHostname returns nil if c is a valid certificate for the named host. -// Otherwise it returns an error describing the mismatch. -func (c *Certificate) VerifyHostname(h string) error { - // IP addresses may be written in [ ]. - candidateIP := h - if len(h) >= 3 && h[0] == '[' && h[len(h)-1] == ']' { - candidateIP = h[1 : len(h)-1] - } - if ip := net.ParseIP(candidateIP); ip != nil { - // We only match IP addresses against IP SANs. - // https://tools.ietf.org/html/rfc6125#appendix-B.2 - for _, candidate := range c.IPAddresses { - if ip.Equal(candidate) { - return nil - } - } - return HostnameError{c, candidateIP} - } - - lowered := toLowerCaseASCII(h) - - if len(c.DNSNames) > 0 { - for _, match := range c.DNSNames { - if matchHostnames(toLowerCaseASCII(match), lowered) { - return nil - } - } - // If Subject Alt Name is given, we ignore the common name. - } else if matchHostnames(toLowerCaseASCII(c.Subject.CommonName), lowered) { - return nil - } - - return HostnameError{c, h} -} - -func checkChainForKeyUsage(chain []*Certificate, keyUsages []ExtKeyUsage) bool { - usages := make([]ExtKeyUsage, len(keyUsages)) - copy(usages, keyUsages) - - if len(chain) == 0 { - return false - } - - usagesRemaining := len(usages) - - // We walk down the list and cross out any usages that aren't supported - // by each certificate. If we cross out all the usages, then the chain - // is unacceptable. - -NextCert: - for i := len(chain) - 1; i >= 0; i-- { - cert := chain[i] - if len(cert.ExtKeyUsage) == 0 && len(cert.UnknownExtKeyUsage) == 0 { - // The certificate doesn't have any extended key usage specified. - continue - } - - for _, usage := range cert.ExtKeyUsage { - if usage == ExtKeyUsageAny { - // The certificate is explicitly good for any usage. - continue NextCert - } - } - - const invalidUsage ExtKeyUsage = -1 - - NextRequestedUsage: - for i, requestedUsage := range usages { - if requestedUsage == invalidUsage { - continue - } - - for _, usage := range cert.ExtKeyUsage { - if requestedUsage == usage { - continue NextRequestedUsage - } else if requestedUsage == ExtKeyUsageServerAuth && - (usage == ExtKeyUsageNetscapeServerGatedCrypto || - usage == ExtKeyUsageMicrosoftServerGatedCrypto) { - // In order to support COMODO - // certificate chains, we have to - // accept Netscape or Microsoft SGC - // usages as equal to ServerAuth. - continue NextRequestedUsage - } - } - - usages[i] = invalidUsage - usagesRemaining-- - if usagesRemaining == 0 { - return false - } - } - } - - return true -} diff --git a/src/pkg/crypto/x509/verify_test.go b/src/pkg/crypto/x509/verify_test.go deleted file mode 100644 index 96b9d9b42..000000000 --- a/src/pkg/crypto/x509/verify_test.go +++ /dev/null @@ -1,1123 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package x509 - -import ( - "crypto/x509/pkix" - "encoding/pem" - "errors" - "runtime" - "strings" - "testing" - "time" -) - -type verifyTest struct { - leaf string - intermediates []string - roots []string - currentTime int64 - dnsName string - systemSkip bool - keyUsages []ExtKeyUsage - testSystemRootsError bool - - errorCallback func(*testing.T, int, error) bool - expectedChains [][]string -} - -var verifyTests = []verifyTest{ - { - leaf: googleLeaf, - intermediates: []string{giag2Intermediate}, - currentTime: 1395785200, - dnsName: "www.google.com", - testSystemRootsError: true, - - // Without any roots specified we should get a system roots - // error. - errorCallback: expectSystemRootsError, - }, - { - leaf: googleLeaf, - intermediates: []string{giag2Intermediate}, - roots: []string{geoTrustRoot}, - currentTime: 1395785200, - dnsName: "www.google.com", - - expectedChains: [][]string{ - {"Google", "Google Internet Authority", "GeoTrust"}, - }, - }, - { - leaf: googleLeaf, - intermediates: []string{giag2Intermediate}, - roots: []string{geoTrustRoot}, - currentTime: 1395785200, - dnsName: "WwW.GooGLE.coM", - - expectedChains: [][]string{ - {"Google", "Google Internet Authority", "GeoTrust"}, - }, - }, - { - leaf: googleLeaf, - intermediates: []string{giag2Intermediate}, - roots: []string{geoTrustRoot}, - currentTime: 1395785200, - dnsName: "www.example.com", - - errorCallback: expectHostnameError, - }, - { - leaf: googleLeaf, - intermediates: []string{giag2Intermediate}, - roots: []string{geoTrustRoot}, - currentTime: 1, - dnsName: "www.example.com", - - errorCallback: expectExpired, - }, - { - leaf: googleLeaf, - roots: []string{geoTrustRoot}, - currentTime: 1395785200, - dnsName: "www.google.com", - - // Skip when using systemVerify, since Windows - // *will* find the missing intermediate cert. - systemSkip: true, - errorCallback: expectAuthorityUnknown, - }, - { - leaf: googleLeaf, - intermediates: []string{geoTrustRoot, giag2Intermediate}, - roots: []string{geoTrustRoot}, - currentTime: 1395785200, - dnsName: "www.google.com", - - expectedChains: [][]string{ - {"Google", "Google Internet Authority", "GeoTrust"}, - // TODO(agl): this is ok, but it would be nice if the - // chain building didn't visit the same SPKI - // twice. - {"Google", "Google Internet Authority", "GeoTrust", "GeoTrust"}, - }, - // CAPI doesn't build the chain with the duplicated GeoTrust - // entry so the results don't match. Thus we skip this test - // until that's fixed. - systemSkip: true, - }, - { - leaf: dnssecExpLeaf, - intermediates: []string{startComIntermediate}, - roots: []string{startComRoot}, - currentTime: 1302726541, - - expectedChains: [][]string{ - {"dnssec-exp", "StartCom Class 1", "StartCom Certification Authority"}, - }, - }, - { - leaf: dnssecExpLeaf, - intermediates: []string{startComIntermediate, startComRoot}, - roots: []string{startComRoot}, - currentTime: 1302726541, - - // Skip when using systemVerify, since Windows - // can only return a single chain to us (for now). - systemSkip: true, - expectedChains: [][]string{ - {"dnssec-exp", "StartCom Class 1", "StartCom Certification Authority"}, - {"dnssec-exp", "StartCom Class 1", "StartCom Certification Authority", "StartCom Certification Authority"}, - }, - }, - { - leaf: googleLeafWithInvalidHash, - intermediates: []string{giag2Intermediate}, - roots: []string{geoTrustRoot}, - currentTime: 1395785200, - dnsName: "www.google.com", - - // The specific error message may not occur when using system - // verification. - systemSkip: true, - errorCallback: expectHashError, - }, - { - // The default configuration should reject an S/MIME chain. - leaf: smimeLeaf, - roots: []string{smimeIntermediate}, - currentTime: 1339436154, - - // Key usage not implemented for Windows yet. - systemSkip: true, - errorCallback: expectUsageError, - }, - { - leaf: smimeLeaf, - roots: []string{smimeIntermediate}, - currentTime: 1339436154, - keyUsages: []ExtKeyUsage{ExtKeyUsageServerAuth}, - - // Key usage not implemented for Windows yet. - systemSkip: true, - errorCallback: expectUsageError, - }, - { - leaf: smimeLeaf, - roots: []string{smimeIntermediate}, - currentTime: 1339436154, - keyUsages: []ExtKeyUsage{ExtKeyUsageEmailProtection}, - - // Key usage not implemented for Windows yet. - systemSkip: true, - expectedChains: [][]string{ - {"Ryan Hurst", "GlobalSign PersonalSign 2 CA - G2"}, - }, - }, - { - leaf: megaLeaf, - intermediates: []string{comodoIntermediate1}, - roots: []string{comodoRoot}, - currentTime: 1360431182, - - // CryptoAPI can find alternative validation paths so we don't - // perform this test with system validation. - systemSkip: true, - expectedChains: [][]string{ - {"mega.co.nz", "EssentialSSL CA", "COMODO Certification Authority"}, - }, - }, - { - // Check that a name constrained intermediate works even when - // it lists multiple constraints. - leaf: nameConstraintsLeaf, - intermediates: []string{nameConstraintsIntermediate1, nameConstraintsIntermediate2}, - roots: []string{globalSignRoot}, - currentTime: 1382387896, - dnsName: "secure.iddl.vt.edu", - - expectedChains: [][]string{ - { - "Technology-enhanced Learning and Online Strategies", - "Virginia Tech Global Qualified Server CA", - "Trusted Root CA G2", - "GlobalSign Root CA", - }, - }, - }, - { - // Check that SHA-384 intermediates (which are popping up) - // work. - leaf: moipLeafCert, - intermediates: []string{comodoIntermediateSHA384, comodoRSAAuthority}, - roots: []string{addTrustRoot}, - currentTime: 1397502195, - dnsName: "api.moip.com.br", - - expectedChains: [][]string{ - { - "api.moip.com.br", - "COMODO RSA Extended Validation Secure Server CA", - "COMODO RSA Certification Authority", - "AddTrust External CA Root", - }, - }, - }, -} - -func expectHostnameError(t *testing.T, i int, err error) (ok bool) { - if _, ok := err.(HostnameError); !ok { - t.Errorf("#%d: error was not a HostnameError: %s", i, err) - return false - } - return true -} - -func expectExpired(t *testing.T, i int, err error) (ok bool) { - if inval, ok := err.(CertificateInvalidError); !ok || inval.Reason != Expired { - t.Errorf("#%d: error was not Expired: %s", i, err) - return false - } - return true -} - -func expectUsageError(t *testing.T, i int, err error) (ok bool) { - if inval, ok := err.(CertificateInvalidError); !ok || inval.Reason != IncompatibleUsage { - t.Errorf("#%d: error was not IncompatibleUsage: %s", i, err) - return false - } - return true -} - -func expectAuthorityUnknown(t *testing.T, i int, err error) (ok bool) { - if _, ok := err.(UnknownAuthorityError); !ok { - t.Errorf("#%d: error was not UnknownAuthorityError: %s", i, err) - return false - } - return true -} - -func expectSystemRootsError(t *testing.T, i int, err error) bool { - if _, ok := err.(SystemRootsError); !ok { - t.Errorf("#%d: error was not SystemRootsError: %s", i, err) - return false - } - return true -} - -func expectHashError(t *testing.T, i int, err error) bool { - if err == nil { - t.Errorf("#%d: no error resulted from invalid hash", i) - return false - } - if expected := "algorithm unimplemented"; !strings.Contains(err.Error(), expected) { - t.Errorf("#%d: error resulting from invalid hash didn't contain '%s', rather it was: %s", i, expected, err) - return false - } - return true -} - -func certificateFromPEM(pemBytes string) (*Certificate, error) { - block, _ := pem.Decode([]byte(pemBytes)) - if block == nil { - return nil, errors.New("failed to decode PEM") - } - return ParseCertificate(block.Bytes) -} - -func testVerify(t *testing.T, useSystemRoots bool) { - for i, test := range verifyTests { - if useSystemRoots && test.systemSkip { - continue - } - if runtime.GOOS == "windows" && test.testSystemRootsError { - continue - } - - opts := VerifyOptions{ - Intermediates: NewCertPool(), - DNSName: test.dnsName, - CurrentTime: time.Unix(test.currentTime, 0), - KeyUsages: test.keyUsages, - } - - if !useSystemRoots { - opts.Roots = NewCertPool() - for j, root := range test.roots { - ok := opts.Roots.AppendCertsFromPEM([]byte(root)) - if !ok { - t.Errorf("#%d: failed to parse root #%d", i, j) - return - } - } - } - - for j, intermediate := range test.intermediates { - ok := opts.Intermediates.AppendCertsFromPEM([]byte(intermediate)) - if !ok { - t.Errorf("#%d: failed to parse intermediate #%d", i, j) - return - } - } - - leaf, err := certificateFromPEM(test.leaf) - if err != nil { - t.Errorf("#%d: failed to parse leaf: %s", i, err) - return - } - - var oldSystemRoots *CertPool - if test.testSystemRootsError { - oldSystemRoots = systemRootsPool() - systemRoots = nil - opts.Roots = nil - } - - chains, err := leaf.Verify(opts) - - if test.testSystemRootsError { - systemRoots = oldSystemRoots - } - - if test.errorCallback == nil && err != nil { - t.Errorf("#%d: unexpected error: %s", i, err) - } - if test.errorCallback != nil { - if !test.errorCallback(t, i, err) { - return - } - } - - if len(chains) != len(test.expectedChains) { - t.Errorf("#%d: wanted %d chains, got %d", i, len(test.expectedChains), len(chains)) - } - - // We check that each returned chain matches a chain from - // expectedChains but an entry in expectedChains can't match - // two chains. - seenChains := make([]bool, len(chains)) - NextOutputChain: - for _, chain := range chains { - TryNextExpected: - for j, expectedChain := range test.expectedChains { - if seenChains[j] { - continue - } - if len(chain) != len(expectedChain) { - continue - } - for k, cert := range chain { - if strings.Index(nameToKey(&cert.Subject), expectedChain[k]) == -1 { - continue TryNextExpected - } - } - // we matched - seenChains[j] = true - continue NextOutputChain - } - t.Errorf("#%d: No expected chain matched %s", i, chainToDebugString(chain)) - } - } -} - -func TestGoVerify(t *testing.T) { - testVerify(t, false) -} - -func TestSystemVerify(t *testing.T) { - if runtime.GOOS != "windows" { - t.Skipf("skipping verify test using system APIs on %q", runtime.GOOS) - } - - testVerify(t, true) -} - -func chainToDebugString(chain []*Certificate) string { - var chainStr string - for _, cert := range chain { - if len(chainStr) > 0 { - chainStr += " -> " - } - chainStr += nameToKey(&cert.Subject) - } - return chainStr -} - -func nameToKey(name *pkix.Name) string { - return strings.Join(name.Country, ",") + "/" + strings.Join(name.Organization, ",") + "/" + strings.Join(name.OrganizationalUnit, ",") + "/" + name.CommonName -} - -const geoTrustRoot = `-----BEGIN CERTIFICATE----- -MIIDVDCCAjygAwIBAgIDAjRWMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT -MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i -YWwgQ0EwHhcNMDIwNTIxMDQwMDAwWhcNMjIwNTIxMDQwMDAwWjBCMQswCQYDVQQG -EwJVUzEWMBQGA1UEChMNR2VvVHJ1c3QgSW5jLjEbMBkGA1UEAxMSR2VvVHJ1c3Qg -R2xvYmFsIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA2swYYzD9 -9BcjGlZ+W988bDjkcbd4kdS8odhM+KhDtgPpTSEHCIjaWC9mOSm9BXiLnTjoBbdq -fnGk5sRgprDvgOSJKA+eJdbtg/OtppHHmMlCGDUUna2YRpIuT8rxh0PBFpVXLVDv -iS2Aelet8u5fa9IAjbkU+BQVNdnARqN7csiRv8lVK83Qlz6cJmTM386DGXHKTubU -1XupGc1V3sjs0l44U+VcT4wt/lAjNvxm5suOpDkZALeVAjmRCw7+OC7RHQWa9k0+ -bw8HHa8sHo9gOeL6NlMTOdReJivbPagUvTLrGAMoUgRx5aszPeE4uwc2hGKceeoW -MPRfwCvocWvk+QIDAQABo1MwUTAPBgNVHRMBAf8EBTADAQH/MB0GA1UdDgQWBBTA -ephojYn7qwVkDBF9qn1luMrMTjAfBgNVHSMEGDAWgBTAephojYn7qwVkDBF9qn1l -uMrMTjANBgkqhkiG9w0BAQUFAAOCAQEANeMpauUvXVSOKVCUn5kaFOSPeCpilKIn -Z57QzxpeR+nBsqTP3UEaBU6bS+5Kb1VSsyShNwrrZHYqLizz/Tt1kL/6cdjHPTfS -tQWVYrmm3ok9Nns4d0iXrKYgjy6myQzCsplFAMfOEVEiIuCl6rYVSAlk6l5PdPcF -PseKUgzbFbS9bZvlxrFUaKnjaZC2mqUPuLk/IH2uSrW4nOQdtqvmlKXBx4Ot2/Un -hw4EbNX/3aBd7YdStysVAq45pmp06drE57xNNB6pXE0zX5IJL4hmXXeXxx12E6nV -5fEWCRE11azbJHFwLJhWC9kXtNHjUStedejV0NxPNO3CBWaAocvmMw== ------END CERTIFICATE----- -` - -const giag2Intermediate = `-----BEGIN CERTIFICATE----- -MIIEBDCCAuygAwIBAgIDAjppMA0GCSqGSIb3DQEBBQUAMEIxCzAJBgNVBAYTAlVT -MRYwFAYDVQQKEw1HZW9UcnVzdCBJbmMuMRswGQYDVQQDExJHZW9UcnVzdCBHbG9i -YWwgQ0EwHhcNMTMwNDA1MTUxNTU1WhcNMTUwNDA0MTUxNTU1WjBJMQswCQYDVQQG -EwJVUzETMBEGA1UEChMKR29vZ2xlIEluYzElMCMGA1UEAxMcR29vZ2xlIEludGVy -bmV0IEF1dGhvcml0eSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB -AJwqBHdc2FCROgajguDYUEi8iT/xGXAaiEZ+4I/F8YnOIe5a/mENtzJEiaB0C1NP -VaTOgmKV7utZX8bhBYASxF6UP7xbSDj0U/ck5vuR6RXEz/RTDfRK/J9U3n2+oGtv -h8DQUB8oMANA2ghzUWx//zo8pzcGjr1LEQTrfSTe5vn8MXH7lNVg8y5Kr0LSy+rE -ahqyzFPdFUuLH8gZYR/Nnag+YyuENWllhMgZxUYi+FOVvuOAShDGKuy6lyARxzmZ -EASg8GF6lSWMTlJ14rbtCMoU/M4iarNOz0YDl5cDfsCx3nuvRTPPuj5xt970JSXC -DTWJnZ37DhF5iR43xa+OcmkCAwEAAaOB+zCB+DAfBgNVHSMEGDAWgBTAephojYn7 -qwVkDBF9qn1luMrMTjAdBgNVHQ4EFgQUSt0GFhu89mi1dvWBtrtiGrpagS8wEgYD -VR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAQYwOgYDVR0fBDMwMTAvoC2g -K4YpaHR0cDovL2NybC5nZW90cnVzdC5jb20vY3Jscy9ndGdsb2JhbC5jcmwwPQYI -KwYBBQUHAQEEMTAvMC0GCCsGAQUFBzABhiFodHRwOi8vZ3RnbG9iYWwtb2NzcC5n -ZW90cnVzdC5jb20wFwYDVR0gBBAwDjAMBgorBgEEAdZ5AgUBMA0GCSqGSIb3DQEB -BQUAA4IBAQA21waAESetKhSbOHezI6B1WLuxfoNCunLaHtiONgaX4PCVOzf9G0JY -/iLIa704XtE7JW4S615ndkZAkNoUyHgN7ZVm2o6Gb4ChulYylYbc3GrKBIxbf/a/ -zG+FA1jDaFETzf3I93k9mTXwVqO94FntT0QJo544evZG0R0SnU++0ED8Vf4GXjza -HFa9llF7b1cq26KqltyMdMKVvvBulRP/F/A8rLIQjcxz++iPAsbw+zOzlTvjwsto -WHPbqCRiOwY1nQ2pM714A5AuTHhdUDqB1O6gyHA43LL5Z/qHQF1hwFGPa4NrzQU6 -yuGnBXj8ytqU0CwIPX4WecigUCAkVDNx ------END CERTIFICATE----- -` - -const googleLeaf = `-----BEGIN CERTIFICATE----- -MIIEdjCCA16gAwIBAgIIcR5k4dkoe04wDQYJKoZIhvcNAQEFBQAwSTELMAkGA1UE -BhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMxJTAjBgNVBAMTHEdvb2dsZSBJbnRl -cm5ldCBBdXRob3JpdHkgRzIwHhcNMTQwMzEyMDkzODMwWhcNMTQwNjEwMDAwMDAw -WjBoMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwN -TW91bnRhaW4gVmlldzETMBEGA1UECgwKR29vZ2xlIEluYzEXMBUGA1UEAwwOd3d3 -Lmdvb2dsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC4zYCe -m0oUBhwE0EwBr65eBOcgcQO2PaSIAB2dEP/c1EMX2tOy0ov8rk83ePhJ+MWdT1z6 -jge9X4zQQI8ZyA9qIiwrKBZOi8DNUvrqNZC7fJAVRrb9aX/99uYOJCypIbpmWG1q -fhbHjJewhwf8xYPj71eU4rLG80a+DapWmphtfq3h52lDQIBzLVf1yYbyrTaELaz4 -NXF7HXb5YkId/gxIsSzM0aFUVu2o8sJcLYAsJqwfFKBKOMxUcn545nlspf0mTcWZ -0APlbwsKznNs4/xCDwIxxWjjqgHrYAFl6y07i1gzbAOqdNEyR24p+3JWI8WZBlBI -dk2KGj0W1fIfsvyxAgMBAAGjggFBMIIBPTAdBgNVHSUEFjAUBggrBgEFBQcDAQYI -KwYBBQUHAwIwGQYDVR0RBBIwEIIOd3d3Lmdvb2dsZS5jb20waAYIKwYBBQUHAQEE -XDBaMCsGCCsGAQUFBzAChh9odHRwOi8vcGtpLmdvb2dsZS5jb20vR0lBRzIuY3J0 -MCsGCCsGAQUFBzABhh9odHRwOi8vY2xpZW50czEuZ29vZ2xlLmNvbS9vY3NwMB0G -A1UdDgQWBBTXD5Bx6iqT+dmEhbFL4OUoHyZn8zAMBgNVHRMBAf8EAjAAMB8GA1Ud -IwQYMBaAFErdBhYbvPZotXb1gba7Yhq6WoEvMBcGA1UdIAQQMA4wDAYKKwYBBAHW -eQIFATAwBgNVHR8EKTAnMCWgI6Ahhh9odHRwOi8vcGtpLmdvb2dsZS5jb20vR0lB -RzIuY3JsMA0GCSqGSIb3DQEBBQUAA4IBAQCR3RJtHzgDh33b/MI1ugiki+nl8Ikj -5larbJRE/rcA5oite+QJyAr6SU1gJJ/rRrK3ItVEHr9L621BCM7GSdoNMjB9MMcf -tJAW0kYGJ+wqKm53wG/JaOADTnnq2Mt/j6F2uvjgN/ouns1nRHufIvd370N0LeH+ -orKqTuAPzXK7imQk6+OycYABbqCtC/9qmwRd8wwn7sF97DtYfK8WuNHtFalCAwyi -8LxJJYJCLWoMhZ+V8GZm+FOex5qkQAjnZrtNlbQJ8ro4r+rpKXtmMFFhfa+7L+PA -Kom08eUK8skxAzfDDijZPh10VtJ66uBoiDPdT+uCBehcBIcmSTrKjFGX ------END CERTIFICATE----- -` - -// googleLeafWithInvalidHash is the same as googleLeaf, but the signature -// algorithm in the certificate contains a nonsense OID. -const googleLeafWithInvalidHash = `-----BEGIN CERTIFICATE----- -MIIEdjCCA16gAwIBAgIIcR5k4dkoe04wDQYJKoZIhvcNAWAFBQAwSTELMAkGA1UE -BhMCVVMxEzARBgNVBAoTCkdvb2dsZSBJbmMxJTAjBgNVBAMTHEdvb2dsZSBJbnRl -cm5ldCBBdXRob3JpdHkgRzIwHhcNMTQwMzEyMDkzODMwWhcNMTQwNjEwMDAwMDAw -WjBoMQswCQYDVQQGEwJVUzETMBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwN -TW91bnRhaW4gVmlldzETMBEGA1UECgwKR29vZ2xlIEluYzEXMBUGA1UEAwwOd3d3 -Lmdvb2dsZS5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC4zYCe -m0oUBhwE0EwBr65eBOcgcQO2PaSIAB2dEP/c1EMX2tOy0ov8rk83ePhJ+MWdT1z6 -jge9X4zQQI8ZyA9qIiwrKBZOi8DNUvrqNZC7fJAVRrb9aX/99uYOJCypIbpmWG1q -fhbHjJewhwf8xYPj71eU4rLG80a+DapWmphtfq3h52lDQIBzLVf1yYbyrTaELaz4 -NXF7HXb5YkId/gxIsSzM0aFUVu2o8sJcLYAsJqwfFKBKOMxUcn545nlspf0mTcWZ -0APlbwsKznNs4/xCDwIxxWjjqgHrYAFl6y07i1gzbAOqdNEyR24p+3JWI8WZBlBI -dk2KGj0W1fIfsvyxAgMBAAGjggFBMIIBPTAdBgNVHSUEFjAUBggrBgEFBQcDAQYI -KwYBBQUHAwIwGQYDVR0RBBIwEIIOd3d3Lmdvb2dsZS5jb20waAYIKwYBBQUHAQEE -XDBaMCsGCCsGAQUFBzAChh9odHRwOi8vcGtpLmdvb2dsZS5jb20vR0lBRzIuY3J0 -MCsGCCsGAQUFBzABhh9odHRwOi8vY2xpZW50czEuZ29vZ2xlLmNvbS9vY3NwMB0G -A1UdDgQWBBTXD5Bx6iqT+dmEhbFL4OUoHyZn8zAMBgNVHRMBAf8EAjAAMB8GA1Ud -IwQYMBaAFErdBhYbvPZotXb1gba7Yhq6WoEvMBcGA1UdIAQQMA4wDAYKKwYBBAHW -eQIFATAwBgNVHR8EKTAnMCWgI6Ahhh9odHRwOi8vcGtpLmdvb2dsZS5jb20vR0lB -RzIuY3JsMA0GCSqGSIb3DQFgBQUAA4IBAQCR3RJtHzgDh33b/MI1ugiki+nl8Ikj -5larbJRE/rcA5oite+QJyAr6SU1gJJ/rRrK3ItVEHr9L621BCM7GSdoNMjB9MMcf -tJAW0kYGJ+wqKm53wG/JaOADTnnq2Mt/j6F2uvjgN/ouns1nRHufIvd370N0LeH+ -orKqTuAPzXK7imQk6+OycYABbqCtC/9qmwRd8wwn7sF97DtYfK8WuNHtFalCAwyi -8LxJJYJCLWoMhZ+V8GZm+FOex5qkQAjnZrtNlbQJ8ro4r+rpKXtmMFFhfa+7L+PA -Kom08eUK8skxAzfDDijZPh10VtJ66uBoiDPdT+uCBehcBIcmSTrKjFGX ------END CERTIFICATE----- -` - -const dnssecExpLeaf = `-----BEGIN CERTIFICATE----- -MIIGzTCCBbWgAwIBAgIDAdD6MA0GCSqGSIb3DQEBBQUAMIGMMQswCQYDVQQGEwJJ -TDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0 -YWwgQ2VydGlmaWNhdGUgU2lnbmluZzE4MDYGA1UEAxMvU3RhcnRDb20gQ2xhc3Mg -MSBQcmltYXJ5IEludGVybWVkaWF0ZSBTZXJ2ZXIgQ0EwHhcNMTAwNzA0MTQ1MjQ1 -WhcNMTEwNzA1MTA1NzA0WjCBwTEgMB4GA1UEDRMXMjIxMTM3LWxpOWE5dHhJRzZM -NnNyVFMxCzAJBgNVBAYTAlVTMR4wHAYDVQQKExVQZXJzb25hIE5vdCBWYWxpZGF0 -ZWQxKTAnBgNVBAsTIFN0YXJ0Q29tIEZyZWUgQ2VydGlmaWNhdGUgTWVtYmVyMRsw -GQYDVQQDExJ3d3cuZG5zc2VjLWV4cC5vcmcxKDAmBgkqhkiG9w0BCQEWGWhvc3Rt -YXN0ZXJAZG5zc2VjLWV4cC5vcmcwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEK -AoIBAQDEdF/22vaxrPbqpgVYMWi+alfpzBctpbfLBdPGuqOazJdCT0NbWcK8/+B4 -X6OlSOURNIlwLzhkmwVsWdVv6dVSaN7d4yI/fJkvgfDB9+au+iBJb6Pcz8ULBfe6 -D8HVvqKdORp6INzHz71z0sghxrQ0EAEkoWAZLh+kcn2ZHdcmZaBNUfjmGbyU6PRt -RjdqoP+owIaC1aktBN7zl4uO7cRjlYFdusINrh2kPP02KAx2W84xjxX1uyj6oS6e -7eBfvcwe8czW/N1rbE0CoR7h9+HnIrjnVG9RhBiZEiw3mUmF++Up26+4KTdRKbu3 -+BL4yMpfd66z0+zzqu+HkvyLpFn5AgMBAAGjggL/MIIC+zAJBgNVHRMEAjAAMAsG -A1UdDwQEAwIDqDATBgNVHSUEDDAKBggrBgEFBQcDATAdBgNVHQ4EFgQUy04I5guM -drzfh2JQaXhgV86+4jUwHwYDVR0jBBgwFoAU60I00Jiwq5/0G2sI98xkLu8OLEUw -LQYDVR0RBCYwJIISd3d3LmRuc3NlYy1leHAub3Jngg5kbnNzZWMtZXhwLm9yZzCC -AUIGA1UdIASCATkwggE1MIIBMQYLKwYBBAGBtTcBAgIwggEgMC4GCCsGAQUFBwIB -FiJodHRwOi8vd3d3LnN0YXJ0c3NsLmNvbS9wb2xpY3kucGRmMDQGCCsGAQUFBwIB -FihodHRwOi8vd3d3LnN0YXJ0c3NsLmNvbS9pbnRlcm1lZGlhdGUucGRmMIG3Bggr -BgEFBQcCAjCBqjAUFg1TdGFydENvbSBMdGQuMAMCAQEagZFMaW1pdGVkIExpYWJp -bGl0eSwgc2VlIHNlY3Rpb24gKkxlZ2FsIExpbWl0YXRpb25zKiBvZiB0aGUgU3Rh -cnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkgUG9saWN5IGF2YWlsYWJsZSBh -dCBodHRwOi8vd3d3LnN0YXJ0c3NsLmNvbS9wb2xpY3kucGRmMGEGA1UdHwRaMFgw -KqAooCaGJGh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL2NydDEtY3JsLmNybDAqoCig -JoYkaHR0cDovL2NybC5zdGFydHNzbC5jb20vY3J0MS1jcmwuY3JsMIGOBggrBgEF -BQcBAQSBgTB/MDkGCCsGAQUFBzABhi1odHRwOi8vb2NzcC5zdGFydHNzbC5jb20v -c3ViL2NsYXNzMS9zZXJ2ZXIvY2EwQgYIKwYBBQUHMAKGNmh0dHA6Ly93d3cuc3Rh -cnRzc2wuY29tL2NlcnRzL3N1Yi5jbGFzczEuc2VydmVyLmNhLmNydDAjBgNVHRIE -HDAahhhodHRwOi8vd3d3LnN0YXJ0c3NsLmNvbS8wDQYJKoZIhvcNAQEFBQADggEB -ACXj6SB59KRJPenn6gUdGEqcta97U769SATyiQ87i9er64qLwvIGLMa3o2Rcgl2Y -kghUeyLdN/EXyFBYA8L8uvZREPoc7EZukpT/ZDLXy9i2S0jkOxvF2fD/XLbcjGjM -iEYG1/6ASw0ri9C0k4oDDoJLCoeH9++yqF7SFCCMcDkJqiAGXNb4euDpa8vCCtEQ -CSS+ObZbfkreRt3cNCf5LfCXe9OsTnCfc8Cuq81c0oLaG+SmaLUQNBuToq8e9/Zm -+b+/a3RVjxmkV5OCcGVBxsXNDn54Q6wsdw0TBMcjwoEndzpLS7yWgFbbkq5ZiGpw -Qibb2+CfKuQ+WFV1GkVQmVA= ------END CERTIFICATE-----` - -const startComIntermediate = `-----BEGIN CERTIFICATE----- -MIIGNDCCBBygAwIBAgIBGDANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJJTDEW -MBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwg -Q2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNh -dGlvbiBBdXRob3JpdHkwHhcNMDcxMDI0MjA1NDE3WhcNMTcxMDI0MjA1NDE3WjCB -jDELMAkGA1UEBhMCSUwxFjAUBgNVBAoTDVN0YXJ0Q29tIEx0ZC4xKzApBgNVBAsT -IlNlY3VyZSBEaWdpdGFsIENlcnRpZmljYXRlIFNpZ25pbmcxODA2BgNVBAMTL1N0 -YXJ0Q29tIENsYXNzIDEgUHJpbWFyeSBJbnRlcm1lZGlhdGUgU2VydmVyIENBMIIB -IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtonGrO8JUngHrJJj0PREGBiE -gFYfka7hh/oyULTTRwbw5gdfcA4Q9x3AzhA2NIVaD5Ksg8asWFI/ujjo/OenJOJA -pgh2wJJuniptTT9uYSAK21ne0n1jsz5G/vohURjXzTCm7QduO3CHtPn66+6CPAVv -kvek3AowHpNz/gfK11+AnSJYUq4G2ouHI2mw5CrY6oPSvfNx23BaKA+vWjhwRRI/ -ME3NO68X5Q/LoKldSKqxYVDLNM08XMML6BDAjJvwAwNi/rJsPnIO7hxDKslIDlc5 -xDEhyBDBLIf+VJVSH1I8MRKbf+fAoKVZ1eKPPvDVqOHXcDGpxLPPr21TLwb0pwID -AQABo4IBrTCCAakwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYD -VR0OBBYEFOtCNNCYsKuf9BtrCPfMZC7vDixFMB8GA1UdIwQYMBaAFE4L7xqkQFul -F2mHMMo0aEPQQa7yMGYGCCsGAQUFBwEBBFowWDAnBggrBgEFBQcwAYYbaHR0cDov -L29jc3Auc3RhcnRzc2wuY29tL2NhMC0GCCsGAQUFBzAChiFodHRwOi8vd3d3LnN0 -YXJ0c3NsLmNvbS9zZnNjYS5jcnQwWwYDVR0fBFQwUjAnoCWgI4YhaHR0cDovL3d3 -dy5zdGFydHNzbC5jb20vc2ZzY2EuY3JsMCegJaAjhiFodHRwOi8vY3JsLnN0YXJ0 -c3NsLmNvbS9zZnNjYS5jcmwwgYAGA1UdIAR5MHcwdQYLKwYBBAGBtTcBAgEwZjAu -BggrBgEFBQcCARYiaHR0cDovL3d3dy5zdGFydHNzbC5jb20vcG9saWN5LnBkZjA0 -BggrBgEFBQcCARYoaHR0cDovL3d3dy5zdGFydHNzbC5jb20vaW50ZXJtZWRpYXRl -LnBkZjANBgkqhkiG9w0BAQUFAAOCAgEAIQlJPqWIbuALi0jaMU2P91ZXouHTYlfp -tVbzhUV1O+VQHwSL5qBaPucAroXQ+/8gA2TLrQLhxpFy+KNN1t7ozD+hiqLjfDen -xk+PNdb01m4Ge90h2c9W/8swIkn+iQTzheWq8ecf6HWQTd35RvdCNPdFWAwRDYSw -xtpdPvkBnufh2lWVvnQce/xNFE+sflVHfXv0pQ1JHpXo9xLBzP92piVH0PN1Nb6X -t1gW66pceG/sUzCv6gRNzKkC4/C2BBL2MLERPZBOVmTX3DxDX3M570uvh+v2/miI -RHLq0gfGabDBoYvvF0nXYbFFSF87ICHpW7LM9NfpMfULFWE7epTj69m8f5SuauNi -YpaoZHy4h/OZMn6SolK+u/hlz8nyMPyLwcKmltdfieFcNID1j0cHL7SRv7Gifl9L -WtBbnySGBVFaaQNlQ0lxxeBvlDRr9hvYqbBMflPrj0jfyjO1SPo2ShpTpjMM0InN -SRXNiTE8kMBy12VLUjWKRhFEuT2OKGWmPnmeXAhEKa2wNREuIU640ucQPl2Eg7PD -wuTSxv0JS3QJ3fGz0xk+gA2iCxnwOOfFwq/iI9th4p1cbiCJSS4jarJiwUW0n6+L -p/EiO/h94pDQehn7Skzj0n1fSoMD7SfWI55rjbRZotnvbIIp3XUZPD9MEI3vu3Un -0q6Dp6jOW6c= ------END CERTIFICATE-----` - -const startComRoot = `-----BEGIN CERTIFICATE----- -MIIHyTCCBbGgAwIBAgIBATANBgkqhkiG9w0BAQUFADB9MQswCQYDVQQGEwJJTDEW -MBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwg -Q2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNh -dGlvbiBBdXRob3JpdHkwHhcNMDYwOTE3MTk0NjM2WhcNMzYwOTE3MTk0NjM2WjB9 -MQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMi -U2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3Rh -cnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUA -A4ICDwAwggIKAoICAQDBiNsJvGxGfHiflXu1M5DycmLWwTYgIiRezul38kMKogZk -pMyONvg45iPwbm2xPN1yo4UcodM9tDMr0y+v/uqwQVlntsQGfQqedIXWeUyAN3rf -OQVSWff0G0ZDpNKFhdLDcfN1YjS6LIp/Ho/u7TTQEceWzVI9ujPW3U3eCztKS5/C -Ji/6tRYccjV3yjxd5srhJosaNnZcAdt0FCX+7bWgiA/deMotHweXMAEtcnn6RtYT -Kqi5pquDSR3l8u/d5AGOGAqPY1MWhWKpDhk6zLVmpsJrdAfkK+F2PrRt2PZE4XNi -HzvEvqBTViVsUQn3qqvKv3b9bZvzndu/PWa8DFaqr5hIlTpL36dYUNk4dalb6kMM -Av+Z6+hsTXBbKWWc3apdzK8BMewM69KN6Oqce+Zu9ydmDBpI125C4z/eIT574Q1w -+2OqqGwaVLRcJXrJosmLFqa7LH4XXgVNWG4SHQHuEhANxjJ/GP/89PrNbpHoNkm+ -Gkhpi8KWTRoSsmkXwQqQ1vp5Iki/untp+HDH+no32NgN0nZPV/+Qt+OR0t3vwmC3 -Zzrd/qqc8NSLf3Iizsafl7b4r4qgEKjZ+xjGtrVcUjyJthkqcwEKDwOzEmDyei+B -26Nu/yYwl/WL3YlXtq09s68rxbd2AvCl1iuahhQqcvbjM4xdCUsT37uMdBNSSwID -AQABo4ICUjCCAk4wDAYDVR0TBAUwAwEB/zALBgNVHQ8EBAMCAa4wHQYDVR0OBBYE -FE4L7xqkQFulF2mHMMo0aEPQQa7yMGQGA1UdHwRdMFswLKAqoCiGJmh0dHA6Ly9j -ZXJ0LnN0YXJ0Y29tLm9yZy9zZnNjYS1jcmwuY3JsMCugKaAnhiVodHRwOi8vY3Js -LnN0YXJ0Y29tLm9yZy9zZnNjYS1jcmwuY3JsMIIBXQYDVR0gBIIBVDCCAVAwggFM -BgsrBgEEAYG1NwEBATCCATswLwYIKwYBBQUHAgEWI2h0dHA6Ly9jZXJ0LnN0YXJ0 -Y29tLm9yZy9wb2xpY3kucGRmMDUGCCsGAQUFBwIBFilodHRwOi8vY2VydC5zdGFy -dGNvbS5vcmcvaW50ZXJtZWRpYXRlLnBkZjCB0AYIKwYBBQUHAgIwgcMwJxYgU3Rh -cnQgQ29tbWVyY2lhbCAoU3RhcnRDb20pIEx0ZC4wAwIBARqBl0xpbWl0ZWQgTGlh -YmlsaXR5LCByZWFkIHRoZSBzZWN0aW9uICpMZWdhbCBMaW1pdGF0aW9ucyogb2Yg -dGhlIFN0YXJ0Q29tIENlcnRpZmljYXRpb24gQXV0aG9yaXR5IFBvbGljeSBhdmFp -bGFibGUgYXQgaHR0cDovL2NlcnQuc3RhcnRjb20ub3JnL3BvbGljeS5wZGYwEQYJ -YIZIAYb4QgEBBAQDAgAHMDgGCWCGSAGG+EIBDQQrFilTdGFydENvbSBGcmVlIFNT -TCBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTANBgkqhkiG9w0BAQUFAAOCAgEAFmyZ -9GYMNPXQhV59CuzaEE44HF7fpiUFS5Eyweg78T3dRAlbB0mKKctmArexmvclmAk8 -jhvh3TaHK0u7aNM5Zj2gJsfyOZEdUauCe37Vzlrk4gNXcGmXCPleWKYK34wGmkUW -FjgKXlf2Ysd6AgXmvB618p70qSmD+LIU424oh0TDkBreOKk8rENNZEXO3SipXPJz -ewT4F+irsfMuXGRuczE6Eri8sxHkfY+BUZo7jYn0TZNmezwD7dOaHZrzZVD1oNB1 -ny+v8OqCQ5j4aZyJecRDjkZy42Q2Eq/3JR44iZB3fsNrarnDy0RLrHiQi+fHLB5L -EUTINFInzQpdn4XBidUaePKVEFMy3YCEZnXZtWgo+2EuvoSoOMCZEoalHmdkrQYu -L6lwhceWD3yJZfWOQ1QOq92lgDmUYMA0yZZwLKMS9R9Ie70cfmu3nZD0Ijuu+Pwq -yvqCUqDvr0tVk+vBtfAii6w0TiYiBKGHLHVKt+V9E9e4DGTANtLJL4YSjCMJwRuC -O3NJo2pXh5Tl1njFmUNj403gdy3hZZlyaQQaRwnmDwFWJPsfvw55qVguucQJAX6V -um0ABj6y6koQOdjQK/W/7HW/lwLFCRsI3FU34oH7N4RDYiDK51ZLZer+bMEkkySh -NOsF/5oirpt9P/FlUQqmMGqz9IgcgA38corog14= ------END CERTIFICATE-----` - -const startComRootSHA256 = `-----BEGIN CERTIFICATE----- -MIIHhzCCBW+gAwIBAgIBLTANBgkqhkiG9w0BAQsFADB9MQswCQYDVQQGEwJJTDEW -MBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMiU2VjdXJlIERpZ2l0YWwg -Q2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3RhcnRDb20gQ2VydGlmaWNh -dGlvbiBBdXRob3JpdHkwHhcNMDYwOTE3MTk0NjM3WhcNMzYwOTE3MTk0NjM2WjB9 -MQswCQYDVQQGEwJJTDEWMBQGA1UEChMNU3RhcnRDb20gTHRkLjErMCkGA1UECxMi -U2VjdXJlIERpZ2l0YWwgQ2VydGlmaWNhdGUgU2lnbmluZzEpMCcGA1UEAxMgU3Rh -cnRDb20gQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwggIiMA0GCSqGSIb3DQEBAQUA -A4ICDwAwggIKAoICAQDBiNsJvGxGfHiflXu1M5DycmLWwTYgIiRezul38kMKogZk -pMyONvg45iPwbm2xPN1yo4UcodM9tDMr0y+v/uqwQVlntsQGfQqedIXWeUyAN3rf -OQVSWff0G0ZDpNKFhdLDcfN1YjS6LIp/Ho/u7TTQEceWzVI9ujPW3U3eCztKS5/C -Ji/6tRYccjV3yjxd5srhJosaNnZcAdt0FCX+7bWgiA/deMotHweXMAEtcnn6RtYT -Kqi5pquDSR3l8u/d5AGOGAqPY1MWhWKpDhk6zLVmpsJrdAfkK+F2PrRt2PZE4XNi -HzvEvqBTViVsUQn3qqvKv3b9bZvzndu/PWa8DFaqr5hIlTpL36dYUNk4dalb6kMM -Av+Z6+hsTXBbKWWc3apdzK8BMewM69KN6Oqce+Zu9ydmDBpI125C4z/eIT574Q1w -+2OqqGwaVLRcJXrJosmLFqa7LH4XXgVNWG4SHQHuEhANxjJ/GP/89PrNbpHoNkm+ -Gkhpi8KWTRoSsmkXwQqQ1vp5Iki/untp+HDH+no32NgN0nZPV/+Qt+OR0t3vwmC3 -Zzrd/qqc8NSLf3Iizsafl7b4r4qgEKjZ+xjGtrVcUjyJthkqcwEKDwOzEmDyei+B -26Nu/yYwl/WL3YlXtq09s68rxbd2AvCl1iuahhQqcvbjM4xdCUsT37uMdBNSSwID -AQABo4ICEDCCAgwwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYD -VR0OBBYEFE4L7xqkQFulF2mHMMo0aEPQQa7yMB8GA1UdIwQYMBaAFE4L7xqkQFul -F2mHMMo0aEPQQa7yMIIBWgYDVR0gBIIBUTCCAU0wggFJBgsrBgEEAYG1NwEBATCC -ATgwLgYIKwYBBQUHAgEWImh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL3BvbGljeS5w -ZGYwNAYIKwYBBQUHAgEWKGh0dHA6Ly93d3cuc3RhcnRzc2wuY29tL2ludGVybWVk -aWF0ZS5wZGYwgc8GCCsGAQUFBwICMIHCMCcWIFN0YXJ0IENvbW1lcmNpYWwgKFN0 -YXJ0Q29tKSBMdGQuMAMCAQEagZZMaW1pdGVkIExpYWJpbGl0eSwgcmVhZCB0aGUg -c2VjdGlvbiAqTGVnYWwgTGltaXRhdGlvbnMqIG9mIHRoZSBTdGFydENvbSBDZXJ0 -aWZpY2F0aW9uIEF1dGhvcml0eSBQb2xpY3kgYXZhaWxhYmxlIGF0IGh0dHA6Ly93 -d3cuc3RhcnRzc2wuY29tL3BvbGljeS5wZGYwEQYJYIZIAYb4QgEBBAQDAgAHMDgG -CWCGSAGG+EIBDQQrFilTdGFydENvbSBGcmVlIFNTTCBDZXJ0aWZpY2F0aW9uIEF1 -dGhvcml0eTANBgkqhkiG9w0BAQsFAAOCAgEAjo/n3JR5fPGFf59Jb2vKXfuM/gTF -wWLRfUKKvFO3lANmMD+x5wqnUCBVJX92ehQN6wQOQOY+2IirByeDqXWmN3PH/UvS -Ta0XQMhGvjt/UfzDtgUx3M2FIk5xt/JxXrAaxrqTi3iSSoX4eA+D/i+tLPfkpLst -0OcNOrg+zvZ49q5HJMqjNTbOx8aHmNrs++myziebiMMEofYLWWivydsQD032ZGNc -pRJvkrKTlMeIFw6Ttn5ii5B/q06f/ON1FE8qMt9bDeD1e5MNq6HPh+GlBEXoPBKl -CcWw0bdT82AUuoVpaiF8H3VhFyAXe2w7QSlc4axa0c2Mm+tgHRns9+Ww2vl5GKVF -P0lDV9LdJNUso/2RjSe15esUBppMeyG7Oq0wBhjA2MFrLH9ZXF2RsXAiV+uKa0hK -1Q8p7MZAwC+ITGgBF3f0JBlPvfrhsiAhS90a2Cl9qrjeVOwhVYBsHvUwyKMQ5bLm -KhQxw4UtjJixhlpPiVktucf3HMiKf8CdBUrmQk9io20ppB+Fq9vlgcitKj1MXVuE -JnHEhV5xJMqlG2zYYdMa4FTbzrqpMrUi9nNBCV24F10OD5mQ1kfabwo6YigUZ4LZ -8dCAWZvLMdibD4x3TrVoivJs9iQOLWxwxXPR3hTQcY+203sC9uO41Alua551hDnm -fyWl8kgAwKQB2j8= ------END CERTIFICATE-----` - -const smimeLeaf = `-----BEGIN CERTIFICATE----- -MIIFBjCCA+6gAwIBAgISESFvrjT8XcJTEe6rBlPptILlMA0GCSqGSIb3DQEBBQUA -MFQxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMSowKAYD -VQQDEyFHbG9iYWxTaWduIFBlcnNvbmFsU2lnbiAyIENBIC0gRzIwHhcNMTIwMTIz -MTYzNjU5WhcNMTUwMTIzMTYzNjU5WjCBlDELMAkGA1UEBhMCVVMxFjAUBgNVBAgT -DU5ldyBIYW1zcGhpcmUxEzARBgNVBAcTClBvcnRzbW91dGgxGTAXBgNVBAoTEEds -b2JhbFNpZ24sIEluYy4xEzARBgNVBAMTClJ5YW4gSHVyc3QxKDAmBgkqhkiG9w0B -CQEWGXJ5YW4uaHVyc3RAZ2xvYmFsc2lnbi5jb20wggEiMA0GCSqGSIb3DQEBAQUA -A4IBDwAwggEKAoIBAQC4ASSTvavmsFQAob60ukSSwOAL9nT/s99ltNUCAf5fPH5j -NceMKxaQse2miOmRRIXaykcq1p/TbI70Ztce38r2mbOwqDHHPVi13GxJEyUXWgaR -BteDMu5OGyWNG1kchVsGWpbstT0Z4v0md5m1BYFnxB20ebJyOR2lXDxsFK28nnKV -+5eMj76U8BpPQ4SCH7yTMG6y0XXsB3cCrBKr2o3TOYgEKv+oNnbaoMt3UxMt9nSf -9jyIshjqfnT5Aew3CUNMatO55g5FXXdIukAweg1YSb1ls05qW3sW00T3d7dQs9/7 -NuxCg/A2elmVJSoy8+MLR8JSFEf/aMgjO/TyLg/jAgMBAAGjggGPMIIBizAOBgNV -HQ8BAf8EBAMCBaAwTQYDVR0gBEYwRDBCBgorBgEEAaAyASgKMDQwMgYIKwYBBQUH -AgEWJmh0dHBzOi8vd3d3Lmdsb2JhbHNpZ24uY29tL3JlcG9zaXRvcnkvMCQGA1Ud -EQQdMBuBGXJ5YW4uaHVyc3RAZ2xvYmFsc2lnbi5jb20wCQYDVR0TBAIwADAdBgNV -HSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwQwQwYDVR0fBDwwOjA4oDagNIYyaHR0 -cDovL2NybC5nbG9iYWxzaWduLmNvbS9ncy9nc3BlcnNvbmFsc2lnbjJnMi5jcmww -VQYIKwYBBQUHAQEESTBHMEUGCCsGAQUFBzAChjlodHRwOi8vc2VjdXJlLmdsb2Jh -bHNpZ24uY29tL2NhY2VydC9nc3BlcnNvbmFsc2lnbjJnMi5jcnQwHQYDVR0OBBYE -FFWiECe0/L72eVYqcWYnLV6SSjzhMB8GA1UdIwQYMBaAFD8V0m18L+cxnkMKBqiU -bCw7xe5lMA0GCSqGSIb3DQEBBQUAA4IBAQAhQi6hLPeudmf3IBF4IDzCvRI0FaYd -BKfprSk/H0PDea4vpsLbWpA0t0SaijiJYtxKjlM4bPd+2chb7ejatDdyrZIzmDVy -q4c30/xMninGKokpYA11/Ve+i2dvjulu65qasrtQRGybAuuZ67lrp/K3OMFgjV5N -C3AHYLzvNU4Dwc4QQ1BaMOg6KzYSrKbABRZajfrpC9uiePsv7mDIXLx/toBPxWNl -a5vJm5DrZdn7uHdvBCE6kMykbOLN5pmEK0UIlwKh6Qi5XD0pzlVkEZliFkBMJgub -d/eF7xeg7TKPWC5xyOFp9SdMolJM7LTC3wnSO3frBAev+q/nGs9Xxyvs ------END CERTIFICATE-----` - -const smimeIntermediate = `-----BEGIN CERTIFICATE----- -MIIEFjCCAv6gAwIBAgILBAAAAAABL07hL1IwDQYJKoZIhvcNAQEFBQAwVzELMAkG -A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv -b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw0xMTA0MTMxMDAw -MDBaFw0xOTA0MTMxMDAwMDBaMFQxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i -YWxTaWduIG52LXNhMSowKAYDVQQDEyFHbG9iYWxTaWduIFBlcnNvbmFsU2lnbiAy -IENBIC0gRzIwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDBa0H5Nez4 -En3dIlFpX7e5E0YndxQ74xOBbz7kdBd+DLX0LOQMjVPU3DAgKL9ujhH+ZhHkURbH -3X/94TQSUL/z2JjsaQvS0NqyZXHhM5eeuquzOJRzEQ8+odETzHg2G0Erv7yjSeww -gkwDWDJnYUDlOjYTDUEG6+i+8Mn425reo4I0E277wD542kmVWeW7+oHv5dZo9e1Q -yWwiKTEP6BEQVVSBgThXMG4traSSDRUt3T1eQTZx5EObpiBEBO4OTqiBTJfg4vEI -YgkXzKLpnfszTB6YMDpR9/QS6p3ANB3kfAb+t6udSO3WCst0DGrwHDLBFGDR4UeY -T5KGGnI7cWL7AgMBAAGjgeUwgeIwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQI -MAYBAf8CAQAwHQYDVR0OBBYEFD8V0m18L+cxnkMKBqiUbCw7xe5lMEcGA1UdIARA -MD4wPAYEVR0gADA0MDIGCCsGAQUFBwIBFiZodHRwczovL3d3dy5nbG9iYWxzaWdu -LmNvbS9yZXBvc2l0b3J5LzAzBgNVHR8ELDAqMCigJqAkhiJodHRwOi8vY3JsLmds -b2JhbHNpZ24ubmV0L3Jvb3QuY3JsMB8GA1UdIwQYMBaAFGB7ZhpFDZfKiVAvfQTN -NKj//P1LMA0GCSqGSIb3DQEBBQUAA4IBAQBDc3nMpMxJMQMcYUCB3+C73UpvwDE8 -eCOr7t2F/uaQKKcyqqstqLZc6vPwI/rcE9oDHugY5QEjQzIBIEaTnN6P0vege2IX -eCOr7t2F/uaQKKcyqqstqLZc6vPwI/rcE9oDHugY5QEjQzIBIEaTnN6P0vege2IX -YEvTWbWwGdPytDFPYIl3/6OqNSXSnZ7DxPcdLJq2uyiga8PB/TTIIHYkdM2+1DE0 -7y3rH/7TjwDVD7SLu5/SdOfKskuMPTjOEvz3K161mymW06klVhubCIWOro/Gx1Q2 -2FQOZ7/2k4uYoOdBTSlb8kTAuzZNgIE0rB2BIYCTz/P6zZIKW0ogbRSH ------END CERTIFICATE-----` - -var megaLeaf = `-----BEGIN CERTIFICATE----- -MIIFOjCCBCKgAwIBAgIQWYE8Dup170kZ+k11Lg51OjANBgkqhkiG9w0BAQUFADBy -MQswCQYDVQQGEwJHQjEbMBkGA1UECBMSR3JlYXRlciBNYW5jaGVzdGVyMRAwDgYD -VQQHEwdTYWxmb3JkMRowGAYDVQQKExFDT01PRE8gQ0EgTGltaXRlZDEYMBYGA1UE -AxMPRXNzZW50aWFsU1NMIENBMB4XDTEyMTIxNDAwMDAwMFoXDTE0MTIxNDIzNTk1 -OVowfzEhMB8GA1UECxMYRG9tYWluIENvbnRyb2wgVmFsaWRhdGVkMS4wLAYDVQQL -EyVIb3N0ZWQgYnkgSW5zdHJhIENvcnBvcmF0aW9uIFB0eS4gTFREMRUwEwYDVQQL -EwxFc3NlbnRpYWxTU0wxEzARBgNVBAMTCm1lZ2EuY28ubnowggEiMA0GCSqGSIb3 -DQEBAQUAA4IBDwAwggEKAoIBAQDcxMCClae8BQIaJHBUIVttlLvhbK4XhXPk3RQ3 -G5XA6tLZMBQ33l3F9knYJ0YErXtr8IdfYoulRQFmKFMJl9GtWyg4cGQi2Rcr5VN5 -S5dA1vu4oyJBxE9fPELcK6Yz1vqaf+n6za+mYTiQYKggVdS8/s8hmNuXP9Zk1pIn -+q0pGsf8NAcSHMJgLqPQrTDw+zae4V03DvcYfNKjuno88d2226ld7MAmQZ7uRNsI -/CnkdelVs+akZsXf0szefSqMJlf08SY32t2jj4Ra7RApVYxOftD9nij/aLfuqOU6 -ow6IgIcIG2ZvXLZwK87c5fxL7UAsTTV+M1sVv8jA33V2oKLhAgMBAAGjggG9MIIB -uTAfBgNVHSMEGDAWgBTay+qtWwhdzP/8JlTOSeVVxjj0+DAdBgNVHQ4EFgQUmP9l -6zhyrZ06Qj4zogt+6LKFk4AwDgYDVR0PAQH/BAQDAgWgMAwGA1UdEwEB/wQCMAAw -NAYDVR0lBC0wKwYIKwYBBQUHAwEGCCsGAQUFBwMCBgorBgEEAYI3CgMDBglghkgB -hvhCBAEwTwYDVR0gBEgwRjA6BgsrBgEEAbIxAQICBzArMCkGCCsGAQUFBwIBFh1o -dHRwczovL3NlY3VyZS5jb21vZG8uY29tL0NQUzAIBgZngQwBAgEwOwYDVR0fBDQw -MjAwoC6gLIYqaHR0cDovL2NybC5jb21vZG9jYS5jb20vRXNzZW50aWFsU1NMQ0Eu -Y3JsMG4GCCsGAQUFBwEBBGIwYDA4BggrBgEFBQcwAoYsaHR0cDovL2NydC5jb21v -ZG9jYS5jb20vRXNzZW50aWFsU1NMQ0FfMi5jcnQwJAYIKwYBBQUHMAGGGGh0dHA6 -Ly9vY3NwLmNvbW9kb2NhLmNvbTAlBgNVHREEHjAcggptZWdhLmNvLm56gg53d3cu -bWVnYS5jby5uejANBgkqhkiG9w0BAQUFAAOCAQEAcYhrsPSvDuwihMOh0ZmRpbOE -Gw6LqKgLNTmaYUPQhzi2cyIjhUhNvugXQQlP5f0lp5j8cixmArafg1dTn4kQGgD3 -ivtuhBTgKO1VYB/VRoAt6Lmswg3YqyiS7JiLDZxjoV7KoS5xdiaINfHDUaBBY4ZH -j2BUlPniNBjCqXe/HndUTVUewlxbVps9FyCmH+C4o9DWzdGBzDpCkcmo5nM+cp7q -ZhTIFTvZfo3zGuBoyu8BzuopCJcFRm3cRiXkpI7iOMUIixO1szkJS6WpL1sKdT73 -UXp08U0LBqoqG130FbzEJBBV3ixbvY6BWMHoCWuaoF12KJnC5kHt2RoWAAgMXA== ------END CERTIFICATE-----` - -var comodoIntermediate1 = `-----BEGIN CERTIFICATE----- -MIIFAzCCA+ugAwIBAgIQGLLLuqME8aAPwfLzJkYqSjANBgkqhkiG9w0BAQUFADCB -gTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G -A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxJzAlBgNV -BAMTHkNPTU9ETyBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjEyMDEwMDAw -MDBaFw0xOTEyMzEyMzU5NTlaMHIxCzAJBgNVBAYTAkdCMRswGQYDVQQIExJHcmVh -dGVyIE1hbmNoZXN0ZXIxEDAOBgNVBAcTB1NhbGZvcmQxGjAYBgNVBAoTEUNPTU9E -TyBDQSBMaW1pdGVkMRgwFgYDVQQDEw9Fc3NlbnRpYWxTU0wgQ0EwggEiMA0GCSqG -SIb3DQEBAQUAA4IBDwAwggEKAoIBAQCt8AiwcsargxIxF3CJhakgEtSYau2A1NHf -5I5ZLdOWIY120j8YC0YZYwvHIPPlC92AGvFaoL0dds23Izp0XmEbdaqb1IX04XiR -0y3hr/yYLgbSeT1awB8hLRyuIVPGOqchfr7tZ291HRqfalsGs2rjsQuqag7nbWzD -ypWMN84hHzWQfdvaGlyoiBSyD8gSIF/F03/o4Tjg27z5H6Gq1huQByH6RSRQXScq -oChBRVt9vKCiL6qbfltTxfEFFld+Edc7tNkBdtzffRDPUanlOPJ7FAB1WfnwWdsX -Pvev5gItpHnBXaIcw5rIp6gLSApqLn8tl2X2xQScRMiZln5+pN0vAgMBAAGjggGD -MIIBfzAfBgNVHSMEGDAWgBQLWOWLxkwVN6RAqTCpIb5HNlpW/zAdBgNVHQ4EFgQU -2svqrVsIXcz//CZUzknlVcY49PgwDgYDVR0PAQH/BAQDAgEGMBIGA1UdEwEB/wQI -MAYBAf8CAQAwIAYDVR0lBBkwFwYKKwYBBAGCNwoDAwYJYIZIAYb4QgQBMD4GA1Ud -IAQ3MDUwMwYEVR0gADArMCkGCCsGAQUFBwIBFh1odHRwczovL3NlY3VyZS5jb21v -ZG8uY29tL0NQUzBJBgNVHR8EQjBAMD6gPKA6hjhodHRwOi8vY3JsLmNvbW9kb2Nh -LmNvbS9DT01PRE9DZXJ0aWZpY2F0aW9uQXV0aG9yaXR5LmNybDBsBggrBgEFBQcB -AQRgMF4wNgYIKwYBBQUHMAKGKmh0dHA6Ly9jcnQuY29tb2RvY2EuY29tL0NvbW9k -b1VUTlNHQ0NBLmNydDAkBggrBgEFBQcwAYYYaHR0cDovL29jc3AuY29tb2RvY2Eu -Y29tMA0GCSqGSIb3DQEBBQUAA4IBAQAtlzR6QDLqcJcvgTtLeRJ3rvuq1xqo2l/z -odueTZbLN3qo6u6bldudu+Ennv1F7Q5Slqz0J790qpL0pcRDAB8OtXj5isWMcL2a -ejGjKdBZa0wztSz4iw+SY1dWrCRnilsvKcKxudokxeRiDn55w/65g+onO7wdQ7Vu -F6r7yJiIatnyfKH2cboZT7g440LX8NqxwCPf3dfxp+0Jj1agq8MLy6SSgIGSH6lv -+Wwz3D5XxqfyH8wqfOQsTEZf6/Nh9yvENZ+NWPU6g0QO2JOsTGvMd/QDzczc4BxL -XSXaPV7Od4rhPsbXlM1wSTz/Dr0ISKvlUhQVnQ6cGodWaK2cCQBk ------END CERTIFICATE-----` - -var comodoRoot = `-----BEGIN CERTIFICATE----- -MIIEHTCCAwWgAwIBAgIQToEtioJl4AsC7j41AkblPTANBgkqhkiG9w0BAQUFADCB -gTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G -A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxJzAlBgNV -BAMTHkNPTU9ETyBDZXJ0aWZpY2F0aW9uIEF1dGhvcml0eTAeFw0wNjEyMDEwMDAw -MDBaFw0yOTEyMzEyMzU5NTlaMIGBMQswCQYDVQQGEwJHQjEbMBkGA1UECBMSR3Jl -YXRlciBNYW5jaGVzdGVyMRAwDgYDVQQHEwdTYWxmb3JkMRowGAYDVQQKExFDT01P -RE8gQ0EgTGltaXRlZDEnMCUGA1UEAxMeQ09NT0RPIENlcnRpZmljYXRpb24gQXV0 -aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA0ECLi3LjkRv3 -UcEbVASY06m/weaKXTuH+7uIzg3jLz8GlvCiKVCZrts7oVewdFFxze1CkU1B/qnI -2GqGd0S7WWaXUF601CxwRM/aN5VCaTwwxHGzUvAhTaHYujl8HJ6jJJ3ygxaYqhZ8 -Q5sVW7euNJH+1GImGEaaP+vB+fGQV+useg2L23IwambV4EajcNxo2f8ESIl33rXp -+2dtQem8Ob0y2WIC8bGoPW43nOIv4tOiJovGuFVDiOEjPqXSJDlqR6sA1KGzqSX+ -DT+nHbrTUcELpNqsOO9VUCQFZUaTNE8tja3G1CEZ0o7KBWFxB3NH5YoZEr0ETc5O -nKVIrLsm9wIDAQABo4GOMIGLMB0GA1UdDgQWBBQLWOWLxkwVN6RAqTCpIb5HNlpW -/zAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0TAQH/BAUwAwEB/zBJBgNVHR8EQjBAMD6g -PKA6hjhodHRwOi8vY3JsLmNvbW9kb2NhLmNvbS9DT01PRE9DZXJ0aWZpY2F0aW9u -QXV0aG9yaXR5LmNybDANBgkqhkiG9w0BAQUFAAOCAQEAPpiem/Yb6dc5t3iuHXIY -SdOH5EOC6z/JqvWote9VfCFSZfnVDeFs9D6Mk3ORLgLETgdxb8CPOGEIqB6BCsAv -IC9Bi5HcSEW88cbeunZrM8gALTFGTO3nnc+IlP8zwFboJIYmuNg4ON8qa90SzMc/ -RxdMosIGlgnW2/4/PEZB31jiVg88O8EckzXZOFKs7sjsLjBOlDW0JB9LeGna8gI4 -zJVSk/BwJVmcIGfE7vmLV2H0knZ9P4SNVbfo5azV8fUZVqZa+5Acr5Pr5RzUZ5dd -BA6+C4OmF4O5MBKgxTMVBbkN+8cFduPYSo38NBejxiEovjBFMR7HeL5YYTisO+IB -ZQ== ------END CERTIFICATE-----` - -var nameConstraintsLeaf = `-----BEGIN CERTIFICATE----- -MIIHMTCCBRmgAwIBAgIIIZaV/3ezOJkwDQYJKoZIhvcNAQEFBQAwgcsxCzAJBgNV -BAYTAlVTMREwDwYDVQQIEwhWaXJnaW5pYTETMBEGA1UEBxMKQmxhY2tzYnVyZzEj -MCEGA1UECxMaR2xvYmFsIFF1YWxpZmllZCBTZXJ2ZXIgQ0ExPDA6BgNVBAoTM1Zp -cmdpbmlhIFBvbHl0ZWNobmljIEluc3RpdHV0ZSBhbmQgU3RhdGUgVW5pdmVyc2l0 -eTExMC8GA1UEAxMoVmlyZ2luaWEgVGVjaCBHbG9iYWwgUXVhbGlmaWVkIFNlcnZl -ciBDQTAeFw0xMzA5MTkxNDM2NTVaFw0xNTA5MTkxNDM2NTVaMIHNMQswCQYDVQQG -EwJVUzERMA8GA1UECAwIVmlyZ2luaWExEzARBgNVBAcMCkJsYWNrc2J1cmcxPDA6 -BgNVBAoMM1ZpcmdpbmlhIFBvbHl0ZWNobmljIEluc3RpdHV0ZSBhbmQgU3RhdGUg -VW5pdmVyc2l0eTE7MDkGA1UECwwyVGVjaG5vbG9neS1lbmhhbmNlZCBMZWFybmlu -ZyBhbmQgT25saW5lIFN0cmF0ZWdpZXMxGzAZBgNVBAMMEnNlY3VyZS5pZGRsLnZ0 -LmVkdTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAKkOyPpsOK/6IuPG -WnIBlVwlHzeYf+cUlggqkLq0b0+vZbiTXgio9/VCuNQ8opSoss7J7o3ygV9to+9Y -YwJKVC5WDT/y5JWpQey0CWILymViJnpNSwnxBc8A+Q8w5NUGDd/UhtPx/U8/hqbd -WPDYj2hbOqyq8UlRhfS5pwtnv6BbCTaY11I6FhCLK7zttISyTuWCf9p9o/ggiipP -ii/5oh4dkl+r5SfuSp5GPNHlYO8lWqys5NAPoDD4fc/kuflcK7Exx7XJ+Oqu0W0/ -psjEY/tES1ZgDWU/ParcxxFpFmKHbD5DXsfPOObzkVWXIY6tGMutSlE1Froy/Nn0 -OZsAOrcCAwEAAaOCAhMwggIPMIG4BggrBgEFBQcBAQSBqzCBqDBYBggrBgEFBQcw -AoZMaHR0cDovL3d3dy5wa2kudnQuZWR1L2dsb2JhbHF1YWxpZmllZHNlcnZlci9j -YWNlcnQvZ2xvYmFscXVhbGlmaWVkc2VydmVyLmNydDBMBggrBgEFBQcwAYZAaHR0 -cDovL3Z0Y2EtcC5lcHJvdi5zZXRpLnZ0LmVkdTo4MDgwL2VqYmNhL3B1YmxpY3dl -Yi9zdGF0dXMvb2NzcDAdBgNVHQ4EFgQUp7xbO6iHkvtZbPE4jmndmnAbSEcwDAYD -VR0TAQH/BAIwADAfBgNVHSMEGDAWgBS8YmAn1eM1SBfpS6tFatDIqHdxjDBqBgNV -HSAEYzBhMA4GDCsGAQQBtGgFAgICATAOBgwrBgEEAbRoBQICAQEwPwYMKwYBBAG0 -aAUCAgMBMC8wLQYIKwYBBQUHAgEWIWh0dHA6Ly93d3cucGtpLnZ0LmVkdS9nbG9i -YWwvY3BzLzBKBgNVHR8EQzBBMD+gPaA7hjlodHRwOi8vd3d3LnBraS52dC5lZHUv -Z2xvYmFscXVhbGlmaWVkc2VydmVyL2NybC9jYWNybC5jcmwwDgYDVR0PAQH/BAQD -AgTwMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjAdBgNVHREEFjAUghJz -ZWN1cmUuaWRkbC52dC5lZHUwDQYJKoZIhvcNAQEFBQADggIBAEgoYo4aUtatY3gI -OyyKp7QlIOaLbTJZywESHqy+L5EGDdJW2DJV+mcE0LDGvqa2/1Lo+AR1ntsZwfOi -Y718JwgVVaX/RCd5+QKP25c5/x72xI8hb/L1bgS0ED9b0YAhd7Qm1K1ot82+6mqX -DW6WiGeDr8Z07MQ3143qQe2rBlq+QI69DYzm2GOqAIAnUIWv7tCyLUm31b4DwmrJ -TeudVreTKUbBNB1TWRFHEPkWhjjXKZnNGRO11wHXcyBu6YekIvVZ+vmx8ePee4jJ -3GFOi7lMuWOeq57jTVL7KOKaKLVXBb6gqo5aq+Wwt8RUD5MakrCAEeQZj7DKaFmZ -oQCO0Pxrsl3InCGvxnGzT+bFVO9nJ/BAMj7hknFdm9Jr6Bg5q33Z+gnf909AD9QF -ESqUSykaHu2LVdJx2MaCH1CyKnRgMw5tEwE15EXpUjCm24m8FMOYC+rNtf18pgrz -5D8Jhh+oxK9PjcBYqXNtnioIxiMCYcV0q5d4w4BYFEh71tk7/bYB0R55CsBUVPmp -timWNOdRd57Tfpk3USaVsumWZAf9MP3wPiC7gb4d5tYEEAG5BuDT8ruFw838wU8G -1VvAVutSiYBg7k3NYO7AUqZ+Ax4klQX3aM9lgonmJ78Qt94UPtbptrfZ4/lSqEf8 -GBUwDrQNTb+gsXsDkjd5lcYxNx6l ------END CERTIFICATE-----` - -var nameConstraintsIntermediate1 = `-----BEGIN CERTIFICATE----- -MIINLjCCDBagAwIBAgIRIqpyf/YoGgvHc8HiDAxAI8owDQYJKoZIhvcNAQEFBQAw -XDELMAkGA1UEBhMCQkUxFTATBgNVBAsTDFRydXN0ZWQgUm9vdDEZMBcGA1UEChMQ -R2xvYmFsU2lnbiBudi1zYTEbMBkGA1UEAxMSVHJ1c3RlZCBSb290IENBIEcyMB4X -DTEyMTIxMzAwMDAwMFoXDTE3MTIxMzAwMDAwMFowgcsxCzAJBgNVBAYTAlVTMREw -DwYDVQQIEwhWaXJnaW5pYTETMBEGA1UEBxMKQmxhY2tzYnVyZzEjMCEGA1UECxMa -R2xvYmFsIFF1YWxpZmllZCBTZXJ2ZXIgQ0ExPDA6BgNVBAoTM1ZpcmdpbmlhIFBv -bHl0ZWNobmljIEluc3RpdHV0ZSBhbmQgU3RhdGUgVW5pdmVyc2l0eTExMC8GA1UE -AxMoVmlyZ2luaWEgVGVjaCBHbG9iYWwgUXVhbGlmaWVkIFNlcnZlciBDQTCCAiIw -DQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBALgIZhEaptBWADBqdJ45ueFGzMXa -GHnzNxoxR1fQIaaRQNdCg4cw3A4dWKMeEgYLtsp65ai3Xfw62Qaus0+KJ3RhgV+r -ihqK81NUzkls78fJlADVDI4fCTlothsrE1CTOMiy97jKHai5mVTiWxmcxpmjv7fm -5Nhc+uHgh2hIz6npryq495mD51ZrUTIaqAQN6Pw/VHfAmR524vgriTOjtp1t4lA9 -pXGWjF/vkhAKFFheOQSQ00rngo2wHgCqMla64UTN0oz70AsCYNZ3jDLx0kOP0YmM -R3Ih91VA63kLqPXA0R6yxmmhhxLZ5bcyAy1SLjr1N302MIxLM/pSy6aquEnbELhz -qyp9yGgRyGJay96QH7c4RJY6gtcoPDbldDcHI9nXngdAL4DrZkJ9OkDkJLyqG66W -ZTF5q4EIs6yMdrywz0x7QP+OXPJrjYpbeFs6tGZCFnWPFfmHCRJF8/unofYrheq+ -9J7Jx3U55S/k57NXbAM1RAJOuMTlfn9Etf9Dpoac9poI4Liav6rBoUQk3N3JWqnV -HNx/NdCyJ1/6UbKMJUZsStAVglsi6lVPo289HHOE4f7iwl3SyekizVOp01wUin3y -cnbZB/rXmZbwapSxTTSBf0EIOr9i4EGfnnhCAVA9U5uLrI5OEB69IY8PNX0071s3 -Z2a2fio5c8m3JkdrAgMBAAGjggh5MIIIdTAOBgNVHQ8BAf8EBAMCAQYwTAYDVR0g -BEUwQzBBBgkrBgEEAaAyATwwNDAyBggrBgEFBQcCARYmaHR0cHM6Ly93d3cuZ2xv -YmFsc2lnbi5jb20vcmVwb3NpdG9yeS8wEgYDVR0TAQH/BAgwBgEB/wIBADCCBtAG -A1UdHgSCBscwggbDoIIGvzASghAzZGJsYWNrc2J1cmcub3JnMBiCFmFjY2VsZXJh -dGV2aXJnaW5pYS5jb20wGIIWYWNjZWxlcmF0ZXZpcmdpbmlhLm9yZzALgglhY3Zj -cC5vcmcwCYIHYmV2Lm5ldDAJggdiZXYub3JnMAuCCWNsaWdzLm9yZzAMggpjbWl3 -ZWIub3JnMBeCFWVhc3Rlcm5icm9va3Ryb3V0Lm5ldDAXghVlYXN0ZXJuYnJvb2t0 -cm91dC5vcmcwEYIPZWNvcnJpZG9ycy5pbmZvMBOCEWVkZ2FycmVzZWFyY2gub3Jn -MBKCEGdldC1lZHVjYXRlZC5jb20wE4IRZ2V0LWVkdWNhdGVkLmluZm8wEYIPZ2V0 -ZWR1Y2F0ZWQubmV0MBKCEGdldC1lZHVjYXRlZC5uZXQwEYIPZ2V0ZWR1Y2F0ZWQu -b3JnMBKCEGdldC1lZHVjYXRlZC5vcmcwD4INaG9raWVjbHViLmNvbTAQgg5ob2tp -ZXBob3RvLmNvbTAPgg1ob2tpZXNob3AuY29tMBGCD2hva2llc3BvcnRzLmNvbTAS -ghBob2tpZXRpY2tldHMuY29tMBKCEGhvdGVscm9hbm9rZS5jb20wE4IRaHVtYW53 -aWxkbGlmZS5vcmcwF4IVaW5uYXR2aXJnaW5pYXRlY2guY29tMA+CDWlzY2hwMjAx -MS5vcmcwD4INbGFuZHJlaGFiLm9yZzAggh5uYXRpb25hbHRpcmVyZXNlYXJjaGNl -bnRlci5jb20wFYITbmV0d29ya3ZpcmdpbmlhLm5ldDAMggpwZHJjdnQuY29tMBiC -FnBldGVkeWVyaXZlcmNvdXJzZS5jb20wDYILcmFkaW9pcS5vcmcwFYITcml2ZXJj -b3Vyc2Vnb2xmLmNvbTALgglzZGltaS5vcmcwEIIOc292YW1vdGlvbi5jb20wHoIc -c3VzdGFpbmFibGUtYmlvbWF0ZXJpYWxzLmNvbTAeghxzdXN0YWluYWJsZS1iaW9t -YXRlcmlhbHMub3JnMBWCE3RoaXNpc3RoZWZ1dHVyZS5jb20wGIIWdGhpcy1pcy10 -aGUtZnV0dXJlLmNvbTAVghN0aGlzaXN0aGVmdXR1cmUubmV0MBiCFnRoaXMtaXMt -dGhlLWZ1dHVyZS5uZXQwCoIIdmFkcy5vcmcwDIIKdmFsZWFmLm9yZzANggt2YXRl -Y2guaW5mbzANggt2YXRlY2gubW9iaTAcghp2YXRlY2hsaWZlbG9uZ2xlYXJuaW5n -LmNvbTAcghp2YXRlY2hsaWZlbG9uZ2xlYXJuaW5nLm5ldDAcghp2YXRlY2hsaWZl -bG9uZ2xlYXJuaW5nLm9yZzAKggh2Y29tLmVkdTASghB2aXJnaW5pYXZpZXcubmV0 -MDSCMnZpcmdpbmlhcG9seXRlY2huaWNpbnN0aXR1dGVhbmRzdGF0ZXVuaXZlcnNp -dHkuY29tMDWCM3ZpcmdpbmlhcG9seXRlY2huaWNpbnN0aXR1dGVhbmRzdGF0ZXVu -aXZlcnNpdHkuaW5mbzA0gjJ2aXJnaW5pYXBvbHl0ZWNobmljaW5zdGl0dXRlYW5k -c3RhdGV1bml2ZXJzaXR5Lm5ldDA0gjJ2aXJnaW5pYXBvbHl0ZWNobmljaW5zdGl0 -dXRlYW5kc3RhdGV1bml2ZXJzaXR5Lm9yZzAZghd2aXJnaW5pYXB1YmxpY3JhZGlv -Lm9yZzASghB2aXJnaW5pYXRlY2guZWR1MBOCEXZpcmdpbmlhdGVjaC5tb2JpMByC -GnZpcmdpbmlhdGVjaGZvdW5kYXRpb24ub3JnMAiCBnZ0LmVkdTALggl2dGFyYy5v -cmcwDIIKdnQtYXJjLm9yZzALggl2dGNyYy5jb20wCoIIdnRpcC5vcmcwDIIKdnRs -ZWFuLm9yZzAWghR2dGtub3dsZWRnZXdvcmtzLmNvbTAYghZ2dGxpZmVsb25nbGVh -cm5pbmcuY29tMBiCFnZ0bGlmZWxvbmdsZWFybmluZy5uZXQwGIIWdnRsaWZlbG9u -Z2xlYXJuaW5nLm9yZzATghF2dHNwb3J0c21lZGlhLmNvbTALggl2dHdlaS5jb20w -D4INd2l3YXR3ZXJjLmNvbTAKggh3dnRmLm9yZzAIgQZ2dC5lZHUwd6R1MHMxCzAJ -BgNVBAYTAlVTMREwDwYDVQQIEwhWaXJnaW5pYTETMBEGA1UEBxMKQmxhY2tzYnVy -ZzE8MDoGA1UEChMzVmlyZ2luaWEgUG9seXRlY2huaWMgSW5zdGl0dXRlIGFuZCBT -dGF0ZSBVbml2ZXJzaXR5MCcGA1UdJQQgMB4GCCsGAQUFBwMCBggrBgEFBQcDAQYI -KwYBBQUHAwkwPQYDVR0fBDYwNDAyoDCgLoYsaHR0cDovL2NybC5nbG9iYWxzaWdu -LmNvbS9ncy90cnVzdHJvb3RnMi5jcmwwgYQGCCsGAQUFBwEBBHgwdjAzBggrBgEF -BQcwAYYnaHR0cDovL29jc3AyLmdsb2JhbHNpZ24uY29tL3RydXN0cm9vdGcyMD8G -CCsGAQUFBzAChjNodHRwOi8vc2VjdXJlLmdsb2JhbHNpZ24uY29tL2NhY2VydC90 -cnVzdHJvb3RnMi5jcnQwHQYDVR0OBBYEFLxiYCfV4zVIF+lLq0Vq0Miod3GMMB8G -A1UdIwQYMBaAFBT25YsxtkWASkxt/MKHico2w5BiMA0GCSqGSIb3DQEBBQUAA4IB -AQAyJm/lOB2Er4tHXhc/+fSufSzgjohJgYfMkvG4LknkvnZ1BjliefR8tTXX49d2 -SCDFWfGjqyJZwavavkl/4p3oXPG/nAMDMvxh4YAT+CfEK9HH+6ICV087kD4BLegi -+aFJMj8MMdReWCzn5sLnSR1rdse2mo2arX3Uod14SW+PGrbUmTuWNyvRbz3fVmxp -UdbGmj3laknO9YPsBGgHfv73pVVsTJkW4ZfY/7KdD/yaVv6ophpOB3coXfjl2+kd -Z4ypn2zK+cx9IL/LSewqd/7W9cD55PCUy4X9OTbEmAccwiz3LB66mQoUGfdHdkoB -jUY+v9vLQXmaVwI0AYL7g9LN ------END CERTIFICATE-----` - -var nameConstraintsIntermediate2 = `-----BEGIN CERTIFICATE----- -MIIEXTCCA0WgAwIBAgILBAAAAAABNuk6OrMwDQYJKoZIhvcNAQEFBQAwVzELMAkG -A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv -b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw0xMjA0MjUxMTAw -MDBaFw0yNzA0MjUxMTAwMDBaMFwxCzAJBgNVBAYTAkJFMRUwEwYDVQQLEwxUcnVz -dGVkIFJvb3QxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExGzAZBgNVBAMTElRy -dXN0ZWQgUm9vdCBDQSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEB -AKyuvqrtcMr7g7EuNbu4sKwxM127UsCmx1RxbxxgcArGS7rjiefpBH/w4LYrymjf -vcw1ueyMNoqLo9nJMz/ORXupb35NNfE667prQYHa+tTjl1IiKpB7QUwt3wXPuTMF -Ja1tXtjKzkqJyuJlNuPKT76HcjgNqgV1s9qG44MD5I2JvI12du8zI1bgdQ+l/KsX -kTfbGjUvhOLOlVNWVQDpL+YMIrGqgBYxy5TUNgrAcRtwpNdS2KkF5otSmMweVb5k -hoUVv3u8UxQH/WWbNhHq1RrIlg/0rBUfi/ziShYFSB7U+aLx5DxPphTFBiDquQGp -tB+FC4JvnukDStFihZCZ1R8CAwEAAaOCASMwggEfMA4GA1UdDwEB/wQEAwIBBjAP -BgNVHRMBAf8EBTADAQH/MEcGA1UdIARAMD4wPAYEVR0gADA0MDIGCCsGAQUFBwIB -FiZodHRwczovL3d3dy5nbG9iYWxzaWduLmNvbS9yZXBvc2l0b3J5LzAdBgNVHQ4E -FgQUFPblizG2RYBKTG38woeJyjbDkGIwMwYDVR0fBCwwKjAooCagJIYiaHR0cDov -L2NybC5nbG9iYWxzaWduLm5ldC9yb290LmNybDA+BggrBgEFBQcBAQQyMDAwLgYI -KwYBBQUHMAGGImh0dHA6Ly9vY3NwMi5nbG9iYWxzaWduLmNvbS9yb290cjEwHwYD -VR0jBBgwFoAUYHtmGkUNl8qJUC99BM00qP/8/UswDQYJKoZIhvcNAQEFBQADggEB -AL7IG0l+k4LkcpI+a/kvZsSRwSM4uA6zGX34e78A2oytr8RG8bJwVb8+AHMUD+Xe -2kYdh/Uj/waQXfqR0OgxQXL9Ct4ZM+JlR1avsNKXWL5AwYXAXCOB3J5PW2XOck7H -Zw0vRbGQhjWjQx+B4KOUFg1b3ov/z6Xkr3yaCfRQhXh7KC0Bc0RXPPG5Nv5lCW+z -tbbg0zMm3kyfQITRusMSg6IBsDJqOnjaiaKQRcXiD0Sk43ZXb2bUKMxC7+Td3QL4 -RyHcWJbQ7YylLTS/x+jxWIcOQ0oO5/54t5PTQ14neYhOz9x4gUk2AYAW6d1vePwb -hcC8roQwkHT7HvfYBoc74FM= ------END CERTIFICATE-----` - -var globalSignRoot = `-----BEGIN CERTIFICATE----- -MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkG -A1UEBhMCQkUxGTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jv -b3QgQ0ExGzAZBgNVBAMTEkdsb2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAw -MDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNVBAYTAkJFMRkwFwYDVQQKExBHbG9i -YWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYDVQQDExJHbG9iYWxT -aWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDaDuaZ -jc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavp -xy0Sy6scTHAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp -1Wrjsok6Vjk4bwY8iGlbKk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdG -snUOhugZitVtbNV4FpWi6cgKOOvyJBNPc1STE4U6G7weNLWLBYy5d4ux2x8gkasJ -U26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrXgzT/LCrBbBlDSgeF59N8 -9iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNVHRMBAf8E -BTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0B -AQUFAAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOz -yj1hTdNGCbM+w6DjY1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE -38NflNUVyRRBnMRddWQVDf9VMOyGj/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymP -AbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhHhm4qxFYxldBniYUr+WymXUad -DKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveCX4XSQRjbgbME -HMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A== ------END CERTIFICATE-----` - -var moipLeafCert = `-----BEGIN CERTIFICATE----- -MIIGQDCCBSigAwIBAgIRAPe/cwh7CUWizo8mYSDavLIwDQYJKoZIhvcNAQELBQAw -gZIxCzAJBgNVBAYTAkdCMRswGQYDVQQIExJHcmVhdGVyIE1hbmNoZXN0ZXIxEDAO -BgNVBAcTB1NhbGZvcmQxGjAYBgNVBAoTEUNPTU9ETyBDQSBMaW1pdGVkMTgwNgYD -VQQDEy9DT01PRE8gUlNBIEV4dGVuZGVkIFZhbGlkYXRpb24gU2VjdXJlIFNlcnZl -ciBDQTAeFw0xMzA4MTUwMDAwMDBaFw0xNDA4MTUyMzU5NTlaMIIBQjEXMBUGA1UE -BRMOMDg3MTg0MzEwMDAxMDgxEzARBgsrBgEEAYI3PAIBAxMCQlIxGjAYBgsrBgEE -AYI3PAIBAhMJU2FvIFBhdWxvMR0wGwYDVQQPExRQcml2YXRlIE9yZ2FuaXphdGlv -bjELMAkGA1UEBhMCQlIxETAPBgNVBBETCDAxNDUyMDAwMRIwEAYDVQQIEwlTYW8g -UGF1bG8xEjAQBgNVBAcTCVNhbyBQYXVsbzEtMCsGA1UECRMkQXZlbmlkYSBCcmln -YWRlaXJvIEZhcmlhIExpbWEgLCAyOTI3MR0wGwYDVQQKExRNb2lwIFBhZ2FtZW50 -b3MgUy5BLjENMAsGA1UECxMETU9JUDEYMBYGA1UECxMPU1NMIEJsaW5kYWRvIEVW -MRgwFgYDVQQDEw9hcGkubW9pcC5jb20uYnIwggEiMA0GCSqGSIb3DQEBAQUAA4IB -DwAwggEKAoIBAQDN0b9x6TrXXA9hPCF8/NjqGJ++2D4LO4ZiMFTjs0VwpXy2Y1Oe -s74/HuiLGnAHxTmAtV7IpZMibiOcTxcnDYp9oEWkf+gR+hZvwFZwyOBC7wyb3SR3 -UvV0N1ZbEVRYpN9kuX/3vjDghjDmzzBwu8a/T+y5JTym5uiJlngVAWyh/RjtIvYi -+NVkQMbyVlPGkoCe6c30pH8DKYuUCZU6DHjUsPTX3jAskqbhDSAnclX9iX0p2bmw -KVBc+5Vh/2geyzDuquF0w+mNIYdU5h7uXvlmJnf3d2Cext5dxdL8/jezD3U0dAqI -pYSKERbyxSkJWxdvRlhdpM9YXMJcpc88xNp1AgMBAAGjggHcMIIB2DAfBgNVHSME -GDAWgBQ52v/KKBSKqHQTCLnkDqnS+n6daTAdBgNVHQ4EFgQU/lXuOa7DMExzZjRj -LQWcMWGZY7swDgYDVR0PAQH/BAQDAgWgMAwGA1UdEwEB/wQCMAAwHQYDVR0lBBYw -FAYIKwYBBQUHAwEGCCsGAQUFBwMCMEYGA1UdIAQ/MD0wOwYMKwYBBAGyMQECAQUB -MCswKQYIKwYBBQUHAgEWHWh0dHBzOi8vc2VjdXJlLmNvbW9kby5jb20vQ1BTMFYG -A1UdHwRPME0wS6BJoEeGRWh0dHA6Ly9jcmwuY29tb2RvY2EuY29tL0NPTU9ET1JT -QUV4dGVuZGVkVmFsaWRhdGlvblNlY3VyZVNlcnZlckNBLmNybDCBhwYIKwYBBQUH -AQEEezB5MFEGCCsGAQUFBzAChkVodHRwOi8vY3J0LmNvbW9kb2NhLmNvbS9DT01P -RE9SU0FFeHRlbmRlZFZhbGlkYXRpb25TZWN1cmVTZXJ2ZXJDQS5jcnQwJAYIKwYB -BQUHMAGGGGh0dHA6Ly9vY3NwLmNvbW9kb2NhLmNvbTAvBgNVHREEKDAmgg9hcGku -bW9pcC5jb20uYnKCE3d3dy5hcGkubW9pcC5jb20uYnIwDQYJKoZIhvcNAQELBQAD -ggEBAFoTmPlaDcf+nudhjXHwud8g7/LRyA8ucb+3/vfmgbn7FUc1eprF5sJS1mA+ -pbiTyXw4IxcJq2KUj0Nw3IPOe9k84mzh+XMmdCKH+QK3NWkE9Udz+VpBOBc0dlqC -1RH5umStYDmuZg/8/r652eeQ5kUDcJyADfpKWBgDPYaGtwzKVT4h3Aok9SLXRHx6 -z/gOaMjEDMarMCMw4VUIG1pvNraZrG5oTaALPaIXXpd8VqbQYPudYJ6fR5eY3FeW -H/ofbYFdRcuD26MfBFWE9VGGral9Fgo8sEHffho+UWhgApuQV4/l5fMzxB5YBXyQ -jhuy8PqqZS9OuLilTeLu4a8z2JI= ------END CERTIFICATE-----` - -var comodoIntermediateSHA384 = `-----BEGIN CERTIFICATE----- -MIIGDjCCA/agAwIBAgIQBqdDgNTr/tQ1taP34Wq92DANBgkqhkiG9w0BAQwFADCB -hTELMAkGA1UEBhMCR0IxGzAZBgNVBAgTEkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4G -A1UEBxMHU2FsZm9yZDEaMBgGA1UEChMRQ09NT0RPIENBIExpbWl0ZWQxKzApBgNV -BAMTIkNPTU9ETyBSU0EgQ2VydGlmaWNhdGlvbiBBdXRob3JpdHkwHhcNMTIwMjEy -MDAwMDAwWhcNMjcwMjExMjM1OTU5WjCBkjELMAkGA1UEBhMCR0IxGzAZBgNVBAgT -EkdyZWF0ZXIgTWFuY2hlc3RlcjEQMA4GA1UEBxMHU2FsZm9yZDEaMBgGA1UEChMR -Q09NT0RPIENBIExpbWl0ZWQxODA2BgNVBAMTL0NPTU9ETyBSU0EgRXh0ZW5kZWQg -VmFsaWRhdGlvbiBTZWN1cmUgU2VydmVyIENBMIIBIjANBgkqhkiG9w0BAQEFAAOC -AQ8AMIIBCgKCAQEAlVbeVLTf1QJJe9FbXKKyHo+cK2JMK40SKPMalaPGEP0p3uGf -CzhAk9HvbpUQ/OGQF3cs7nU+e2PsYZJuTzurgElr3wDqAwB/L3XVKC/sVmePgIOj -vdwDmZOLlJFWW6G4ajo/Br0OksxgnP214J9mMF/b5pTwlWqvyIqvgNnmiDkBfBzA -xSr3e5Wg8narbZtyOTDr0VdVAZ1YEZ18bYSPSeidCfw8/QpKdhQhXBZzQCMZdMO6 -WAqmli7eNuWf0MLw4eDBYuPCGEUZUaoXHugjddTI0JYT/8ck0YwLJ66eetw6YWNg -iJctXQUL5Tvrrs46R3N2qPos3cCHF+msMJn4HwIDAQABo4IBaTCCAWUwHwYDVR0j -BBgwFoAUu69+Aj36pvE8hI6t7jiY7NkyMtQwHQYDVR0OBBYEFDna/8ooFIqodBMI -ueQOqdL6fp1pMA4GA1UdDwEB/wQEAwIBBjASBgNVHRMBAf8ECDAGAQH/AgEAMD4G -A1UdIAQ3MDUwMwYEVR0gADArMCkGCCsGAQUFBwIBFh1odHRwczovL3NlY3VyZS5j -b21vZG8uY29tL0NQUzBMBgNVHR8ERTBDMEGgP6A9hjtodHRwOi8vY3JsLmNvbW9k -b2NhLmNvbS9DT01PRE9SU0FDZXJ0aWZpY2F0aW9uQXV0aG9yaXR5LmNybDBxBggr -BgEFBQcBAQRlMGMwOwYIKwYBBQUHMAKGL2h0dHA6Ly9jcnQuY29tb2RvY2EuY29t -L0NPTU9ET1JTQUFkZFRydXN0Q0EuY3J0MCQGCCsGAQUFBzABhhhodHRwOi8vb2Nz -cC5jb21vZG9jYS5jb20wDQYJKoZIhvcNAQEMBQADggIBAERCnUFRK0iIXZebeV4R -AUpSGXtBLMeJPNBy3IX6WK/VJeQT+FhlZ58N/1eLqYVeyqZLsKeyLeCMIs37/3mk -jCuN/gI9JN6pXV/kD0fQ22YlPodHDK4ixVAihNftSlka9pOlk7DgG4HyVsTIEFPk -1Hax0VtpS3ey4E/EhOfUoFDuPPpE/NBXueEoU/1Tzdy5H3pAvTA/2GzS8+cHnx8i -teoiccsq8FZ8/qyo0QYPFBRSTP5kKwxpKrgNUG4+BAe/eiCL+O5lCeHHSQgyPQ0o -fkkdt0rvAucNgBfIXOBhYsvss2B5JdoaZXOcOBCgJjqwyBZ9kzEi7nQLiMBciUEA -KKlHMd99SUWa9eanRRrSjhMQ34Ovmw2tfn6dNVA0BM7pINae253UqNpktNEvWS5e -ojZh1CSggjMziqHRbO9haKPl0latxf1eYusVqHQSTC8xjOnB3xBLAer2VBvNfzu9 -XJ/B288ByvK6YBIhMe2pZLiySVgXbVrXzYxtvp5/4gJYp9vDLVj2dAZqmvZh+fYA -tmnYOosxWd2R5nwnI4fdAw+PKowegwFOAWEMUnNt/AiiuSpm5HZNMaBWm9lTjaK2 -jwLI5jqmBNFI+8NKAnb9L9K8E7bobTQk+p0pisehKxTxlgBzuRPpwLk6R1YCcYAn -pLwltum95OmYdBbxN4SBB7SC ------END CERTIFICATE-----` - -const comodoRSAAuthority = `-----BEGIN CERTIFICATE----- -MIIFdDCCBFygAwIBAgIQJ2buVutJ846r13Ci/ITeIjANBgkqhkiG9w0BAQwFADBv -MQswCQYDVQQGEwJTRTEUMBIGA1UEChMLQWRkVHJ1c3QgQUIxJjAkBgNVBAsTHUFk -ZFRydXN0IEV4dGVybmFsIFRUUCBOZXR3b3JrMSIwIAYDVQQDExlBZGRUcnVzdCBF -eHRlcm5hbCBDQSBSb290MB4XDTAwMDUzMDEwNDgzOFoXDTIwMDUzMDEwNDgzOFow -gYUxCzAJBgNVBAYTAkdCMRswGQYDVQQIExJHcmVhdGVyIE1hbmNoZXN0ZXIxEDAO -BgNVBAcTB1NhbGZvcmQxGjAYBgNVBAoTEUNPTU9ETyBDQSBMaW1pdGVkMSswKQYD -VQQDEyJDT01PRE8gUlNBIENlcnRpZmljYXRpb24gQXV0aG9yaXR5MIICIjANBgkq -hkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAkehUktIKVrGsDSTdxc9EZ3SZKzejfSNw -AHG8U9/E+ioSj0t/EFa9n3Byt2F/yUsPF6c947AEYe7/EZfH9IY+Cvo+XPmT5jR6 -2RRr55yzhaCCenavcZDX7P0N+pxs+t+wgvQUfvm+xKYvT3+Zf7X8Z0NyvQwA1onr -ayzT7Y+YHBSrfuXjbvzYqOSSJNpDa2K4Vf3qwbxstovzDo2a5JtsaZn4eEgwRdWt -4Q08RWD8MpZRJ7xnw8outmvqRsfHIKCxH2XeSAi6pE6p8oNGN4Tr6MyBSENnTnIq -m1y9TBsoilwie7SrmNnu4FGDwwlGTm0+mfqVF9p8M1dBPI1R7Qu2XK8sYxrfV8g/ -vOldxJuvRZnio1oktLqpVj3Pb6r/SVi+8Kj/9Lit6Tf7urj0Czr56ENCHonYhMsT -8dm74YlguIwoVqwUHZwK53Hrzw7dPamWoUi9PPevtQ0iTMARgexWO/bTouJbt7IE -IlKVgJNp6I5MZfGRAy1wdALqi2cVKWlSArvX31BqVUa/oKMoYX9w0MOiqiwhqkfO -KJwGRXa/ghgntNWutMtQ5mv0TIZxMOmm3xaG4Nj/QN370EKIf6MzOi5cHkERgWPO -GHFrK+ymircxXDpqR+DDeVnWIBqv8mqYqnK8V0rSS527EPywTEHl7R09XiidnMy/ -s1Hap0flhFMCAwEAAaOB9DCB8TAfBgNVHSMEGDAWgBStvZh6NLQm9/rEJlTvA73g -JMtUGjAdBgNVHQ4EFgQUu69+Aj36pvE8hI6t7jiY7NkyMtQwDgYDVR0PAQH/BAQD -AgGGMA8GA1UdEwEB/wQFMAMBAf8wEQYDVR0gBAowCDAGBgRVHSAAMEQGA1UdHwQ9 -MDswOaA3oDWGM2h0dHA6Ly9jcmwudXNlcnRydXN0LmNvbS9BZGRUcnVzdEV4dGVy -bmFsQ0FSb290LmNybDA1BggrBgEFBQcBAQQpMCcwJQYIKwYBBQUHMAGGGWh0dHA6 -Ly9vY3NwLnVzZXJ0cnVzdC5jb20wDQYJKoZIhvcNAQEMBQADggEBAGS/g/FfmoXQ -zbihKVcN6Fr30ek+8nYEbvFScLsePP9NDXRqzIGCJdPDoCpdTPW6i6FtxFQJdcfj -Jw5dhHk3QBN39bSsHNA7qxcS1u80GH4r6XnTq1dFDK8o+tDb5VCViLvfhVdpfZLY -Uspzgb8c8+a4bmYRBbMelC1/kZWSWfFMzqORcUx8Rww7Cxn2obFshj5cqsQugsv5 -B5a6SE2Q8pTIqXOi6wZ7I53eovNNVZ96YUWYGGjHXkBrI/V5eu+MtWuLt29G9Hvx -PUsE2JOAWVrgQSQdso8VYFhH2+9uRv0V9dlfmrPb2LjkQLPNlzmuhbsdjrzch5vR -pu/xO28QOG8= ------END CERTIFICATE-----` - -const addTrustRoot = `-----BEGIN CERTIFICATE----- -MIIENjCCAx6gAwIBAgIBATANBgkqhkiG9w0BAQUFADBvMQswCQYDVQQGEwJTRTEU -MBIGA1UEChMLQWRkVHJ1c3QgQUIxJjAkBgNVBAsTHUFkZFRydXN0IEV4dGVybmFs -IFRUUCBOZXR3b3JrMSIwIAYDVQQDExlBZGRUcnVzdCBFeHRlcm5hbCBDQSBSb290 -MB4XDTAwMDUzMDEwNDgzOFoXDTIwMDUzMDEwNDgzOFowbzELMAkGA1UEBhMCU0Ux -FDASBgNVBAoTC0FkZFRydXN0IEFCMSYwJAYDVQQLEx1BZGRUcnVzdCBFeHRlcm5h -bCBUVFAgTmV0d29yazEiMCAGA1UEAxMZQWRkVHJ1c3QgRXh0ZXJuYWwgQ0EgUm9v -dDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALf3GjPm8gAELTngTlvt -H7xsD821+iO2zt6bETOXpClMfZOfvUq8k+0DGuOPz+VtUFrWlymUWoCwSXrbLpX9 -uMq/NzgtHj6RQa1wVsfwTz/oMp50ysiQVOnGXw94nZpAPA6sYapeFI+eh6FqUNzX -mk6vBbOmcZSccbNQYArHE504B4YCqOmoaSYYkKtMsE8jqzpPhNjfzp/haW+710LX -a0Tkx63ubUFfclpxCDezeWWkWaCUN/cALw3CknLa0Dhy2xSoRcRdKn23tNbE7qzN -E0S3ySvdQwAl+mG5aWpYIxG3pzOPVnVZ9c0p10a3CitlttNCbxWyuHv77+ldU9U0 -WicCAwEAAaOB3DCB2TAdBgNVHQ4EFgQUrb2YejS0Jvf6xCZU7wO94CTLVBowCwYD -VR0PBAQDAgEGMA8GA1UdEwEB/wQFMAMBAf8wgZkGA1UdIwSBkTCBjoAUrb2YejS0 -Jvf6xCZU7wO94CTLVBqhc6RxMG8xCzAJBgNVBAYTAlNFMRQwEgYDVQQKEwtBZGRU -cnVzdCBBQjEmMCQGA1UECxMdQWRkVHJ1c3QgRXh0ZXJuYWwgVFRQIE5ldHdvcmsx -IjAgBgNVBAMTGUFkZFRydXN0IEV4dGVybmFsIENBIFJvb3SCAQEwDQYJKoZIhvcN -AQEFBQADggEBALCb4IUlwtYj4g+WBpKdQZic2YR5gdkeWxQHIzZlj7DYd7usQWxH -YINRsPkyPef89iYTx4AWpb9a/IfPeHmJIZriTAcKhjW88t5RxNKWt9x+Tu5w/Rw5 -6wwCURQtjr0W4MHfRnXnJK3s9EK0hZNwEGe6nQY1ShjTK3rMUUKhemPR5ruhxSvC -Nr4TDea9Y355e6cJDUCrat2PisP29owaQgVR1EX1n6diIWgVIEM8med8vSTYqZEX -c4g/VhsxOBi0cQ+azcgOno4uG+GMmIPLHzHxREzGBHNJdmAPx/i9F4BrLunMTA5a -mnkPIAou1Z5jJh5VkpTYghdae9C8x49OhgQ= ------END CERTIFICATE-----` diff --git a/src/pkg/crypto/x509/x509.go b/src/pkg/crypto/x509/x509.go deleted file mode 100644 index c347fb384..000000000 --- a/src/pkg/crypto/x509/x509.go +++ /dev/null @@ -1,1903 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package x509 parses X.509-encoded keys and certificates. -package x509 - -import ( - "bytes" - "crypto" - "crypto/dsa" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rsa" - "crypto/sha1" - _ "crypto/sha256" - _ "crypto/sha512" - "crypto/x509/pkix" - "encoding/asn1" - "encoding/pem" - "errors" - "io" - "math/big" - "net" - "strconv" - "time" -) - -// pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo -// in RFC 3280. -type pkixPublicKey struct { - Algo pkix.AlgorithmIdentifier - BitString asn1.BitString -} - -// ParsePKIXPublicKey parses a DER encoded public key. These values are -// typically found in PEM blocks with "BEGIN PUBLIC KEY". -func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) { - var pki publicKeyInfo - if _, err = asn1.Unmarshal(derBytes, &pki); err != nil { - return - } - algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm) - if algo == UnknownPublicKeyAlgorithm { - return nil, errors.New("x509: unknown public key algorithm") - } - return parsePublicKey(algo, &pki) -} - -func marshalPublicKey(pub interface{}) (publicKeyBytes []byte, publicKeyAlgorithm pkix.AlgorithmIdentifier, err error) { - switch pub := pub.(type) { - case *rsa.PublicKey: - publicKeyBytes, err = asn1.Marshal(rsaPublicKey{ - N: pub.N, - E: pub.E, - }) - publicKeyAlgorithm.Algorithm = oidPublicKeyRSA - // This is a NULL parameters value which is technically - // superfluous, but most other code includes it and, by - // doing this, we match their public key hashes. - publicKeyAlgorithm.Parameters = asn1.RawValue{ - Tag: 5, - } - case *ecdsa.PublicKey: - publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y) - oid, ok := oidFromNamedCurve(pub.Curve) - if !ok { - return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: unsupported elliptic curve") - } - publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA - var paramBytes []byte - paramBytes, err = asn1.Marshal(oid) - if err != nil { - return - } - publicKeyAlgorithm.Parameters.FullBytes = paramBytes - default: - return nil, pkix.AlgorithmIdentifier{}, errors.New("x509: only RSA and ECDSA public keys supported") - } - - return publicKeyBytes, publicKeyAlgorithm, nil -} - -// MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format. -func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) { - var publicKeyBytes []byte - var publicKeyAlgorithm pkix.AlgorithmIdentifier - var err error - - if publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(pub); err != nil { - return nil, err - } - - pkix := pkixPublicKey{ - Algo: publicKeyAlgorithm, - BitString: asn1.BitString{ - Bytes: publicKeyBytes, - BitLength: 8 * len(publicKeyBytes), - }, - } - - ret, _ := asn1.Marshal(pkix) - return ret, nil -} - -// These structures reflect the ASN.1 structure of X.509 certificates.: - -type certificate struct { - Raw asn1.RawContent - TBSCertificate tbsCertificate - SignatureAlgorithm pkix.AlgorithmIdentifier - SignatureValue asn1.BitString -} - -type tbsCertificate struct { - Raw asn1.RawContent - Version int `asn1:"optional,explicit,default:1,tag:0"` - SerialNumber *big.Int - SignatureAlgorithm pkix.AlgorithmIdentifier - Issuer asn1.RawValue - Validity validity - Subject asn1.RawValue - PublicKey publicKeyInfo - UniqueId asn1.BitString `asn1:"optional,tag:1"` - SubjectUniqueId asn1.BitString `asn1:"optional,tag:2"` - Extensions []pkix.Extension `asn1:"optional,explicit,tag:3"` -} - -type dsaAlgorithmParameters struct { - P, Q, G *big.Int -} - -type dsaSignature struct { - R, S *big.Int -} - -type ecdsaSignature dsaSignature - -type validity struct { - NotBefore, NotAfter time.Time -} - -type publicKeyInfo struct { - Raw asn1.RawContent - Algorithm pkix.AlgorithmIdentifier - PublicKey asn1.BitString -} - -// RFC 5280, 4.2.1.1 -type authKeyId struct { - Id []byte `asn1:"optional,tag:0"` -} - -type SignatureAlgorithm int - -const ( - UnknownSignatureAlgorithm SignatureAlgorithm = iota - MD2WithRSA - MD5WithRSA - SHA1WithRSA - SHA256WithRSA - SHA384WithRSA - SHA512WithRSA - DSAWithSHA1 - DSAWithSHA256 - ECDSAWithSHA1 - ECDSAWithSHA256 - ECDSAWithSHA384 - ECDSAWithSHA512 -) - -type PublicKeyAlgorithm int - -const ( - UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota - RSA - DSA - ECDSA -) - -// OIDs for signature algorithms -// -// pkcs-1 OBJECT IDENTIFIER ::= { -// iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 } -// -// -// RFC 3279 2.2.1 RSA Signature Algorithms -// -// md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 } -// -// md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 } -// -// sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 } -// -// dsaWithSha1 OBJECT IDENTIFIER ::= { -// iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 } -// -// RFC 3279 2.2.3 ECDSA Signature Algorithm -// -// ecdsa-with-SHA1 OBJECT IDENTIFIER ::= { -// iso(1) member-body(2) us(840) ansi-x962(10045) -// signatures(4) ecdsa-with-SHA1(1)} -// -// -// RFC 4055 5 PKCS #1 Version 1.5 -// -// sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 } -// -// sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 } -// -// sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 } -// -// -// RFC 5758 3.1 DSA Signature Algorithms -// -// dsaWithSha256 OBJECT IDENTIFIER ::= { -// joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101) -// csor(3) algorithms(4) id-dsa-with-sha2(3) 2} -// -// RFC 5758 3.2 ECDSA Signature Algorithm -// -// ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2) -// us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 } -// -// ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2) -// us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 } -// -// ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2) -// us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 } - -var ( - oidSignatureMD2WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2} - oidSignatureMD5WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4} - oidSignatureSHA1WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5} - oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11} - oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12} - oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13} - oidSignatureDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3} - oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 4, 3, 2} - oidSignatureECDSAWithSHA1 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1} - oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2} - oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3} - oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4} -) - -var signatureAlgorithmDetails = []struct { - algo SignatureAlgorithm - oid asn1.ObjectIdentifier - pubKeyAlgo PublicKeyAlgorithm - hash crypto.Hash -}{ - {MD2WithRSA, oidSignatureMD2WithRSA, RSA, crypto.Hash(0) /* no value for MD2 */}, - {MD5WithRSA, oidSignatureMD5WithRSA, RSA, crypto.MD5}, - {SHA1WithRSA, oidSignatureSHA1WithRSA, RSA, crypto.SHA1}, - {SHA256WithRSA, oidSignatureSHA256WithRSA, RSA, crypto.SHA256}, - {SHA384WithRSA, oidSignatureSHA384WithRSA, RSA, crypto.SHA384}, - {SHA512WithRSA, oidSignatureSHA512WithRSA, RSA, crypto.SHA512}, - {DSAWithSHA1, oidSignatureDSAWithSHA1, DSA, crypto.SHA1}, - {DSAWithSHA256, oidSignatureDSAWithSHA256, DSA, crypto.SHA256}, - {ECDSAWithSHA1, oidSignatureECDSAWithSHA1, ECDSA, crypto.SHA1}, - {ECDSAWithSHA256, oidSignatureECDSAWithSHA256, ECDSA, crypto.SHA256}, - {ECDSAWithSHA384, oidSignatureECDSAWithSHA384, ECDSA, crypto.SHA384}, - {ECDSAWithSHA512, oidSignatureECDSAWithSHA512, ECDSA, crypto.SHA512}, -} - -func getSignatureAlgorithmFromOID(oid asn1.ObjectIdentifier) SignatureAlgorithm { - for _, details := range signatureAlgorithmDetails { - if oid.Equal(details.oid) { - return details.algo - } - } - return UnknownSignatureAlgorithm -} - -// RFC 3279, 2.3 Public Key Algorithms -// -// pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840) -// rsadsi(113549) pkcs(1) 1 } -// -// rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 } -// -// id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840) -// x9-57(10040) x9cm(4) 1 } -// -// RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters -// -// id-ecPublicKey OBJECT IDENTIFIER ::= { -// iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 } -var ( - oidPublicKeyRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1} - oidPublicKeyDSA = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1} - oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1} -) - -func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm { - switch { - case oid.Equal(oidPublicKeyRSA): - return RSA - case oid.Equal(oidPublicKeyDSA): - return DSA - case oid.Equal(oidPublicKeyECDSA): - return ECDSA - } - return UnknownPublicKeyAlgorithm -} - -// RFC 5480, 2.1.1.1. Named Curve -// -// secp224r1 OBJECT IDENTIFIER ::= { -// iso(1) identified-organization(3) certicom(132) curve(0) 33 } -// -// secp256r1 OBJECT IDENTIFIER ::= { -// iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) -// prime(1) 7 } -// -// secp384r1 OBJECT IDENTIFIER ::= { -// iso(1) identified-organization(3) certicom(132) curve(0) 34 } -// -// secp521r1 OBJECT IDENTIFIER ::= { -// iso(1) identified-organization(3) certicom(132) curve(0) 35 } -// -// NB: secp256r1 is equivalent to prime256v1 -var ( - oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33} - oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7} - oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34} - oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35} -) - -func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve { - switch { - case oid.Equal(oidNamedCurveP224): - return elliptic.P224() - case oid.Equal(oidNamedCurveP256): - return elliptic.P256() - case oid.Equal(oidNamedCurveP384): - return elliptic.P384() - case oid.Equal(oidNamedCurveP521): - return elliptic.P521() - } - return nil -} - -func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) { - switch curve { - case elliptic.P224(): - return oidNamedCurveP224, true - case elliptic.P256(): - return oidNamedCurveP256, true - case elliptic.P384(): - return oidNamedCurveP384, true - case elliptic.P521(): - return oidNamedCurveP521, true - } - - return nil, false -} - -// KeyUsage represents the set of actions that are valid for a given key. It's -// a bitmap of the KeyUsage* constants. -type KeyUsage int - -const ( - KeyUsageDigitalSignature KeyUsage = 1 << iota - KeyUsageContentCommitment - KeyUsageKeyEncipherment - KeyUsageDataEncipherment - KeyUsageKeyAgreement - KeyUsageCertSign - KeyUsageCRLSign - KeyUsageEncipherOnly - KeyUsageDecipherOnly -) - -// RFC 5280, 4.2.1.12 Extended Key Usage -// -// anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 } -// -// id-kp OBJECT IDENTIFIER ::= { id-pkix 3 } -// -// id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 } -// id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 } -// id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 } -// id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 } -// id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 } -// id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 } -var ( - oidExtKeyUsageAny = asn1.ObjectIdentifier{2, 5, 29, 37, 0} - oidExtKeyUsageServerAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1} - oidExtKeyUsageClientAuth = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2} - oidExtKeyUsageCodeSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3} - oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4} - oidExtKeyUsageIPSECEndSystem = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5} - oidExtKeyUsageIPSECTunnel = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6} - oidExtKeyUsageIPSECUser = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7} - oidExtKeyUsageTimeStamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8} - oidExtKeyUsageOCSPSigning = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9} - oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3} - oidExtKeyUsageNetscapeServerGatedCrypto = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1} -) - -// ExtKeyUsage represents an extended set of actions that are valid for a given key. -// Each of the ExtKeyUsage* constants define a unique action. -type ExtKeyUsage int - -const ( - ExtKeyUsageAny ExtKeyUsage = iota - ExtKeyUsageServerAuth - ExtKeyUsageClientAuth - ExtKeyUsageCodeSigning - ExtKeyUsageEmailProtection - ExtKeyUsageIPSECEndSystem - ExtKeyUsageIPSECTunnel - ExtKeyUsageIPSECUser - ExtKeyUsageTimeStamping - ExtKeyUsageOCSPSigning - ExtKeyUsageMicrosoftServerGatedCrypto - ExtKeyUsageNetscapeServerGatedCrypto -) - -// extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID. -var extKeyUsageOIDs = []struct { - extKeyUsage ExtKeyUsage - oid asn1.ObjectIdentifier -}{ - {ExtKeyUsageAny, oidExtKeyUsageAny}, - {ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth}, - {ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth}, - {ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning}, - {ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection}, - {ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem}, - {ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel}, - {ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser}, - {ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping}, - {ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning}, - {ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto}, - {ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto}, -} - -func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) { - for _, pair := range extKeyUsageOIDs { - if oid.Equal(pair.oid) { - return pair.extKeyUsage, true - } - } - return -} - -func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) { - for _, pair := range extKeyUsageOIDs { - if eku == pair.extKeyUsage { - return pair.oid, true - } - } - return -} - -// A Certificate represents an X.509 certificate. -type Certificate struct { - Raw []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature). - RawTBSCertificate []byte // Certificate part of raw ASN.1 DER content. - RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo. - RawSubject []byte // DER encoded Subject - RawIssuer []byte // DER encoded Issuer - - Signature []byte - SignatureAlgorithm SignatureAlgorithm - - PublicKeyAlgorithm PublicKeyAlgorithm - PublicKey interface{} - - Version int - SerialNumber *big.Int - Issuer pkix.Name - Subject pkix.Name - NotBefore, NotAfter time.Time // Validity bounds. - KeyUsage KeyUsage - - // Extensions contains raw X.509 extensions. When parsing certificates, - // this can be used to extract non-critical extensions that are not - // parsed by this package. When marshaling certificates, the Extensions - // field is ignored, see ExtraExtensions. - Extensions []pkix.Extension - - // ExtraExtensions contains extensions to be copied, raw, into any - // marshaled certificates. Values override any extensions that would - // otherwise be produced based on the other fields. The ExtraExtensions - // field is not populated when parsing certificates, see Extensions. - ExtraExtensions []pkix.Extension - - ExtKeyUsage []ExtKeyUsage // Sequence of extended key usages. - UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package. - - BasicConstraintsValid bool // if true then the next two fields are valid. - IsCA bool - MaxPathLen int - - SubjectKeyId []byte - AuthorityKeyId []byte - - // RFC 5280, 4.2.2.1 (Authority Information Access) - OCSPServer []string - IssuingCertificateURL []string - - // Subject Alternate Name values - DNSNames []string - EmailAddresses []string - IPAddresses []net.IP - - // Name constraints - PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical. - PermittedDNSDomains []string - - // CRL Distribution Points - CRLDistributionPoints []string - - PolicyIdentifiers []asn1.ObjectIdentifier -} - -// ErrUnsupportedAlgorithm results from attempting to perform an operation that -// involves algorithms that are not currently implemented. -var ErrUnsupportedAlgorithm = errors.New("x509: cannot verify signature: algorithm unimplemented") - -// ConstraintViolationError results when a requested usage is not permitted by -// a certificate. For example: checking a signature when the public key isn't a -// certificate signing key. -type ConstraintViolationError struct{} - -func (ConstraintViolationError) Error() string { - return "x509: invalid signature: parent certificate cannot sign this kind of certificate" -} - -func (c *Certificate) Equal(other *Certificate) bool { - return bytes.Equal(c.Raw, other.Raw) -} - -// Entrust have a broken root certificate (CN=Entrust.net Certification -// Authority (2048)) which isn't marked as a CA certificate and is thus invalid -// according to PKIX. -// We recognise this certificate by its SubjectPublicKeyInfo and exempt it -// from the Basic Constraints requirement. -// See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869 -// -// TODO(agl): remove this hack once their reissued root is sufficiently -// widespread. -var entrustBrokenSPKI = []byte{ - 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, - 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, - 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, - 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01, - 0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05, - 0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3, - 0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff, - 0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10, - 0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff, - 0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50, - 0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8, - 0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6, - 0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04, - 0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c, - 0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65, - 0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38, - 0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda, - 0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9, - 0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7, - 0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37, - 0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde, - 0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6, - 0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c, - 0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a, - 0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5, - 0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2, - 0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc, - 0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4, - 0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b, - 0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e, - 0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48, - 0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05, - 0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09, - 0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2, - 0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d, - 0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68, - 0x55, 0x02, 0x03, 0x01, 0x00, 0x01, -} - -// CheckSignatureFrom verifies that the signature on c is a valid signature -// from parent. -func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err error) { - // RFC 5280, 4.2.1.9: - // "If the basic constraints extension is not present in a version 3 - // certificate, or the extension is present but the cA boolean is not - // asserted, then the certified public key MUST NOT be used to verify - // certificate signatures." - // (except for Entrust, see comment above entrustBrokenSPKI) - if (parent.Version == 3 && !parent.BasicConstraintsValid || - parent.BasicConstraintsValid && !parent.IsCA) && - !bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) { - return ConstraintViolationError{} - } - - if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 { - return ConstraintViolationError{} - } - - if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm { - return ErrUnsupportedAlgorithm - } - - // TODO(agl): don't ignore the path length constraint. - - return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature) -} - -// CheckSignature verifies that signature is a valid signature over signed from -// c's public key. -func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) (err error) { - var hashType crypto.Hash - - switch algo { - case SHA1WithRSA, DSAWithSHA1, ECDSAWithSHA1: - hashType = crypto.SHA1 - case SHA256WithRSA, DSAWithSHA256, ECDSAWithSHA256: - hashType = crypto.SHA256 - case SHA384WithRSA, ECDSAWithSHA384: - hashType = crypto.SHA384 - case SHA512WithRSA, ECDSAWithSHA512: - hashType = crypto.SHA512 - default: - return ErrUnsupportedAlgorithm - } - - if !hashType.Available() { - return ErrUnsupportedAlgorithm - } - h := hashType.New() - - h.Write(signed) - digest := h.Sum(nil) - - switch pub := c.PublicKey.(type) { - case *rsa.PublicKey: - return rsa.VerifyPKCS1v15(pub, hashType, digest, signature) - case *dsa.PublicKey: - dsaSig := new(dsaSignature) - if _, err := asn1.Unmarshal(signature, dsaSig); err != nil { - return err - } - if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 { - return errors.New("x509: DSA signature contained zero or negative values") - } - if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) { - return errors.New("x509: DSA verification failure") - } - return - case *ecdsa.PublicKey: - ecdsaSig := new(ecdsaSignature) - if _, err := asn1.Unmarshal(signature, ecdsaSig); err != nil { - return err - } - if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 { - return errors.New("x509: ECDSA signature contained zero or negative values") - } - if !ecdsa.Verify(pub, digest, ecdsaSig.R, ecdsaSig.S) { - return errors.New("x509: ECDSA verification failure") - } - return - } - return ErrUnsupportedAlgorithm -} - -// CheckCRLSignature checks that the signature in crl is from c. -func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) (err error) { - algo := getSignatureAlgorithmFromOID(crl.SignatureAlgorithm.Algorithm) - return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign()) -} - -type UnhandledCriticalExtension struct{} - -func (h UnhandledCriticalExtension) Error() string { - return "x509: unhandled critical extension" -} - -type basicConstraints struct { - IsCA bool `asn1:"optional"` - MaxPathLen int `asn1:"optional,default:-1"` -} - -// RFC 5280 4.2.1.4 -type policyInformation struct { - Policy asn1.ObjectIdentifier - // policyQualifiers omitted -} - -// RFC 5280, 4.2.1.10 -type nameConstraints struct { - Permitted []generalSubtree `asn1:"optional,tag:0"` - Excluded []generalSubtree `asn1:"optional,tag:1"` -} - -type generalSubtree struct { - Name string `asn1:"tag:2,optional,ia5"` -} - -// RFC 5280, 4.2.2.1 -type authorityInfoAccess struct { - Method asn1.ObjectIdentifier - Location asn1.RawValue -} - -// RFC 5280, 4.2.1.14 -type distributionPoint struct { - DistributionPoint distributionPointName `asn1:"optional,tag:0"` - Reason asn1.BitString `asn1:"optional,tag:1"` - CRLIssuer asn1.RawValue `asn1:"optional,tag:2"` -} - -type distributionPointName struct { - FullName asn1.RawValue `asn1:"optional,tag:0"` - RelativeName pkix.RDNSequence `asn1:"optional,tag:1"` -} - -func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) { - asn1Data := keyData.PublicKey.RightAlign() - switch algo { - case RSA: - p := new(rsaPublicKey) - _, err := asn1.Unmarshal(asn1Data, p) - if err != nil { - return nil, err - } - - if p.N.Sign() <= 0 { - return nil, errors.New("x509: RSA modulus is not a positive number") - } - if p.E <= 0 { - return nil, errors.New("x509: RSA public exponent is not a positive number") - } - - pub := &rsa.PublicKey{ - E: p.E, - N: p.N, - } - return pub, nil - case DSA: - var p *big.Int - _, err := asn1.Unmarshal(asn1Data, &p) - if err != nil { - return nil, err - } - paramsData := keyData.Algorithm.Parameters.FullBytes - params := new(dsaAlgorithmParameters) - _, err = asn1.Unmarshal(paramsData, params) - if err != nil { - return nil, err - } - if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 { - return nil, errors.New("x509: zero or negative DSA parameter") - } - pub := &dsa.PublicKey{ - Parameters: dsa.Parameters{ - P: params.P, - Q: params.Q, - G: params.G, - }, - Y: p, - } - return pub, nil - case ECDSA: - paramsData := keyData.Algorithm.Parameters.FullBytes - namedCurveOID := new(asn1.ObjectIdentifier) - _, err := asn1.Unmarshal(paramsData, namedCurveOID) - if err != nil { - return nil, err - } - namedCurve := namedCurveFromOID(*namedCurveOID) - if namedCurve == nil { - return nil, errors.New("x509: unsupported elliptic curve") - } - x, y := elliptic.Unmarshal(namedCurve, asn1Data) - if x == nil { - return nil, errors.New("x509: failed to unmarshal elliptic curve point") - } - pub := &ecdsa.PublicKey{ - Curve: namedCurve, - X: x, - Y: y, - } - return pub, nil - default: - return nil, nil - } -} - -func parseSANExtension(value []byte) (dnsNames, emailAddresses []string, ipAddresses []net.IP, err error) { - // RFC 5280, 4.2.1.6 - - // SubjectAltName ::= GeneralNames - // - // GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName - // - // GeneralName ::= CHOICE { - // otherName [0] OtherName, - // rfc822Name [1] IA5String, - // dNSName [2] IA5String, - // x400Address [3] ORAddress, - // directoryName [4] Name, - // ediPartyName [5] EDIPartyName, - // uniformResourceIdentifier [6] IA5String, - // iPAddress [7] OCTET STRING, - // registeredID [8] OBJECT IDENTIFIER } - var seq asn1.RawValue - if _, err = asn1.Unmarshal(value, &seq); err != nil { - return - } - if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 { - err = asn1.StructuralError{Msg: "bad SAN sequence"} - return - } - - rest := seq.Bytes - for len(rest) > 0 { - var v asn1.RawValue - rest, err = asn1.Unmarshal(rest, &v) - if err != nil { - return - } - switch v.Tag { - case 1: - emailAddresses = append(emailAddresses, string(v.Bytes)) - case 2: - dnsNames = append(dnsNames, string(v.Bytes)) - case 7: - switch len(v.Bytes) { - case net.IPv4len, net.IPv6len: - ipAddresses = append(ipAddresses, v.Bytes) - default: - err = errors.New("x509: certificate contained IP address of length " + strconv.Itoa(len(v.Bytes))) - return - } - } - } - - return -} - -func parseCertificate(in *certificate) (*Certificate, error) { - out := new(Certificate) - out.Raw = in.Raw - out.RawTBSCertificate = in.TBSCertificate.Raw - out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw - out.RawSubject = in.TBSCertificate.Subject.FullBytes - out.RawIssuer = in.TBSCertificate.Issuer.FullBytes - - out.Signature = in.SignatureValue.RightAlign() - out.SignatureAlgorithm = - getSignatureAlgorithmFromOID(in.TBSCertificate.SignatureAlgorithm.Algorithm) - - out.PublicKeyAlgorithm = - getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm) - var err error - out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey) - if err != nil { - return nil, err - } - - if in.TBSCertificate.SerialNumber.Sign() < 0 { - return nil, errors.New("x509: negative serial number") - } - - out.Version = in.TBSCertificate.Version + 1 - out.SerialNumber = in.TBSCertificate.SerialNumber - - var issuer, subject pkix.RDNSequence - if _, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil { - return nil, err - } - if _, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil { - return nil, err - } - - out.Issuer.FillFromRDNSequence(&issuer) - out.Subject.FillFromRDNSequence(&subject) - - out.NotBefore = in.TBSCertificate.Validity.NotBefore - out.NotAfter = in.TBSCertificate.Validity.NotAfter - - for _, e := range in.TBSCertificate.Extensions { - out.Extensions = append(out.Extensions, e) - - if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 { - switch e.Id[3] { - case 15: - // RFC 5280, 4.2.1.3 - var usageBits asn1.BitString - _, err := asn1.Unmarshal(e.Value, &usageBits) - - if err == nil { - var usage int - for i := 0; i < 9; i++ { - if usageBits.At(i) != 0 { - usage |= 1 << uint(i) - } - } - out.KeyUsage = KeyUsage(usage) - continue - } - case 19: - // RFC 5280, 4.2.1.9 - var constraints basicConstraints - _, err := asn1.Unmarshal(e.Value, &constraints) - - if err == nil { - out.BasicConstraintsValid = true - out.IsCA = constraints.IsCA - out.MaxPathLen = constraints.MaxPathLen - continue - } - case 17: - out.DNSNames, out.EmailAddresses, out.IPAddresses, err = parseSANExtension(e.Value) - if err != nil { - return nil, err - } - - if len(out.DNSNames) > 0 || len(out.EmailAddresses) > 0 || len(out.IPAddresses) > 0 { - continue - } - // If we didn't parse any of the names then we - // fall through to the critical check below. - - case 30: - // RFC 5280, 4.2.1.10 - - // NameConstraints ::= SEQUENCE { - // permittedSubtrees [0] GeneralSubtrees OPTIONAL, - // excludedSubtrees [1] GeneralSubtrees OPTIONAL } - // - // GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree - // - // GeneralSubtree ::= SEQUENCE { - // base GeneralName, - // minimum [0] BaseDistance DEFAULT 0, - // maximum [1] BaseDistance OPTIONAL } - // - // BaseDistance ::= INTEGER (0..MAX) - - var constraints nameConstraints - _, err := asn1.Unmarshal(e.Value, &constraints) - if err != nil { - return nil, err - } - - if len(constraints.Excluded) > 0 && e.Critical { - return out, UnhandledCriticalExtension{} - } - - for _, subtree := range constraints.Permitted { - if len(subtree.Name) == 0 { - if e.Critical { - return out, UnhandledCriticalExtension{} - } - continue - } - out.PermittedDNSDomains = append(out.PermittedDNSDomains, subtree.Name) - } - continue - - case 31: - // RFC 5280, 4.2.1.14 - - // CRLDistributionPoints ::= SEQUENCE SIZE (1..MAX) OF DistributionPoint - // - // DistributionPoint ::= SEQUENCE { - // distributionPoint [0] DistributionPointName OPTIONAL, - // reasons [1] ReasonFlags OPTIONAL, - // cRLIssuer [2] GeneralNames OPTIONAL } - // - // DistributionPointName ::= CHOICE { - // fullName [0] GeneralNames, - // nameRelativeToCRLIssuer [1] RelativeDistinguishedName } - - var cdp []distributionPoint - _, err := asn1.Unmarshal(e.Value, &cdp) - if err != nil { - return nil, err - } - - for _, dp := range cdp { - var n asn1.RawValue - _, err = asn1.Unmarshal(dp.DistributionPoint.FullName.Bytes, &n) - if err != nil { - return nil, err - } - - if n.Tag == 6 { - out.CRLDistributionPoints = append(out.CRLDistributionPoints, string(n.Bytes)) - } - } - continue - - case 35: - // RFC 5280, 4.2.1.1 - var a authKeyId - _, err = asn1.Unmarshal(e.Value, &a) - if err != nil { - return nil, err - } - out.AuthorityKeyId = a.Id - continue - - case 37: - // RFC 5280, 4.2.1.12. Extended Key Usage - - // id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 } - // - // ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId - // - // KeyPurposeId ::= OBJECT IDENTIFIER - - var keyUsage []asn1.ObjectIdentifier - _, err = asn1.Unmarshal(e.Value, &keyUsage) - if err != nil { - return nil, err - } - - for _, u := range keyUsage { - if extKeyUsage, ok := extKeyUsageFromOID(u); ok { - out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage) - } else { - out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u) - } - } - - continue - - case 14: - // RFC 5280, 4.2.1.2 - var keyid []byte - _, err = asn1.Unmarshal(e.Value, &keyid) - if err != nil { - return nil, err - } - out.SubjectKeyId = keyid - continue - - case 32: - // RFC 5280 4.2.1.4: Certificate Policies - var policies []policyInformation - if _, err = asn1.Unmarshal(e.Value, &policies); err != nil { - return nil, err - } - out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies)) - for i, policy := range policies { - out.PolicyIdentifiers[i] = policy.Policy - } - } - } else if e.Id.Equal(oidExtensionAuthorityInfoAccess) { - // RFC 5280 4.2.2.1: Authority Information Access - var aia []authorityInfoAccess - if _, err = asn1.Unmarshal(e.Value, &aia); err != nil { - return nil, err - } - - for _, v := range aia { - // GeneralName: uniformResourceIdentifier [6] IA5String - if v.Location.Tag != 6 { - continue - } - if v.Method.Equal(oidAuthorityInfoAccessOcsp) { - out.OCSPServer = append(out.OCSPServer, string(v.Location.Bytes)) - } else if v.Method.Equal(oidAuthorityInfoAccessIssuers) { - out.IssuingCertificateURL = append(out.IssuingCertificateURL, string(v.Location.Bytes)) - } - } - } - - if e.Critical { - return out, UnhandledCriticalExtension{} - } - } - - return out, nil -} - -// ParseCertificate parses a single certificate from the given ASN.1 DER data. -func ParseCertificate(asn1Data []byte) (*Certificate, error) { - var cert certificate - rest, err := asn1.Unmarshal(asn1Data, &cert) - if err != nil { - return nil, err - } - if len(rest) > 0 { - return nil, asn1.SyntaxError{Msg: "trailing data"} - } - - return parseCertificate(&cert) -} - -// ParseCertificates parses one or more certificates from the given ASN.1 DER -// data. The certificates must be concatenated with no intermediate padding. -func ParseCertificates(asn1Data []byte) ([]*Certificate, error) { - var v []*certificate - - for len(asn1Data) > 0 { - cert := new(certificate) - var err error - asn1Data, err = asn1.Unmarshal(asn1Data, cert) - if err != nil { - return nil, err - } - v = append(v, cert) - } - - ret := make([]*Certificate, len(v)) - for i, ci := range v { - cert, err := parseCertificate(ci) - if err != nil { - return nil, err - } - ret[i] = cert - } - - return ret, nil -} - -func reverseBitsInAByte(in byte) byte { - b1 := in>>4 | in<<4 - b2 := b1>>2&0x33 | b1<<2&0xcc - b3 := b2>>1&0x55 | b2<<1&0xaa - return b3 -} - -var ( - oidExtensionSubjectKeyId = []int{2, 5, 29, 14} - oidExtensionKeyUsage = []int{2, 5, 29, 15} - oidExtensionExtendedKeyUsage = []int{2, 5, 29, 37} - oidExtensionAuthorityKeyId = []int{2, 5, 29, 35} - oidExtensionBasicConstraints = []int{2, 5, 29, 19} - oidExtensionSubjectAltName = []int{2, 5, 29, 17} - oidExtensionCertificatePolicies = []int{2, 5, 29, 32} - oidExtensionNameConstraints = []int{2, 5, 29, 30} - oidExtensionCRLDistributionPoints = []int{2, 5, 29, 31} - oidExtensionAuthorityInfoAccess = []int{1, 3, 6, 1, 5, 5, 7, 1, 1} -) - -var ( - oidAuthorityInfoAccessOcsp = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 1} - oidAuthorityInfoAccessIssuers = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 48, 2} -) - -// oidNotInExtensions returns whether an extension with the given oid exists in -// extensions. -func oidInExtensions(oid asn1.ObjectIdentifier, extensions []pkix.Extension) bool { - for _, e := range extensions { - if e.Id.Equal(oid) { - return true - } - } - return false -} - -// marshalSANs marshals a list of addresses into a the contents of an X.509 -// SubjectAlternativeName extension. -func marshalSANs(dnsNames, emailAddresses []string, ipAddresses []net.IP) (derBytes []byte, err error) { - var rawValues []asn1.RawValue - for _, name := range dnsNames { - rawValues = append(rawValues, asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)}) - } - for _, email := range emailAddresses { - rawValues = append(rawValues, asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(email)}) - } - for _, rawIP := range ipAddresses { - // If possible, we always want to encode IPv4 addresses in 4 bytes. - ip := rawIP.To4() - if ip == nil { - ip = rawIP - } - rawValues = append(rawValues, asn1.RawValue{Tag: 7, Class: 2, Bytes: ip}) - } - return asn1.Marshal(rawValues) -} - -func buildExtensions(template *Certificate) (ret []pkix.Extension, err error) { - ret = make([]pkix.Extension, 10 /* maximum number of elements. */) - n := 0 - - if template.KeyUsage != 0 && - !oidInExtensions(oidExtensionKeyUsage, template.ExtraExtensions) { - ret[n].Id = oidExtensionKeyUsage - ret[n].Critical = true - - var a [2]byte - a[0] = reverseBitsInAByte(byte(template.KeyUsage)) - a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8)) - - l := 1 - if a[1] != 0 { - l = 2 - } - - ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: a[0:l], BitLength: l * 8}) - if err != nil { - return - } - n++ - } - - if (len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0) && - !oidInExtensions(oidExtensionExtendedKeyUsage, template.ExtraExtensions) { - ret[n].Id = oidExtensionExtendedKeyUsage - - var oids []asn1.ObjectIdentifier - for _, u := range template.ExtKeyUsage { - if oid, ok := oidFromExtKeyUsage(u); ok { - oids = append(oids, oid) - } else { - panic("internal error") - } - } - - oids = append(oids, template.UnknownExtKeyUsage...) - - ret[n].Value, err = asn1.Marshal(oids) - if err != nil { - return - } - n++ - } - - if template.BasicConstraintsValid && !oidInExtensions(oidExtensionBasicConstraints, template.ExtraExtensions) { - ret[n].Id = oidExtensionBasicConstraints - ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, template.MaxPathLen}) - ret[n].Critical = true - if err != nil { - return - } - n++ - } - - if len(template.SubjectKeyId) > 0 && !oidInExtensions(oidExtensionSubjectKeyId, template.ExtraExtensions) { - ret[n].Id = oidExtensionSubjectKeyId - ret[n].Value, err = asn1.Marshal(template.SubjectKeyId) - if err != nil { - return - } - n++ - } - - if len(template.AuthorityKeyId) > 0 && !oidInExtensions(oidExtensionAuthorityKeyId, template.ExtraExtensions) { - ret[n].Id = oidExtensionAuthorityKeyId - ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId}) - if err != nil { - return - } - n++ - } - - if (len(template.OCSPServer) > 0 || len(template.IssuingCertificateURL) > 0) && - !oidInExtensions(oidExtensionAuthorityInfoAccess, template.ExtraExtensions) { - ret[n].Id = oidExtensionAuthorityInfoAccess - var aiaValues []authorityInfoAccess - for _, name := range template.OCSPServer { - aiaValues = append(aiaValues, authorityInfoAccess{ - Method: oidAuthorityInfoAccessOcsp, - Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)}, - }) - } - for _, name := range template.IssuingCertificateURL { - aiaValues = append(aiaValues, authorityInfoAccess{ - Method: oidAuthorityInfoAccessIssuers, - Location: asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)}, - }) - } - ret[n].Value, err = asn1.Marshal(aiaValues) - if err != nil { - return - } - n++ - } - - if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) && - !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) { - ret[n].Id = oidExtensionSubjectAltName - ret[n].Value, err = marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses) - if err != nil { - return - } - n++ - } - - if len(template.PolicyIdentifiers) > 0 && - !oidInExtensions(oidExtensionCertificatePolicies, template.ExtraExtensions) { - ret[n].Id = oidExtensionCertificatePolicies - policies := make([]policyInformation, len(template.PolicyIdentifiers)) - for i, policy := range template.PolicyIdentifiers { - policies[i].Policy = policy - } - ret[n].Value, err = asn1.Marshal(policies) - if err != nil { - return - } - n++ - } - - if len(template.PermittedDNSDomains) > 0 && - !oidInExtensions(oidExtensionNameConstraints, template.ExtraExtensions) { - ret[n].Id = oidExtensionNameConstraints - ret[n].Critical = template.PermittedDNSDomainsCritical - - var out nameConstraints - out.Permitted = make([]generalSubtree, len(template.PermittedDNSDomains)) - for i, permitted := range template.PermittedDNSDomains { - out.Permitted[i] = generalSubtree{Name: permitted} - } - ret[n].Value, err = asn1.Marshal(out) - if err != nil { - return - } - n++ - } - - if len(template.CRLDistributionPoints) > 0 && - !oidInExtensions(oidExtensionCRLDistributionPoints, template.ExtraExtensions) { - ret[n].Id = oidExtensionCRLDistributionPoints - - var crlDp []distributionPoint - for _, name := range template.CRLDistributionPoints { - rawFullName, _ := asn1.Marshal(asn1.RawValue{Tag: 6, Class: 2, Bytes: []byte(name)}) - - dp := distributionPoint{ - DistributionPoint: distributionPointName{ - FullName: asn1.RawValue{Tag: 0, Class: 2, Bytes: rawFullName}, - }, - } - crlDp = append(crlDp, dp) - } - - ret[n].Value, err = asn1.Marshal(crlDp) - if err != nil { - return - } - n++ - } - - // Adding another extension here? Remember to update the maximum number - // of elements in the make() at the top of the function. - - return append(ret[:n], template.ExtraExtensions...), nil -} - -func subjectBytes(cert *Certificate) ([]byte, error) { - if len(cert.RawSubject) > 0 { - return cert.RawSubject, nil - } - - return asn1.Marshal(cert.Subject.ToRDNSequence()) -} - -// signingParamsForPrivateKey returns the parameters to use for signing with -// priv. If requestedSigAlgo is not zero then it overrides the default -// signature algorithm. -func signingParamsForPrivateKey(priv interface{}, requestedSigAlgo SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) { - var pubType PublicKeyAlgorithm - - switch priv := priv.(type) { - case *rsa.PrivateKey: - pubType = RSA - sigAlgo.Algorithm = oidSignatureSHA256WithRSA - hashFunc = crypto.SHA256 - - case *ecdsa.PrivateKey: - pubType = ECDSA - - switch priv.Curve { - case elliptic.P224(), elliptic.P256(): - hashFunc = crypto.SHA256 - sigAlgo.Algorithm = oidSignatureECDSAWithSHA256 - case elliptic.P384(): - hashFunc = crypto.SHA384 - sigAlgo.Algorithm = oidSignatureECDSAWithSHA384 - case elliptic.P521(): - hashFunc = crypto.SHA512 - sigAlgo.Algorithm = oidSignatureECDSAWithSHA512 - default: - err = errors.New("x509: unknown elliptic curve") - } - - default: - err = errors.New("x509: only RSA and ECDSA private keys supported") - } - - if err != nil { - return - } - - if requestedSigAlgo == 0 { - return - } - - found := false - for _, details := range signatureAlgorithmDetails { - if details.algo == requestedSigAlgo { - if details.pubKeyAlgo != pubType { - err = errors.New("x509: requested SignatureAlgorithm does not match private key type") - return - } - sigAlgo.Algorithm, hashFunc = details.oid, details.hash - if hashFunc == 0 { - err = errors.New("x509: cannot sign with hash function requested") - return - } - found = true - break - } - } - - if !found { - err = errors.New("x509: unknown SignatureAlgorithm") - } - - return -} - -// CreateCertificate creates a new certificate based on a template. The -// following members of template are used: SerialNumber, Subject, NotBefore, -// NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid, -// IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical, -// PermittedDNSDomains, SignatureAlgorithm. -// -// The certificate is signed by parent. If parent is equal to template then the -// certificate is self-signed. The parameter pub is the public key of the -// signee and priv is the private key of the signer. -// -// The returned slice is the certificate in DER encoding. -// -// The only supported key types are RSA and ECDSA (*rsa.PublicKey or -// *ecdsa.PublicKey for pub, *rsa.PrivateKey or *ecdsa.PrivateKey for priv). -func CreateCertificate(rand io.Reader, template, parent *Certificate, pub interface{}, priv interface{}) (cert []byte, err error) { - hashFunc, signatureAlgorithm, err := signingParamsForPrivateKey(priv, template.SignatureAlgorithm) - if err != nil { - return nil, err - } - - publicKeyBytes, publicKeyAlgorithm, err := marshalPublicKey(pub) - if err != nil { - return nil, err - } - - if err != nil { - return - } - - if len(parent.SubjectKeyId) > 0 { - template.AuthorityKeyId = parent.SubjectKeyId - } - - extensions, err := buildExtensions(template) - if err != nil { - return - } - - asn1Issuer, err := subjectBytes(parent) - if err != nil { - return - } - - asn1Subject, err := subjectBytes(template) - if err != nil { - return - } - - encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes} - c := tbsCertificate{ - Version: 2, - SerialNumber: template.SerialNumber, - SignatureAlgorithm: signatureAlgorithm, - Issuer: asn1.RawValue{FullBytes: asn1Issuer}, - Validity: validity{template.NotBefore.UTC(), template.NotAfter.UTC()}, - Subject: asn1.RawValue{FullBytes: asn1Subject}, - PublicKey: publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey}, - Extensions: extensions, - } - - tbsCertContents, err := asn1.Marshal(c) - if err != nil { - return - } - - c.Raw = tbsCertContents - - h := hashFunc.New() - h.Write(tbsCertContents) - digest := h.Sum(nil) - - var signature []byte - - switch priv := priv.(type) { - case *rsa.PrivateKey: - signature, err = rsa.SignPKCS1v15(rand, priv, hashFunc, digest) - case *ecdsa.PrivateKey: - var r, s *big.Int - if r, s, err = ecdsa.Sign(rand, priv, digest); err == nil { - signature, err = asn1.Marshal(ecdsaSignature{r, s}) - } - default: - panic("internal error") - } - - if err != nil { - return - } - - cert, err = asn1.Marshal(certificate{ - nil, - c, - signatureAlgorithm, - asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, - }) - return -} - -// pemCRLPrefix is the magic string that indicates that we have a PEM encoded -// CRL. -var pemCRLPrefix = []byte("-----BEGIN X509 CRL") - -// pemType is the type of a PEM encoded CRL. -var pemType = "X509 CRL" - -// ParseCRL parses a CRL from the given bytes. It's often the case that PEM -// encoded CRLs will appear where they should be DER encoded, so this function -// will transparently handle PEM encoding as long as there isn't any leading -// garbage. -func ParseCRL(crlBytes []byte) (certList *pkix.CertificateList, err error) { - if bytes.HasPrefix(crlBytes, pemCRLPrefix) { - block, _ := pem.Decode(crlBytes) - if block != nil && block.Type == pemType { - crlBytes = block.Bytes - } - } - return ParseDERCRL(crlBytes) -} - -// ParseDERCRL parses a DER encoded CRL from the given bytes. -func ParseDERCRL(derBytes []byte) (certList *pkix.CertificateList, err error) { - certList = new(pkix.CertificateList) - _, err = asn1.Unmarshal(derBytes, certList) - if err != nil { - certList = nil - } - return -} - -// CreateCRL returns a DER encoded CRL, signed by this Certificate, that -// contains the given list of revoked certificates. -// -// The only supported key type is RSA (*rsa.PrivateKey for priv). -func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) { - rsaPriv, ok := priv.(*rsa.PrivateKey) - if !ok { - return nil, errors.New("x509: non-RSA private keys not supported") - } - tbsCertList := pkix.TBSCertificateList{ - Version: 2, - Signature: pkix.AlgorithmIdentifier{ - Algorithm: oidSignatureSHA1WithRSA, - }, - Issuer: c.Subject.ToRDNSequence(), - ThisUpdate: now.UTC(), - NextUpdate: expiry.UTC(), - RevokedCertificates: revokedCerts, - } - - tbsCertListContents, err := asn1.Marshal(tbsCertList) - if err != nil { - return - } - - h := sha1.New() - h.Write(tbsCertListContents) - digest := h.Sum(nil) - - signature, err := rsa.SignPKCS1v15(rand, rsaPriv, crypto.SHA1, digest) - if err != nil { - return - } - - return asn1.Marshal(pkix.CertificateList{ - TBSCertList: tbsCertList, - SignatureAlgorithm: pkix.AlgorithmIdentifier{ - Algorithm: oidSignatureSHA1WithRSA, - }, - SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8}, - }) -} - -// CertificateRequest represents a PKCS #10, certificate signature request. -type CertificateRequest struct { - Raw []byte // Complete ASN.1 DER content (CSR, signature algorithm and signature). - RawTBSCertificateRequest []byte // Certificate request info part of raw ASN.1 DER content. - RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo. - RawSubject []byte // DER encoded Subject. - - Version int - Signature []byte - SignatureAlgorithm SignatureAlgorithm - - PublicKeyAlgorithm PublicKeyAlgorithm - PublicKey interface{} - - Subject pkix.Name - - // Attributes is a collection of attributes providing - // additional information about the subject of the certificate. - // See RFC 2986 section 4.1. - Attributes []pkix.AttributeTypeAndValueSET - - // Extensions contains raw X.509 extensions. When parsing CSRs, this - // can be used to extract extensions that are not parsed by this - // package. - Extensions []pkix.Extension - - // ExtraExtensions contains extensions to be copied, raw, into any - // marshaled CSR. Values override any extensions that would otherwise - // be produced based on the other fields but are overridden by any - // extensions specified in Attributes. - // - // The ExtraExtensions field is not populated when parsing CSRs, see - // Extensions. - ExtraExtensions []pkix.Extension - - // Subject Alternate Name values. - DNSNames []string - EmailAddresses []string - IPAddresses []net.IP -} - -// These structures reflect the ASN.1 structure of X.509 certificate -// signature requests (see RFC 2986): - -type tbsCertificateRequest struct { - Raw asn1.RawContent - Version int - Subject asn1.RawValue - PublicKey publicKeyInfo - Attributes []pkix.AttributeTypeAndValueSET `asn1:"tag:0"` -} - -type certificateRequest struct { - Raw asn1.RawContent - TBSCSR tbsCertificateRequest - SignatureAlgorithm pkix.AlgorithmIdentifier - SignatureValue asn1.BitString -} - -// oidExtensionRequest is a PKCS#9 OBJECT IDENTIFIER that indicates requested -// extensions in a CSR. -var oidExtensionRequest = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 9, 14} - -// CreateCertificateRequest creates a new certificate based on a template. The -// following members of template are used: Subject, Attributes, -// SignatureAlgorithm, Extension, DNSNames, EmailAddresses, and IPAddresses. -// The private key is the private key of the signer. -// -// The returned slice is the certificate request in DER encoding. -// -// The only supported key types are RSA (*rsa.PrivateKey) and ECDSA -// (*ecdsa.PrivateKey). -func CreateCertificateRequest(rand io.Reader, template *CertificateRequest, priv interface{}) (csr []byte, err error) { - hashFunc, sigAlgo, err := signingParamsForPrivateKey(priv, template.SignatureAlgorithm) - if err != nil { - return nil, err - } - - var publicKeyBytes []byte - var publicKeyAlgorithm pkix.AlgorithmIdentifier - - switch priv := priv.(type) { - case *rsa.PrivateKey: - publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(&priv.PublicKey) - case *ecdsa.PrivateKey: - publicKeyBytes, publicKeyAlgorithm, err = marshalPublicKey(&priv.PublicKey) - default: - panic("internal error") - } - - if err != nil { - return nil, err - } - - var extensions []pkix.Extension - - if (len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0) && - !oidInExtensions(oidExtensionSubjectAltName, template.ExtraExtensions) { - sanBytes, err := marshalSANs(template.DNSNames, template.EmailAddresses, template.IPAddresses) - if err != nil { - return nil, err - } - - extensions = append(extensions, pkix.Extension{ - Id: oidExtensionSubjectAltName, - Value: sanBytes, - }) - } - - extensions = append(extensions, template.ExtraExtensions...) - - var attributes []pkix.AttributeTypeAndValueSET - attributes = append(attributes, template.Attributes...) - - if len(extensions) > 0 { - // specifiedExtensions contains all the extensions that we - // found specified via template.Attributes. - specifiedExtensions := make(map[string]bool) - - for _, atvSet := range template.Attributes { - if !atvSet.Type.Equal(oidExtensionRequest) { - continue - } - - for _, atvs := range atvSet.Value { - for _, atv := range atvs { - specifiedExtensions[atv.Type.String()] = true - } - } - } - - atvs := make([]pkix.AttributeTypeAndValue, 0, len(extensions)) - for _, e := range extensions { - if specifiedExtensions[e.Id.String()] { - // Attributes already contained a value for - // this extension and it takes priority. - continue - } - - atvs = append(atvs, pkix.AttributeTypeAndValue{ - // There is no place for the critical flag in a CSR. - Type: e.Id, - Value: e.Value, - }) - } - - // Append the extensions to an existing attribute if possible. - appended := false - for _, atvSet := range attributes { - if !atvSet.Type.Equal(oidExtensionRequest) || len(atvSet.Value) == 0 { - continue - } - - atvSet.Value[0] = append(atvSet.Value[0], atvs...) - appended = true - break - } - - // Otherwise, add a new attribute for the extensions. - if !appended { - attributes = append(attributes, pkix.AttributeTypeAndValueSET{ - Type: oidExtensionRequest, - Value: [][]pkix.AttributeTypeAndValue{ - atvs, - }, - }) - } - } - - asn1Subject := template.RawSubject - if len(asn1Subject) == 0 { - asn1Subject, err = asn1.Marshal(template.Subject.ToRDNSequence()) - if err != nil { - return - } - } - - tbsCSR := tbsCertificateRequest{ - Version: 0, // PKCS #10, RFC 2986 - Subject: asn1.RawValue{FullBytes: asn1Subject}, - PublicKey: publicKeyInfo{ - Algorithm: publicKeyAlgorithm, - PublicKey: asn1.BitString{ - Bytes: publicKeyBytes, - BitLength: len(publicKeyBytes) * 8, - }, - }, - Attributes: attributes, - } - - tbsCSRContents, err := asn1.Marshal(tbsCSR) - if err != nil { - return - } - tbsCSR.Raw = tbsCSRContents - - h := hashFunc.New() - h.Write(tbsCSRContents) - digest := h.Sum(nil) - - var signature []byte - switch priv := priv.(type) { - case *rsa.PrivateKey: - signature, err = rsa.SignPKCS1v15(rand, priv, hashFunc, digest) - case *ecdsa.PrivateKey: - var r, s *big.Int - if r, s, err = ecdsa.Sign(rand, priv, digest); err == nil { - signature, err = asn1.Marshal(ecdsaSignature{r, s}) - } - default: - panic("internal error") - } - - if err != nil { - return - } - - return asn1.Marshal(certificateRequest{ - TBSCSR: tbsCSR, - SignatureAlgorithm: sigAlgo, - SignatureValue: asn1.BitString{ - Bytes: signature, - BitLength: len(signature) * 8, - }, - }) -} - -// ParseCertificateRequest parses a single certificate request from the -// given ASN.1 DER data. -func ParseCertificateRequest(asn1Data []byte) (*CertificateRequest, error) { - var csr certificateRequest - - rest, err := asn1.Unmarshal(asn1Data, &csr) - if err != nil { - return nil, err - } else if len(rest) != 0 { - return nil, asn1.SyntaxError{Msg: "trailing data"} - } - - return parseCertificateRequest(&csr) -} - -func parseCertificateRequest(in *certificateRequest) (*CertificateRequest, error) { - out := &CertificateRequest{ - Raw: in.Raw, - RawTBSCertificateRequest: in.TBSCSR.Raw, - RawSubjectPublicKeyInfo: in.TBSCSR.PublicKey.Raw, - RawSubject: in.TBSCSR.Subject.FullBytes, - - Signature: in.SignatureValue.RightAlign(), - SignatureAlgorithm: getSignatureAlgorithmFromOID(in.SignatureAlgorithm.Algorithm), - - PublicKeyAlgorithm: getPublicKeyAlgorithmFromOID(in.TBSCSR.PublicKey.Algorithm.Algorithm), - - Version: in.TBSCSR.Version, - Attributes: in.TBSCSR.Attributes, - } - - var err error - out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCSR.PublicKey) - if err != nil { - return nil, err - } - - var subject pkix.RDNSequence - if _, err := asn1.Unmarshal(in.TBSCSR.Subject.FullBytes, &subject); err != nil { - return nil, err - } - - out.Subject.FillFromRDNSequence(&subject) - - var extensions []pkix.AttributeTypeAndValue - - for _, atvSet := range in.TBSCSR.Attributes { - if !atvSet.Type.Equal(oidExtensionRequest) { - continue - } - - for _, atvs := range atvSet.Value { - extensions = append(extensions, atvs...) - } - } - - out.Extensions = make([]pkix.Extension, 0, len(extensions)) - - for _, e := range extensions { - value, ok := e.Value.([]byte) - if !ok { - return nil, errors.New("x509: extension attribute contained non-OCTET STRING data") - } - - out.Extensions = append(out.Extensions, pkix.Extension{ - Id: e.Type, - Value: value, - }) - - if len(e.Type) == 4 && e.Type[0] == 2 && e.Type[1] == 5 && e.Type[2] == 29 { - switch e.Type[3] { - case 17: - out.DNSNames, out.EmailAddresses, out.IPAddresses, err = parseSANExtension(value) - if err != nil { - return nil, err - } - } - } - } - - return out, nil -} diff --git a/src/pkg/crypto/x509/x509_test.go b/src/pkg/crypto/x509/x509_test.go deleted file mode 100644 index 56f7a9832..000000000 --- a/src/pkg/crypto/x509/x509_test.go +++ /dev/null @@ -1,953 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package x509 - -import ( - "bytes" - "crypto/dsa" - "crypto/ecdsa" - "crypto/elliptic" - "crypto/rand" - "crypto/rsa" - _ "crypto/sha256" - _ "crypto/sha512" - "crypto/x509/pkix" - "encoding/asn1" - "encoding/base64" - "encoding/hex" - "encoding/pem" - "math/big" - "net" - "os/exec" - "reflect" - "runtime" - "testing" - "time" -) - -func TestParsePKCS1PrivateKey(t *testing.T) { - block, _ := pem.Decode([]byte(pemPrivateKey)) - priv, err := ParsePKCS1PrivateKey(block.Bytes) - if err != nil { - t.Errorf("Failed to parse private key: %s", err) - return - } - if priv.PublicKey.N.Cmp(rsaPrivateKey.PublicKey.N) != 0 || - priv.PublicKey.E != rsaPrivateKey.PublicKey.E || - priv.D.Cmp(rsaPrivateKey.D) != 0 || - priv.Primes[0].Cmp(rsaPrivateKey.Primes[0]) != 0 || - priv.Primes[1].Cmp(rsaPrivateKey.Primes[1]) != 0 { - t.Errorf("got:%+v want:%+v", priv, rsaPrivateKey) - } -} - -func TestParsePKIXPublicKey(t *testing.T) { - block, _ := pem.Decode([]byte(pemPublicKey)) - pub, err := ParsePKIXPublicKey(block.Bytes) - if err != nil { - t.Errorf("Failed to parse RSA public key: %s", err) - return - } - rsaPub, ok := pub.(*rsa.PublicKey) - if !ok { - t.Errorf("Value returned from ParsePKIXPublicKey was not an RSA public key") - return - } - - pubBytes2, err := MarshalPKIXPublicKey(rsaPub) - if err != nil { - t.Errorf("Failed to marshal RSA public key for the second time: %s", err) - return - } - if !bytes.Equal(pubBytes2, block.Bytes) { - t.Errorf("Reserialization of public key didn't match. got %x, want %x", pubBytes2, block.Bytes) - } -} - -var pemPublicKey = `-----BEGIN PUBLIC KEY----- -MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3VoPN9PKUjKFLMwOge6+ -wnDi8sbETGIx2FKXGgqtAKpzmem53kRGEQg8WeqRmp12wgp74TGpkEXsGae7RS1k -enJCnma4fii+noGH7R0qKgHvPrI2Bwa9hzsH8tHxpyM3qrXslOmD45EH9SxIDUBJ -FehNdaPbLP1gFyahKMsdfxFJLUvbUycuZSJ2ZnIgeVxwm4qbSvZInL9Iu4FzuPtg -fINKcbbovy1qq4KvPIrXzhbY3PWDc6btxCf3SE0JdE1MCPThntB62/bLMSQ7xdDR -FF53oIpvxe/SCOymfWq/LW849Ytv3Xwod0+wzAP8STXG4HSELS4UedPYeHJJJYcZ -+QIDAQAB ------END PUBLIC KEY----- -` - -var pemPrivateKey = `-----BEGIN RSA PRIVATE KEY----- -MIIBOgIBAAJBALKZD0nEffqM1ACuak0bijtqE2QrI/KLADv7l3kK3ppMyCuLKoF0 -fd7Ai2KW5ToIwzFofvJcS/STa6HA5gQenRUCAwEAAQJBAIq9amn00aS0h/CrjXqu -/ThglAXJmZhOMPVn4eiu7/ROixi9sex436MaVeMqSNf7Ex9a8fRNfWss7Sqd9eWu -RTUCIQDasvGASLqmjeffBNLTXV2A5g4t+kLVCpsEIZAycV5GswIhANEPLmax0ME/ -EO+ZJ79TJKN5yiGBRsv5yvx5UiHxajEXAiAhAol5N4EUyq6I9w1rYdhPMGpLfk7A -IU2snfRJ6Nq2CQIgFrPsWRCkV+gOYcajD17rEqmuLrdIRexpg8N1DOSXoJ8CIGlS -tAboUGBxTDq3ZroNism3DaMIbKPyYrAqhKov1h5V ------END RSA PRIVATE KEY----- -` - -func bigFromString(s string) *big.Int { - ret := new(big.Int) - ret.SetString(s, 10) - return ret -} - -func fromBase10(base10 string) *big.Int { - i := new(big.Int) - i.SetString(base10, 10) - return i -} - -func bigFromHexString(s string) *big.Int { - ret := new(big.Int) - ret.SetString(s, 16) - return ret -} - -var rsaPrivateKey = &rsa.PrivateKey{ - PublicKey: rsa.PublicKey{ - N: bigFromString("9353930466774385905609975137998169297361893554149986716853295022578535724979677252958524466350471210367835187480748268864277464700638583474144061408845077"), - E: 65537, - }, - D: bigFromString("7266398431328116344057699379749222532279343923819063639497049039389899328538543087657733766554155839834519529439851673014800261285757759040931985506583861"), - Primes: []*big.Int{ - bigFromString("98920366548084643601728869055592650835572950932266967461790948584315647051443"), - bigFromString("94560208308847015747498523884063394671606671904944666360068158221458669711639"), - }, -} - -func TestMarshalRSAPrivateKey(t *testing.T) { - priv := &rsa.PrivateKey{ - PublicKey: rsa.PublicKey{ - N: fromBase10("16346378922382193400538269749936049106320265317511766357599732575277382844051791096569333808598921852351577762718529818072849191122419410612033592401403764925096136759934497687765453905884149505175426053037420486697072448609022753683683718057795566811401938833367954642951433473337066311978821180526439641496973296037000052546108507805269279414789035461158073156772151892452251106173507240488993608650881929629163465099476849643165682709047462010581308719577053905787496296934240246311806555924593059995202856826239801816771116902778517096212527979497399966526283516447337775509777558018145573127308919204297111496233"), - E: 3, - }, - D: fromBase10("10897585948254795600358846499957366070880176878341177571733155050184921896034527397712889205732614568234385175145686545381899460748279607074689061600935843283397424506622998458510302603922766336783617368686090042765718290914099334449154829375179958369993407724946186243249568928237086215759259909861748642124071874879861299389874230489928271621259294894142840428407196932444474088857746123104978617098858619445675532587787023228852383149557470077802718705420275739737958953794088728369933811184572620857678792001136676902250566845618813972833750098806496641114644760255910789397593428910198080271317419213080834885003"), - Primes: []*big.Int{ - fromBase10("1025363189502892836833747188838978207017355117492483312747347695538428729137306368764177201532277413433182799108299960196606011786562992097313508180436744488171474690412562218914213688661311117337381958560443"), - fromBase10("3467903426626310123395340254094941045497208049900750380025518552334536945536837294961497712862519984786362199788654739924501424784631315081391467293694361474867825728031147665777546570788493758372218019373"), - fromBase10("4597024781409332673052708605078359346966325141767460991205742124888960305710298765592730135879076084498363772408626791576005136245060321874472727132746643162385746062759369754202494417496879741537284589047"), - }, - } - - derBytes := MarshalPKCS1PrivateKey(priv) - - priv2, err := ParsePKCS1PrivateKey(derBytes) - if err != nil { - t.Errorf("error parsing serialized key: %s", err) - return - } - if priv.PublicKey.N.Cmp(priv2.PublicKey.N) != 0 || - priv.PublicKey.E != priv2.PublicKey.E || - priv.D.Cmp(priv2.D) != 0 || - len(priv2.Primes) != 3 || - priv.Primes[0].Cmp(priv2.Primes[0]) != 0 || - priv.Primes[1].Cmp(priv2.Primes[1]) != 0 || - priv.Primes[2].Cmp(priv2.Primes[2]) != 0 { - t.Errorf("got:%+v want:%+v", priv, priv2) - } -} - -type matchHostnamesTest struct { - pattern, host string - ok bool -} - -var matchHostnamesTests = []matchHostnamesTest{ - {"a.b.c", "a.b.c", true}, - {"a.b.c", "b.b.c", false}, - {"", "b.b.c", false}, - {"a.b.c", "", false}, - {"example.com", "example.com", true}, - {"example.com", "www.example.com", false}, - {"*.example.com", "www.example.com", true}, - {"*.example.com", "xyz.www.example.com", false}, - {"*.*.example.com", "xyz.www.example.com", true}, - {"*.www.*.com", "xyz.www.example.com", true}, -} - -func TestMatchHostnames(t *testing.T) { - for i, test := range matchHostnamesTests { - r := matchHostnames(test.pattern, test.host) - if r != test.ok { - t.Errorf("#%d mismatch got: %t want: %t", i, r, test.ok) - } - } -} - -func TestMatchIP(t *testing.T) { - // Check that pattern matching is working. - c := &Certificate{ - DNSNames: []string{"*.foo.bar.baz"}, - Subject: pkix.Name{ - CommonName: "*.foo.bar.baz", - }, - } - err := c.VerifyHostname("quux.foo.bar.baz") - if err != nil { - t.Fatalf("VerifyHostname(quux.foo.bar.baz): %v", err) - } - - // But check that if we change it to be matching against an IP address, - // it is rejected. - c = &Certificate{ - DNSNames: []string{"*.2.3.4"}, - Subject: pkix.Name{ - CommonName: "*.2.3.4", - }, - } - err = c.VerifyHostname("1.2.3.4") - if err == nil { - t.Fatalf("VerifyHostname(1.2.3.4) should have failed, did not") - } - - c = &Certificate{ - IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")}, - } - err = c.VerifyHostname("127.0.0.1") - if err != nil { - t.Fatalf("VerifyHostname(127.0.0.1): %v", err) - } - err = c.VerifyHostname("::1") - if err != nil { - t.Fatalf("VerifyHostname(::1): %v", err) - } - err = c.VerifyHostname("[::1]") - if err != nil { - t.Fatalf("VerifyHostname([::1]): %v", err) - } -} - -func TestCertificateParse(t *testing.T) { - s, _ := hex.DecodeString(certBytes) - certs, err := ParseCertificates(s) - if err != nil { - t.Error(err) - } - if len(certs) != 2 { - t.Errorf("Wrong number of certs: got %d want 2", len(certs)) - return - } - - err = certs[0].CheckSignatureFrom(certs[1]) - if err != nil { - t.Error(err) - } - - if err := certs[0].VerifyHostname("mail.google.com"); err != nil { - t.Error(err) - } - - const expectedExtensions = 4 - if n := len(certs[0].Extensions); n != expectedExtensions { - t.Errorf("want %d extensions, got %d", expectedExtensions, n) - } -} - -var certBytes = "308203223082028ba00302010202106edf0d9499fd4533dd1297fc42a93be1300d06092a864886" + - "f70d0101050500304c310b3009060355040613025a4131253023060355040a131c546861777465" + - "20436f6e73756c74696e67202850747929204c74642e311630140603550403130d546861777465" + - "20534743204341301e170d3039303332353136343932395a170d3130303332353136343932395a" + - "3069310b3009060355040613025553311330110603550408130a43616c69666f726e6961311630" + - "140603550407130d4d6f756e7461696e205669657731133011060355040a130a476f6f676c6520" + - "496e63311830160603550403130f6d61696c2e676f6f676c652e636f6d30819f300d06092a8648" + - "86f70d010101050003818d0030818902818100c5d6f892fccaf5614b064149e80a2c9581a218ef" + - "41ec35bd7a58125ae76f9ea54ddc893abbeb029f6b73616bf0ffd868791fba7af9c4aebf3706ba" + - "3eeaeed27435b4ddcfb157c05f351d66aa87fee0de072d66d773affbd36ab78bef090e0cc861a9" + - "03ac90dd98b51c9c41566c017f0beec3bff391051ffba0f5cc6850ad2a590203010001a381e730" + - "81e430280603551d250421301f06082b0601050507030106082b06010505070302060960864801" + - "86f842040130360603551d1f042f302d302ba029a0278625687474703a2f2f63726c2e74686177" + - "74652e636f6d2f54686177746553474343412e63726c307206082b060105050701010466306430" + - "2206082b060105050730018616687474703a2f2f6f6373702e7468617774652e636f6d303e0608" + - "2b060105050730028632687474703a2f2f7777772e7468617774652e636f6d2f7265706f736974" + - "6f72792f5468617774655f5347435f43412e637274300c0603551d130101ff04023000300d0609" + - "2a864886f70d01010505000381810062f1f3050ebc105e497c7aedf87e24d2f4a986bb3b837bd1" + - "9b91ebcad98b065992f6bd2b49b7d6d3cb2e427a99d606c7b1d46352527fac39e6a8b6726de5bf" + - "70212a52cba07634a5e332011bd1868e78eb5e3c93cf03072276786f207494feaa0ed9d53b2110" + - "a76571f90209cdae884385c882587030ee15f33d761e2e45a6bc308203233082028ca003020102" + - "020430000002300d06092a864886f70d0101050500305f310b3009060355040613025553311730" + - "15060355040a130e566572695369676e2c20496e632e31373035060355040b132e436c61737320" + - "33205075626c6963205072696d6172792043657274696669636174696f6e20417574686f726974" + - "79301e170d3034303531333030303030305a170d3134303531323233353935395a304c310b3009" + - "060355040613025a4131253023060355040a131c54686177746520436f6e73756c74696e672028" + - "50747929204c74642e311630140603550403130d5468617774652053474320434130819f300d06" + - "092a864886f70d010101050003818d0030818902818100d4d367d08d157faecd31fe7d1d91a13f" + - "0b713cacccc864fb63fc324b0794bd6f80ba2fe10493c033fc093323e90b742b71c403c6d2cde2" + - "2ff50963cdff48a500bfe0e7f388b72d32de9836e60aad007bc4644a3b847503f270927d0e62f5" + - "21ab693684317590f8bfc76c881b06957cc9e5a8de75a12c7a68dfd5ca1c875860190203010001" + - "a381fe3081fb30120603551d130101ff040830060101ff020100300b0603551d0f040403020106" + - "301106096086480186f842010104040302010630280603551d110421301fa41d301b3119301706" + - "035504031310507269766174654c6162656c332d313530310603551d1f042a30283026a024a022" + - "8620687474703a2f2f63726c2e766572697369676e2e636f6d2f706361332e63726c303206082b" + - "0601050507010104263024302206082b060105050730018616687474703a2f2f6f6373702e7468" + - "617774652e636f6d30340603551d25042d302b06082b0601050507030106082b06010505070302" + - "06096086480186f8420401060a6086480186f845010801300d06092a864886f70d010105050003" + - "81810055ac63eadea1ddd2905f9f0bce76be13518f93d9052bc81b774bad6950a1eededcfddb07" + - "e9e83994dcab72792f06bfab8170c4a8edea5334edef1e53d906c7562bd15cf4d18a8eb42bb137" + - "9048084225c53e8acb7feb6f04d16dc574a2f7a27c7b603c77cd0ece48027f012fb69b37e02a2a" + - "36dcd585d6ace53f546f961e05af" - -func TestCreateSelfSignedCertificate(t *testing.T) { - random := rand.Reader - - block, _ := pem.Decode([]byte(pemPrivateKey)) - rsaPriv, err := ParsePKCS1PrivateKey(block.Bytes) - if err != nil { - t.Fatalf("Failed to parse private key: %s", err) - } - - ecdsaPriv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatalf("Failed to generate ECDSA key: %s", err) - } - - tests := []struct { - name string - pub, priv interface{} - checkSig bool - sigAlgo SignatureAlgorithm - }{ - {"RSA/RSA", &rsaPriv.PublicKey, rsaPriv, true, SHA1WithRSA}, - {"RSA/ECDSA", &rsaPriv.PublicKey, ecdsaPriv, false, ECDSAWithSHA384}, - {"ECDSA/RSA", &ecdsaPriv.PublicKey, rsaPriv, false, SHA256WithRSA}, - {"ECDSA/ECDSA", &ecdsaPriv.PublicKey, ecdsaPriv, true, ECDSAWithSHA1}, - } - - testExtKeyUsage := []ExtKeyUsage{ExtKeyUsageClientAuth, ExtKeyUsageServerAuth} - testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}} - extraExtensionData := []byte("extra extension") - - for _, test := range tests { - commonName := "test.example.com" - template := Certificate{ - SerialNumber: big.NewInt(1), - Subject: pkix.Name{ - CommonName: commonName, - Organization: []string{"Σ Acme Co"}, - }, - NotBefore: time.Unix(1000, 0), - NotAfter: time.Unix(100000, 0), - - SignatureAlgorithm: test.sigAlgo, - - SubjectKeyId: []byte{1, 2, 3, 4}, - KeyUsage: KeyUsageCertSign, - - ExtKeyUsage: testExtKeyUsage, - UnknownExtKeyUsage: testUnknownExtKeyUsage, - - BasicConstraintsValid: true, - IsCA: true, - - OCSPServer: []string{"http://ocsp.example.com"}, - IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"}, - - DNSNames: []string{"test.example.com"}, - EmailAddresses: []string{"gopher@golang.org"}, - IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")}, - - PolicyIdentifiers: []asn1.ObjectIdentifier{[]int{1, 2, 3}}, - PermittedDNSDomains: []string{".example.com", "example.com"}, - - CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"}, - - ExtraExtensions: []pkix.Extension{ - { - Id: []int{1, 2, 3, 4}, - Value: extraExtensionData, - }, - // This extension should override the SubjectKeyId, above. - { - Id: oidExtensionSubjectKeyId, - Critical: false, - Value: []byte{0x04, 0x04, 4, 3, 2, 1}, - }, - }, - } - - derBytes, err := CreateCertificate(random, &template, &template, test.pub, test.priv) - if err != nil { - t.Errorf("%s: failed to create certificate: %s", test.name, err) - continue - } - - cert, err := ParseCertificate(derBytes) - if err != nil { - t.Errorf("%s: failed to parse certificate: %s", test.name, err) - continue - } - - if len(cert.PolicyIdentifiers) != 1 || !cert.PolicyIdentifiers[0].Equal(template.PolicyIdentifiers[0]) { - t.Errorf("%s: failed to parse policy identifiers: got:%#v want:%#v", test.name, cert.PolicyIdentifiers, template.PolicyIdentifiers) - } - - if len(cert.PermittedDNSDomains) != 2 || cert.PermittedDNSDomains[0] != ".example.com" || cert.PermittedDNSDomains[1] != "example.com" { - t.Errorf("%s: failed to parse name constraints: %#v", test.name, cert.PermittedDNSDomains) - } - - if cert.Subject.CommonName != commonName { - t.Errorf("%s: subject wasn't correctly copied from the template. Got %s, want %s", test.name, cert.Subject.CommonName, commonName) - } - - if cert.Issuer.CommonName != commonName { - t.Errorf("%s: issuer wasn't correctly copied from the template. Got %s, want %s", test.name, cert.Issuer.CommonName, commonName) - } - - if cert.SignatureAlgorithm != test.sigAlgo { - t.Errorf("%s: SignatureAlgorithm wasn't copied from template. Got %v, want %v", test.name, cert.SignatureAlgorithm, test.sigAlgo) - } - - if !reflect.DeepEqual(cert.ExtKeyUsage, testExtKeyUsage) { - t.Errorf("%s: extkeyusage wasn't correctly copied from the template. Got %v, want %v", test.name, cert.ExtKeyUsage, testExtKeyUsage) - } - - if !reflect.DeepEqual(cert.UnknownExtKeyUsage, testUnknownExtKeyUsage) { - t.Errorf("%s: unknown extkeyusage wasn't correctly copied from the template. Got %v, want %v", test.name, cert.UnknownExtKeyUsage, testUnknownExtKeyUsage) - } - - if !reflect.DeepEqual(cert.OCSPServer, template.OCSPServer) { - t.Errorf("%s: OCSP servers differ from template. Got %v, want %v", test.name, cert.OCSPServer, template.OCSPServer) - } - - if !reflect.DeepEqual(cert.IssuingCertificateURL, template.IssuingCertificateURL) { - t.Errorf("%s: Issuing certificate URLs differ from template. Got %v, want %v", test.name, cert.IssuingCertificateURL, template.IssuingCertificateURL) - } - - if !reflect.DeepEqual(cert.DNSNames, template.DNSNames) { - t.Errorf("%s: SAN DNS names differ from template. Got %v, want %v", test.name, cert.DNSNames, template.DNSNames) - } - - if !reflect.DeepEqual(cert.EmailAddresses, template.EmailAddresses) { - t.Errorf("%s: SAN emails differ from template. Got %v, want %v", test.name, cert.EmailAddresses, template.EmailAddresses) - } - - if !reflect.DeepEqual(cert.IPAddresses, template.IPAddresses) { - t.Errorf("%s: SAN IPs differ from template. Got %v, want %v", test.name, cert.IPAddresses, template.IPAddresses) - } - - if !reflect.DeepEqual(cert.CRLDistributionPoints, template.CRLDistributionPoints) { - t.Errorf("%s: CRL distribution points differ from template. Got %v, want %v", test.name, cert.CRLDistributionPoints, template.CRLDistributionPoints) - } - - if !bytes.Equal(cert.SubjectKeyId, []byte{4, 3, 2, 1}) { - t.Errorf("%s: ExtraExtensions didn't override SubjectKeyId", test.name) - } - - if bytes.Index(derBytes, extraExtensionData) == -1 { - t.Errorf("%s: didn't find extra extension in DER output", test.name) - } - - if test.checkSig { - err = cert.CheckSignatureFrom(cert) - if err != nil { - t.Errorf("%s: signature verification failed: %s", test.name, err) - } - } - } -} - -// Self-signed certificate using ECDSA with SHA1 & secp256r1 -var ecdsaSHA1CertPem = ` ------BEGIN CERTIFICATE----- -MIICDjCCAbUCCQDF6SfN0nsnrjAJBgcqhkjOPQQBMIGPMQswCQYDVQQGEwJVUzET -MBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEVMBMG -A1UECgwMR29vZ2xlLCBJbmMuMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG -CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIwMjAyMDUw -WhcNMjIwNTE4MjAyMDUwWjCBjzELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm -b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFTATBgNVBAoMDEdvb2dsZSwg -SW5jLjEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20xIzAhBgkqhkiG9w0BCQEWFGdv -bGFuZy1kZXZAZ21haWwuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE/Wgn -WQDo5+bz71T0327ERgd5SDDXFbXLpzIZDXTkjpe8QTEbsF+ezsQfrekrpDPC4Cd3 -P9LY0tG+aI8IyVKdUjAJBgcqhkjOPQQBA0gAMEUCIGlsqMcRqWVIWTD6wXwe6Jk2 -DKxL46r/FLgJYnzBEH99AiEA3fBouObsvV1R3oVkb4BQYnD4/4LeId6lAT43YvyV -a/A= ------END CERTIFICATE----- -` - -// Self-signed certificate using ECDSA with SHA256 & secp256r1 -var ecdsaSHA256p256CertPem = ` ------BEGIN CERTIFICATE----- -MIICDzCCAbYCCQDlsuMWvgQzhTAKBggqhkjOPQQDAjCBjzELMAkGA1UEBhMCVVMx -EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFTAT -BgNVBAoMDEdvb2dsZSwgSW5jLjEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20xIzAh -BgkqhkiG9w0BCQEWFGdvbGFuZy1kZXZAZ21haWwuY29tMB4XDTEyMDUyMTAwMTkx -NloXDTIyMDUxOTAwMTkxNlowgY8xCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxp -Zm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MRUwEwYDVQQKDAxHb29nbGUs -IEluYy4xFzAVBgNVBAMMDnd3dy5nb29nbGUuY29tMSMwIQYJKoZIhvcNAQkBFhRn -b2xhbmctZGV2QGdtYWlsLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABPMt -2ErhxAty5EJRu9yM+MTy+hUXm3pdW1ensAv382KoGExSXAFWP7pjJnNtHO+XSwVm -YNtqjcAGFKpweoN//kQwCgYIKoZIzj0EAwIDRwAwRAIgIYSaUA/IB81gjbIw/hUV -70twxJr5EcgOo0hLp3Jm+EYCIFDO3NNcgmURbJ1kfoS3N/0O+irUtoPw38YoNkqJ -h5wi ------END CERTIFICATE----- -` - -// Self-signed certificate using ECDSA with SHA256 & secp384r1 -var ecdsaSHA256p384CertPem = ` ------BEGIN CERTIFICATE----- -MIICSjCCAdECCQDje/no7mXkVzAKBggqhkjOPQQDAjCBjjELMAkGA1UEBhMCVVMx -EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS -BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG -CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMDYxMDM0 -WhcNMjIwNTE5MDYxMDM0WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm -b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg -SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s -YW5nLWRldkBnbWFpbC5jb20wdjAQBgcqhkjOPQIBBgUrgQQAIgNiAARRuzRNIKRK -jIktEmXanNmrTR/q/FaHXLhWRZ6nHWe26Fw7Rsrbk+VjGy4vfWtNn7xSFKrOu5ze -qxKnmE0h5E480MNgrUiRkaGO2GMJJVmxx20aqkXOk59U8yGA4CghE6MwCgYIKoZI -zj0EAwIDZwAwZAIwBZEN8gvmRmfeP/9C1PRLzODIY4JqWub2PLRT4mv9GU+yw3Gr -PU9A3CHMdEcdw/MEAjBBO1lId8KOCh9UZunsSMfqXiVurpzmhWd6VYZ/32G+M+Mh -3yILeYQzllt/g0rKVRk= ------END CERTIFICATE----- -` - -// Self-signed certificate using ECDSA with SHA384 & secp521r1 -var ecdsaSHA384p521CertPem = ` ------BEGIN CERTIFICATE----- -MIICljCCAfcCCQDhp1AFD/ahKjAKBggqhkjOPQQDAzCBjjELMAkGA1UEBhMCVVMx -EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS -BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG -CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMTUwNDI5 -WhcNMjIwNTE5MTUwNDI5WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm -b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg -SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s -YW5nLWRldkBnbWFpbC5jb20wgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACqx9Rv -IssRs1LWYcNN+WffwlHw4Tv3y8/LIAA9MF1ZScIonU9nRMxt4a2uGJVCPDw6JHpz -PaYc0E9puLoE9AfKpwFr59Jkot7dBg55SKPEFkddoip/rvmN7NPAWjMBirOwjOkm -8FPthvPhGPqsu9AvgVuHu3PosWiHGNrhh379pva8MzAKBggqhkjOPQQDAwOBjAAw -gYgCQgEHNmswkUdPpHqrVxp9PvLVl+xxPuHBkT+75z9JizyxtqykHQo9Uh6SWCYH -BF9KLolo01wMt8DjoYP5Fb3j5MH7xwJCAbWZzTOp4l4DPkIvAh4LeC4VWbwPPyqh -kBg71w/iEcSY3wUKgHGcJJrObZw7wys91I5kENljqw/Samdr3ka+jBJa ------END CERTIFICATE----- -` - -var ecdsaTests = []struct { - sigAlgo SignatureAlgorithm - pemCert string -}{ - {ECDSAWithSHA1, ecdsaSHA1CertPem}, - {ECDSAWithSHA256, ecdsaSHA256p256CertPem}, - {ECDSAWithSHA256, ecdsaSHA256p384CertPem}, - {ECDSAWithSHA384, ecdsaSHA384p521CertPem}, -} - -func TestECDSA(t *testing.T) { - for i, test := range ecdsaTests { - pemBlock, _ := pem.Decode([]byte(test.pemCert)) - cert, err := ParseCertificate(pemBlock.Bytes) - if err != nil { - t.Errorf("%d: failed to parse certificate: %s", i, err) - continue - } - if sa := cert.SignatureAlgorithm; sa != test.sigAlgo { - t.Errorf("%d: signature algorithm is %v, want %v", i, sa, test.sigAlgo) - } - if parsedKey, ok := cert.PublicKey.(*ecdsa.PublicKey); !ok { - t.Errorf("%d: wanted an ECDSA public key but found: %#v", i, parsedKey) - } - if pka := cert.PublicKeyAlgorithm; pka != ECDSA { - t.Errorf("%d: public key algorithm is %v, want ECDSA", i, pka) - } - if err = cert.CheckSignatureFrom(cert); err != nil { - t.Errorf("%d: certificate verification failed: %s", i, err) - } - } -} - -// Self-signed certificate using DSA with SHA1 -var dsaCertPem = `-----BEGIN CERTIFICATE----- -MIIEDTCCA82gAwIBAgIJALHPghaoxeDhMAkGByqGSM44BAMweTELMAkGA1UEBhMC -VVMxCzAJBgNVBAgTAk5DMQ8wDQYDVQQHEwZOZXd0b24xFDASBgNVBAoTC0dvb2ds -ZSwgSW5jMRIwEAYDVQQDEwlKb24gQWxsaWUxIjAgBgkqhkiG9w0BCQEWE2pvbmFs -bGllQGdvb2dsZS5jb20wHhcNMTEwNTE0MDMwMTQ1WhcNMTEwNjEzMDMwMTQ1WjB5 -MQswCQYDVQQGEwJVUzELMAkGA1UECBMCTkMxDzANBgNVBAcTBk5ld3RvbjEUMBIG -A1UEChMLR29vZ2xlLCBJbmMxEjAQBgNVBAMTCUpvbiBBbGxpZTEiMCAGCSqGSIb3 -DQEJARYTam9uYWxsaWVAZ29vZ2xlLmNvbTCCAbcwggEsBgcqhkjOOAQBMIIBHwKB -gQC8hLUnQ7FpFYu4WXTj6DKvXvz8QrJkNJCVMTpKAT7uBpobk32S5RrPKXocd4gN -8lyGB9ggS03EVlEwXvSmO0DH2MQtke2jl9j1HLydClMf4sbx5V6TV9IFw505U1iW -jL7awRMgxge+FsudtJK254FjMFo03ZnOQ8ZJJ9E6AEDrlwIVAJpnBn9moyP11Ox5 -Asc/5dnjb6dPAoGBAJFHd4KVv1iTVCvEG6gGiYop5DJh28hUQcN9kul+2A0yPUSC -X93oN00P8Vh3eYgSaCWZsha7zDG53MrVJ0Zf6v/X/CoZNhLldeNOepivTRAzn+Rz -kKUYy5l1sxYLHQKF0UGNCXfFKZT0PCmgU+PWhYNBBMn6/cIh44vp85ideo5CA4GE -AAKBgFmifCafzeRaohYKXJgMGSEaggCVCRq5xdyDCat+wbOkjC4mfG01/um3G8u5 -LxasjlWRKTR/tcAL7t0QuokVyQaYdVypZXNaMtx1db7YBuHjj3aP+8JOQRI9xz8c -bp5NDJ5pISiFOv4p3GZfqZPcqckDt78AtkQrmnal2txhhjF6o4HeMIHbMB0GA1Ud -DgQWBBQVyyr7hO11ZFFpWX50298Sa3V+rzCBqwYDVR0jBIGjMIGggBQVyyr7hO11 -ZFFpWX50298Sa3V+r6F9pHsweTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAk5DMQ8w -DQYDVQQHEwZOZXd0b24xFDASBgNVBAoTC0dvb2dsZSwgSW5jMRIwEAYDVQQDEwlK -b24gQWxsaWUxIjAgBgkqhkiG9w0BCQEWE2pvbmFsbGllQGdvb2dsZS5jb22CCQCx -z4IWqMXg4TAMBgNVHRMEBTADAQH/MAkGByqGSM44BAMDLwAwLAIUPtn/5j8Q1jJI -7ggOIsgrhgUdjGQCFCsmDq1H11q9+9Wp9IMeGrTSKHIM ------END CERTIFICATE----- -` - -func TestParseCertificateWithDsaPublicKey(t *testing.T) { - expectedKey := &dsa.PublicKey{ - Parameters: dsa.Parameters{ - P: bigFromHexString("00BC84B52743B169158BB85974E3E832AF5EFCFC42B264349095313A4A013EEE069A1B937D92E51ACF297A1C77880DF25C8607D8204B4DC45651305EF4A63B40C7D8C42D91EDA397D8F51CBC9D0A531FE2C6F1E55E9357D205C39D395358968CBEDAC11320C607BE16CB9DB492B6E78163305A34DD99CE43C64927D13A0040EB97"), - Q: bigFromHexString("009A67067F66A323F5D4EC7902C73FE5D9E36FA74F"), - G: bigFromHexString("009147778295BF5893542BC41BA806898A29E43261DBC85441C37D92E97ED80D323D44825FDDE8374D0FF15877798812682599B216BBCC31B9DCCAD527465FEAFFD7FC2A193612E575E34E7A98AF4D10339FE47390A518CB9975B3160B1D0285D1418D0977C52994F43C29A053E3D685834104C9FAFDC221E38BE9F3989D7A8E42"), - }, - Y: bigFromHexString("59A27C269FCDE45AA2160A5C980C19211A820095091AB9C5DC8309AB7EC1B3A48C2E267C6D35FEE9B71BCBB92F16AC8E559129347FB5C00BEEDD10BA8915C90698755CA965735A32DC7575BED806E1E38F768FFBC24E41123DC73F1C6E9E4D0C9E692128853AFE29DC665FA993DCA9C903B7BF00B6442B9A76A5DADC6186317A"), - } - pemBlock, _ := pem.Decode([]byte(dsaCertPem)) - cert, err := ParseCertificate(pemBlock.Bytes) - if err != nil { - t.Fatalf("Failed to parse certificate: %s", err) - } - if cert.PublicKeyAlgorithm != DSA { - t.Errorf("Parsed key algorithm was not DSA") - } - parsedKey, ok := cert.PublicKey.(*dsa.PublicKey) - if !ok { - t.Fatalf("Parsed key was not a DSA key: %s", err) - } - if expectedKey.Y.Cmp(parsedKey.Y) != 0 || - expectedKey.P.Cmp(parsedKey.P) != 0 || - expectedKey.Q.Cmp(parsedKey.Q) != 0 || - expectedKey.G.Cmp(parsedKey.G) != 0 { - t.Fatal("Parsed key differs from expected key") - } -} - -func TestParseCertificateWithDSASignatureAlgorithm(t *testing.T) { - pemBlock, _ := pem.Decode([]byte(dsaCertPem)) - cert, err := ParseCertificate(pemBlock.Bytes) - if err != nil { - t.Fatalf("Failed to parse certificate: %s", err) - } - if cert.SignatureAlgorithm != DSAWithSHA1 { - t.Errorf("Parsed signature algorithm was not DSAWithSHA1") - } -} - -func TestVerifyCertificateWithDSASignature(t *testing.T) { - pemBlock, _ := pem.Decode([]byte(dsaCertPem)) - cert, err := ParseCertificate(pemBlock.Bytes) - if err != nil { - t.Fatalf("Failed to parse certificate: %s", err) - } - // test cert is self-signed - if err = cert.CheckSignatureFrom(cert); err != nil { - t.Fatalf("DSA Certificate verification failed: %s", err) - } -} - -const pemCertificate = `-----BEGIN CERTIFICATE----- -MIIB5DCCAZCgAwIBAgIBATALBgkqhkiG9w0BAQUwLTEQMA4GA1UEChMHQWNtZSBDbzEZMBcGA1UE -AxMQdGVzdC5leGFtcGxlLmNvbTAeFw03MDAxMDEwMDE2NDBaFw03MDAxMDIwMzQ2NDBaMC0xEDAO -BgNVBAoTB0FjbWUgQ28xGTAXBgNVBAMTEHRlc3QuZXhhbXBsZS5jb20wWjALBgkqhkiG9w0BAQED -SwAwSAJBALKZD0nEffqM1ACuak0bijtqE2QrI/KLADv7l3kK3ppMyCuLKoF0fd7Ai2KW5ToIwzFo -fvJcS/STa6HA5gQenRUCAwEAAaOBnjCBmzAOBgNVHQ8BAf8EBAMCAAQwDwYDVR0TAQH/BAUwAwEB -/zANBgNVHQ4EBgQEAQIDBDAPBgNVHSMECDAGgAQBAgMEMBsGA1UdEQQUMBKCEHRlc3QuZXhhbXBs -ZS5jb20wDwYDVR0gBAgwBjAEBgIqAzAqBgNVHR4EIzAhoB8wDoIMLmV4YW1wbGUuY29tMA2CC2V4 -YW1wbGUuY29tMAsGCSqGSIb3DQEBBQNBAHKZKoS1wEQOGhgklx4+/yFYQlnqwKXvar/ZecQvJwui -0seMQnwBhwdBkHfVIU2Fu5VUMRyxlf0ZNaDXcpU581k= ------END CERTIFICATE-----` - -func TestCRLCreation(t *testing.T) { - block, _ := pem.Decode([]byte(pemPrivateKey)) - priv, _ := ParsePKCS1PrivateKey(block.Bytes) - block, _ = pem.Decode([]byte(pemCertificate)) - cert, _ := ParseCertificate(block.Bytes) - - now := time.Unix(1000, 0) - expiry := time.Unix(10000, 0) - - revokedCerts := []pkix.RevokedCertificate{ - { - SerialNumber: big.NewInt(1), - RevocationTime: now, - }, - { - SerialNumber: big.NewInt(42), - RevocationTime: now, - }, - } - - crlBytes, err := cert.CreateCRL(rand.Reader, priv, revokedCerts, now, expiry) - if err != nil { - t.Errorf("error creating CRL: %s", err) - } - - _, err = ParseDERCRL(crlBytes) - if err != nil { - t.Errorf("error reparsing CRL: %s", err) - } -} - -func fromBase64(in string) []byte { - out := make([]byte, base64.StdEncoding.DecodedLen(len(in))) - n, err := base64.StdEncoding.Decode(out, []byte(in)) - if err != nil { - panic("failed to base64 decode") - } - return out[:n] -} - -func TestParseDERCRL(t *testing.T) { - derBytes := fromBase64(derCRLBase64) - certList, err := ParseDERCRL(derBytes) - if err != nil { - t.Errorf("error parsing: %s", err) - return - } - numCerts := len(certList.TBSCertList.RevokedCertificates) - expected := 88 - if numCerts != expected { - t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected) - } - - if certList.HasExpired(time.Unix(1302517272, 0)) { - t.Errorf("CRL has expired (but shouldn't have)") - } - - // Can't check the signature here without a package cycle. -} - -func TestParsePEMCRL(t *testing.T) { - pemBytes := fromBase64(pemCRLBase64) - certList, err := ParseCRL(pemBytes) - if err != nil { - t.Errorf("error parsing: %s", err) - return - } - numCerts := len(certList.TBSCertList.RevokedCertificates) - expected := 2 - if numCerts != expected { - t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected) - } - - if certList.HasExpired(time.Unix(1302517272, 0)) { - t.Errorf("CRL has expired (but shouldn't have)") - } - - // Can't check the signature here without a package cycle. -} - -func TestImports(t *testing.T) { - switch runtime.GOOS { - case "android", "nacl": - t.Skipf("skipping on %s", runtime.GOOS) - } - - if err := exec.Command("go", "run", "x509_test_import.go").Run(); err != nil { - t.Errorf("failed to run x509_test_import.go: %s", err) - } -} - -const derCRLBase64 = "MIINqzCCDJMCAQEwDQYJKoZIhvcNAQEFBQAwVjEZMBcGA1UEAxMQUEtJIEZJTk1FQ0NBTklDQTEVMBMGA1UEChMMRklOTUVDQ0FOSUNBMRUwEwYDVQQLEwxGSU5NRUNDQU5JQ0ExCzAJBgNVBAYTAklUFw0xMTA1MDQxNjU3NDJaFw0xMTA1MDQyMDU3NDJaMIIMBzAhAg4Ze1od49Lt1qIXBydAzhcNMDkwNzE2MDg0MzIyWjAAMCECDl0HSL9bcZ1Ci/UHJ0DPFw0wOTA3MTYwODQzMTNaMAAwIQIOESB9tVAmX3cY7QcnQNAXDTA5MDcxNjA4NDUyMlowADAhAg4S1tGAQ3mHt8uVBydA1RcNMDkwODA0MTUyNTIyWjAAMCECDlQ249Y7vtC25ScHJ0DWFw0wOTA4MDQxNTI1MzdaMAAwIQIOISMop3NkA4PfYwcnQNkXDTA5MDgwNDExMDAzNFowADAhAg56/BMoS29KEShTBydA2hcNMDkwODA0MTEwMTAzWjAAMCECDnBp/22HPH5CSWoHJ0DbFw0wOTA4MDQxMDU0NDlaMAAwIQIOV9IP+8CD8bK+XAcnQNwXDTA5MDgwNDEwNTcxN1owADAhAg4v5aRz0IxWqYiXBydA3RcNMDkwODA0MTA1NzQ1WjAAMCECDlOU34VzvZAybQwHJ0DeFw0wOTA4MDQxMDU4MjFaMAAwIAINO4CD9lluIxcwBydBAxcNMDkwNzIyMTUzMTU5WjAAMCECDgOllfO8Y1QA7/wHJ0ExFw0wOTA3MjQxMTQxNDNaMAAwIQIOJBX7jbiCdRdyjgcnQUQXDTA5MDkxNjA5MzAwOFowADAhAg5iYSAgmDrlH/RZBydBRRcNMDkwOTE2MDkzMDE3WjAAMCECDmu6k6srP3jcMaQHJ0FRFw0wOTA4MDQxMDU2NDBaMAAwIQIOX8aHlO0V+WVH4QcnQVMXDTA5MDgwNDEwNTcyOVowADAhAg5flK2rg3NnsRgDBydBzhcNMTEwMjAxMTUzMzQ2WjAAMCECDg35yJDL1jOPTgoHJ0HPFw0xMTAyMDExNTM0MjZaMAAwIQIOMyFJ6+e9iiGVBQcnQdAXDTA5MDkxODEzMjAwNVowADAhAg5Emb/Oykucmn8fBydB1xcNMDkwOTIxMTAxMDQ3WjAAMCECDjQKCncV+MnUavMHJ0HaFw0wOTA5MjIwODE1MjZaMAAwIQIOaxiFUt3dpd+tPwcnQfQXDTEwMDYxODA4NDI1MVowADAhAg5G7P8nO0tkrMt7BydB9RcNMTAwNjE4MDg0MjMwWjAAMCECDmTCC3SXhmDRst4HJ0H2Fw0wOTA5MjgxMjA3MjBaMAAwIQIOHoGhUr/pRwzTKgcnQfcXDTA5MDkyODEyMDcyNFowADAhAg50wrcrCiw8mQmPBydCBBcNMTAwMjE2MTMwMTA2WjAAMCECDifWmkvwyhEqwEcHJ0IFFw0xMDAyMTYxMzAxMjBaMAAwIQIOfgPmlW9fg+osNgcnQhwXDTEwMDQxMzA5NTIwMFowADAhAg4YHAGuA6LgCk7tBydCHRcNMTAwNDEzMDk1MTM4WjAAMCECDi1zH1bxkNJhokAHJ0IsFw0xMDA0MTMwOTU5MzBaMAAwIQIOMipNccsb/wo2fwcnQi0XDTEwMDQxMzA5NTkwMFowADAhAg46lCmvPl4GpP6ABydCShcNMTAwMTE5MDk1MjE3WjAAMCECDjaTcaj+wBpcGAsHJ0JLFw0xMDAxMTkwOTUyMzRaMAAwIQIOOMC13EOrBuxIOQcnQloXDTEwMDIwMTA5NDcwNVowADAhAg5KmZl+krz4RsmrBydCWxcNMTAwMjAxMDk0NjQwWjAAMCECDmLG3zQJ/fzdSsUHJ0JiFw0xMDAzMDEwOTUxNDBaMAAwIQIOP39ksgHdojf4owcnQmMXDTEwMDMwMTA5NTExN1owADAhAg4LDQzvWNRlD6v9BydCZBcNMTAwMzAxMDk0NjIyWjAAMCECDkmNfeclaFhIaaUHJ0JlFw0xMDAzMDEwOTQ2MDVaMAAwIQIOT/qWWfpH/m8NTwcnQpQXDTEwMDUxMTA5MTgyMVowADAhAg5m/ksYxvCEgJSvBydClRcNMTAwNTExMDkxODAxWjAAMCECDgvf3Ohq6JOPU9AHJ0KWFw0xMDA1MTEwOTIxMjNaMAAwIQIOKSPas10z4jNVIQcnQpcXDTEwMDUxMTA5MjEwMlowADAhAg4mCWmhoZ3lyKCDBydCohcNMTEwNDI4MTEwMjI1WjAAMCECDkeiyRsBMK0Gvr4HJ0KjFw0xMTA0MjgxMTAyMDdaMAAwIQIOa09b/nH2+55SSwcnQq4XDTExMDQwMTA4Mjk0NlowADAhAg5O7M7iq7gGplr1BydCrxcNMTEwNDAxMDgzMDE3WjAAMCECDjlT6mJxUjTvyogHJ0K1Fw0xMTAxMjcxNTQ4NTJaMAAwIQIODS/l4UUFLe21NAcnQrYXDTExMDEyNzE1NDgyOFowADAhAg5lPRA0XdOUF6lSBydDHhcNMTEwMTI4MTQzNTA1WjAAMCECDixKX4fFGGpENwgHJ0MfFw0xMTAxMjgxNDM1MzBaMAAwIQIORNBkqsPnpKTtbAcnQ08XDTEwMDkwOTA4NDg0MlowADAhAg5QL+EMM3lohedEBydDUBcNMTAwOTA5MDg0ODE5WjAAMCECDlhDnHK+HiTRAXcHJ0NUFw0xMDEwMTkxNjIxNDBaMAAwIQIOdBFqAzq/INz53gcnQ1UXDTEwMTAxOTE2MjA0NFowADAhAg4OjR7s8MgKles1BydDWhcNMTEwMTI3MTY1MzM2WjAAMCECDmfR/elHee+d0SoHJ0NbFw0xMTAxMjcxNjUzNTZaMAAwIQIOBTKv2ui+KFMI+wcnQ5YXDTEwMDkxNTEwMjE1N1owADAhAg49F3c/GSah+oRUBydDmxcNMTEwMTI3MTczMjMzWjAAMCECDggv4I61WwpKFMMHJ0OcFw0xMTAxMjcxNzMyNTVaMAAwIQIOXx/Y8sEvwS10LAcnQ6UXDTExMDEyODExMjkzN1owADAhAg5LSLbnVrSKaw/9BydDphcNMTEwMTI4MTEyOTIwWjAAMCECDmFFoCuhKUeACQQHJ0PfFw0xMTAxMTExMDE3MzdaMAAwIQIOQTDdFh2fSPF6AAcnQ+AXDTExMDExMTEwMTcxMFowADAhAg5B8AOXX61FpvbbBydD5RcNMTAxMDA2MTAxNDM2WjAAMCECDh41P2Gmi7PkwI4HJ0PmFw0xMDEwMDYxMDE2MjVaMAAwIQIOWUHGLQCd+Ale9gcnQ/0XDTExMDUwMjA3NTYxMFowADAhAg5Z2c9AYkikmgWOBydD/hcNMTEwNTAyMDc1NjM0WjAAMCECDmf/UD+/h8nf+74HJ0QVFw0xMTA0MTUwNzI4MzNaMAAwIQIOICvj4epy3MrqfwcnRBYXDTExMDQxNTA3Mjg1NlowADAhAg4bouRMfOYqgv4xBydEHxcNMTEwMzA4MTYyNDI1WjAAMCECDhebWHGoKiTp7pEHJ0QgFw0xMTAzMDgxNjI0NDhaMAAwIQIOX+qnxxAqJ8LtawcnRDcXDTExMDEzMTE1MTIyOFowADAhAg4j0fICqZ+wkOdqBydEOBcNMTEwMTMxMTUxMTQxWjAAMCECDhmXjsV4SUpWtAMHJ0RLFw0xMTAxMjgxMTI0MTJaMAAwIQIODno/w+zG43kkTwcnREwXDTExMDEyODExMjM1MlowADAhAg4b1gc88767Fr+LBydETxcNMTEwMTI4MTEwMjA4WjAAMCECDn+M3Pa1w2nyFeUHJ0RQFw0xMTAxMjgxMDU4NDVaMAAwIQIOaduoyIH61tqybAcnRJUXDTEwMTIxNTA5NDMyMlowADAhAg4nLqQPkyi3ESAKBydElhcNMTAxMjE1MDk0MzM2WjAAMCECDi504NIMH8578gQHJ0SbFw0xMTAyMTQxNDA1NDFaMAAwIQIOGuaM8PDaC5u1egcnRJwXDTExMDIxNDE0MDYwNFowADAhAg4ehYq/BXGnB5PWBydEnxcNMTEwMjA0MDgwOTUxWjAAMCECDkSD4eS4FxW5H20HJ0SgFw0xMTAyMDQwODA5MjVaMAAwIQIOOCcb6ilYObt1egcnRKEXDTExMDEyNjEwNDEyOVowADAhAg58tISWCCwFnKGnBydEohcNMTEwMjA0MDgxMzQyWjAAMCECDn5rjtabY/L/WL0HJ0TJFw0xMTAyMDQxMTAzNDFaMAAwDQYJKoZIhvcNAQEFBQADggEBAGnF2Gs0+LNiYCW1Ipm83OXQYP/bd5tFFRzyz3iepFqNfYs4D68/QihjFoRHQoXEB0OEe1tvaVnnPGnEOpi6krwekquMxo4H88B5SlyiFIqemCOIss0SxlCFs69LmfRYvPPvPEhoXtQ3ZThe0UvKG83GOklhvGl6OaiRf4Mt+m8zOT4Wox/j6aOBK6cw6qKCdmD+Yj1rrNqFGg1CnSWMoD6S6mwNgkzwdBUJZ22BwrzAAo4RHa2Uy3ef1FjwD0XtU5N3uDSxGGBEDvOe5z82rps3E22FpAA8eYl8kaXtmWqyvYU0epp4brGuTxCuBMCAsxt/OjIjeNNQbBGkwxgfYA0=" - -const pemCRLBase64 = "LS0tLS1CRUdJTiBYNTA5IENSTC0tLS0tDQpNSUlCOWpDQ0FWOENBUUV3RFFZSktvWklodmNOQVFFRkJRQXdiREVhTUJnR0ExVUVDaE1SVWxOQklGTmxZM1Z5DQphWFI1SUVsdVl5NHhIakFjQmdOVkJBTVRGVkpUUVNCUWRXSnNhV01nVW05dmRDQkRRU0IyTVRFdU1Dd0dDU3FHDQpTSWIzRFFFSkFSWWZjbk5oYTJWdmJuSnZiM1J6YVdkdVFISnpZWE5sWTNWeWFYUjVMbU52YlJjTk1URXdNakl6DQpNVGt5T0RNd1doY05NVEV3T0RJeU1Ua3lPRE13V2pDQmpEQktBaEVBckRxb2g5RkhKSFhUN09QZ3V1bjQrQmNODQpNRGt4TVRBeU1UUXlOekE1V2pBbU1Bb0dBMVVkRlFRRENnRUpNQmdHQTFVZEdBUVJHQTh5TURBNU1URXdNakUwDQpNalExTlZvd1BnSVJBTEd6blowOTVQQjVhQU9MUGc1N2ZNTVhEVEF5TVRBeU16RTBOVEF4TkZvd0dqQVlCZ05WDQpIUmdFRVJnUE1qQXdNakV3TWpNeE5EVXdNVFJhb0RBd0xqQWZCZ05WSFNNRUdEQVdnQlQxVERGNlVRTS9MTmVMDQpsNWx2cUhHUXEzZzltekFMQmdOVkhSUUVCQUlDQUlRd0RRWUpLb1pJaHZjTkFRRUZCUUFEZ1lFQUZVNUFzNk16DQpxNVBSc2lmYW9iUVBHaDFhSkx5QytNczVBZ2MwYld5QTNHQWR4dXI1U3BQWmVSV0NCamlQL01FSEJXSkNsQkhQDQpHUmNxNXlJZDNFakRrYUV5eFJhK2k2N0x6dmhJNmMyOUVlNks5cFNZd2ppLzdSVWhtbW5Qclh0VHhsTDBsckxyDQptUVFKNnhoRFJhNUczUUE0Q21VZHNITnZicnpnbUNZcHZWRT0NCi0tLS0tRU5EIFg1MDkgQ1JMLS0tLS0NCg0K" - -func TestCreateCertificateRequest(t *testing.T) { - random := rand.Reader - - block, _ := pem.Decode([]byte(pemPrivateKey)) - rsaPriv, err := ParsePKCS1PrivateKey(block.Bytes) - if err != nil { - t.Fatalf("Failed to parse private key: %s", err) - } - - ecdsa256Priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) - if err != nil { - t.Fatalf("Failed to generate ECDSA key: %s", err) - } - - ecdsa384Priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) - if err != nil { - t.Fatalf("Failed to generate ECDSA key: %s", err) - } - - ecdsa521Priv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) - if err != nil { - t.Fatalf("Failed to generate ECDSA key: %s", err) - } - - tests := []struct { - name string - priv interface{} - sigAlgo SignatureAlgorithm - }{ - {"RSA", rsaPriv, SHA1WithRSA}, - {"ECDSA-256", ecdsa256Priv, ECDSAWithSHA1}, - {"ECDSA-384", ecdsa384Priv, ECDSAWithSHA1}, - {"ECDSA-521", ecdsa521Priv, ECDSAWithSHA1}, - } - - for _, test := range tests { - template := CertificateRequest{ - Subject: pkix.Name{ - CommonName: "test.example.com", - Organization: []string{"Σ Acme Co"}, - }, - SignatureAlgorithm: test.sigAlgo, - DNSNames: []string{"test.example.com"}, - EmailAddresses: []string{"gopher@golang.org"}, - IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")}, - } - - derBytes, err := CreateCertificateRequest(random, &template, test.priv) - if err != nil { - t.Errorf("%s: failed to create certificate request: %s", test.name, err) - continue - } - - out, err := ParseCertificateRequest(derBytes) - if err != nil { - t.Errorf("%s: failed to create certificate request: %s", test.name, err) - continue - } - - if out.Subject.CommonName != template.Subject.CommonName { - t.Errorf("%s: output subject common name and template subject common name don't match", test.name) - } else if len(out.Subject.Organization) != len(template.Subject.Organization) { - t.Errorf("%s: output subject organisation and template subject organisation don't match", test.name) - } else if len(out.DNSNames) != len(template.DNSNames) { - t.Errorf("%s: output DNS names and template DNS names don't match", test.name) - } else if len(out.EmailAddresses) != len(template.EmailAddresses) { - t.Errorf("%s: output email addresses and template email addresses don't match", test.name) - } else if len(out.IPAddresses) != len(template.IPAddresses) { - t.Errorf("%s: output IP addresses and template IP addresses names don't match", test.name) - } - } -} - -func marshalAndParseCSR(t *testing.T, template *CertificateRequest) *CertificateRequest { - block, _ := pem.Decode([]byte(pemPrivateKey)) - rsaPriv, err := ParsePKCS1PrivateKey(block.Bytes) - if err != nil { - t.Fatal(err) - } - - derBytes, err := CreateCertificateRequest(rand.Reader, template, rsaPriv) - if err != nil { - t.Fatal(err) - } - - csr, err := ParseCertificateRequest(derBytes) - if err != nil { - t.Fatal(err) - } - - return csr -} - -func TestCertificateRequestOverrides(t *testing.T) { - sanContents, err := marshalSANs([]string{"foo.example.com"}, nil, nil) - if err != nil { - t.Fatal(err) - } - - template := CertificateRequest{ - Subject: pkix.Name{ - CommonName: "test.example.com", - Organization: []string{"Σ Acme Co"}, - }, - DNSNames: []string{"test.example.com"}, - - // An explicit extension should override the DNSNames from the - // template. - ExtraExtensions: []pkix.Extension{ - { - Id: oidExtensionSubjectAltName, - Value: sanContents, - }, - }, - } - - csr := marshalAndParseCSR(t, &template) - - if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "foo.example.com" { - t.Errorf("Extension did not override template. Got %v\n", csr.DNSNames) - } - - // If there is already an attribute with X.509 extensions then the - // extra extensions should be added to it rather than creating a CSR - // with two extension attributes. - - template.Attributes = []pkix.AttributeTypeAndValueSET{ - { - Type: oidExtensionRequest, - Value: [][]pkix.AttributeTypeAndValue{ - { - { - Type: oidExtensionAuthorityInfoAccess, - Value: []byte("foo"), - }, - }, - }, - }, - } - - csr = marshalAndParseCSR(t, &template) - if l := len(csr.Attributes); l != 1 { - t.Errorf("incorrect number of attributes: %d\n", l) - } - - if !csr.Attributes[0].Type.Equal(oidExtensionRequest) || - len(csr.Attributes[0].Value) != 1 || - len(csr.Attributes[0].Value[0]) != 2 { - t.Errorf("bad attributes: %#v\n", csr.Attributes) - } - - sanContents2, err := marshalSANs([]string{"foo2.example.com"}, nil, nil) - if err != nil { - t.Fatal(err) - } - - // Extensions in Attributes should override those in ExtraExtensions. - template.Attributes[0].Value[0] = append(template.Attributes[0].Value[0], pkix.AttributeTypeAndValue{ - Type: oidExtensionSubjectAltName, - Value: sanContents2, - }) - - csr = marshalAndParseCSR(t, &template) - - if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "foo2.example.com" { - t.Errorf("Attributes did not override ExtraExtensions. Got %v\n", csr.DNSNames) - } -} - -func TestParseCertificateRequest(t *testing.T) { - csrBytes := fromBase64(csrBase64) - csr, err := ParseCertificateRequest(csrBytes) - if err != nil { - t.Fatalf("failed to parse CSR: %s", err) - } - - if len(csr.EmailAddresses) != 1 || csr.EmailAddresses[0] != "gopher@golang.org" { - t.Errorf("incorrect email addresses found: %v", csr.EmailAddresses) - } - - if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "test.example.com" { - t.Errorf("incorrect DNS names found: %v", csr.DNSNames) - } - - if len(csr.Subject.Country) != 1 || csr.Subject.Country[0] != "AU" { - t.Errorf("incorrect Subject name: %v", csr.Subject) - } - - found := false - for _, e := range csr.Extensions { - if e.Id.Equal(oidExtensionBasicConstraints) { - found = true - break - } - } - if !found { - t.Errorf("basic constraints extension not found in CSR") - } -} - -// This CSR was generated with OpenSSL: -// openssl req -out CSR.csr -new -newkey rsa:2048 -nodes -keyout privateKey.key -config openssl.cnf -// -// The openssl.cnf needs to include this section: -// [ v3_req ] -// basicConstraints = CA:FALSE -// keyUsage = nonRepudiation, digitalSignature, keyEncipherment -// subjectAltName = email:gopher@golang.org,DNS:test.example.com -const csrBase64 = "MIIC4zCCAcsCAQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOY+MVedRg2JEnyeLcSzcsMv2VcsTfkB5+Etd6hihAh6MrGezNyASMMKuQN6YhCX1icQDiQtGsDLTtheNnSXK06tAhHjAP/hGlszRJp+5+rP2M58fDBAkUBEhskbCUWwpY14jFtVuGNJ8vF8h8IeczdolvQhX9lVai9G0EUXJMliMKdjA899H0mRs9PzHyidyrXFNiZlQXfD8Kg7gETn2Ny965iyI6ujAIYSCvam6TnxRHYH2MBKyVGvsYGbPYUQJCsgdgyajEg6ekihvQY3SzO1HSAlZAd7d1QYO4VeWJ2mY6Wu3Jpmh+AmG19S9CcHqGjd0bhuAX9cpPOKgnEmqn0CAwEAAaBZMFcGCSqGSIb3DQEJDjFKMEgwCQYDVR0TBAIwADALBgNVHQ8EBAMCBeAwLgYDVR0RBCcwJYERZ29waGVyQGdvbGFuZy5vcmeCEHRlc3QuZXhhbXBsZS5jb20wDQYJKoZIhvcNAQEFBQADggEBAC9+QpKfdabxwCWwf4IEe1cKjdXLS1ScSuw27a3kZzQiPV78WJMa6dB8dqhdH5BRwGZ/qsgLrO6ZHlNeIv2Ib41Ccq71ecHW/nXc94A1BzJ/bVdI9LZcmTUvR1/m1jCpN7UqQ0ml1u9VihK7Pe762hEYxuWDQzYEU0l15S/bXmqeq3eF1A59XT/2jwe5+NV0Wwf4UQlkTXsAQMsJ+KzrQafd8Qv2A49o048uRvmjeJDrXLawGVianZ7D5A6Fpd1rZh6XcjqBpmgLw41DRQWENOdzhy+HyphKRv1MlY8OLkNqpGMhu8DdgJVGoT16DGiickoEa7Z3UCPVNgdTkT9jq7U=" diff --git a/src/pkg/crypto/x509/x509_test_import.go b/src/pkg/crypto/x509/x509_test_import.go deleted file mode 100644 index 3fda7da18..000000000 --- a/src/pkg/crypto/x509/x509_test_import.go +++ /dev/null @@ -1,53 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -// This file is run by the x509 tests to ensure that a program with minimal -// imports can sign certificates without errors resulting from missing hash -// functions. -package main - -import ( - "crypto/rand" - "crypto/x509" - "crypto/x509/pkix" - "encoding/pem" - "math/big" - "time" -) - -func main() { - block, _ := pem.Decode([]byte(pemPrivateKey)) - rsaPriv, err := x509.ParsePKCS1PrivateKey(block.Bytes) - if err != nil { - panic("Failed to parse private key: " + err.Error()) - } - - template := x509.Certificate{ - SerialNumber: big.NewInt(1), - Subject: pkix.Name{ - CommonName: "test", - Organization: []string{"Σ Acme Co"}, - }, - NotBefore: time.Unix(1000, 0), - NotAfter: time.Unix(100000, 0), - KeyUsage: x509.KeyUsageCertSign, - } - - if _, err = x509.CreateCertificate(rand.Reader, &template, &template, &rsaPriv.PublicKey, rsaPriv); err != nil { - panic("failed to create certificate with basic imports: " + err.Error()) - } -} - -var pemPrivateKey = `-----BEGIN RSA PRIVATE KEY----- -MIIBOgIBAAJBALKZD0nEffqM1ACuak0bijtqE2QrI/KLADv7l3kK3ppMyCuLKoF0 -fd7Ai2KW5ToIwzFofvJcS/STa6HA5gQenRUCAwEAAQJBAIq9amn00aS0h/CrjXqu -/ThglAXJmZhOMPVn4eiu7/ROixi9sex436MaVeMqSNf7Ex9a8fRNfWss7Sqd9eWu -RTUCIQDasvGASLqmjeffBNLTXV2A5g4t+kLVCpsEIZAycV5GswIhANEPLmax0ME/ -EO+ZJ79TJKN5yiGBRsv5yvx5UiHxajEXAiAhAol5N4EUyq6I9w1rYdhPMGpLfk7A -IU2snfRJ6Nq2CQIgFrPsWRCkV+gOYcajD17rEqmuLrdIRexpg8N1DOSXoJ8CIGlS -tAboUGBxTDq3ZroNism3DaMIbKPyYrAqhKov1h5V ------END RSA PRIVATE KEY----- -` diff --git a/src/pkg/database/sql/convert.go b/src/pkg/database/sql/convert.go deleted file mode 100644 index c0b38a249..000000000 --- a/src/pkg/database/sql/convert.go +++ /dev/null @@ -1,299 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Type conversions for Scan. - -package sql - -import ( - "database/sql/driver" - "errors" - "fmt" - "reflect" - "strconv" -) - -var errNilPtr = errors.New("destination pointer is nil") // embedded in descriptive error - -// driverArgs converts arguments from callers of Stmt.Exec and -// Stmt.Query into driver Values. -// -// The statement ds may be nil, if no statement is available. -func driverArgs(ds *driverStmt, args []interface{}) ([]driver.Value, error) { - dargs := make([]driver.Value, len(args)) - var si driver.Stmt - if ds != nil { - si = ds.si - } - cc, ok := si.(driver.ColumnConverter) - - // Normal path, for a driver.Stmt that is not a ColumnConverter. - if !ok { - for n, arg := range args { - var err error - dargs[n], err = driver.DefaultParameterConverter.ConvertValue(arg) - if err != nil { - return nil, fmt.Errorf("sql: converting Exec argument #%d's type: %v", n, err) - } - } - return dargs, nil - } - - // Let the Stmt convert its own arguments. - for n, arg := range args { - // First, see if the value itself knows how to convert - // itself to a driver type. For example, a NullString - // struct changing into a string or nil. - if svi, ok := arg.(driver.Valuer); ok { - sv, err := svi.Value() - if err != nil { - return nil, fmt.Errorf("sql: argument index %d from Value: %v", n, err) - } - if !driver.IsValue(sv) { - return nil, fmt.Errorf("sql: argument index %d: non-subset type %T returned from Value", n, sv) - } - arg = sv - } - - // Second, ask the column to sanity check itself. For - // example, drivers might use this to make sure that - // an int64 values being inserted into a 16-bit - // integer field is in range (before getting - // truncated), or that a nil can't go into a NOT NULL - // column before going across the network to get the - // same error. - var err error - ds.Lock() - dargs[n], err = cc.ColumnConverter(n).ConvertValue(arg) - ds.Unlock() - if err != nil { - return nil, fmt.Errorf("sql: converting argument #%d's type: %v", n, err) - } - if !driver.IsValue(dargs[n]) { - return nil, fmt.Errorf("sql: driver ColumnConverter error converted %T to unsupported type %T", - arg, dargs[n]) - } - } - - return dargs, nil -} - -// convertAssign copies to dest the value in src, converting it if possible. -// An error is returned if the copy would result in loss of information. -// dest should be a pointer type. -func convertAssign(dest, src interface{}) error { - // Common cases, without reflect. - switch s := src.(type) { - case string: - switch d := dest.(type) { - case *string: - if d == nil { - return errNilPtr - } - *d = s - return nil - case *[]byte: - if d == nil { - return errNilPtr - } - *d = []byte(s) - return nil - } - case []byte: - switch d := dest.(type) { - case *string: - if d == nil { - return errNilPtr - } - *d = string(s) - return nil - case *interface{}: - if d == nil { - return errNilPtr - } - *d = cloneBytes(s) - return nil - case *[]byte: - if d == nil { - return errNilPtr - } - *d = cloneBytes(s) - return nil - case *RawBytes: - if d == nil { - return errNilPtr - } - *d = s - return nil - } - case nil: - switch d := dest.(type) { - case *interface{}: - if d == nil { - return errNilPtr - } - *d = nil - return nil - case *[]byte: - if d == nil { - return errNilPtr - } - *d = nil - return nil - case *RawBytes: - if d == nil { - return errNilPtr - } - *d = nil - return nil - } - } - - var sv reflect.Value - - switch d := dest.(type) { - case *string: - sv = reflect.ValueOf(src) - switch sv.Kind() { - case reflect.Bool, - reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, - reflect.Float32, reflect.Float64: - *d = asString(src) - return nil - } - case *[]byte: - sv = reflect.ValueOf(src) - if b, ok := asBytes(nil, sv); ok { - *d = b - return nil - } - case *RawBytes: - sv = reflect.ValueOf(src) - if b, ok := asBytes([]byte(*d)[:0], sv); ok { - *d = RawBytes(b) - return nil - } - case *bool: - bv, err := driver.Bool.ConvertValue(src) - if err == nil { - *d = bv.(bool) - } - return err - case *interface{}: - *d = src - return nil - } - - if scanner, ok := dest.(Scanner); ok { - return scanner.Scan(src) - } - - dpv := reflect.ValueOf(dest) - if dpv.Kind() != reflect.Ptr { - return errors.New("destination not a pointer") - } - if dpv.IsNil() { - return errNilPtr - } - - if !sv.IsValid() { - sv = reflect.ValueOf(src) - } - - dv := reflect.Indirect(dpv) - if dv.Kind() == sv.Kind() { - dv.Set(sv) - return nil - } - - switch dv.Kind() { - case reflect.Ptr: - if src == nil { - dv.Set(reflect.Zero(dv.Type())) - return nil - } else { - dv.Set(reflect.New(dv.Type().Elem())) - return convertAssign(dv.Interface(), src) - } - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - s := asString(src) - i64, err := strconv.ParseInt(s, 10, dv.Type().Bits()) - if err != nil { - return fmt.Errorf("converting string %q to a %s: %v", s, dv.Kind(), err) - } - dv.SetInt(i64) - return nil - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - s := asString(src) - u64, err := strconv.ParseUint(s, 10, dv.Type().Bits()) - if err != nil { - return fmt.Errorf("converting string %q to a %s: %v", s, dv.Kind(), err) - } - dv.SetUint(u64) - return nil - case reflect.Float32, reflect.Float64: - s := asString(src) - f64, err := strconv.ParseFloat(s, dv.Type().Bits()) - if err != nil { - return fmt.Errorf("converting string %q to a %s: %v", s, dv.Kind(), err) - } - dv.SetFloat(f64) - return nil - } - - return fmt.Errorf("unsupported driver -> Scan pair: %T -> %T", src, dest) -} - -func cloneBytes(b []byte) []byte { - if b == nil { - return nil - } else { - c := make([]byte, len(b)) - copy(c, b) - return c - } -} - -func asString(src interface{}) string { - switch v := src.(type) { - case string: - return v - case []byte: - return string(v) - } - rv := reflect.ValueOf(src) - switch rv.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return strconv.FormatInt(rv.Int(), 10) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return strconv.FormatUint(rv.Uint(), 10) - case reflect.Float64: - return strconv.FormatFloat(rv.Float(), 'g', -1, 64) - case reflect.Float32: - return strconv.FormatFloat(rv.Float(), 'g', -1, 32) - case reflect.Bool: - return strconv.FormatBool(rv.Bool()) - } - return fmt.Sprintf("%v", src) -} - -func asBytes(buf []byte, rv reflect.Value) (b []byte, ok bool) { - switch rv.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return strconv.AppendInt(buf, rv.Int(), 10), true - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - return strconv.AppendUint(buf, rv.Uint(), 10), true - case reflect.Float32: - return strconv.AppendFloat(buf, rv.Float(), 'g', -1, 32), true - case reflect.Float64: - return strconv.AppendFloat(buf, rv.Float(), 'g', -1, 64), true - case reflect.Bool: - return strconv.AppendBool(buf, rv.Bool()), true - case reflect.String: - s := rv.String() - return append(buf, s...), true - } - return -} diff --git a/src/pkg/database/sql/convert_test.go b/src/pkg/database/sql/convert_test.go deleted file mode 100644 index 98af9fb64..000000000 --- a/src/pkg/database/sql/convert_test.go +++ /dev/null @@ -1,348 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package sql - -import ( - "database/sql/driver" - "fmt" - "reflect" - "runtime" - "testing" - "time" -) - -var someTime = time.Unix(123, 0) -var answer int64 = 42 - -type conversionTest struct { - s, d interface{} // source and destination - - // following are used if they're non-zero - wantint int64 - wantuint uint64 - wantstr string - wantbytes []byte - wantraw RawBytes - wantf32 float32 - wantf64 float64 - wanttime time.Time - wantbool bool // used if d is of type *bool - wanterr string - wantiface interface{} - wantptr *int64 // if non-nil, *d's pointed value must be equal to *wantptr - wantnil bool // if true, *d must be *int64(nil) -} - -// Target variables for scanning into. -var ( - scanstr string - scanbytes []byte - scanraw RawBytes - scanint int - scanint8 int8 - scanint16 int16 - scanint32 int32 - scanuint8 uint8 - scanuint16 uint16 - scanbool bool - scanf32 float32 - scanf64 float64 - scantime time.Time - scanptr *int64 - scaniface interface{} -) - -var conversionTests = []conversionTest{ - // Exact conversions (destination pointer type matches source type) - {s: "foo", d: &scanstr, wantstr: "foo"}, - {s: 123, d: &scanint, wantint: 123}, - {s: someTime, d: &scantime, wanttime: someTime}, - - // To strings - {s: "string", d: &scanstr, wantstr: "string"}, - {s: []byte("byteslice"), d: &scanstr, wantstr: "byteslice"}, - {s: 123, d: &scanstr, wantstr: "123"}, - {s: int8(123), d: &scanstr, wantstr: "123"}, - {s: int64(123), d: &scanstr, wantstr: "123"}, - {s: uint8(123), d: &scanstr, wantstr: "123"}, - {s: uint16(123), d: &scanstr, wantstr: "123"}, - {s: uint32(123), d: &scanstr, wantstr: "123"}, - {s: uint64(123), d: &scanstr, wantstr: "123"}, - {s: 1.5, d: &scanstr, wantstr: "1.5"}, - - // To []byte - {s: nil, d: &scanbytes, wantbytes: nil}, - {s: "string", d: &scanbytes, wantbytes: []byte("string")}, - {s: []byte("byteslice"), d: &scanbytes, wantbytes: []byte("byteslice")}, - {s: 123, d: &scanbytes, wantbytes: []byte("123")}, - {s: int8(123), d: &scanbytes, wantbytes: []byte("123")}, - {s: int64(123), d: &scanbytes, wantbytes: []byte("123")}, - {s: uint8(123), d: &scanbytes, wantbytes: []byte("123")}, - {s: uint16(123), d: &scanbytes, wantbytes: []byte("123")}, - {s: uint32(123), d: &scanbytes, wantbytes: []byte("123")}, - {s: uint64(123), d: &scanbytes, wantbytes: []byte("123")}, - {s: 1.5, d: &scanbytes, wantbytes: []byte("1.5")}, - - // To RawBytes - {s: nil, d: &scanraw, wantraw: nil}, - {s: []byte("byteslice"), d: &scanraw, wantraw: RawBytes("byteslice")}, - {s: 123, d: &scanraw, wantraw: RawBytes("123")}, - {s: int8(123), d: &scanraw, wantraw: RawBytes("123")}, - {s: int64(123), d: &scanraw, wantraw: RawBytes("123")}, - {s: uint8(123), d: &scanraw, wantraw: RawBytes("123")}, - {s: uint16(123), d: &scanraw, wantraw: RawBytes("123")}, - {s: uint32(123), d: &scanraw, wantraw: RawBytes("123")}, - {s: uint64(123), d: &scanraw, wantraw: RawBytes("123")}, - {s: 1.5, d: &scanraw, wantraw: RawBytes("1.5")}, - - // Strings to integers - {s: "255", d: &scanuint8, wantuint: 255}, - {s: "256", d: &scanuint8, wanterr: `converting string "256" to a uint8: strconv.ParseUint: parsing "256": value out of range`}, - {s: "256", d: &scanuint16, wantuint: 256}, - {s: "-1", d: &scanint, wantint: -1}, - {s: "foo", d: &scanint, wanterr: `converting string "foo" to a int: strconv.ParseInt: parsing "foo": invalid syntax`}, - - // True bools - {s: true, d: &scanbool, wantbool: true}, - {s: "True", d: &scanbool, wantbool: true}, - {s: "TRUE", d: &scanbool, wantbool: true}, - {s: "1", d: &scanbool, wantbool: true}, - {s: 1, d: &scanbool, wantbool: true}, - {s: int64(1), d: &scanbool, wantbool: true}, - {s: uint16(1), d: &scanbool, wantbool: true}, - - // False bools - {s: false, d: &scanbool, wantbool: false}, - {s: "false", d: &scanbool, wantbool: false}, - {s: "FALSE", d: &scanbool, wantbool: false}, - {s: "0", d: &scanbool, wantbool: false}, - {s: 0, d: &scanbool, wantbool: false}, - {s: int64(0), d: &scanbool, wantbool: false}, - {s: uint16(0), d: &scanbool, wantbool: false}, - - // Not bools - {s: "yup", d: &scanbool, wanterr: `sql/driver: couldn't convert "yup" into type bool`}, - {s: 2, d: &scanbool, wanterr: `sql/driver: couldn't convert 2 into type bool`}, - - // Floats - {s: float64(1.5), d: &scanf64, wantf64: float64(1.5)}, - {s: int64(1), d: &scanf64, wantf64: float64(1)}, - {s: float64(1.5), d: &scanf32, wantf32: float32(1.5)}, - {s: "1.5", d: &scanf32, wantf32: float32(1.5)}, - {s: "1.5", d: &scanf64, wantf64: float64(1.5)}, - - // Pointers - {s: interface{}(nil), d: &scanptr, wantnil: true}, - {s: int64(42), d: &scanptr, wantptr: &answer}, - - // To interface{} - {s: float64(1.5), d: &scaniface, wantiface: float64(1.5)}, - {s: int64(1), d: &scaniface, wantiface: int64(1)}, - {s: "str", d: &scaniface, wantiface: "str"}, - {s: []byte("byteslice"), d: &scaniface, wantiface: []byte("byteslice")}, - {s: true, d: &scaniface, wantiface: true}, - {s: nil, d: &scaniface}, - {s: []byte(nil), d: &scaniface, wantiface: []byte(nil)}, -} - -func intPtrValue(intptr interface{}) interface{} { - return reflect.Indirect(reflect.Indirect(reflect.ValueOf(intptr))).Int() -} - -func intValue(intptr interface{}) int64 { - return reflect.Indirect(reflect.ValueOf(intptr)).Int() -} - -func uintValue(intptr interface{}) uint64 { - return reflect.Indirect(reflect.ValueOf(intptr)).Uint() -} - -func float64Value(ptr interface{}) float64 { - return *(ptr.(*float64)) -} - -func float32Value(ptr interface{}) float32 { - return *(ptr.(*float32)) -} - -func timeValue(ptr interface{}) time.Time { - return *(ptr.(*time.Time)) -} - -func TestConversions(t *testing.T) { - for n, ct := range conversionTests { - err := convertAssign(ct.d, ct.s) - errstr := "" - if err != nil { - errstr = err.Error() - } - errf := func(format string, args ...interface{}) { - base := fmt.Sprintf("convertAssign #%d: for %v (%T) -> %T, ", n, ct.s, ct.s, ct.d) - t.Errorf(base+format, args...) - } - if errstr != ct.wanterr { - errf("got error %q, want error %q", errstr, ct.wanterr) - } - if ct.wantstr != "" && ct.wantstr != scanstr { - errf("want string %q, got %q", ct.wantstr, scanstr) - } - if ct.wantint != 0 && ct.wantint != intValue(ct.d) { - errf("want int %d, got %d", ct.wantint, intValue(ct.d)) - } - if ct.wantuint != 0 && ct.wantuint != uintValue(ct.d) { - errf("want uint %d, got %d", ct.wantuint, uintValue(ct.d)) - } - if ct.wantf32 != 0 && ct.wantf32 != float32Value(ct.d) { - errf("want float32 %v, got %v", ct.wantf32, float32Value(ct.d)) - } - if ct.wantf64 != 0 && ct.wantf64 != float64Value(ct.d) { - errf("want float32 %v, got %v", ct.wantf64, float64Value(ct.d)) - } - if bp, boolTest := ct.d.(*bool); boolTest && *bp != ct.wantbool && ct.wanterr == "" { - errf("want bool %v, got %v", ct.wantbool, *bp) - } - if !ct.wanttime.IsZero() && !ct.wanttime.Equal(timeValue(ct.d)) { - errf("want time %v, got %v", ct.wanttime, timeValue(ct.d)) - } - if ct.wantnil && *ct.d.(**int64) != nil { - errf("want nil, got %v", intPtrValue(ct.d)) - } - if ct.wantptr != nil { - if *ct.d.(**int64) == nil { - errf("want pointer to %v, got nil", *ct.wantptr) - } else if *ct.wantptr != intPtrValue(ct.d) { - errf("want pointer to %v, got %v", *ct.wantptr, intPtrValue(ct.d)) - } - } - if ifptr, ok := ct.d.(*interface{}); ok { - if !reflect.DeepEqual(ct.wantiface, scaniface) { - errf("want interface %#v, got %#v", ct.wantiface, scaniface) - continue - } - if srcBytes, ok := ct.s.([]byte); ok { - dstBytes := (*ifptr).([]byte) - if len(srcBytes) > 0 && &dstBytes[0] == &srcBytes[0] { - errf("copy into interface{} didn't copy []byte data") - } - } - } - } -} - -func TestNullString(t *testing.T) { - var ns NullString - convertAssign(&ns, []byte("foo")) - if !ns.Valid { - t.Errorf("expecting not null") - } - if ns.String != "foo" { - t.Errorf("expecting foo; got %q", ns.String) - } - convertAssign(&ns, nil) - if ns.Valid { - t.Errorf("expecting null on nil") - } - if ns.String != "" { - t.Errorf("expecting blank on nil; got %q", ns.String) - } -} - -type valueConverterTest struct { - c driver.ValueConverter - in, out interface{} - err string -} - -var valueConverterTests = []valueConverterTest{ - {driver.DefaultParameterConverter, NullString{"hi", true}, "hi", ""}, - {driver.DefaultParameterConverter, NullString{"", false}, nil, ""}, -} - -func TestValueConverters(t *testing.T) { - for i, tt := range valueConverterTests { - out, err := tt.c.ConvertValue(tt.in) - goterr := "" - if err != nil { - goterr = err.Error() - } - if goterr != tt.err { - t.Errorf("test %d: %T(%T(%v)) error = %q; want error = %q", - i, tt.c, tt.in, tt.in, goterr, tt.err) - } - if tt.err != "" { - continue - } - if !reflect.DeepEqual(out, tt.out) { - t.Errorf("test %d: %T(%T(%v)) = %v (%T); want %v (%T)", - i, tt.c, tt.in, tt.in, out, out, tt.out, tt.out) - } - } -} - -// Tests that assigning to RawBytes doesn't allocate (and also works). -func TestRawBytesAllocs(t *testing.T) { - var tests = []struct { - name string - in interface{} - want string - }{ - {"uint64", uint64(12345678), "12345678"}, - {"uint32", uint32(1234), "1234"}, - {"uint16", uint16(12), "12"}, - {"uint8", uint8(1), "1"}, - {"uint", uint(123), "123"}, - {"int", int(123), "123"}, - {"int8", int8(1), "1"}, - {"int16", int16(12), "12"}, - {"int32", int32(1234), "1234"}, - {"int64", int64(12345678), "12345678"}, - {"float32", float32(1.5), "1.5"}, - {"float64", float64(64), "64"}, - {"bool", false, "false"}, - } - - buf := make(RawBytes, 10) - test := func(name string, in interface{}, want string) { - if err := convertAssign(&buf, in); err != nil { - t.Fatalf("%s: convertAssign = %v", name, err) - } - match := len(buf) == len(want) - if match { - for i, b := range buf { - if want[i] != b { - match = false - break - } - } - } - if !match { - t.Fatalf("%s: got %q (len %d); want %q (len %d)", name, buf, len(buf), want, len(want)) - } - } - - n := testing.AllocsPerRun(100, func() { - for _, tt := range tests { - test(tt.name, tt.in, tt.want) - } - }) - - // The numbers below are only valid for 64-bit interface word sizes, - // and gc. With 32-bit words there are more convT2E allocs, and - // with gccgo, only pointers currently go in interface data. - // So only care on amd64 gc for now. - measureAllocs := runtime.GOARCH == "amd64" && runtime.Compiler == "gc" - - if n > 0.5 && measureAllocs { - t.Fatalf("allocs = %v; want 0", n) - } - - // This one involves a convT2E allocation, string -> interface{} - n = testing.AllocsPerRun(100, func() { - test("string", "foo", "foo") - }) - if n > 1.5 && measureAllocs { - t.Fatalf("allocs = %v; want max 1", n) - } -} diff --git a/src/pkg/database/sql/doc.txt b/src/pkg/database/sql/doc.txt deleted file mode 100644 index 405c5ed2a..000000000 --- a/src/pkg/database/sql/doc.txt +++ /dev/null @@ -1,46 +0,0 @@ -Goals of the sql and sql/driver packages: - -* Provide a generic database API for a variety of SQL or SQL-like - databases. There currently exist Go libraries for SQLite, MySQL, - and Postgres, but all with a very different feel, and often - a non-Go-like feel. - -* Feel like Go. - -* Care mostly about the common cases. Common SQL should be portable. - SQL edge cases or db-specific extensions can be detected and - conditionally used by the application. It is a non-goal to care - about every particular db's extension or quirk. - -* Separate out the basic implementation of a database driver - (implementing the sql/driver interfaces) vs the implementation - of all the user-level types and convenience methods. - In a nutshell: - - User Code ---> sql package (concrete types) ---> sql/driver (interfaces) - Database Driver -> sql (to register) + sql/driver (implement interfaces) - -* Make type casting/conversions consistent between all drivers. To - achieve this, most of the conversions are done in the sql package, - not in each driver. The drivers then only have to deal with a - smaller set of types. - -* Be flexible with type conversions, but be paranoid about silent - truncation or other loss of precision. - -* Handle concurrency well. Users shouldn't need to care about the - database's per-connection thread safety issues (or lack thereof), - and shouldn't have to maintain their own free pools of connections. - The 'db' package should deal with that bookkeeping as needed. Given - an *sql.DB, it should be possible to share that instance between - multiple goroutines, without any extra synchronization. - -* Push complexity, where necessary, down into the sql+driver packages, - rather than exposing it to users. Said otherwise, the sql package - should expose an ideal database that's not finnicky about how it's - accessed, even if that's not true. - -* Provide optional interfaces in sql/driver for drivers to implement - for special cases or fastpaths. But the only party that knows about - those is the sql package. To user code, some stuff just might start - working or start working slightly faster. diff --git a/src/pkg/database/sql/driver/driver.go b/src/pkg/database/sql/driver/driver.go deleted file mode 100644 index eca25f29a..000000000 --- a/src/pkg/database/sql/driver/driver.go +++ /dev/null @@ -1,211 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package driver defines interfaces to be implemented by database -// drivers as used by package sql. -// -// Most code should use package sql. -package driver - -import "errors" - -// Value is a value that drivers must be able to handle. -// It is either nil or an instance of one of these types: -// -// int64 -// float64 -// bool -// []byte -// string [*] everywhere except from Rows.Next. -// time.Time -type Value interface{} - -// Driver is the interface that must be implemented by a database -// driver. -type Driver interface { - // Open returns a new connection to the database. - // The name is a string in a driver-specific format. - // - // Open may return a cached connection (one previously - // closed), but doing so is unnecessary; the sql package - // maintains a pool of idle connections for efficient re-use. - // - // The returned connection is only used by one goroutine at a - // time. - Open(name string) (Conn, error) -} - -// ErrSkip may be returned by some optional interfaces' methods to -// indicate at runtime that the fast path is unavailable and the sql -// package should continue as if the optional interface was not -// implemented. ErrSkip is only supported where explicitly -// documented. -var ErrSkip = errors.New("driver: skip fast-path; continue as if unimplemented") - -// ErrBadConn should be returned by a driver to signal to the sql -// package that a driver.Conn is in a bad state (such as the server -// having earlier closed the connection) and the sql package should -// retry on a new connection. -// -// To prevent duplicate operations, ErrBadConn should NOT be returned -// if there's a possibility that the database server might have -// performed the operation. Even if the server sends back an error, -// you shouldn't return ErrBadConn. -var ErrBadConn = errors.New("driver: bad connection") - -// Execer is an optional interface that may be implemented by a Conn. -// -// If a Conn does not implement Execer, the sql package's DB.Exec will -// first prepare a query, execute the statement, and then close the -// statement. -// -// Exec may return ErrSkip. -type Execer interface { - Exec(query string, args []Value) (Result, error) -} - -// Queryer is an optional interface that may be implemented by a Conn. -// -// If a Conn does not implement Queryer, the sql package's DB.Query will -// first prepare a query, execute the statement, and then close the -// statement. -// -// Query may return ErrSkip. -type Queryer interface { - Query(query string, args []Value) (Rows, error) -} - -// Conn is a connection to a database. It is not used concurrently -// by multiple goroutines. -// -// Conn is assumed to be stateful. -type Conn interface { - // Prepare returns a prepared statement, bound to this connection. - Prepare(query string) (Stmt, error) - - // Close invalidates and potentially stops any current - // prepared statements and transactions, marking this - // connection as no longer in use. - // - // Because the sql package maintains a free pool of - // connections and only calls Close when there's a surplus of - // idle connections, it shouldn't be necessary for drivers to - // do their own connection caching. - Close() error - - // Begin starts and returns a new transaction. - Begin() (Tx, error) -} - -// Result is the result of a query execution. -type Result interface { - // LastInsertId returns the database's auto-generated ID - // after, for example, an INSERT into a table with primary - // key. - LastInsertId() (int64, error) - - // RowsAffected returns the number of rows affected by the - // query. - RowsAffected() (int64, error) -} - -// Stmt is a prepared statement. It is bound to a Conn and not -// used by multiple goroutines concurrently. -type Stmt interface { - // Close closes the statement. - // - // As of Go 1.1, a Stmt will not be closed if it's in use - // by any queries. - Close() error - - // NumInput returns the number of placeholder parameters. - // - // If NumInput returns >= 0, the sql package will sanity check - // argument counts from callers and return errors to the caller - // before the statement's Exec or Query methods are called. - // - // NumInput may also return -1, if the driver doesn't know - // its number of placeholders. In that case, the sql package - // will not sanity check Exec or Query argument counts. - NumInput() int - - // Exec executes a query that doesn't return rows, such - // as an INSERT or UPDATE. - Exec(args []Value) (Result, error) - - // Query executes a query that may return rows, such as a - // SELECT. - Query(args []Value) (Rows, error) -} - -// ColumnConverter may be optionally implemented by Stmt if the -// statement is aware of its own columns' types and can convert from -// any type to a driver Value. -type ColumnConverter interface { - // ColumnConverter returns a ValueConverter for the provided - // column index. If the type of a specific column isn't known - // or shouldn't be handled specially, DefaultValueConverter - // can be returned. - ColumnConverter(idx int) ValueConverter -} - -// Rows is an iterator over an executed query's results. -type Rows interface { - // Columns returns the names of the columns. The number of - // columns of the result is inferred from the length of the - // slice. If a particular column name isn't known, an empty - // string should be returned for that entry. - Columns() []string - - // Close closes the rows iterator. - Close() error - - // Next is called to populate the next row of data into - // the provided slice. The provided slice will be the same - // size as the Columns() are wide. - // - // The dest slice may be populated only with - // a driver Value type, but excluding string. - // All string values must be converted to []byte. - // - // Next should return io.EOF when there are no more rows. - Next(dest []Value) error -} - -// Tx is a transaction. -type Tx interface { - Commit() error - Rollback() error -} - -// RowsAffected implements Result for an INSERT or UPDATE operation -// which mutates a number of rows. -type RowsAffected int64 - -var _ Result = RowsAffected(0) - -func (RowsAffected) LastInsertId() (int64, error) { - return 0, errors.New("no LastInsertId available") -} - -func (v RowsAffected) RowsAffected() (int64, error) { - return int64(v), nil -} - -// ResultNoRows is a pre-defined Result for drivers to return when a DDL -// command (such as a CREATE TABLE) succeeds. It returns an error for both -// LastInsertId and RowsAffected. -var ResultNoRows noRows - -type noRows struct{} - -var _ Result = noRows{} - -func (noRows) LastInsertId() (int64, error) { - return 0, errors.New("no LastInsertId available after DDL statement") -} - -func (noRows) RowsAffected() (int64, error) { - return 0, errors.New("no RowsAffected available after DDL statement") -} diff --git a/src/pkg/database/sql/driver/types.go b/src/pkg/database/sql/driver/types.go deleted file mode 100644 index 3305354df..000000000 --- a/src/pkg/database/sql/driver/types.go +++ /dev/null @@ -1,252 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package driver - -import ( - "fmt" - "reflect" - "strconv" - "time" -) - -// ValueConverter is the interface providing the ConvertValue method. -// -// Various implementations of ValueConverter are provided by the -// driver package to provide consistent implementations of conversions -// between drivers. The ValueConverters have several uses: -// -// * converting from the Value types as provided by the sql package -// into a database table's specific column type and making sure it -// fits, such as making sure a particular int64 fits in a -// table's uint16 column. -// -// * converting a value as given from the database into one of the -// driver Value types. -// -// * by the sql package, for converting from a driver's Value type -// to a user's type in a scan. -type ValueConverter interface { - // ConvertValue converts a value to a driver Value. - ConvertValue(v interface{}) (Value, error) -} - -// Valuer is the interface providing the Value method. -// -// Types implementing Valuer interface are able to convert -// themselves to a driver Value. -type Valuer interface { - // Value returns a driver Value. - Value() (Value, error) -} - -// Bool is a ValueConverter that converts input values to bools. -// -// The conversion rules are: -// - booleans are returned unchanged -// - for integer types, -// 1 is true -// 0 is false, -// other integers are an error -// - for strings and []byte, same rules as strconv.ParseBool -// - all other types are an error -var Bool boolType - -type boolType struct{} - -var _ ValueConverter = boolType{} - -func (boolType) String() string { return "Bool" } - -func (boolType) ConvertValue(src interface{}) (Value, error) { - switch s := src.(type) { - case bool: - return s, nil - case string: - b, err := strconv.ParseBool(s) - if err != nil { - return nil, fmt.Errorf("sql/driver: couldn't convert %q into type bool", s) - } - return b, nil - case []byte: - b, err := strconv.ParseBool(string(s)) - if err != nil { - return nil, fmt.Errorf("sql/driver: couldn't convert %q into type bool", s) - } - return b, nil - } - - sv := reflect.ValueOf(src) - switch sv.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - iv := sv.Int() - if iv == 1 || iv == 0 { - return iv == 1, nil - } - return nil, fmt.Errorf("sql/driver: couldn't convert %d into type bool", iv) - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - uv := sv.Uint() - if uv == 1 || uv == 0 { - return uv == 1, nil - } - return nil, fmt.Errorf("sql/driver: couldn't convert %d into type bool", uv) - } - - return nil, fmt.Errorf("sql/driver: couldn't convert %v (%T) into type bool", src, src) -} - -// Int32 is a ValueConverter that converts input values to int64, -// respecting the limits of an int32 value. -var Int32 int32Type - -type int32Type struct{} - -var _ ValueConverter = int32Type{} - -func (int32Type) ConvertValue(v interface{}) (Value, error) { - rv := reflect.ValueOf(v) - switch rv.Kind() { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - i64 := rv.Int() - if i64 > (1<<31)-1 || i64 < -(1<<31) { - return nil, fmt.Errorf("sql/driver: value %d overflows int32", v) - } - return i64, nil - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - u64 := rv.Uint() - if u64 > (1<<31)-1 { - return nil, fmt.Errorf("sql/driver: value %d overflows int32", v) - } - return int64(u64), nil - case reflect.String: - i, err := strconv.Atoi(rv.String()) - if err != nil { - return nil, fmt.Errorf("sql/driver: value %q can't be converted to int32", v) - } - return int64(i), nil - } - return nil, fmt.Errorf("sql/driver: unsupported value %v (type %T) converting to int32", v, v) -} - -// String is a ValueConverter that converts its input to a string. -// If the value is already a string or []byte, it's unchanged. -// If the value is of another type, conversion to string is done -// with fmt.Sprintf("%v", v). -var String stringType - -type stringType struct{} - -func (stringType) ConvertValue(v interface{}) (Value, error) { - switch v.(type) { - case string, []byte: - return v, nil - } - return fmt.Sprintf("%v", v), nil -} - -// Null is a type that implements ValueConverter by allowing nil -// values but otherwise delegating to another ValueConverter. -type Null struct { - Converter ValueConverter -} - -func (n Null) ConvertValue(v interface{}) (Value, error) { - if v == nil { - return nil, nil - } - return n.Converter.ConvertValue(v) -} - -// NotNull is a type that implements ValueConverter by disallowing nil -// values but otherwise delegating to another ValueConverter. -type NotNull struct { - Converter ValueConverter -} - -func (n NotNull) ConvertValue(v interface{}) (Value, error) { - if v == nil { - return nil, fmt.Errorf("nil value not allowed") - } - return n.Converter.ConvertValue(v) -} - -// IsValue reports whether v is a valid Value parameter type. -// Unlike IsScanValue, IsValue permits the string type. -func IsValue(v interface{}) bool { - if IsScanValue(v) { - return true - } - if _, ok := v.(string); ok { - return true - } - return false -} - -// IsScanValue reports whether v is a valid Value scan type. -// Unlike IsValue, IsScanValue does not permit the string type. -func IsScanValue(v interface{}) bool { - if v == nil { - return true - } - switch v.(type) { - case int64, float64, []byte, bool, time.Time: - return true - } - return false -} - -// DefaultParameterConverter is the default implementation of -// ValueConverter that's used when a Stmt doesn't implement -// ColumnConverter. -// -// DefaultParameterConverter returns the given value directly if -// IsValue(value). Otherwise integer type are converted to -// int64, floats to float64, and strings to []byte. Other types are -// an error. -var DefaultParameterConverter defaultConverter - -type defaultConverter struct{} - -var _ ValueConverter = defaultConverter{} - -func (defaultConverter) ConvertValue(v interface{}) (Value, error) { - if IsValue(v) { - return v, nil - } - - if svi, ok := v.(Valuer); ok { - sv, err := svi.Value() - if err != nil { - return nil, err - } - if !IsValue(sv) { - return nil, fmt.Errorf("non-Value type %T returned from Value", sv) - } - return sv, nil - } - - rv := reflect.ValueOf(v) - switch rv.Kind() { - case reflect.Ptr: - // indirect pointers - if rv.IsNil() { - return nil, nil - } else { - return defaultConverter{}.ConvertValue(rv.Elem().Interface()) - } - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return rv.Int(), nil - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32: - return int64(rv.Uint()), nil - case reflect.Uint64: - u64 := rv.Uint() - if u64 >= 1<<63 { - return nil, fmt.Errorf("uint64 values with high bit set are not supported") - } - return int64(u64), nil - case reflect.Float32, reflect.Float64: - return rv.Float(), nil - } - return nil, fmt.Errorf("unsupported type %T, a %s", v, rv.Kind()) -} diff --git a/src/pkg/database/sql/driver/types_test.go b/src/pkg/database/sql/driver/types_test.go deleted file mode 100644 index 1ce0ff065..000000000 --- a/src/pkg/database/sql/driver/types_test.go +++ /dev/null @@ -1,65 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package driver - -import ( - "reflect" - "testing" - "time" -) - -type valueConverterTest struct { - c ValueConverter - in interface{} - out interface{} - err string -} - -var now = time.Now() -var answer int64 = 42 - -var valueConverterTests = []valueConverterTest{ - {Bool, "true", true, ""}, - {Bool, "True", true, ""}, - {Bool, []byte("t"), true, ""}, - {Bool, true, true, ""}, - {Bool, "1", true, ""}, - {Bool, 1, true, ""}, - {Bool, int64(1), true, ""}, - {Bool, uint16(1), true, ""}, - {Bool, "false", false, ""}, - {Bool, false, false, ""}, - {Bool, "0", false, ""}, - {Bool, 0, false, ""}, - {Bool, int64(0), false, ""}, - {Bool, uint16(0), false, ""}, - {c: Bool, in: "foo", err: "sql/driver: couldn't convert \"foo\" into type bool"}, - {c: Bool, in: 2, err: "sql/driver: couldn't convert 2 into type bool"}, - {DefaultParameterConverter, now, now, ""}, - {DefaultParameterConverter, (*int64)(nil), nil, ""}, - {DefaultParameterConverter, &answer, answer, ""}, - {DefaultParameterConverter, &now, now, ""}, -} - -func TestValueConverters(t *testing.T) { - for i, tt := range valueConverterTests { - out, err := tt.c.ConvertValue(tt.in) - goterr := "" - if err != nil { - goterr = err.Error() - } - if goterr != tt.err { - t.Errorf("test %d: %T(%T(%v)) error = %q; want error = %q", - i, tt.c, tt.in, tt.in, goterr, tt.err) - } - if tt.err != "" { - continue - } - if !reflect.DeepEqual(out, tt.out) { - t.Errorf("test %d: %T(%T(%v)) = %v (%T); want %v (%T)", - i, tt.c, tt.in, tt.in, out, out, tt.out, tt.out) - } - } -} diff --git a/src/pkg/database/sql/example_test.go b/src/pkg/database/sql/example_test.go deleted file mode 100644 index dcb74e069..000000000 --- a/src/pkg/database/sql/example_test.go +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package sql_test - -import ( - "database/sql" - "fmt" - "log" -) - -var db *sql.DB - -func ExampleDB_Query() { - age := 27 - rows, err := db.Query("SELECT name FROM users WHERE age=?", age) - if err != nil { - log.Fatal(err) - } - defer rows.Close() - for rows.Next() { - var name string - if err := rows.Scan(&name); err != nil { - log.Fatal(err) - } - fmt.Printf("%s is %d\n", name, age) - } - if err := rows.Err(); err != nil { - log.Fatal(err) - } -} - -func ExampleDB_QueryRow() { - id := 123 - var username string - err := db.QueryRow("SELECT username FROM users WHERE id=?", id).Scan(&username) - switch { - case err == sql.ErrNoRows: - log.Printf("No user with that ID.") - case err != nil: - log.Fatal(err) - default: - fmt.Printf("Username is %s\n", username) - } -} diff --git a/src/pkg/database/sql/fakedb_test.go b/src/pkg/database/sql/fakedb_test.go deleted file mode 100644 index c7db0dd77..000000000 --- a/src/pkg/database/sql/fakedb_test.go +++ /dev/null @@ -1,805 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package sql - -import ( - "database/sql/driver" - "errors" - "fmt" - "io" - "log" - "strconv" - "strings" - "sync" - "testing" - "time" -) - -var _ = log.Printf - -// fakeDriver is a fake database that implements Go's driver.Driver -// interface, just for testing. -// -// It speaks a query language that's semantically similar to but -// syntactically different and simpler than SQL. The syntax is as -// follows: -// -// WIPE -// CREATE||=,=,... -// where types are: "string", [u]int{8,16,32,64}, "bool" -// INSERT||col=val,col2=val2,col3=? -// SELECT||projectcol1,projectcol2|filtercol=?,filtercol2=? -// -// When opening a fakeDriver's database, it starts empty with no -// tables. All tables and data are stored in memory only. -type fakeDriver struct { - mu sync.Mutex // guards 3 following fields - openCount int // conn opens - closeCount int // conn closes - waitCh chan struct{} - waitingCh chan struct{} - dbs map[string]*fakeDB -} - -type fakeDB struct { - name string - - mu sync.Mutex - free []*fakeConn - tables map[string]*table - badConn bool -} - -type table struct { - mu sync.Mutex - colname []string - coltype []string - rows []*row -} - -func (t *table) columnIndex(name string) int { - for n, nname := range t.colname { - if name == nname { - return n - } - } - return -1 -} - -type row struct { - cols []interface{} // must be same size as its table colname + coltype -} - -func (r *row) clone() *row { - nrow := &row{cols: make([]interface{}, len(r.cols))} - copy(nrow.cols, r.cols) - return nrow -} - -type fakeConn struct { - db *fakeDB // where to return ourselves to - - currTx *fakeTx - - // Stats for tests: - mu sync.Mutex - stmtsMade int - stmtsClosed int - numPrepare int - bad bool -} - -func (c *fakeConn) incrStat(v *int) { - c.mu.Lock() - *v++ - c.mu.Unlock() -} - -type fakeTx struct { - c *fakeConn -} - -type fakeStmt struct { - c *fakeConn - q string // just for debugging - - cmd string - table string - - closed bool - - colName []string // used by CREATE, INSERT, SELECT (selected columns) - colType []string // used by CREATE - colValue []interface{} // used by INSERT (mix of strings and "?" for bound params) - placeholders int // used by INSERT/SELECT: number of ? params - - whereCol []string // used by SELECT (all placeholders) - - placeholderConverter []driver.ValueConverter // used by INSERT -} - -var fdriver driver.Driver = &fakeDriver{} - -func init() { - Register("test", fdriver) -} - -// Supports dsn forms: -// -// ; (only currently supported option is `badConn`, -// which causes driver.ErrBadConn to be returned on -// every other conn.Begin()) -func (d *fakeDriver) Open(dsn string) (driver.Conn, error) { - parts := strings.Split(dsn, ";") - if len(parts) < 1 { - return nil, errors.New("fakedb: no database name") - } - name := parts[0] - - db := d.getDB(name) - - d.mu.Lock() - d.openCount++ - d.mu.Unlock() - conn := &fakeConn{db: db} - - if len(parts) >= 2 && parts[1] == "badConn" { - conn.bad = true - } - if d.waitCh != nil { - d.waitingCh <- struct{}{} - <-d.waitCh - d.waitCh = nil - d.waitingCh = nil - } - return conn, nil -} - -func (d *fakeDriver) getDB(name string) *fakeDB { - d.mu.Lock() - defer d.mu.Unlock() - if d.dbs == nil { - d.dbs = make(map[string]*fakeDB) - } - db, ok := d.dbs[name] - if !ok { - db = &fakeDB{name: name} - d.dbs[name] = db - } - return db -} - -func (db *fakeDB) wipe() { - db.mu.Lock() - defer db.mu.Unlock() - db.tables = nil -} - -func (db *fakeDB) createTable(name string, columnNames, columnTypes []string) error { - db.mu.Lock() - defer db.mu.Unlock() - if db.tables == nil { - db.tables = make(map[string]*table) - } - if _, exist := db.tables[name]; exist { - return fmt.Errorf("table %q already exists", name) - } - if len(columnNames) != len(columnTypes) { - return fmt.Errorf("create table of %q len(names) != len(types): %d vs %d", - name, len(columnNames), len(columnTypes)) - } - db.tables[name] = &table{colname: columnNames, coltype: columnTypes} - return nil -} - -// must be called with db.mu lock held -func (db *fakeDB) table(table string) (*table, bool) { - if db.tables == nil { - return nil, false - } - t, ok := db.tables[table] - return t, ok -} - -func (db *fakeDB) columnType(table, column string) (typ string, ok bool) { - db.mu.Lock() - defer db.mu.Unlock() - t, ok := db.table(table) - if !ok { - return - } - for n, cname := range t.colname { - if cname == column { - return t.coltype[n], true - } - } - return "", false -} - -func (c *fakeConn) isBad() bool { - // if not simulating bad conn, do nothing - if !c.bad { - return false - } - // alternate between bad conn and not bad conn - c.db.badConn = !c.db.badConn - return c.db.badConn -} - -func (c *fakeConn) Begin() (driver.Tx, error) { - if c.isBad() { - return nil, driver.ErrBadConn - } - if c.currTx != nil { - return nil, errors.New("already in a transaction") - } - c.currTx = &fakeTx{c: c} - return c.currTx, nil -} - -var hookPostCloseConn struct { - sync.Mutex - fn func(*fakeConn, error) -} - -func setHookpostCloseConn(fn func(*fakeConn, error)) { - hookPostCloseConn.Lock() - defer hookPostCloseConn.Unlock() - hookPostCloseConn.fn = fn -} - -var testStrictClose *testing.T - -// setStrictFakeConnClose sets the t to Errorf on when fakeConn.Close -// fails to close. If nil, the check is disabled. -func setStrictFakeConnClose(t *testing.T) { - testStrictClose = t -} - -func (c *fakeConn) Close() (err error) { - drv := fdriver.(*fakeDriver) - defer func() { - if err != nil && testStrictClose != nil { - testStrictClose.Errorf("failed to close a test fakeConn: %v", err) - } - hookPostCloseConn.Lock() - fn := hookPostCloseConn.fn - hookPostCloseConn.Unlock() - if fn != nil { - fn(c, err) - } - if err == nil { - drv.mu.Lock() - drv.closeCount++ - drv.mu.Unlock() - } - }() - if c.currTx != nil { - return errors.New("can't close fakeConn; in a Transaction") - } - if c.db == nil { - return errors.New("can't close fakeConn; already closed") - } - if c.stmtsMade > c.stmtsClosed { - return errors.New("can't close; dangling statement(s)") - } - c.db = nil - return nil -} - -func checkSubsetTypes(args []driver.Value) error { - for n, arg := range args { - switch arg.(type) { - case int64, float64, bool, nil, []byte, string, time.Time: - default: - return fmt.Errorf("fakedb_test: invalid argument #%d: %v, type %T", n+1, arg, arg) - } - } - return nil -} - -func (c *fakeConn) Exec(query string, args []driver.Value) (driver.Result, error) { - // This is an optional interface, but it's implemented here - // just to check that all the args are of the proper types. - // ErrSkip is returned so the caller acts as if we didn't - // implement this at all. - err := checkSubsetTypes(args) - if err != nil { - return nil, err - } - return nil, driver.ErrSkip -} - -func (c *fakeConn) Query(query string, args []driver.Value) (driver.Rows, error) { - // This is an optional interface, but it's implemented here - // just to check that all the args are of the proper types. - // ErrSkip is returned so the caller acts as if we didn't - // implement this at all. - err := checkSubsetTypes(args) - if err != nil { - return nil, err - } - return nil, driver.ErrSkip -} - -func errf(msg string, args ...interface{}) error { - return errors.New("fakedb: " + fmt.Sprintf(msg, args...)) -} - -// parts are table|selectCol1,selectCol2|whereCol=?,whereCol2=? -// (note that where columns must always contain ? marks, -// just a limitation for fakedb) -func (c *fakeConn) prepareSelect(stmt *fakeStmt, parts []string) (driver.Stmt, error) { - if len(parts) != 3 { - stmt.Close() - return nil, errf("invalid SELECT syntax with %d parts; want 3", len(parts)) - } - stmt.table = parts[0] - stmt.colName = strings.Split(parts[1], ",") - for n, colspec := range strings.Split(parts[2], ",") { - if colspec == "" { - continue - } - nameVal := strings.Split(colspec, "=") - if len(nameVal) != 2 { - stmt.Close() - return nil, errf("SELECT on table %q has invalid column spec of %q (index %d)", stmt.table, colspec, n) - } - column, value := nameVal[0], nameVal[1] - _, ok := c.db.columnType(stmt.table, column) - if !ok { - stmt.Close() - return nil, errf("SELECT on table %q references non-existent column %q", stmt.table, column) - } - if value != "?" { - stmt.Close() - return nil, errf("SELECT on table %q has pre-bound value for where column %q; need a question mark", - stmt.table, column) - } - stmt.whereCol = append(stmt.whereCol, column) - stmt.placeholders++ - } - return stmt, nil -} - -// parts are table|col=type,col2=type2 -func (c *fakeConn) prepareCreate(stmt *fakeStmt, parts []string) (driver.Stmt, error) { - if len(parts) != 2 { - stmt.Close() - return nil, errf("invalid CREATE syntax with %d parts; want 2", len(parts)) - } - stmt.table = parts[0] - for n, colspec := range strings.Split(parts[1], ",") { - nameType := strings.Split(colspec, "=") - if len(nameType) != 2 { - stmt.Close() - return nil, errf("CREATE table %q has invalid column spec of %q (index %d)", stmt.table, colspec, n) - } - stmt.colName = append(stmt.colName, nameType[0]) - stmt.colType = append(stmt.colType, nameType[1]) - } - return stmt, nil -} - -// parts are table|col=?,col2=val -func (c *fakeConn) prepareInsert(stmt *fakeStmt, parts []string) (driver.Stmt, error) { - if len(parts) != 2 { - stmt.Close() - return nil, errf("invalid INSERT syntax with %d parts; want 2", len(parts)) - } - stmt.table = parts[0] - for n, colspec := range strings.Split(parts[1], ",") { - nameVal := strings.Split(colspec, "=") - if len(nameVal) != 2 { - stmt.Close() - return nil, errf("INSERT table %q has invalid column spec of %q (index %d)", stmt.table, colspec, n) - } - column, value := nameVal[0], nameVal[1] - ctype, ok := c.db.columnType(stmt.table, column) - if !ok { - stmt.Close() - return nil, errf("INSERT table %q references non-existent column %q", stmt.table, column) - } - stmt.colName = append(stmt.colName, column) - - if value != "?" { - var subsetVal interface{} - // Convert to driver subset type - switch ctype { - case "string": - subsetVal = []byte(value) - case "blob": - subsetVal = []byte(value) - case "int32": - i, err := strconv.Atoi(value) - if err != nil { - stmt.Close() - return nil, errf("invalid conversion to int32 from %q", value) - } - subsetVal = int64(i) // int64 is a subset type, but not int32 - default: - stmt.Close() - return nil, errf("unsupported conversion for pre-bound parameter %q to type %q", value, ctype) - } - stmt.colValue = append(stmt.colValue, subsetVal) - } else { - stmt.placeholders++ - stmt.placeholderConverter = append(stmt.placeholderConverter, converterForType(ctype)) - stmt.colValue = append(stmt.colValue, "?") - } - } - return stmt, nil -} - -// hook to simulate broken connections -var hookPrepareBadConn func() bool - -func (c *fakeConn) Prepare(query string) (driver.Stmt, error) { - c.numPrepare++ - if c.db == nil { - panic("nil c.db; conn = " + fmt.Sprintf("%#v", c)) - } - - if hookPrepareBadConn != nil && hookPrepareBadConn() { - return nil, driver.ErrBadConn - } - - parts := strings.Split(query, "|") - if len(parts) < 1 { - return nil, errf("empty query") - } - cmd := parts[0] - parts = parts[1:] - stmt := &fakeStmt{q: query, c: c, cmd: cmd} - c.incrStat(&c.stmtsMade) - switch cmd { - case "WIPE": - // Nothing - case "SELECT": - return c.prepareSelect(stmt, parts) - case "CREATE": - return c.prepareCreate(stmt, parts) - case "INSERT": - return c.prepareInsert(stmt, parts) - case "NOSERT": - // Do all the prep-work like for an INSERT but don't actually insert the row. - // Used for some of the concurrent tests. - return c.prepareInsert(stmt, parts) - default: - stmt.Close() - return nil, errf("unsupported command type %q", cmd) - } - return stmt, nil -} - -func (s *fakeStmt) ColumnConverter(idx int) driver.ValueConverter { - if len(s.placeholderConverter) == 0 { - return driver.DefaultParameterConverter - } - return s.placeholderConverter[idx] -} - -func (s *fakeStmt) Close() error { - if s.c == nil { - panic("nil conn in fakeStmt.Close") - } - if s.c.db == nil { - panic("in fakeStmt.Close, conn's db is nil (already closed)") - } - if !s.closed { - s.c.incrStat(&s.c.stmtsClosed) - s.closed = true - } - return nil -} - -var errClosed = errors.New("fakedb: statement has been closed") - -// hook to simulate broken connections -var hookExecBadConn func() bool - -func (s *fakeStmt) Exec(args []driver.Value) (driver.Result, error) { - if s.closed { - return nil, errClosed - } - - if hookExecBadConn != nil && hookExecBadConn() { - return nil, driver.ErrBadConn - } - - err := checkSubsetTypes(args) - if err != nil { - return nil, err - } - - db := s.c.db - switch s.cmd { - case "WIPE": - db.wipe() - return driver.ResultNoRows, nil - case "CREATE": - if err := db.createTable(s.table, s.colName, s.colType); err != nil { - return nil, err - } - return driver.ResultNoRows, nil - case "INSERT": - return s.execInsert(args, true) - case "NOSERT": - // Do all the prep-work like for an INSERT but don't actually insert the row. - // Used for some of the concurrent tests. - return s.execInsert(args, false) - } - fmt.Printf("EXEC statement, cmd=%q: %#v\n", s.cmd, s) - return nil, fmt.Errorf("unimplemented statement Exec command type of %q", s.cmd) -} - -// When doInsert is true, add the row to the table. -// When doInsert is false do prep-work and error checking, but don't -// actually add the row to the table. -func (s *fakeStmt) execInsert(args []driver.Value, doInsert bool) (driver.Result, error) { - db := s.c.db - if len(args) != s.placeholders { - panic("error in pkg db; should only get here if size is correct") - } - db.mu.Lock() - t, ok := db.table(s.table) - db.mu.Unlock() - if !ok { - return nil, fmt.Errorf("fakedb: table %q doesn't exist", s.table) - } - - t.mu.Lock() - defer t.mu.Unlock() - - var cols []interface{} - if doInsert { - cols = make([]interface{}, len(t.colname)) - } - argPos := 0 - for n, colname := range s.colName { - colidx := t.columnIndex(colname) - if colidx == -1 { - return nil, fmt.Errorf("fakedb: column %q doesn't exist or dropped since prepared statement was created", colname) - } - var val interface{} - if strvalue, ok := s.colValue[n].(string); ok && strvalue == "?" { - val = args[argPos] - argPos++ - } else { - val = s.colValue[n] - } - if doInsert { - cols[colidx] = val - } - } - - if doInsert { - t.rows = append(t.rows, &row{cols: cols}) - } - return driver.RowsAffected(1), nil -} - -// hook to simulate broken connections -var hookQueryBadConn func() bool - -func (s *fakeStmt) Query(args []driver.Value) (driver.Rows, error) { - if s.closed { - return nil, errClosed - } - - if hookQueryBadConn != nil && hookQueryBadConn() { - return nil, driver.ErrBadConn - } - - err := checkSubsetTypes(args) - if err != nil { - return nil, err - } - - db := s.c.db - if len(args) != s.placeholders { - panic("error in pkg db; should only get here if size is correct") - } - - db.mu.Lock() - t, ok := db.table(s.table) - db.mu.Unlock() - if !ok { - return nil, fmt.Errorf("fakedb: table %q doesn't exist", s.table) - } - - if s.table == "magicquery" { - if len(s.whereCol) == 2 && s.whereCol[0] == "op" && s.whereCol[1] == "millis" { - if args[0] == "sleep" { - time.Sleep(time.Duration(args[1].(int64)) * time.Millisecond) - } - } - } - - t.mu.Lock() - defer t.mu.Unlock() - - colIdx := make(map[string]int) // select column name -> column index in table - for _, name := range s.colName { - idx := t.columnIndex(name) - if idx == -1 { - return nil, fmt.Errorf("fakedb: unknown column name %q", name) - } - colIdx[name] = idx - } - - mrows := []*row{} -rows: - for _, trow := range t.rows { - // Process the where clause, skipping non-match rows. This is lazy - // and just uses fmt.Sprintf("%v") to test equality. Good enough - // for test code. - for widx, wcol := range s.whereCol { - idx := t.columnIndex(wcol) - if idx == -1 { - return nil, fmt.Errorf("db: invalid where clause column %q", wcol) - } - tcol := trow.cols[idx] - if bs, ok := tcol.([]byte); ok { - // lazy hack to avoid sprintf %v on a []byte - tcol = string(bs) - } - if fmt.Sprintf("%v", tcol) != fmt.Sprintf("%v", args[widx]) { - continue rows - } - } - mrow := &row{cols: make([]interface{}, len(s.colName))} - for seli, name := range s.colName { - mrow.cols[seli] = trow.cols[colIdx[name]] - } - mrows = append(mrows, mrow) - } - - cursor := &rowsCursor{ - pos: -1, - rows: mrows, - cols: s.colName, - errPos: -1, - } - return cursor, nil -} - -func (s *fakeStmt) NumInput() int { - return s.placeholders -} - -func (tx *fakeTx) Commit() error { - tx.c.currTx = nil - return nil -} - -func (tx *fakeTx) Rollback() error { - tx.c.currTx = nil - return nil -} - -type rowsCursor struct { - cols []string - pos int - rows []*row - closed bool - - // errPos and err are for making Next return early with error. - errPos int - err error - - // a clone of slices to give out to clients, indexed by the - // the original slice's first byte address. we clone them - // just so we're able to corrupt them on close. - bytesClone map[*byte][]byte -} - -func (rc *rowsCursor) Close() error { - if !rc.closed { - for _, bs := range rc.bytesClone { - bs[0] = 255 // first byte corrupted - } - } - rc.closed = true - return nil -} - -func (rc *rowsCursor) Columns() []string { - return rc.cols -} - -var rowsCursorNextHook func(dest []driver.Value) error - -func (rc *rowsCursor) Next(dest []driver.Value) error { - if rowsCursorNextHook != nil { - return rowsCursorNextHook(dest) - } - - if rc.closed { - return errors.New("fakedb: cursor is closed") - } - rc.pos++ - if rc.pos == rc.errPos { - return rc.err - } - if rc.pos >= len(rc.rows) { - return io.EOF // per interface spec - } - for i, v := range rc.rows[rc.pos].cols { - // TODO(bradfitz): convert to subset types? naah, I - // think the subset types should only be input to - // driver, but the sql package should be able to handle - // a wider range of types coming out of drivers. all - // for ease of drivers, and to prevent drivers from - // messing up conversions or doing them differently. - dest[i] = v - - if bs, ok := v.([]byte); ok { - if rc.bytesClone == nil { - rc.bytesClone = make(map[*byte][]byte) - } - clone, ok := rc.bytesClone[&bs[0]] - if !ok { - clone = make([]byte, len(bs)) - copy(clone, bs) - rc.bytesClone[&bs[0]] = clone - } - dest[i] = clone - } - } - return nil -} - -// fakeDriverString is like driver.String, but indirects pointers like -// DefaultValueConverter. -// -// This could be surprising behavior to retroactively apply to -// driver.String now that Go1 is out, but this is convenient for -// our TestPointerParamsAndScans. -// -type fakeDriverString struct{} - -func (fakeDriverString) ConvertValue(v interface{}) (driver.Value, error) { - switch c := v.(type) { - case string, []byte: - return v, nil - case *string: - if c == nil { - return nil, nil - } - return *c, nil - } - return fmt.Sprintf("%v", v), nil -} - -func converterForType(typ string) driver.ValueConverter { - switch typ { - case "bool": - return driver.Bool - case "nullbool": - return driver.Null{Converter: driver.Bool} - case "int32": - return driver.Int32 - case "string": - return driver.NotNull{Converter: fakeDriverString{}} - case "nullstring": - return driver.Null{Converter: fakeDriverString{}} - case "int64": - // TODO(coopernurse): add type-specific converter - return driver.NotNull{Converter: driver.DefaultParameterConverter} - case "nullint64": - // TODO(coopernurse): add type-specific converter - return driver.Null{Converter: driver.DefaultParameterConverter} - case "float64": - // TODO(coopernurse): add type-specific converter - return driver.NotNull{Converter: driver.DefaultParameterConverter} - case "nullfloat64": - // TODO(coopernurse): add type-specific converter - return driver.Null{Converter: driver.DefaultParameterConverter} - case "datetime": - return driver.DefaultParameterConverter - } - panic("invalid fakedb column type of " + typ) -} diff --git a/src/pkg/database/sql/sql.go b/src/pkg/database/sql/sql.go deleted file mode 100644 index 90f813d82..000000000 --- a/src/pkg/database/sql/sql.go +++ /dev/null @@ -1,1723 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package sql provides a generic interface around SQL (or SQL-like) -// databases. -// -// The sql package must be used in conjunction with a database driver. -// See http://golang.org/s/sqldrivers for a list of drivers. -// -// For more usage examples, see the wiki page at -// http://golang.org/s/sqlwiki. -package sql - -import ( - "database/sql/driver" - "errors" - "fmt" - "io" - "runtime" - "sync" -) - -var drivers = make(map[string]driver.Driver) - -// Register makes a database driver available by the provided name. -// If Register is called twice with the same name or if driver is nil, -// it panics. -func Register(name string, driver driver.Driver) { - if driver == nil { - panic("sql: Register driver is nil") - } - if _, dup := drivers[name]; dup { - panic("sql: Register called twice for driver " + name) - } - drivers[name] = driver -} - -// RawBytes is a byte slice that holds a reference to memory owned by -// the database itself. After a Scan into a RawBytes, the slice is only -// valid until the next call to Next, Scan, or Close. -type RawBytes []byte - -// NullString represents a string that may be null. -// NullString implements the Scanner interface so -// it can be used as a scan destination: -// -// var s NullString -// err := db.QueryRow("SELECT name FROM foo WHERE id=?", id).Scan(&s) -// ... -// if s.Valid { -// // use s.String -// } else { -// // NULL value -// } -// -type NullString struct { - String string - Valid bool // Valid is true if String is not NULL -} - -// Scan implements the Scanner interface. -func (ns *NullString) Scan(value interface{}) error { - if value == nil { - ns.String, ns.Valid = "", false - return nil - } - ns.Valid = true - return convertAssign(&ns.String, value) -} - -// Value implements the driver Valuer interface. -func (ns NullString) Value() (driver.Value, error) { - if !ns.Valid { - return nil, nil - } - return ns.String, nil -} - -// NullInt64 represents an int64 that may be null. -// NullInt64 implements the Scanner interface so -// it can be used as a scan destination, similar to NullString. -type NullInt64 struct { - Int64 int64 - Valid bool // Valid is true if Int64 is not NULL -} - -// Scan implements the Scanner interface. -func (n *NullInt64) Scan(value interface{}) error { - if value == nil { - n.Int64, n.Valid = 0, false - return nil - } - n.Valid = true - return convertAssign(&n.Int64, value) -} - -// Value implements the driver Valuer interface. -func (n NullInt64) Value() (driver.Value, error) { - if !n.Valid { - return nil, nil - } - return n.Int64, nil -} - -// NullFloat64 represents a float64 that may be null. -// NullFloat64 implements the Scanner interface so -// it can be used as a scan destination, similar to NullString. -type NullFloat64 struct { - Float64 float64 - Valid bool // Valid is true if Float64 is not NULL -} - -// Scan implements the Scanner interface. -func (n *NullFloat64) Scan(value interface{}) error { - if value == nil { - n.Float64, n.Valid = 0, false - return nil - } - n.Valid = true - return convertAssign(&n.Float64, value) -} - -// Value implements the driver Valuer interface. -func (n NullFloat64) Value() (driver.Value, error) { - if !n.Valid { - return nil, nil - } - return n.Float64, nil -} - -// NullBool represents a bool that may be null. -// NullBool implements the Scanner interface so -// it can be used as a scan destination, similar to NullString. -type NullBool struct { - Bool bool - Valid bool // Valid is true if Bool is not NULL -} - -// Scan implements the Scanner interface. -func (n *NullBool) Scan(value interface{}) error { - if value == nil { - n.Bool, n.Valid = false, false - return nil - } - n.Valid = true - return convertAssign(&n.Bool, value) -} - -// Value implements the driver Valuer interface. -func (n NullBool) Value() (driver.Value, error) { - if !n.Valid { - return nil, nil - } - return n.Bool, nil -} - -// Scanner is an interface used by Scan. -type Scanner interface { - // Scan assigns a value from a database driver. - // - // The src value will be of one of the following restricted - // set of types: - // - // int64 - // float64 - // bool - // []byte - // string - // time.Time - // nil - for NULL values - // - // An error should be returned if the value can not be stored - // without loss of information. - Scan(src interface{}) error -} - -// ErrNoRows is returned by Scan when QueryRow doesn't return a -// row. In such a case, QueryRow returns a placeholder *Row value that -// defers this error until a Scan. -var ErrNoRows = errors.New("sql: no rows in result set") - -// DB is a database handle representing a pool of zero or more -// underlying connections. It's safe for concurrent use by multiple -// goroutines. -// -// The sql package creates and frees connections automatically; it -// also maintains a free pool of idle connections. If the database has -// a concept of per-connection state, such state can only be reliably -// observed within a transaction. Once DB.Begin is called, the -// returned Tx is bound to a single connection. Once Commit or -// Rollback is called on the transaction, that transaction's -// connection is returned to DB's idle connection pool. The pool size -// can be controlled with SetMaxIdleConns. -type DB struct { - driver driver.Driver - dsn string - - mu sync.Mutex // protects following fields - freeConn []*driverConn - connRequests []chan connRequest - numOpen int - pendingOpens int - // Used to signal the need for new connections - // a goroutine running connectionOpener() reads on this chan and - // maybeOpenNewConnections sends on the chan (one send per needed connection) - // It is closed during db.Close(). The close tells the connectionOpener - // goroutine to exit. - openerCh chan struct{} - closed bool - dep map[finalCloser]depSet - lastPut map[*driverConn]string // stacktrace of last conn's put; debug only - maxIdle int // zero means defaultMaxIdleConns; negative means 0 - maxOpen int // <= 0 means unlimited -} - -// driverConn wraps a driver.Conn with a mutex, to -// be held during all calls into the Conn. (including any calls onto -// interfaces returned via that Conn, such as calls on Tx, Stmt, -// Result, Rows) -type driverConn struct { - db *DB - - sync.Mutex // guards following - ci driver.Conn - closed bool - finalClosed bool // ci.Close has been called - openStmt map[driver.Stmt]bool - - // guarded by db.mu - inUse bool - onPut []func() // code (with db.mu held) run when conn is next returned - dbmuClosed bool // same as closed, but guarded by db.mu, for connIfFree -} - -func (dc *driverConn) releaseConn(err error) { - dc.db.putConn(dc, err) -} - -func (dc *driverConn) removeOpenStmt(si driver.Stmt) { - dc.Lock() - defer dc.Unlock() - delete(dc.openStmt, si) -} - -func (dc *driverConn) prepareLocked(query string) (driver.Stmt, error) { - si, err := dc.ci.Prepare(query) - if err == nil { - // Track each driverConn's open statements, so we can close them - // before closing the conn. - // - // TODO(bradfitz): let drivers opt out of caring about - // stmt closes if the conn is about to close anyway? For now - // do the safe thing, in case stmts need to be closed. - // - // TODO(bradfitz): after Go 1.2, closing driver.Stmts - // should be moved to driverStmt, using unique - // *driverStmts everywhere (including from - // *Stmt.connStmt, instead of returning a - // driver.Stmt), using driverStmt as a pointer - // everywhere, and making it a finalCloser. - if dc.openStmt == nil { - dc.openStmt = make(map[driver.Stmt]bool) - } - dc.openStmt[si] = true - } - return si, err -} - -// the dc.db's Mutex is held. -func (dc *driverConn) closeDBLocked() func() error { - dc.Lock() - defer dc.Unlock() - if dc.closed { - return func() error { return errors.New("sql: duplicate driverConn close") } - } - dc.closed = true - return dc.db.removeDepLocked(dc, dc) -} - -func (dc *driverConn) Close() error { - dc.Lock() - if dc.closed { - dc.Unlock() - return errors.New("sql: duplicate driverConn close") - } - dc.closed = true - dc.Unlock() // not defer; removeDep finalClose calls may need to lock - - // And now updates that require holding dc.mu.Lock. - dc.db.mu.Lock() - dc.dbmuClosed = true - fn := dc.db.removeDepLocked(dc, dc) - dc.db.mu.Unlock() - return fn() -} - -func (dc *driverConn) finalClose() error { - dc.Lock() - - for si := range dc.openStmt { - si.Close() - } - dc.openStmt = nil - - err := dc.ci.Close() - dc.ci = nil - dc.finalClosed = true - dc.Unlock() - - dc.db.mu.Lock() - dc.db.numOpen-- - dc.db.maybeOpenNewConnections() - dc.db.mu.Unlock() - - return err -} - -// driverStmt associates a driver.Stmt with the -// *driverConn from which it came, so the driverConn's lock can be -// held during calls. -type driverStmt struct { - sync.Locker // the *driverConn - si driver.Stmt -} - -func (ds *driverStmt) Close() error { - ds.Lock() - defer ds.Unlock() - return ds.si.Close() -} - -// depSet is a finalCloser's outstanding dependencies -type depSet map[interface{}]bool // set of true bools - -// The finalCloser interface is used by (*DB).addDep and related -// dependency reference counting. -type finalCloser interface { - // finalClose is called when the reference count of an object - // goes to zero. (*DB).mu is not held while calling it. - finalClose() error -} - -// addDep notes that x now depends on dep, and x's finalClose won't be -// called until all of x's dependencies are removed with removeDep. -func (db *DB) addDep(x finalCloser, dep interface{}) { - //println(fmt.Sprintf("addDep(%T %p, %T %p)", x, x, dep, dep)) - db.mu.Lock() - defer db.mu.Unlock() - db.addDepLocked(x, dep) -} - -func (db *DB) addDepLocked(x finalCloser, dep interface{}) { - if db.dep == nil { - db.dep = make(map[finalCloser]depSet) - } - xdep := db.dep[x] - if xdep == nil { - xdep = make(depSet) - db.dep[x] = xdep - } - xdep[dep] = true -} - -// removeDep notes that x no longer depends on dep. -// If x still has dependencies, nil is returned. -// If x no longer has any dependencies, its finalClose method will be -// called and its error value will be returned. -func (db *DB) removeDep(x finalCloser, dep interface{}) error { - db.mu.Lock() - fn := db.removeDepLocked(x, dep) - db.mu.Unlock() - return fn() -} - -func (db *DB) removeDepLocked(x finalCloser, dep interface{}) func() error { - //println(fmt.Sprintf("removeDep(%T %p, %T %p)", x, x, dep, dep)) - - xdep, ok := db.dep[x] - if !ok { - panic(fmt.Sprintf("unpaired removeDep: no deps for %T", x)) - } - - l0 := len(xdep) - delete(xdep, dep) - - switch len(xdep) { - case l0: - // Nothing removed. Shouldn't happen. - panic(fmt.Sprintf("unpaired removeDep: no %T dep on %T", dep, x)) - case 0: - // No more dependencies. - delete(db.dep, x) - return x.finalClose - default: - // Dependencies remain. - return func() error { return nil } - } -} - -// This is the size of the connectionOpener request chan (dn.openerCh). -// This value should be larger than the maximum typical value -// used for db.maxOpen. If maxOpen is significantly larger than -// connectionRequestQueueSize then it is possible for ALL calls into the *DB -// to block until the connectionOpener can satisfy the backlog of requests. -var connectionRequestQueueSize = 1000000 - -// Open opens a database specified by its database driver name and a -// driver-specific data source name, usually consisting of at least a -// database name and connection information. -// -// Most users will open a database via a driver-specific connection -// helper function that returns a *DB. No database drivers are included -// in the Go standard library. See http://golang.org/s/sqldrivers for -// a list of third-party drivers. -// -// Open may just validate its arguments without creating a connection -// to the database. To verify that the data source name is valid, call -// Ping. -// -// The returned DB is safe for concurrent use by multiple goroutines -// and maintains its own pool of idle connections. Thus, the Open -// function should be called just once. It is rarely necessary to -// close a DB. -func Open(driverName, dataSourceName string) (*DB, error) { - driveri, ok := drivers[driverName] - if !ok { - return nil, fmt.Errorf("sql: unknown driver %q (forgotten import?)", driverName) - } - db := &DB{ - driver: driveri, - dsn: dataSourceName, - openerCh: make(chan struct{}, connectionRequestQueueSize), - lastPut: make(map[*driverConn]string), - } - go db.connectionOpener() - return db, nil -} - -// Ping verifies a connection to the database is still alive, -// establishing a connection if necessary. -func (db *DB) Ping() error { - // TODO(bradfitz): give drivers an optional hook to implement - // this in a more efficient or more reliable way, if they - // have one. - dc, err := db.conn() - if err != nil { - return err - } - db.putConn(dc, nil) - return nil -} - -// Close closes the database, releasing any open resources. -// -// It is rare to Close a DB, as the DB handle is meant to be -// long-lived and shared between many goroutines. -func (db *DB) Close() error { - db.mu.Lock() - if db.closed { // Make DB.Close idempotent - db.mu.Unlock() - return nil - } - close(db.openerCh) - var err error - fns := make([]func() error, 0, len(db.freeConn)) - for _, dc := range db.freeConn { - fns = append(fns, dc.closeDBLocked()) - } - db.freeConn = nil - db.closed = true - for _, req := range db.connRequests { - close(req) - } - db.mu.Unlock() - for _, fn := range fns { - err1 := fn() - if err1 != nil { - err = err1 - } - } - return err -} - -const defaultMaxIdleConns = 2 - -func (db *DB) maxIdleConnsLocked() int { - n := db.maxIdle - switch { - case n == 0: - // TODO(bradfitz): ask driver, if supported, for its default preference - return defaultMaxIdleConns - case n < 0: - return 0 - default: - return n - } -} - -// SetMaxIdleConns sets the maximum number of connections in the idle -// connection pool. -// -// If MaxOpenConns is greater than 0 but less than the new MaxIdleConns -// then the new MaxIdleConns will be reduced to match the MaxOpenConns limit -// -// If n <= 0, no idle connections are retained. -func (db *DB) SetMaxIdleConns(n int) { - db.mu.Lock() - if n > 0 { - db.maxIdle = n - } else { - // No idle connections. - db.maxIdle = -1 - } - // Make sure maxIdle doesn't exceed maxOpen - if db.maxOpen > 0 && db.maxIdleConnsLocked() > db.maxOpen { - db.maxIdle = db.maxOpen - } - var closing []*driverConn - idleCount := len(db.freeConn) - maxIdle := db.maxIdleConnsLocked() - if idleCount > maxIdle { - closing = db.freeConn[maxIdle:] - db.freeConn = db.freeConn[:maxIdle] - } - db.mu.Unlock() - for _, c := range closing { - c.Close() - } -} - -// SetMaxOpenConns sets the maximum number of open connections to the database. -// -// If MaxIdleConns is greater than 0 and the new MaxOpenConns is less than -// MaxIdleConns, then MaxIdleConns will be reduced to match the new -// MaxOpenConns limit -// -// If n <= 0, then there is no limit on the number of open connections. -// The default is 0 (unlimited). -func (db *DB) SetMaxOpenConns(n int) { - db.mu.Lock() - db.maxOpen = n - if n < 0 { - db.maxOpen = 0 - } - syncMaxIdle := db.maxOpen > 0 && db.maxIdleConnsLocked() > db.maxOpen - db.mu.Unlock() - if syncMaxIdle { - db.SetMaxIdleConns(n) - } -} - -// Assumes db.mu is locked. -// If there are connRequests and the connection limit hasn't been reached, -// then tell the connectionOpener to open new connections. -func (db *DB) maybeOpenNewConnections() { - numRequests := len(db.connRequests) - db.pendingOpens - if db.maxOpen > 0 { - numCanOpen := db.maxOpen - (db.numOpen + db.pendingOpens) - if numRequests > numCanOpen { - numRequests = numCanOpen - } - } - for numRequests > 0 { - db.pendingOpens++ - numRequests-- - db.openerCh <- struct{}{} - } -} - -// Runs in a separate goroutine, opens new connections when requested. -func (db *DB) connectionOpener() { - for range db.openerCh { - db.openNewConnection() - } -} - -// Open one new connection -func (db *DB) openNewConnection() { - ci, err := db.driver.Open(db.dsn) - db.mu.Lock() - defer db.mu.Unlock() - if db.closed { - if err == nil { - ci.Close() - } - return - } - db.pendingOpens-- - if err != nil { - db.putConnDBLocked(nil, err) - return - } - dc := &driverConn{ - db: db, - ci: ci, - } - if db.putConnDBLocked(dc, err) { - db.addDepLocked(dc, dc) - db.numOpen++ - } else { - ci.Close() - } -} - -// connRequest represents one request for a new connection -// When there are no idle connections available, DB.conn will create -// a new connRequest and put it on the db.connRequests list. -type connRequest struct { - conn *driverConn - err error -} - -var errDBClosed = errors.New("sql: database is closed") - -// conn returns a newly-opened or cached *driverConn -func (db *DB) conn() (*driverConn, error) { - db.mu.Lock() - if db.closed { - db.mu.Unlock() - return nil, errDBClosed - } - - // If db.maxOpen > 0 and the number of open connections is over the limit - // and there are no free connection, make a request and wait. - if db.maxOpen > 0 && db.numOpen >= db.maxOpen && len(db.freeConn) == 0 { - // Make the connRequest channel. It's buffered so that the - // connectionOpener doesn't block while waiting for the req to be read. - req := make(chan connRequest, 1) - db.connRequests = append(db.connRequests, req) - db.maybeOpenNewConnections() - db.mu.Unlock() - ret := <-req - return ret.conn, ret.err - } - - if c := len(db.freeConn); c > 0 { - conn := db.freeConn[0] - copy(db.freeConn, db.freeConn[1:]) - db.freeConn = db.freeConn[:c-1] - conn.inUse = true - db.mu.Unlock() - return conn, nil - } - - db.numOpen++ // optimistically - db.mu.Unlock() - ci, err := db.driver.Open(db.dsn) - if err != nil { - db.mu.Lock() - db.numOpen-- // correct for earlier optimism - db.mu.Unlock() - return nil, err - } - db.mu.Lock() - dc := &driverConn{ - db: db, - ci: ci, - } - db.addDepLocked(dc, dc) - dc.inUse = true - db.mu.Unlock() - return dc, nil -} - -var ( - errConnClosed = errors.New("database/sql: internal sentinel error: conn is closed") - errConnBusy = errors.New("database/sql: internal sentinel error: conn is busy") -) - -// connIfFree returns (wanted, nil) if wanted is still a valid conn and -// isn't in use. -// -// The error is errConnClosed if the connection if the requested connection -// is invalid because it's been closed. -// -// The error is errConnBusy if the connection is in use. -func (db *DB) connIfFree(wanted *driverConn) (*driverConn, error) { - db.mu.Lock() - defer db.mu.Unlock() - if wanted.dbmuClosed { - return nil, errConnClosed - } - if wanted.inUse { - return nil, errConnBusy - } - idx := -1 - for ii, v := range db.freeConn { - if v == wanted { - idx = ii - break - } - } - if idx >= 0 { - db.freeConn = append(db.freeConn[:idx], db.freeConn[idx+1:]...) - wanted.inUse = true - return wanted, nil - } - // TODO(bradfitz): shouldn't get here. After Go 1.1, change this to: - // panic("connIfFree call requested a non-closed, non-busy, non-free conn") - // Which passes all the tests, but I'm too paranoid to include this - // late in Go 1.1. - // Instead, treat it like a busy connection: - return nil, errConnBusy -} - -// putConnHook is a hook for testing. -var putConnHook func(*DB, *driverConn) - -// noteUnusedDriverStatement notes that si is no longer used and should -// be closed whenever possible (when c is next not in use), unless c is -// already closed. -func (db *DB) noteUnusedDriverStatement(c *driverConn, si driver.Stmt) { - db.mu.Lock() - defer db.mu.Unlock() - if c.inUse { - c.onPut = append(c.onPut, func() { - si.Close() - }) - } else { - c.Lock() - defer c.Unlock() - if !c.finalClosed { - si.Close() - } - } -} - -// debugGetPut determines whether getConn & putConn calls' stack traces -// are returned for more verbose crashes. -const debugGetPut = false - -// putConn adds a connection to the db's free pool. -// err is optionally the last error that occurred on this connection. -func (db *DB) putConn(dc *driverConn, err error) { - db.mu.Lock() - if !dc.inUse { - if debugGetPut { - fmt.Printf("putConn(%v) DUPLICATE was: %s\n\nPREVIOUS was: %s", dc, stack(), db.lastPut[dc]) - } - panic("sql: connection returned that was never out") - } - if debugGetPut { - db.lastPut[dc] = stack() - } - dc.inUse = false - - for _, fn := range dc.onPut { - fn() - } - dc.onPut = nil - - if err == driver.ErrBadConn { - // Don't reuse bad connections. - // Since the conn is considered bad and is being discarded, treat it - // as closed. Don't decrement the open count here, finalClose will - // take care of that. - db.maybeOpenNewConnections() - db.mu.Unlock() - dc.Close() - return - } - if putConnHook != nil { - putConnHook(db, dc) - } - added := db.putConnDBLocked(dc, nil) - db.mu.Unlock() - - if !added { - dc.Close() - } -} - -// Satisfy a connRequest or put the driverConn in the idle pool and return true -// or return false. -// putConnDBLocked will satisfy a connRequest if there is one, or it will -// return the *driverConn to the freeConn list if err == nil and the idle -// connection limit will not be exceeded. -// If err != nil, the value of dc is ignored. -// If err == nil, then dc must not equal nil. -// If a connRequest was fulfilled or the *driverConn was placed in the -// freeConn list, then true is returned, otherwise false is returned. -func (db *DB) putConnDBLocked(dc *driverConn, err error) bool { - if c := len(db.connRequests); c > 0 { - req := db.connRequests[0] - // This copy is O(n) but in practice faster than a linked list. - // TODO: consider compacting it down less often and - // moving the base instead? - copy(db.connRequests, db.connRequests[1:]) - db.connRequests = db.connRequests[:c-1] - if err == nil { - dc.inUse = true - } - req <- connRequest{ - conn: dc, - err: err, - } - return true - } else if err == nil && !db.closed && db.maxIdleConnsLocked() > len(db.freeConn) { - db.freeConn = append(db.freeConn, dc) - return true - } - return false -} - -// maxBadConnRetries is the number of maximum retries if the driver returns -// driver.ErrBadConn to signal a broken connection. -const maxBadConnRetries = 10 - -// Prepare creates a prepared statement for later queries or executions. -// Multiple queries or executions may be run concurrently from the -// returned statement. -func (db *DB) Prepare(query string) (*Stmt, error) { - var stmt *Stmt - var err error - for i := 0; i < maxBadConnRetries; i++ { - stmt, err = db.prepare(query) - if err != driver.ErrBadConn { - break - } - } - return stmt, err -} - -func (db *DB) prepare(query string) (*Stmt, error) { - // TODO: check if db.driver supports an optional - // driver.Preparer interface and call that instead, if so, - // otherwise we make a prepared statement that's bound - // to a connection, and to execute this prepared statement - // we either need to use this connection (if it's free), else - // get a new connection + re-prepare + execute on that one. - dc, err := db.conn() - if err != nil { - return nil, err - } - dc.Lock() - si, err := dc.prepareLocked(query) - dc.Unlock() - if err != nil { - db.putConn(dc, err) - return nil, err - } - stmt := &Stmt{ - db: db, - query: query, - css: []connStmt{{dc, si}}, - } - db.addDep(stmt, stmt) - db.putConn(dc, nil) - return stmt, nil -} - -// Exec executes a query without returning any rows. -// The args are for any placeholder parameters in the query. -func (db *DB) Exec(query string, args ...interface{}) (Result, error) { - var res Result - var err error - for i := 0; i < maxBadConnRetries; i++ { - res, err = db.exec(query, args) - if err != driver.ErrBadConn { - break - } - } - return res, err -} - -func (db *DB) exec(query string, args []interface{}) (res Result, err error) { - dc, err := db.conn() - if err != nil { - return nil, err - } - defer func() { - db.putConn(dc, err) - }() - - if execer, ok := dc.ci.(driver.Execer); ok { - dargs, err := driverArgs(nil, args) - if err != nil { - return nil, err - } - dc.Lock() - resi, err := execer.Exec(query, dargs) - dc.Unlock() - if err != driver.ErrSkip { - if err != nil { - return nil, err - } - return driverResult{dc, resi}, nil - } - } - - dc.Lock() - si, err := dc.ci.Prepare(query) - dc.Unlock() - if err != nil { - return nil, err - } - defer withLock(dc, func() { si.Close() }) - return resultFromStatement(driverStmt{dc, si}, args...) -} - -// Query executes a query that returns rows, typically a SELECT. -// The args are for any placeholder parameters in the query. -func (db *DB) Query(query string, args ...interface{}) (*Rows, error) { - var rows *Rows - var err error - for i := 0; i < maxBadConnRetries; i++ { - rows, err = db.query(query, args) - if err != driver.ErrBadConn { - break - } - } - return rows, err -} - -func (db *DB) query(query string, args []interface{}) (*Rows, error) { - ci, err := db.conn() - if err != nil { - return nil, err - } - - return db.queryConn(ci, ci.releaseConn, query, args) -} - -// queryConn executes a query on the given connection. -// The connection gets released by the releaseConn function. -func (db *DB) queryConn(dc *driverConn, releaseConn func(error), query string, args []interface{}) (*Rows, error) { - if queryer, ok := dc.ci.(driver.Queryer); ok { - dargs, err := driverArgs(nil, args) - if err != nil { - releaseConn(err) - return nil, err - } - dc.Lock() - rowsi, err := queryer.Query(query, dargs) - dc.Unlock() - if err != driver.ErrSkip { - if err != nil { - releaseConn(err) - return nil, err - } - // Note: ownership of dc passes to the *Rows, to be freed - // with releaseConn. - rows := &Rows{ - dc: dc, - releaseConn: releaseConn, - rowsi: rowsi, - } - return rows, nil - } - } - - dc.Lock() - si, err := dc.ci.Prepare(query) - dc.Unlock() - if err != nil { - releaseConn(err) - return nil, err - } - - ds := driverStmt{dc, si} - rowsi, err := rowsiFromStatement(ds, args...) - if err != nil { - dc.Lock() - si.Close() - dc.Unlock() - releaseConn(err) - return nil, err - } - - // Note: ownership of ci passes to the *Rows, to be freed - // with releaseConn. - rows := &Rows{ - dc: dc, - releaseConn: releaseConn, - rowsi: rowsi, - closeStmt: si, - } - return rows, nil -} - -// QueryRow executes a query that is expected to return at most one row. -// QueryRow always return a non-nil value. Errors are deferred until -// Row's Scan method is called. -func (db *DB) QueryRow(query string, args ...interface{}) *Row { - rows, err := db.Query(query, args...) - return &Row{rows: rows, err: err} -} - -// Begin starts a transaction. The isolation level is dependent on -// the driver. -func (db *DB) Begin() (*Tx, error) { - var tx *Tx - var err error - for i := 0; i < maxBadConnRetries; i++ { - tx, err = db.begin() - if err != driver.ErrBadConn { - break - } - } - return tx, err -} - -func (db *DB) begin() (tx *Tx, err error) { - dc, err := db.conn() - if err != nil { - return nil, err - } - dc.Lock() - txi, err := dc.ci.Begin() - dc.Unlock() - if err != nil { - db.putConn(dc, err) - return nil, err - } - return &Tx{ - db: db, - dc: dc, - txi: txi, - }, nil -} - -// Driver returns the database's underlying driver. -func (db *DB) Driver() driver.Driver { - return db.driver -} - -// Tx is an in-progress database transaction. -// -// A transaction must end with a call to Commit or Rollback. -// -// After a call to Commit or Rollback, all operations on the -// transaction fail with ErrTxDone. -type Tx struct { - db *DB - - // dc is owned exclusively until Commit or Rollback, at which point - // it's returned with putConn. - dc *driverConn - txi driver.Tx - - // done transitions from false to true exactly once, on Commit - // or Rollback. once done, all operations fail with - // ErrTxDone. - done bool -} - -var ErrTxDone = errors.New("sql: Transaction has already been committed or rolled back") - -func (tx *Tx) close() { - if tx.done { - panic("double close") // internal error - } - tx.done = true - tx.db.putConn(tx.dc, nil) - tx.dc = nil - tx.txi = nil -} - -func (tx *Tx) grabConn() (*driverConn, error) { - if tx.done { - return nil, ErrTxDone - } - return tx.dc, nil -} - -// Commit commits the transaction. -func (tx *Tx) Commit() error { - if tx.done { - return ErrTxDone - } - defer tx.close() - tx.dc.Lock() - defer tx.dc.Unlock() - return tx.txi.Commit() -} - -// Rollback aborts the transaction. -func (tx *Tx) Rollback() error { - if tx.done { - return ErrTxDone - } - defer tx.close() - tx.dc.Lock() - defer tx.dc.Unlock() - return tx.txi.Rollback() -} - -// Prepare creates a prepared statement for use within a transaction. -// -// The returned statement operates within the transaction and can no longer -// be used once the transaction has been committed or rolled back. -// -// To use an existing prepared statement on this transaction, see Tx.Stmt. -func (tx *Tx) Prepare(query string) (*Stmt, error) { - // TODO(bradfitz): We could be more efficient here and either - // provide a method to take an existing Stmt (created on - // perhaps a different Conn), and re-create it on this Conn if - // necessary. Or, better: keep a map in DB of query string to - // Stmts, and have Stmt.Execute do the right thing and - // re-prepare if the Conn in use doesn't have that prepared - // statement. But we'll want to avoid caching the statement - // in the case where we only call conn.Prepare implicitly - // (such as in db.Exec or tx.Exec), but the caller package - // can't be holding a reference to the returned statement. - // Perhaps just looking at the reference count (by noting - // Stmt.Close) would be enough. We might also want a finalizer - // on Stmt to drop the reference count. - dc, err := tx.grabConn() - if err != nil { - return nil, err - } - - dc.Lock() - si, err := dc.ci.Prepare(query) - dc.Unlock() - if err != nil { - return nil, err - } - - stmt := &Stmt{ - db: tx.db, - tx: tx, - txsi: &driverStmt{ - Locker: dc, - si: si, - }, - query: query, - } - return stmt, nil -} - -// Stmt returns a transaction-specific prepared statement from -// an existing statement. -// -// Example: -// updateMoney, err := db.Prepare("UPDATE balance SET money=money+? WHERE id=?") -// ... -// tx, err := db.Begin() -// ... -// res, err := tx.Stmt(updateMoney).Exec(123.45, 98293203) -func (tx *Tx) Stmt(stmt *Stmt) *Stmt { - // TODO(bradfitz): optimize this. Currently this re-prepares - // each time. This is fine for now to illustrate the API but - // we should really cache already-prepared statements - // per-Conn. See also the big comment in Tx.Prepare. - - if tx.db != stmt.db { - return &Stmt{stickyErr: errors.New("sql: Tx.Stmt: statement from different database used")} - } - dc, err := tx.grabConn() - if err != nil { - return &Stmt{stickyErr: err} - } - dc.Lock() - si, err := dc.ci.Prepare(stmt.query) - dc.Unlock() - return &Stmt{ - db: tx.db, - tx: tx, - txsi: &driverStmt{ - Locker: dc, - si: si, - }, - query: stmt.query, - stickyErr: err, - } -} - -// Exec executes a query that doesn't return rows. -// For example: an INSERT and UPDATE. -func (tx *Tx) Exec(query string, args ...interface{}) (Result, error) { - dc, err := tx.grabConn() - if err != nil { - return nil, err - } - - if execer, ok := dc.ci.(driver.Execer); ok { - dargs, err := driverArgs(nil, args) - if err != nil { - return nil, err - } - dc.Lock() - resi, err := execer.Exec(query, dargs) - dc.Unlock() - if err == nil { - return driverResult{dc, resi}, nil - } - if err != driver.ErrSkip { - return nil, err - } - } - - dc.Lock() - si, err := dc.ci.Prepare(query) - dc.Unlock() - if err != nil { - return nil, err - } - defer withLock(dc, func() { si.Close() }) - - return resultFromStatement(driverStmt{dc, si}, args...) -} - -// Query executes a query that returns rows, typically a SELECT. -func (tx *Tx) Query(query string, args ...interface{}) (*Rows, error) { - dc, err := tx.grabConn() - if err != nil { - return nil, err - } - releaseConn := func(error) {} - return tx.db.queryConn(dc, releaseConn, query, args) -} - -// QueryRow executes a query that is expected to return at most one row. -// QueryRow always return a non-nil value. Errors are deferred until -// Row's Scan method is called. -func (tx *Tx) QueryRow(query string, args ...interface{}) *Row { - rows, err := tx.Query(query, args...) - return &Row{rows: rows, err: err} -} - -// connStmt is a prepared statement on a particular connection. -type connStmt struct { - dc *driverConn - si driver.Stmt -} - -// Stmt is a prepared statement. Stmt is safe for concurrent use by multiple goroutines. -type Stmt struct { - // Immutable: - db *DB // where we came from - query string // that created the Stmt - stickyErr error // if non-nil, this error is returned for all operations - - closemu sync.RWMutex // held exclusively during close, for read otherwise. - - // If in a transaction, else both nil: - tx *Tx - txsi *driverStmt - - mu sync.Mutex // protects the rest of the fields - closed bool - - // css is a list of underlying driver statement interfaces - // that are valid on particular connections. This is only - // used if tx == nil and one is found that has idle - // connections. If tx != nil, txsi is always used. - css []connStmt -} - -// Exec executes a prepared statement with the given arguments and -// returns a Result summarizing the effect of the statement. -func (s *Stmt) Exec(args ...interface{}) (Result, error) { - s.closemu.RLock() - defer s.closemu.RUnlock() - - var res Result - for i := 0; i < maxBadConnRetries; i++ { - dc, releaseConn, si, err := s.connStmt() - if err != nil { - if err == driver.ErrBadConn { - continue - } - return nil, err - } - - res, err = resultFromStatement(driverStmt{dc, si}, args...) - releaseConn(err) - if err != driver.ErrBadConn { - return res, err - } - } - return nil, driver.ErrBadConn -} - -func resultFromStatement(ds driverStmt, args ...interface{}) (Result, error) { - ds.Lock() - want := ds.si.NumInput() - ds.Unlock() - - // -1 means the driver doesn't know how to count the number of - // placeholders, so we won't sanity check input here and instead let the - // driver deal with errors. - if want != -1 && len(args) != want { - return nil, fmt.Errorf("sql: expected %d arguments, got %d", want, len(args)) - } - - dargs, err := driverArgs(&ds, args) - if err != nil { - return nil, err - } - - ds.Lock() - resi, err := ds.si.Exec(dargs) - ds.Unlock() - if err != nil { - return nil, err - } - return driverResult{ds.Locker, resi}, nil -} - -// connStmt returns a free driver connection on which to execute the -// statement, a function to call to release the connection, and a -// statement bound to that connection. -func (s *Stmt) connStmt() (ci *driverConn, releaseConn func(error), si driver.Stmt, err error) { - if err = s.stickyErr; err != nil { - return - } - s.mu.Lock() - if s.closed { - s.mu.Unlock() - err = errors.New("sql: statement is closed") - return - } - - // In a transaction, we always use the connection that the - // transaction was created on. - if s.tx != nil { - s.mu.Unlock() - ci, err = s.tx.grabConn() // blocks, waiting for the connection. - if err != nil { - return - } - releaseConn = func(error) {} - return ci, releaseConn, s.txsi.si, nil - } - - for i := 0; i < len(s.css); i++ { - v := s.css[i] - _, err := s.db.connIfFree(v.dc) - if err == nil { - s.mu.Unlock() - return v.dc, v.dc.releaseConn, v.si, nil - } - if err == errConnClosed { - // Lazily remove dead conn from our freelist. - s.css[i] = s.css[len(s.css)-1] - s.css = s.css[:len(s.css)-1] - i-- - } - - } - s.mu.Unlock() - - // If all connections are busy, either wait for one to become available (if - // we've already hit the maximum number of open connections) or create a - // new one. - // - // TODO(bradfitz): or always wait for one? make configurable later? - dc, err := s.db.conn() - if err != nil { - return nil, nil, nil, err - } - - // Do another pass over the list to see whether this statement has - // already been prepared on the connection assigned to us. - s.mu.Lock() - for _, v := range s.css { - if v.dc == dc { - s.mu.Unlock() - return dc, dc.releaseConn, v.si, nil - } - } - s.mu.Unlock() - - // No luck; we need to prepare the statement on this connection - dc.Lock() - si, err = dc.prepareLocked(s.query) - dc.Unlock() - if err != nil { - s.db.putConn(dc, err) - return nil, nil, nil, err - } - s.mu.Lock() - cs := connStmt{dc, si} - s.css = append(s.css, cs) - s.mu.Unlock() - - return dc, dc.releaseConn, si, nil -} - -// Query executes a prepared query statement with the given arguments -// and returns the query results as a *Rows. -func (s *Stmt) Query(args ...interface{}) (*Rows, error) { - s.closemu.RLock() - defer s.closemu.RUnlock() - - var rowsi driver.Rows - for i := 0; i < maxBadConnRetries; i++ { - dc, releaseConn, si, err := s.connStmt() - if err != nil { - if err == driver.ErrBadConn { - continue - } - return nil, err - } - - rowsi, err = rowsiFromStatement(driverStmt{dc, si}, args...) - if err == nil { - // Note: ownership of ci passes to the *Rows, to be freed - // with releaseConn. - rows := &Rows{ - dc: dc, - rowsi: rowsi, - // releaseConn set below - } - s.db.addDep(s, rows) - rows.releaseConn = func(err error) { - releaseConn(err) - s.db.removeDep(s, rows) - } - return rows, nil - } - - releaseConn(err) - if err != driver.ErrBadConn { - return nil, err - } - } - return nil, driver.ErrBadConn -} - -func rowsiFromStatement(ds driverStmt, args ...interface{}) (driver.Rows, error) { - ds.Lock() - want := ds.si.NumInput() - ds.Unlock() - - // -1 means the driver doesn't know how to count the number of - // placeholders, so we won't sanity check input here and instead let the - // driver deal with errors. - if want != -1 && len(args) != want { - return nil, fmt.Errorf("sql: statement expects %d inputs; got %d", want, len(args)) - } - - dargs, err := driverArgs(&ds, args) - if err != nil { - return nil, err - } - - ds.Lock() - rowsi, err := ds.si.Query(dargs) - ds.Unlock() - if err != nil { - return nil, err - } - return rowsi, nil -} - -// QueryRow executes a prepared query statement with the given arguments. -// If an error occurs during the execution of the statement, that error will -// be returned by a call to Scan on the returned *Row, which is always non-nil. -// If the query selects no rows, the *Row's Scan will return ErrNoRows. -// Otherwise, the *Row's Scan scans the first selected row and discards -// the rest. -// -// Example usage: -// -// var name string -// err := nameByUseridStmt.QueryRow(id).Scan(&name) -func (s *Stmt) QueryRow(args ...interface{}) *Row { - rows, err := s.Query(args...) - if err != nil { - return &Row{err: err} - } - return &Row{rows: rows} -} - -// Close closes the statement. -func (s *Stmt) Close() error { - s.closemu.Lock() - defer s.closemu.Unlock() - - if s.stickyErr != nil { - return s.stickyErr - } - s.mu.Lock() - if s.closed { - s.mu.Unlock() - return nil - } - s.closed = true - - if s.tx != nil { - s.txsi.Close() - s.mu.Unlock() - return nil - } - s.mu.Unlock() - - return s.db.removeDep(s, s) -} - -func (s *Stmt) finalClose() error { - s.mu.Lock() - defer s.mu.Unlock() - if s.css != nil { - for _, v := range s.css { - s.db.noteUnusedDriverStatement(v.dc, v.si) - v.dc.removeOpenStmt(v.si) - } - s.css = nil - } - return nil -} - -// Rows is the result of a query. Its cursor starts before the first row -// of the result set. Use Next to advance through the rows: -// -// rows, err := db.Query("SELECT ...") -// ... -// defer rows.Close() -// for rows.Next() { -// var id int -// var name string -// err = rows.Scan(&id, &name) -// ... -// } -// err = rows.Err() // get any error encountered during iteration -// ... -type Rows struct { - dc *driverConn // owned; must call releaseConn when closed to release - releaseConn func(error) - rowsi driver.Rows - - closed bool - lastcols []driver.Value - lasterr error // non-nil only if closed is true - closeStmt driver.Stmt // if non-nil, statement to Close on close -} - -// Next prepares the next result row for reading with the Scan method. It -// returns true on success, or false if there is no next result row or an error -// happened while preparing it. Err should be consulted to distinguish between -// the two cases. -// -// Every call to Scan, even the first one, must be preceded by a call to Next. -func (rs *Rows) Next() bool { - if rs.closed { - return false - } - if rs.lastcols == nil { - rs.lastcols = make([]driver.Value, len(rs.rowsi.Columns())) - } - rs.lasterr = rs.rowsi.Next(rs.lastcols) - if rs.lasterr != nil { - rs.Close() - return false - } - return true -} - -// Err returns the error, if any, that was encountered during iteration. -// Err may be called after an explicit or implicit Close. -func (rs *Rows) Err() error { - if rs.lasterr == io.EOF { - return nil - } - return rs.lasterr -} - -// Columns returns the column names. -// Columns returns an error if the rows are closed, or if the rows -// are from QueryRow and there was a deferred error. -func (rs *Rows) Columns() ([]string, error) { - if rs.closed { - return nil, errors.New("sql: Rows are closed") - } - if rs.rowsi == nil { - return nil, errors.New("sql: no Rows available") - } - return rs.rowsi.Columns(), nil -} - -// Scan copies the columns in the current row into the values pointed -// at by dest. -// -// If an argument has type *[]byte, Scan saves in that argument a copy -// of the corresponding data. The copy is owned by the caller and can -// be modified and held indefinitely. The copy can be avoided by using -// an argument of type *RawBytes instead; see the documentation for -// RawBytes for restrictions on its use. -// -// If an argument has type *interface{}, Scan copies the value -// provided by the underlying driver without conversion. If the value -// is of type []byte, a copy is made and the caller owns the result. -func (rs *Rows) Scan(dest ...interface{}) error { - if rs.closed { - return errors.New("sql: Rows are closed") - } - if rs.lastcols == nil { - return errors.New("sql: Scan called without calling Next") - } - if len(dest) != len(rs.lastcols) { - return fmt.Errorf("sql: expected %d destination arguments in Scan, not %d", len(rs.lastcols), len(dest)) - } - for i, sv := range rs.lastcols { - err := convertAssign(dest[i], sv) - if err != nil { - return fmt.Errorf("sql: Scan error on column index %d: %v", i, err) - } - } - return nil -} - -var rowsCloseHook func(*Rows, *error) - -// Close closes the Rows, preventing further enumeration. If Next returns -// false, the Rows are closed automatically and it will suffice to check the -// result of Err. Close is idempotent and does not affect the result of Err. -func (rs *Rows) Close() error { - if rs.closed { - return nil - } - rs.closed = true - err := rs.rowsi.Close() - if fn := rowsCloseHook; fn != nil { - fn(rs, &err) - } - if rs.closeStmt != nil { - rs.closeStmt.Close() - } - rs.releaseConn(err) - return err -} - -// Row is the result of calling QueryRow to select a single row. -type Row struct { - // One of these two will be non-nil: - err error // deferred error for easy chaining - rows *Rows -} - -// Scan copies the columns from the matched row into the values -// pointed at by dest. If more than one row matches the query, -// Scan uses the first row and discards the rest. If no row matches -// the query, Scan returns ErrNoRows. -func (r *Row) Scan(dest ...interface{}) error { - if r.err != nil { - return r.err - } - - // TODO(bradfitz): for now we need to defensively clone all - // []byte that the driver returned (not permitting - // *RawBytes in Rows.Scan), since we're about to close - // the Rows in our defer, when we return from this function. - // the contract with the driver.Next(...) interface is that it - // can return slices into read-only temporary memory that's - // only valid until the next Scan/Close. But the TODO is that - // for a lot of drivers, this copy will be unnecessary. We - // should provide an optional interface for drivers to - // implement to say, "don't worry, the []bytes that I return - // from Next will not be modified again." (for instance, if - // they were obtained from the network anyway) But for now we - // don't care. - defer r.rows.Close() - for _, dp := range dest { - if _, ok := dp.(*RawBytes); ok { - return errors.New("sql: RawBytes isn't allowed on Row.Scan") - } - } - - if !r.rows.Next() { - if err := r.rows.Err(); err != nil { - return err - } - return ErrNoRows - } - err := r.rows.Scan(dest...) - if err != nil { - return err - } - // Make sure the query can be processed to completion with no errors. - if err := r.rows.Close(); err != nil { - return err - } - - return nil -} - -// A Result summarizes an executed SQL command. -type Result interface { - // LastInsertId returns the integer generated by the database - // in response to a command. Typically this will be from an - // "auto increment" column when inserting a new row. Not all - // databases support this feature, and the syntax of such - // statements varies. - LastInsertId() (int64, error) - - // RowsAffected returns the number of rows affected by an - // update, insert, or delete. Not every database or database - // driver may support this. - RowsAffected() (int64, error) -} - -type driverResult struct { - sync.Locker // the *driverConn - resi driver.Result -} - -func (dr driverResult) LastInsertId() (int64, error) { - dr.Lock() - defer dr.Unlock() - return dr.resi.LastInsertId() -} - -func (dr driverResult) RowsAffected() (int64, error) { - dr.Lock() - defer dr.Unlock() - return dr.resi.RowsAffected() -} - -func stack() string { - var buf [2 << 10]byte - return string(buf[:runtime.Stack(buf[:], false)]) -} - -// withLock runs while holding lk. -func withLock(lk sync.Locker, fn func()) { - lk.Lock() - fn() - lk.Unlock() -} diff --git a/src/pkg/database/sql/sql_test.go b/src/pkg/database/sql/sql_test.go deleted file mode 100644 index 12e5a6fd6..000000000 --- a/src/pkg/database/sql/sql_test.go +++ /dev/null @@ -1,1956 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package sql - -import ( - "database/sql/driver" - "errors" - "fmt" - "math/rand" - "reflect" - "runtime" - "strings" - "sync" - "testing" - "time" -) - -func init() { - type dbConn struct { - db *DB - c *driverConn - } - freedFrom := make(map[dbConn]string) - putConnHook = func(db *DB, c *driverConn) { - idx := -1 - for i, v := range db.freeConn { - if v == c { - idx = i - break - } - } - if idx >= 0 { - // print before panic, as panic may get lost due to conflicting panic - // (all goroutines asleep) elsewhere, since we might not unlock - // the mutex in freeConn here. - println("double free of conn. conflicts are:\nA) " + freedFrom[dbConn{db, c}] + "\n\nand\nB) " + stack()) - panic("double free of conn.") - } - freedFrom[dbConn{db, c}] = stack() - } -} - -const fakeDBName = "foo" - -var chrisBirthday = time.Unix(123456789, 0) - -func newTestDB(t testing.TB, name string) *DB { - db, err := Open("test", fakeDBName) - if err != nil { - t.Fatalf("Open: %v", err) - } - if _, err := db.Exec("WIPE"); err != nil { - t.Fatalf("exec wipe: %v", err) - } - if name == "people" { - exec(t, db, "CREATE|people|name=string,age=int32,photo=blob,dead=bool,bdate=datetime") - exec(t, db, "INSERT|people|name=Alice,age=?,photo=APHOTO", 1) - exec(t, db, "INSERT|people|name=Bob,age=?,photo=BPHOTO", 2) - exec(t, db, "INSERT|people|name=Chris,age=?,photo=CPHOTO,bdate=?", 3, chrisBirthday) - } - if name == "magicquery" { - // Magic table name and column, known by fakedb_test.go. - exec(t, db, "CREATE|magicquery|op=string,millis=int32") - exec(t, db, "INSERT|magicquery|op=sleep,millis=10") - } - return db -} - -func exec(t testing.TB, db *DB, query string, args ...interface{}) { - _, err := db.Exec(query, args...) - if err != nil { - t.Fatalf("Exec of %q: %v", query, err) - } -} - -func closeDB(t testing.TB, db *DB) { - if e := recover(); e != nil { - fmt.Printf("Panic: %v\n", e) - panic(e) - } - defer setHookpostCloseConn(nil) - setHookpostCloseConn(func(_ *fakeConn, err error) { - if err != nil { - t.Errorf("Error closing fakeConn: %v", err) - } - }) - for i, dc := range db.freeConn { - if n := len(dc.openStmt); n > 0 { - // Just a sanity check. This is legal in - // general, but if we make the tests clean up - // their statements first, then we can safely - // verify this is always zero here, and any - // other value is a leak. - t.Errorf("while closing db, freeConn %d/%d had %d open stmts; want 0", i, len(db.freeConn), n) - } - } - err := db.Close() - if err != nil { - t.Fatalf("error closing DB: %v", err) - } - db.mu.Lock() - count := db.numOpen - db.mu.Unlock() - if count != 0 { - t.Fatalf("%d connections still open after closing DB", db.numOpen) - } -} - -// numPrepares assumes that db has exactly 1 idle conn and returns -// its count of calls to Prepare -func numPrepares(t *testing.T, db *DB) int { - if n := len(db.freeConn); n != 1 { - t.Fatalf("free conns = %d; want 1", n) - } - return db.freeConn[0].ci.(*fakeConn).numPrepare -} - -func (db *DB) numDeps() int { - db.mu.Lock() - defer db.mu.Unlock() - return len(db.dep) -} - -// Dependencies are closed via a goroutine, so this polls waiting for -// numDeps to fall to want, waiting up to d. -func (db *DB) numDepsPollUntil(want int, d time.Duration) int { - deadline := time.Now().Add(d) - for { - n := db.numDeps() - if n <= want || time.Now().After(deadline) { - return n - } - time.Sleep(50 * time.Millisecond) - } -} - -func (db *DB) numFreeConns() int { - db.mu.Lock() - defer db.mu.Unlock() - return len(db.freeConn) -} - -func (db *DB) dumpDeps(t *testing.T) { - for fc := range db.dep { - db.dumpDep(t, 0, fc, map[finalCloser]bool{}) - } -} - -func (db *DB) dumpDep(t *testing.T, depth int, dep finalCloser, seen map[finalCloser]bool) { - seen[dep] = true - indent := strings.Repeat(" ", depth) - ds := db.dep[dep] - for k := range ds { - t.Logf("%s%T (%p) waiting for -> %T (%p)", indent, dep, dep, k, k) - if fc, ok := k.(finalCloser); ok { - if !seen[fc] { - db.dumpDep(t, depth+1, fc, seen) - } - } - } -} - -func TestQuery(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - prepares0 := numPrepares(t, db) - rows, err := db.Query("SELECT|people|age,name|") - if err != nil { - t.Fatalf("Query: %v", err) - } - type row struct { - age int - name string - } - got := []row{} - for rows.Next() { - var r row - err = rows.Scan(&r.age, &r.name) - if err != nil { - t.Fatalf("Scan: %v", err) - } - got = append(got, r) - } - err = rows.Err() - if err != nil { - t.Fatalf("Err: %v", err) - } - want := []row{ - {age: 1, name: "Alice"}, - {age: 2, name: "Bob"}, - {age: 3, name: "Chris"}, - } - if !reflect.DeepEqual(got, want) { - t.Errorf("mismatch.\n got: %#v\nwant: %#v", got, want) - } - - // And verify that the final rows.Next() call, which hit EOF, - // also closed the rows connection. - if n := db.numFreeConns(); n != 1 { - t.Fatalf("free conns after query hitting EOF = %d; want 1", n) - } - if prepares := numPrepares(t, db) - prepares0; prepares != 1 { - t.Errorf("executed %d Prepare statements; want 1", prepares) - } -} - -func TestByteOwnership(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - rows, err := db.Query("SELECT|people|name,photo|") - if err != nil { - t.Fatalf("Query: %v", err) - } - type row struct { - name []byte - photo RawBytes - } - got := []row{} - for rows.Next() { - var r row - err = rows.Scan(&r.name, &r.photo) - if err != nil { - t.Fatalf("Scan: %v", err) - } - got = append(got, r) - } - corruptMemory := []byte("\xffPHOTO") - want := []row{ - {name: []byte("Alice"), photo: corruptMemory}, - {name: []byte("Bob"), photo: corruptMemory}, - {name: []byte("Chris"), photo: corruptMemory}, - } - if !reflect.DeepEqual(got, want) { - t.Errorf("mismatch.\n got: %#v\nwant: %#v", got, want) - } - - var photo RawBytes - err = db.QueryRow("SELECT|people|photo|name=?", "Alice").Scan(&photo) - if err == nil { - t.Error("want error scanning into RawBytes from QueryRow") - } -} - -func TestRowsColumns(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - rows, err := db.Query("SELECT|people|age,name|") - if err != nil { - t.Fatalf("Query: %v", err) - } - cols, err := rows.Columns() - if err != nil { - t.Fatalf("Columns: %v", err) - } - want := []string{"age", "name"} - if !reflect.DeepEqual(cols, want) { - t.Errorf("got %#v; want %#v", cols, want) - } - if err := rows.Close(); err != nil { - t.Errorf("error closing rows: %s", err) - } -} - -func TestQueryRow(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - var name string - var age int - var birthday time.Time - - err := db.QueryRow("SELECT|people|age,name|age=?", 3).Scan(&age) - if err == nil || !strings.Contains(err.Error(), "expected 2 destination arguments") { - t.Errorf("expected error from wrong number of arguments; actually got: %v", err) - } - - err = db.QueryRow("SELECT|people|bdate|age=?", 3).Scan(&birthday) - if err != nil || !birthday.Equal(chrisBirthday) { - t.Errorf("chris birthday = %v, err = %v; want %v", birthday, err, chrisBirthday) - } - - err = db.QueryRow("SELECT|people|age,name|age=?", 2).Scan(&age, &name) - if err != nil { - t.Fatalf("age QueryRow+Scan: %v", err) - } - if name != "Bob" { - t.Errorf("expected name Bob, got %q", name) - } - if age != 2 { - t.Errorf("expected age 2, got %d", age) - } - - err = db.QueryRow("SELECT|people|age,name|name=?", "Alice").Scan(&age, &name) - if err != nil { - t.Fatalf("name QueryRow+Scan: %v", err) - } - if name != "Alice" { - t.Errorf("expected name Alice, got %q", name) - } - if age != 1 { - t.Errorf("expected age 1, got %d", age) - } - - var photo []byte - err = db.QueryRow("SELECT|people|photo|name=?", "Alice").Scan(&photo) - if err != nil { - t.Fatalf("photo QueryRow+Scan: %v", err) - } - want := []byte("APHOTO") - if !reflect.DeepEqual(photo, want) { - t.Errorf("photo = %q; want %q", photo, want) - } -} - -func TestStatementErrorAfterClose(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - stmt, err := db.Prepare("SELECT|people|age|name=?") - if err != nil { - t.Fatalf("Prepare: %v", err) - } - err = stmt.Close() - if err != nil { - t.Fatalf("Close: %v", err) - } - var name string - err = stmt.QueryRow("foo").Scan(&name) - if err == nil { - t.Errorf("expected error from QueryRow.Scan after Stmt.Close") - } -} - -func TestStatementQueryRow(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - stmt, err := db.Prepare("SELECT|people|age|name=?") - if err != nil { - t.Fatalf("Prepare: %v", err) - } - defer stmt.Close() - var age int - for n, tt := range []struct { - name string - want int - }{ - {"Alice", 1}, - {"Bob", 2}, - {"Chris", 3}, - } { - if err := stmt.QueryRow(tt.name).Scan(&age); err != nil { - t.Errorf("%d: on %q, QueryRow/Scan: %v", n, tt.name, err) - } else if age != tt.want { - t.Errorf("%d: age=%d, want %d", n, age, tt.want) - } - } -} - -// golang.org/issue/3734 -func TestStatementQueryRowConcurrent(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - stmt, err := db.Prepare("SELECT|people|age|name=?") - if err != nil { - t.Fatalf("Prepare: %v", err) - } - defer stmt.Close() - - const n = 10 - ch := make(chan error, n) - for i := 0; i < n; i++ { - go func() { - var age int - err := stmt.QueryRow("Alice").Scan(&age) - if err == nil && age != 1 { - err = fmt.Errorf("unexpected age %d", age) - } - ch <- err - }() - } - for i := 0; i < n; i++ { - if err := <-ch; err != nil { - t.Error(err) - } - } -} - -// just a test of fakedb itself -func TestBogusPreboundParameters(t *testing.T) { - db := newTestDB(t, "foo") - defer closeDB(t, db) - exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool") - _, err := db.Prepare("INSERT|t1|name=?,age=bogusconversion") - if err == nil { - t.Fatalf("expected error") - } - if err.Error() != `fakedb: invalid conversion to int32 from "bogusconversion"` { - t.Errorf("unexpected error: %v", err) - } -} - -func TestExec(t *testing.T) { - db := newTestDB(t, "foo") - defer closeDB(t, db) - exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool") - stmt, err := db.Prepare("INSERT|t1|name=?,age=?") - if err != nil { - t.Errorf("Stmt, err = %v, %v", stmt, err) - } - defer stmt.Close() - - type execTest struct { - args []interface{} - wantErr string - } - execTests := []execTest{ - // Okay: - {[]interface{}{"Brad", 31}, ""}, - {[]interface{}{"Brad", int64(31)}, ""}, - {[]interface{}{"Bob", "32"}, ""}, - {[]interface{}{7, 9}, ""}, - - // Invalid conversions: - {[]interface{}{"Brad", int64(0xFFFFFFFF)}, "sql: converting argument #1's type: sql/driver: value 4294967295 overflows int32"}, - {[]interface{}{"Brad", "strconv fail"}, "sql: converting argument #1's type: sql/driver: value \"strconv fail\" can't be converted to int32"}, - - // Wrong number of args: - {[]interface{}{}, "sql: expected 2 arguments, got 0"}, - {[]interface{}{1, 2, 3}, "sql: expected 2 arguments, got 3"}, - } - for n, et := range execTests { - _, err := stmt.Exec(et.args...) - errStr := "" - if err != nil { - errStr = err.Error() - } - if errStr != et.wantErr { - t.Errorf("stmt.Execute #%d: for %v, got error %q, want error %q", - n, et.args, errStr, et.wantErr) - } - } -} - -func TestTxStmt(t *testing.T) { - db := newTestDB(t, "") - defer closeDB(t, db) - exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool") - stmt, err := db.Prepare("INSERT|t1|name=?,age=?") - if err != nil { - t.Fatalf("Stmt, err = %v, %v", stmt, err) - } - defer stmt.Close() - tx, err := db.Begin() - if err != nil { - t.Fatalf("Begin = %v", err) - } - txs := tx.Stmt(stmt) - defer txs.Close() - _, err = txs.Exec("Bobby", 7) - if err != nil { - t.Fatalf("Exec = %v", err) - } - err = tx.Commit() - if err != nil { - t.Fatalf("Commit = %v", err) - } -} - -// Issue: http://golang.org/issue/2784 -// This test didn't fail before because we got lucky with the fakedb driver. -// It was failing, and now not, in github.com/bradfitz/go-sql-test -func TestTxQuery(t *testing.T) { - db := newTestDB(t, "") - defer closeDB(t, db) - exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool") - exec(t, db, "INSERT|t1|name=Alice") - - tx, err := db.Begin() - if err != nil { - t.Fatal(err) - } - defer tx.Rollback() - - r, err := tx.Query("SELECT|t1|name|") - if err != nil { - t.Fatal(err) - } - defer r.Close() - - if !r.Next() { - if r.Err() != nil { - t.Fatal(r.Err()) - } - t.Fatal("expected one row") - } - - var x string - err = r.Scan(&x) - if err != nil { - t.Fatal(err) - } -} - -func TestTxQueryInvalid(t *testing.T) { - db := newTestDB(t, "") - defer closeDB(t, db) - - tx, err := db.Begin() - if err != nil { - t.Fatal(err) - } - defer tx.Rollback() - - _, err = tx.Query("SELECT|t1|name|") - if err == nil { - t.Fatal("Error expected") - } -} - -// Tests fix for issue 4433, that retries in Begin happen when -// conn.Begin() returns ErrBadConn -func TestTxErrBadConn(t *testing.T) { - db, err := Open("test", fakeDBName+";badConn") - if err != nil { - t.Fatalf("Open: %v", err) - } - if _, err := db.Exec("WIPE"); err != nil { - t.Fatalf("exec wipe: %v", err) - } - defer closeDB(t, db) - exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool") - stmt, err := db.Prepare("INSERT|t1|name=?,age=?") - if err != nil { - t.Fatalf("Stmt, err = %v, %v", stmt, err) - } - defer stmt.Close() - tx, err := db.Begin() - if err != nil { - t.Fatalf("Begin = %v", err) - } - txs := tx.Stmt(stmt) - defer txs.Close() - _, err = txs.Exec("Bobby", 7) - if err != nil { - t.Fatalf("Exec = %v", err) - } - err = tx.Commit() - if err != nil { - t.Fatalf("Commit = %v", err) - } -} - -// Tests fix for issue 2542, that we release a lock when querying on -// a closed connection. -func TestIssue2542Deadlock(t *testing.T) { - db := newTestDB(t, "people") - closeDB(t, db) - for i := 0; i < 2; i++ { - _, err := db.Query("SELECT|people|age,name|") - if err == nil { - t.Fatalf("expected error") - } - } -} - -// From golang.org/issue/3865 -func TestCloseStmtBeforeRows(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - - s, err := db.Prepare("SELECT|people|name|") - if err != nil { - t.Fatal(err) - } - - r, err := s.Query() - if err != nil { - s.Close() - t.Fatal(err) - } - - err = s.Close() - if err != nil { - t.Fatal(err) - } - - r.Close() -} - -// Tests fix for issue 2788, that we bind nil to a []byte if the -// value in the column is sql null -func TestNullByteSlice(t *testing.T) { - db := newTestDB(t, "") - defer closeDB(t, db) - exec(t, db, "CREATE|t|id=int32,name=nullstring") - exec(t, db, "INSERT|t|id=10,name=?", nil) - - var name []byte - - err := db.QueryRow("SELECT|t|name|id=?", 10).Scan(&name) - if err != nil { - t.Fatal(err) - } - if name != nil { - t.Fatalf("name []byte should be nil for null column value, got: %#v", name) - } - - exec(t, db, "INSERT|t|id=11,name=?", "bob") - err = db.QueryRow("SELECT|t|name|id=?", 11).Scan(&name) - if err != nil { - t.Fatal(err) - } - if string(name) != "bob" { - t.Fatalf("name []byte should be bob, got: %q", string(name)) - } -} - -func TestPointerParamsAndScans(t *testing.T) { - db := newTestDB(t, "") - defer closeDB(t, db) - exec(t, db, "CREATE|t|id=int32,name=nullstring") - - bob := "bob" - var name *string - - name = &bob - exec(t, db, "INSERT|t|id=10,name=?", name) - name = nil - exec(t, db, "INSERT|t|id=20,name=?", name) - - err := db.QueryRow("SELECT|t|name|id=?", 10).Scan(&name) - if err != nil { - t.Fatalf("querying id 10: %v", err) - } - if name == nil { - t.Errorf("id 10's name = nil; want bob") - } else if *name != "bob" { - t.Errorf("id 10's name = %q; want bob", *name) - } - - err = db.QueryRow("SELECT|t|name|id=?", 20).Scan(&name) - if err != nil { - t.Fatalf("querying id 20: %v", err) - } - if name != nil { - t.Errorf("id 20 = %q; want nil", *name) - } -} - -func TestQueryRowClosingStmt(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - var name string - var age int - err := db.QueryRow("SELECT|people|age,name|age=?", 3).Scan(&age, &name) - if err != nil { - t.Fatal(err) - } - if len(db.freeConn) != 1 { - t.Fatalf("expected 1 free conn") - } - fakeConn := db.freeConn[0].ci.(*fakeConn) - if made, closed := fakeConn.stmtsMade, fakeConn.stmtsClosed; made != closed { - t.Errorf("statement close mismatch: made %d, closed %d", made, closed) - } -} - -// Test issue 6651 -func TestIssue6651(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - - var v string - - want := "error in rows.Next" - rowsCursorNextHook = func(dest []driver.Value) error { - return fmt.Errorf(want) - } - defer func() { rowsCursorNextHook = nil }() - err := db.QueryRow("SELECT|people|name|").Scan(&v) - if err == nil || err.Error() != want { - t.Errorf("error = %q; want %q", err, want) - } - rowsCursorNextHook = nil - - want = "error in rows.Close" - rowsCloseHook = func(rows *Rows, err *error) { - *err = fmt.Errorf(want) - } - defer func() { rowsCloseHook = nil }() - err = db.QueryRow("SELECT|people|name|").Scan(&v) - if err == nil || err.Error() != want { - t.Errorf("error = %q; want %q", err, want) - } -} - -type nullTestRow struct { - nullParam interface{} - notNullParam interface{} - scanNullVal interface{} -} - -type nullTestSpec struct { - nullType string - notNullType string - rows [6]nullTestRow -} - -func TestNullStringParam(t *testing.T) { - spec := nullTestSpec{"nullstring", "string", [6]nullTestRow{ - {NullString{"aqua", true}, "", NullString{"aqua", true}}, - {NullString{"brown", false}, "", NullString{"", false}}, - {"chartreuse", "", NullString{"chartreuse", true}}, - {NullString{"darkred", true}, "", NullString{"darkred", true}}, - {NullString{"eel", false}, "", NullString{"", false}}, - {"foo", NullString{"black", false}, nil}, - }} - nullTestRun(t, spec) -} - -func TestNullInt64Param(t *testing.T) { - spec := nullTestSpec{"nullint64", "int64", [6]nullTestRow{ - {NullInt64{31, true}, 1, NullInt64{31, true}}, - {NullInt64{-22, false}, 1, NullInt64{0, false}}, - {22, 1, NullInt64{22, true}}, - {NullInt64{33, true}, 1, NullInt64{33, true}}, - {NullInt64{222, false}, 1, NullInt64{0, false}}, - {0, NullInt64{31, false}, nil}, - }} - nullTestRun(t, spec) -} - -func TestNullFloat64Param(t *testing.T) { - spec := nullTestSpec{"nullfloat64", "float64", [6]nullTestRow{ - {NullFloat64{31.2, true}, 1, NullFloat64{31.2, true}}, - {NullFloat64{13.1, false}, 1, NullFloat64{0, false}}, - {-22.9, 1, NullFloat64{-22.9, true}}, - {NullFloat64{33.81, true}, 1, NullFloat64{33.81, true}}, - {NullFloat64{222, false}, 1, NullFloat64{0, false}}, - {10, NullFloat64{31.2, false}, nil}, - }} - nullTestRun(t, spec) -} - -func TestNullBoolParam(t *testing.T) { - spec := nullTestSpec{"nullbool", "bool", [6]nullTestRow{ - {NullBool{false, true}, true, NullBool{false, true}}, - {NullBool{true, false}, false, NullBool{false, false}}, - {true, true, NullBool{true, true}}, - {NullBool{true, true}, false, NullBool{true, true}}, - {NullBool{true, false}, true, NullBool{false, false}}, - {true, NullBool{true, false}, nil}, - }} - nullTestRun(t, spec) -} - -func nullTestRun(t *testing.T, spec nullTestSpec) { - db := newTestDB(t, "") - defer closeDB(t, db) - exec(t, db, fmt.Sprintf("CREATE|t|id=int32,name=string,nullf=%s,notnullf=%s", spec.nullType, spec.notNullType)) - - // Inserts with db.Exec: - exec(t, db, "INSERT|t|id=?,name=?,nullf=?,notnullf=?", 1, "alice", spec.rows[0].nullParam, spec.rows[0].notNullParam) - exec(t, db, "INSERT|t|id=?,name=?,nullf=?,notnullf=?", 2, "bob", spec.rows[1].nullParam, spec.rows[1].notNullParam) - - // Inserts with a prepared statement: - stmt, err := db.Prepare("INSERT|t|id=?,name=?,nullf=?,notnullf=?") - if err != nil { - t.Fatalf("prepare: %v", err) - } - defer stmt.Close() - if _, err := stmt.Exec(3, "chris", spec.rows[2].nullParam, spec.rows[2].notNullParam); err != nil { - t.Errorf("exec insert chris: %v", err) - } - if _, err := stmt.Exec(4, "dave", spec.rows[3].nullParam, spec.rows[3].notNullParam); err != nil { - t.Errorf("exec insert dave: %v", err) - } - if _, err := stmt.Exec(5, "eleanor", spec.rows[4].nullParam, spec.rows[4].notNullParam); err != nil { - t.Errorf("exec insert eleanor: %v", err) - } - - // Can't put null val into non-null col - if _, err := stmt.Exec(6, "bob", spec.rows[5].nullParam, spec.rows[5].notNullParam); err == nil { - t.Errorf("expected error inserting nil val with prepared statement Exec") - } - - _, err = db.Exec("INSERT|t|id=?,name=?,nullf=?", 999, nil, nil) - if err == nil { - // TODO: this test fails, but it's just because - // fakeConn implements the optional Execer interface, - // so arguably this is the correct behavior. But - // maybe I should flesh out the fakeConn.Exec - // implementation so this properly fails. - // t.Errorf("expected error inserting nil name with Exec") - } - - paramtype := reflect.TypeOf(spec.rows[0].nullParam) - bindVal := reflect.New(paramtype).Interface() - - for i := 0; i < 5; i++ { - id := i + 1 - if err := db.QueryRow("SELECT|t|nullf|id=?", id).Scan(bindVal); err != nil { - t.Errorf("id=%d Scan: %v", id, err) - } - bindValDeref := reflect.ValueOf(bindVal).Elem().Interface() - if !reflect.DeepEqual(bindValDeref, spec.rows[i].scanNullVal) { - t.Errorf("id=%d got %#v, want %#v", id, bindValDeref, spec.rows[i].scanNullVal) - } - } -} - -// golang.org/issue/4859 -func TestQueryRowNilScanDest(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - var name *string // nil pointer - err := db.QueryRow("SELECT|people|name|").Scan(name) - want := "sql: Scan error on column index 0: destination pointer is nil" - if err == nil || err.Error() != want { - t.Errorf("error = %q; want %q", err.Error(), want) - } -} - -func TestIssue4902(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - - driver := db.driver.(*fakeDriver) - opens0 := driver.openCount - - var stmt *Stmt - var err error - for i := 0; i < 10; i++ { - stmt, err = db.Prepare("SELECT|people|name|") - if err != nil { - t.Fatal(err) - } - err = stmt.Close() - if err != nil { - t.Fatal(err) - } - } - - opens := driver.openCount - opens0 - if opens > 1 { - t.Errorf("opens = %d; want <= 1", opens) - t.Logf("db = %#v", db) - t.Logf("driver = %#v", driver) - t.Logf("stmt = %#v", stmt) - } -} - -// Issue 3857 -// This used to deadlock. -func TestSimultaneousQueries(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - - tx, err := db.Begin() - if err != nil { - t.Fatal(err) - } - defer tx.Rollback() - - r1, err := tx.Query("SELECT|people|name|") - if err != nil { - t.Fatal(err) - } - defer r1.Close() - - r2, err := tx.Query("SELECT|people|name|") - if err != nil { - t.Fatal(err) - } - defer r2.Close() -} - -func TestMaxIdleConns(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - - tx, err := db.Begin() - if err != nil { - t.Fatal(err) - } - tx.Commit() - if got := len(db.freeConn); got != 1 { - t.Errorf("freeConns = %d; want 1", got) - } - - db.SetMaxIdleConns(0) - - if got := len(db.freeConn); got != 0 { - t.Errorf("freeConns after set to zero = %d; want 0", got) - } - - tx, err = db.Begin() - if err != nil { - t.Fatal(err) - } - tx.Commit() - if got := len(db.freeConn); got != 0 { - t.Errorf("freeConns = %d; want 0", got) - } -} - -func TestMaxOpenConns(t *testing.T) { - if testing.Short() { - t.Skip("skipping in short mode") - } - defer setHookpostCloseConn(nil) - setHookpostCloseConn(func(_ *fakeConn, err error) { - if err != nil { - t.Errorf("Error closing fakeConn: %v", err) - } - }) - - db := newTestDB(t, "magicquery") - defer closeDB(t, db) - - driver := db.driver.(*fakeDriver) - - // Force the number of open connections to 0 so we can get an accurate - // count for the test - db.SetMaxIdleConns(0) - - if g, w := db.numFreeConns(), 0; g != w { - t.Errorf("free conns = %d; want %d", g, w) - } - - if n := db.numDepsPollUntil(0, time.Second); n > 0 { - t.Errorf("number of dependencies = %d; expected 0", n) - db.dumpDeps(t) - } - - driver.mu.Lock() - opens0 := driver.openCount - closes0 := driver.closeCount - driver.mu.Unlock() - - db.SetMaxIdleConns(10) - db.SetMaxOpenConns(10) - - stmt, err := db.Prepare("SELECT|magicquery|op|op=?,millis=?") - if err != nil { - t.Fatal(err) - } - - // Start 50 parallel slow queries. - const ( - nquery = 50 - sleepMillis = 25 - nbatch = 2 - ) - var wg sync.WaitGroup - for batch := 0; batch < nbatch; batch++ { - for i := 0; i < nquery; i++ { - wg.Add(1) - go func() { - defer wg.Done() - var op string - if err := stmt.QueryRow("sleep", sleepMillis).Scan(&op); err != nil && err != ErrNoRows { - t.Error(err) - } - }() - } - // Sleep for twice the expected length of time for the - // batch of 50 queries above to finish before starting - // the next round. - time.Sleep(2 * sleepMillis * time.Millisecond) - } - wg.Wait() - - if g, w := db.numFreeConns(), 10; g != w { - t.Errorf("free conns = %d; want %d", g, w) - } - - if n := db.numDepsPollUntil(20, time.Second); n > 20 { - t.Errorf("number of dependencies = %d; expected <= 20", n) - db.dumpDeps(t) - } - - driver.mu.Lock() - opens := driver.openCount - opens0 - closes := driver.closeCount - closes0 - driver.mu.Unlock() - - if opens > 10 { - t.Logf("open calls = %d", opens) - t.Logf("close calls = %d", closes) - t.Errorf("db connections opened = %d; want <= 10", opens) - db.dumpDeps(t) - } - - if err := stmt.Close(); err != nil { - t.Fatal(err) - } - - if g, w := db.numFreeConns(), 10; g != w { - t.Errorf("free conns = %d; want %d", g, w) - } - - if n := db.numDepsPollUntil(10, time.Second); n > 10 { - t.Errorf("number of dependencies = %d; expected <= 10", n) - db.dumpDeps(t) - } - - db.SetMaxOpenConns(5) - - if g, w := db.numFreeConns(), 5; g != w { - t.Errorf("free conns = %d; want %d", g, w) - } - - if n := db.numDepsPollUntil(5, time.Second); n > 5 { - t.Errorf("number of dependencies = %d; expected 0", n) - db.dumpDeps(t) - } - - db.SetMaxOpenConns(0) - - if g, w := db.numFreeConns(), 5; g != w { - t.Errorf("free conns = %d; want %d", g, w) - } - - if n := db.numDepsPollUntil(5, time.Second); n > 5 { - t.Errorf("number of dependencies = %d; expected 0", n) - db.dumpDeps(t) - } - - db.SetMaxIdleConns(0) - - if g, w := db.numFreeConns(), 0; g != w { - t.Errorf("free conns = %d; want %d", g, w) - } - - if n := db.numDepsPollUntil(0, time.Second); n > 0 { - t.Errorf("number of dependencies = %d; expected 0", n) - db.dumpDeps(t) - } -} - -func TestSingleOpenConn(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - - db.SetMaxOpenConns(1) - - rows, err := db.Query("SELECT|people|name|") - if err != nil { - t.Fatal(err) - } - if err = rows.Close(); err != nil { - t.Fatal(err) - } - // shouldn't deadlock - rows, err = db.Query("SELECT|people|name|") - if err != nil { - t.Fatal(err) - } - if err = rows.Close(); err != nil { - t.Fatal(err) - } -} - -// golang.org/issue/5323 -func TestStmtCloseDeps(t *testing.T) { - if testing.Short() { - t.Skip("skipping in short mode") - } - defer setHookpostCloseConn(nil) - setHookpostCloseConn(func(_ *fakeConn, err error) { - if err != nil { - t.Errorf("Error closing fakeConn: %v", err) - } - }) - - db := newTestDB(t, "magicquery") - defer closeDB(t, db) - - driver := db.driver.(*fakeDriver) - - driver.mu.Lock() - opens0 := driver.openCount - closes0 := driver.closeCount - driver.mu.Unlock() - openDelta0 := opens0 - closes0 - - stmt, err := db.Prepare("SELECT|magicquery|op|op=?,millis=?") - if err != nil { - t.Fatal(err) - } - - // Start 50 parallel slow queries. - const ( - nquery = 50 - sleepMillis = 25 - nbatch = 2 - ) - var wg sync.WaitGroup - for batch := 0; batch < nbatch; batch++ { - for i := 0; i < nquery; i++ { - wg.Add(1) - go func() { - defer wg.Done() - var op string - if err := stmt.QueryRow("sleep", sleepMillis).Scan(&op); err != nil && err != ErrNoRows { - t.Error(err) - } - }() - } - // Sleep for twice the expected length of time for the - // batch of 50 queries above to finish before starting - // the next round. - time.Sleep(2 * sleepMillis * time.Millisecond) - } - wg.Wait() - - if g, w := db.numFreeConns(), 2; g != w { - t.Errorf("free conns = %d; want %d", g, w) - } - - if n := db.numDepsPollUntil(4, time.Second); n > 4 { - t.Errorf("number of dependencies = %d; expected <= 4", n) - db.dumpDeps(t) - } - - driver.mu.Lock() - opens := driver.openCount - opens0 - closes := driver.closeCount - closes0 - openDelta := (driver.openCount - driver.closeCount) - openDelta0 - driver.mu.Unlock() - - if openDelta > 2 { - t.Logf("open calls = %d", opens) - t.Logf("close calls = %d", closes) - t.Logf("open delta = %d", openDelta) - t.Errorf("db connections opened = %d; want <= 2", openDelta) - db.dumpDeps(t) - } - - if len(stmt.css) > nquery { - t.Errorf("len(stmt.css) = %d; want <= %d", len(stmt.css), nquery) - } - - if err := stmt.Close(); err != nil { - t.Fatal(err) - } - - if g, w := db.numFreeConns(), 2; g != w { - t.Errorf("free conns = %d; want %d", g, w) - } - - if n := db.numDepsPollUntil(2, time.Second); n > 2 { - t.Errorf("number of dependencies = %d; expected <= 2", n) - db.dumpDeps(t) - } - - db.SetMaxIdleConns(0) - - if g, w := db.numFreeConns(), 0; g != w { - t.Errorf("free conns = %d; want %d", g, w) - } - - if n := db.numDepsPollUntil(0, time.Second); n > 0 { - t.Errorf("number of dependencies = %d; expected 0", n) - db.dumpDeps(t) - } -} - -// golang.org/issue/5046 -func TestCloseConnBeforeStmts(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - - defer setHookpostCloseConn(nil) - setHookpostCloseConn(func(_ *fakeConn, err error) { - if err != nil { - t.Errorf("Error closing fakeConn: %v; from %s", err, stack()) - db.dumpDeps(t) - t.Errorf("DB = %#v", db) - } - }) - - stmt, err := db.Prepare("SELECT|people|name|") - if err != nil { - t.Fatal(err) - } - - if len(db.freeConn) != 1 { - t.Fatalf("expected 1 freeConn; got %d", len(db.freeConn)) - } - dc := db.freeConn[0] - if dc.closed { - t.Errorf("conn shouldn't be closed") - } - - if n := len(dc.openStmt); n != 1 { - t.Errorf("driverConn num openStmt = %d; want 1", n) - } - err = db.Close() - if err != nil { - t.Errorf("db Close = %v", err) - } - if !dc.closed { - t.Errorf("after db.Close, driverConn should be closed") - } - if n := len(dc.openStmt); n != 0 { - t.Errorf("driverConn num openStmt = %d; want 0", n) - } - - err = stmt.Close() - if err != nil { - t.Errorf("Stmt close = %v", err) - } - - if !dc.closed { - t.Errorf("conn should be closed") - } - if dc.ci != nil { - t.Errorf("after Stmt Close, driverConn's Conn interface should be nil") - } -} - -// golang.org/issue/5283: don't release the Rows' connection in Close -// before calling Stmt.Close. -func TestRowsCloseOrder(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - - db.SetMaxIdleConns(0) - setStrictFakeConnClose(t) - defer setStrictFakeConnClose(nil) - - rows, err := db.Query("SELECT|people|age,name|") - if err != nil { - t.Fatal(err) - } - err = rows.Close() - if err != nil { - t.Fatal(err) - } -} - -func TestRowsImplicitClose(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - - rows, err := db.Query("SELECT|people|age,name|") - if err != nil { - t.Fatal(err) - } - - want, fail := 2, errors.New("fail") - r := rows.rowsi.(*rowsCursor) - r.errPos, r.err = want, fail - - got := 0 - for rows.Next() { - got++ - } - if got != want { - t.Errorf("got %d rows, want %d", got, want) - } - if err := rows.Err(); err != fail { - t.Errorf("got error %v, want %v", err, fail) - } - if !r.closed { - t.Errorf("r.closed is false, want true") - } -} - -func TestStmtCloseOrder(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - - db.SetMaxIdleConns(0) - setStrictFakeConnClose(t) - defer setStrictFakeConnClose(nil) - - _, err := db.Query("SELECT|non_existent|name|") - if err == nil { - t.Fatal("Quering non-existent table should fail") - } -} - -// golang.org/issue/5781 -func TestErrBadConnReconnect(t *testing.T) { - db := newTestDB(t, "foo") - defer closeDB(t, db) - exec(t, db, "CREATE|t1|name=string,age=int32,dead=bool") - - simulateBadConn := func(name string, hook *func() bool, op func() error) { - broken, retried := false, false - numOpen := db.numOpen - - // simulate a broken connection on the first try - *hook = func() bool { - if !broken { - broken = true - return true - } - retried = true - return false - } - - if err := op(); err != nil { - t.Errorf(name+": %v", err) - return - } - - if !broken || !retried { - t.Error(name + ": Failed to simulate broken connection") - } - *hook = nil - - if numOpen != db.numOpen { - t.Errorf(name+": leaked %d connection(s)!", db.numOpen-numOpen) - numOpen = db.numOpen - } - } - - // db.Exec - dbExec := func() error { - _, err := db.Exec("INSERT|t1|name=?,age=?,dead=?", "Gordon", 3, true) - return err - } - simulateBadConn("db.Exec prepare", &hookPrepareBadConn, dbExec) - simulateBadConn("db.Exec exec", &hookExecBadConn, dbExec) - - // db.Query - dbQuery := func() error { - rows, err := db.Query("SELECT|t1|age,name|") - if err == nil { - err = rows.Close() - } - return err - } - simulateBadConn("db.Query prepare", &hookPrepareBadConn, dbQuery) - simulateBadConn("db.Query query", &hookQueryBadConn, dbQuery) - - // db.Prepare - simulateBadConn("db.Prepare", &hookPrepareBadConn, func() error { - stmt, err := db.Prepare("INSERT|t1|name=?,age=?,dead=?") - if err != nil { - return err - } - stmt.Close() - return nil - }) - - // Provide a way to force a re-prepare of a statement on next execution - forcePrepare := func(stmt *Stmt) { - stmt.css = nil - } - - // stmt.Exec - stmt1, err := db.Prepare("INSERT|t1|name=?,age=?,dead=?") - if err != nil { - t.Fatalf("prepare: %v", err) - } - defer stmt1.Close() - // make sure we must prepare the stmt first - forcePrepare(stmt1) - - stmtExec := func() error { - _, err := stmt1.Exec("Gopher", 3, false) - return err - } - simulateBadConn("stmt.Exec prepare", &hookPrepareBadConn, stmtExec) - simulateBadConn("stmt.Exec exec", &hookExecBadConn, stmtExec) - - // stmt.Query - stmt2, err := db.Prepare("SELECT|t1|age,name|") - if err != nil { - t.Fatalf("prepare: %v", err) - } - defer stmt2.Close() - // make sure we must prepare the stmt first - forcePrepare(stmt2) - - stmtQuery := func() error { - rows, err := stmt2.Query() - if err == nil { - err = rows.Close() - } - return err - } - simulateBadConn("stmt.Query prepare", &hookPrepareBadConn, stmtQuery) - simulateBadConn("stmt.Query exec", &hookQueryBadConn, stmtQuery) -} - -type concurrentTest interface { - init(t testing.TB, db *DB) - finish(t testing.TB) - test(t testing.TB) error -} - -type concurrentDBQueryTest struct { - db *DB -} - -func (c *concurrentDBQueryTest) init(t testing.TB, db *DB) { - c.db = db -} - -func (c *concurrentDBQueryTest) finish(t testing.TB) { - c.db = nil -} - -func (c *concurrentDBQueryTest) test(t testing.TB) error { - rows, err := c.db.Query("SELECT|people|name|") - if err != nil { - t.Error(err) - return err - } - var name string - for rows.Next() { - rows.Scan(&name) - } - rows.Close() - return nil -} - -type concurrentDBExecTest struct { - db *DB -} - -func (c *concurrentDBExecTest) init(t testing.TB, db *DB) { - c.db = db -} - -func (c *concurrentDBExecTest) finish(t testing.TB) { - c.db = nil -} - -func (c *concurrentDBExecTest) test(t testing.TB) error { - _, err := c.db.Exec("NOSERT|people|name=Chris,age=?,photo=CPHOTO,bdate=?", 3, chrisBirthday) - if err != nil { - t.Error(err) - return err - } - return nil -} - -type concurrentStmtQueryTest struct { - db *DB - stmt *Stmt -} - -func (c *concurrentStmtQueryTest) init(t testing.TB, db *DB) { - c.db = db - var err error - c.stmt, err = db.Prepare("SELECT|people|name|") - if err != nil { - t.Fatal(err) - } -} - -func (c *concurrentStmtQueryTest) finish(t testing.TB) { - if c.stmt != nil { - c.stmt.Close() - c.stmt = nil - } - c.db = nil -} - -func (c *concurrentStmtQueryTest) test(t testing.TB) error { - rows, err := c.stmt.Query() - if err != nil { - t.Errorf("error on query: %v", err) - return err - } - - var name string - for rows.Next() { - rows.Scan(&name) - } - rows.Close() - return nil -} - -type concurrentStmtExecTest struct { - db *DB - stmt *Stmt -} - -func (c *concurrentStmtExecTest) init(t testing.TB, db *DB) { - c.db = db - var err error - c.stmt, err = db.Prepare("NOSERT|people|name=Chris,age=?,photo=CPHOTO,bdate=?") - if err != nil { - t.Fatal(err) - } -} - -func (c *concurrentStmtExecTest) finish(t testing.TB) { - if c.stmt != nil { - c.stmt.Close() - c.stmt = nil - } - c.db = nil -} - -func (c *concurrentStmtExecTest) test(t testing.TB) error { - _, err := c.stmt.Exec(3, chrisBirthday) - if err != nil { - t.Errorf("error on exec: %v", err) - return err - } - return nil -} - -type concurrentTxQueryTest struct { - db *DB - tx *Tx -} - -func (c *concurrentTxQueryTest) init(t testing.TB, db *DB) { - c.db = db - var err error - c.tx, err = c.db.Begin() - if err != nil { - t.Fatal(err) - } -} - -func (c *concurrentTxQueryTest) finish(t testing.TB) { - if c.tx != nil { - c.tx.Rollback() - c.tx = nil - } - c.db = nil -} - -func (c *concurrentTxQueryTest) test(t testing.TB) error { - rows, err := c.db.Query("SELECT|people|name|") - if err != nil { - t.Error(err) - return err - } - var name string - for rows.Next() { - rows.Scan(&name) - } - rows.Close() - return nil -} - -type concurrentTxExecTest struct { - db *DB - tx *Tx -} - -func (c *concurrentTxExecTest) init(t testing.TB, db *DB) { - c.db = db - var err error - c.tx, err = c.db.Begin() - if err != nil { - t.Fatal(err) - } -} - -func (c *concurrentTxExecTest) finish(t testing.TB) { - if c.tx != nil { - c.tx.Rollback() - c.tx = nil - } - c.db = nil -} - -func (c *concurrentTxExecTest) test(t testing.TB) error { - _, err := c.tx.Exec("NOSERT|people|name=Chris,age=?,photo=CPHOTO,bdate=?", 3, chrisBirthday) - if err != nil { - t.Error(err) - return err - } - return nil -} - -type concurrentTxStmtQueryTest struct { - db *DB - tx *Tx - stmt *Stmt -} - -func (c *concurrentTxStmtQueryTest) init(t testing.TB, db *DB) { - c.db = db - var err error - c.tx, err = c.db.Begin() - if err != nil { - t.Fatal(err) - } - c.stmt, err = c.tx.Prepare("SELECT|people|name|") - if err != nil { - t.Fatal(err) - } -} - -func (c *concurrentTxStmtQueryTest) finish(t testing.TB) { - if c.stmt != nil { - c.stmt.Close() - c.stmt = nil - } - if c.tx != nil { - c.tx.Rollback() - c.tx = nil - } - c.db = nil -} - -func (c *concurrentTxStmtQueryTest) test(t testing.TB) error { - rows, err := c.stmt.Query() - if err != nil { - t.Errorf("error on query: %v", err) - return err - } - - var name string - for rows.Next() { - rows.Scan(&name) - } - rows.Close() - return nil -} - -type concurrentTxStmtExecTest struct { - db *DB - tx *Tx - stmt *Stmt -} - -func (c *concurrentTxStmtExecTest) init(t testing.TB, db *DB) { - c.db = db - var err error - c.tx, err = c.db.Begin() - if err != nil { - t.Fatal(err) - } - c.stmt, err = c.tx.Prepare("NOSERT|people|name=Chris,age=?,photo=CPHOTO,bdate=?") - if err != nil { - t.Fatal(err) - } -} - -func (c *concurrentTxStmtExecTest) finish(t testing.TB) { - if c.stmt != nil { - c.stmt.Close() - c.stmt = nil - } - if c.tx != nil { - c.tx.Rollback() - c.tx = nil - } - c.db = nil -} - -func (c *concurrentTxStmtExecTest) test(t testing.TB) error { - _, err := c.stmt.Exec(3, chrisBirthday) - if err != nil { - t.Errorf("error on exec: %v", err) - return err - } - return nil -} - -type concurrentRandomTest struct { - tests []concurrentTest -} - -func (c *concurrentRandomTest) init(t testing.TB, db *DB) { - c.tests = []concurrentTest{ - new(concurrentDBQueryTest), - new(concurrentDBExecTest), - new(concurrentStmtQueryTest), - new(concurrentStmtExecTest), - new(concurrentTxQueryTest), - new(concurrentTxExecTest), - new(concurrentTxStmtQueryTest), - new(concurrentTxStmtExecTest), - } - for _, ct := range c.tests { - ct.init(t, db) - } -} - -func (c *concurrentRandomTest) finish(t testing.TB) { - for _, ct := range c.tests { - ct.finish(t) - } -} - -func (c *concurrentRandomTest) test(t testing.TB) error { - ct := c.tests[rand.Intn(len(c.tests))] - return ct.test(t) -} - -func doConcurrentTest(t testing.TB, ct concurrentTest) { - maxProcs, numReqs := 1, 500 - if testing.Short() { - maxProcs, numReqs = 4, 50 - } - defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(maxProcs)) - - db := newTestDB(t, "people") - defer closeDB(t, db) - - ct.init(t, db) - defer ct.finish(t) - - var wg sync.WaitGroup - wg.Add(numReqs) - - reqs := make(chan bool) - defer close(reqs) - - for i := 0; i < maxProcs*2; i++ { - go func() { - for range reqs { - err := ct.test(t) - if err != nil { - wg.Done() - continue - } - wg.Done() - } - }() - } - - for i := 0; i < numReqs; i++ { - reqs <- true - } - - wg.Wait() -} - -func manyConcurrentQueries(t testing.TB) { - maxProcs, numReqs := 16, 500 - if testing.Short() { - maxProcs, numReqs = 4, 50 - } - defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(maxProcs)) - - db := newTestDB(t, "people") - defer closeDB(t, db) - - stmt, err := db.Prepare("SELECT|people|name|") - if err != nil { - t.Fatal(err) - } - defer stmt.Close() - - var wg sync.WaitGroup - wg.Add(numReqs) - - reqs := make(chan bool) - defer close(reqs) - - for i := 0; i < maxProcs*2; i++ { - go func() { - for range reqs { - rows, err := stmt.Query() - if err != nil { - t.Errorf("error on query: %v", err) - wg.Done() - continue - } - - var name string - for rows.Next() { - rows.Scan(&name) - } - rows.Close() - - wg.Done() - } - }() - } - - for i := 0; i < numReqs; i++ { - reqs <- true - } - - wg.Wait() -} - -func TestIssue6081(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - - drv := db.driver.(*fakeDriver) - drv.mu.Lock() - opens0 := drv.openCount - closes0 := drv.closeCount - drv.mu.Unlock() - - stmt, err := db.Prepare("SELECT|people|name|") - if err != nil { - t.Fatal(err) - } - rowsCloseHook = func(rows *Rows, err *error) { - *err = driver.ErrBadConn - } - defer func() { rowsCloseHook = nil }() - for i := 0; i < 10; i++ { - rows, err := stmt.Query() - if err != nil { - t.Fatal(err) - } - rows.Close() - } - if n := len(stmt.css); n > 1 { - t.Errorf("len(css slice) = %d; want <= 1", n) - } - stmt.Close() - if n := len(stmt.css); n != 0 { - t.Errorf("len(css slice) after Close = %d; want 0", n) - } - - drv.mu.Lock() - opens := drv.openCount - opens0 - closes := drv.closeCount - closes0 - drv.mu.Unlock() - if opens < 9 { - t.Errorf("opens = %d; want >= 9", opens) - } - if closes < 9 { - t.Errorf("closes = %d; want >= 9", closes) - } -} - -func TestConcurrency(t *testing.T) { - doConcurrentTest(t, new(concurrentDBQueryTest)) - doConcurrentTest(t, new(concurrentDBExecTest)) - doConcurrentTest(t, new(concurrentStmtQueryTest)) - doConcurrentTest(t, new(concurrentStmtExecTest)) - doConcurrentTest(t, new(concurrentTxQueryTest)) - doConcurrentTest(t, new(concurrentTxExecTest)) - doConcurrentTest(t, new(concurrentTxStmtQueryTest)) - doConcurrentTest(t, new(concurrentTxStmtExecTest)) - doConcurrentTest(t, new(concurrentRandomTest)) -} - -func TestConnectionLeak(t *testing.T) { - db := newTestDB(t, "people") - defer closeDB(t, db) - // Start by opening defaultMaxIdleConns - rows := make([]*Rows, defaultMaxIdleConns) - // We need to SetMaxOpenConns > MaxIdleConns, so the DB can open - // a new connection and we can fill the idle queue with the released - // connections. - db.SetMaxOpenConns(len(rows) + 1) - for ii := range rows { - r, err := db.Query("SELECT|people|name|") - if err != nil { - t.Fatal(err) - } - r.Next() - if err := r.Err(); err != nil { - t.Fatal(err) - } - rows[ii] = r - } - // Now we have defaultMaxIdleConns busy connections. Open - // a new one, but wait until the busy connections are released - // before returning control to DB. - drv := db.driver.(*fakeDriver) - drv.waitCh = make(chan struct{}, 1) - drv.waitingCh = make(chan struct{}, 1) - var wg sync.WaitGroup - wg.Add(1) - go func() { - r, err := db.Query("SELECT|people|name|") - if err != nil { - t.Fatal(err) - } - r.Close() - wg.Done() - }() - // Wait until the goroutine we've just created has started waiting. - <-drv.waitingCh - // Now close the busy connections. This provides a connection for - // the blocked goroutine and then fills up the idle queue. - for _, v := range rows { - v.Close() - } - // At this point we give the new connection to DB. This connection is - // now useless, since the idle queue is full and there are no pending - // requests. DB should deal with this situation without leaking the - // connection. - drv.waitCh <- struct{}{} - wg.Wait() -} - -func BenchmarkConcurrentDBExec(b *testing.B) { - b.ReportAllocs() - ct := new(concurrentDBExecTest) - for i := 0; i < b.N; i++ { - doConcurrentTest(b, ct) - } -} - -func BenchmarkConcurrentStmtQuery(b *testing.B) { - b.ReportAllocs() - ct := new(concurrentStmtQueryTest) - for i := 0; i < b.N; i++ { - doConcurrentTest(b, ct) - } -} - -func BenchmarkConcurrentStmtExec(b *testing.B) { - b.ReportAllocs() - ct := new(concurrentStmtExecTest) - for i := 0; i < b.N; i++ { - doConcurrentTest(b, ct) - } -} - -func BenchmarkConcurrentTxQuery(b *testing.B) { - b.ReportAllocs() - ct := new(concurrentTxQueryTest) - for i := 0; i < b.N; i++ { - doConcurrentTest(b, ct) - } -} - -func BenchmarkConcurrentTxExec(b *testing.B) { - b.ReportAllocs() - ct := new(concurrentTxExecTest) - for i := 0; i < b.N; i++ { - doConcurrentTest(b, ct) - } -} - -func BenchmarkConcurrentTxStmtQuery(b *testing.B) { - b.ReportAllocs() - ct := new(concurrentTxStmtQueryTest) - for i := 0; i < b.N; i++ { - doConcurrentTest(b, ct) - } -} - -func BenchmarkConcurrentTxStmtExec(b *testing.B) { - b.ReportAllocs() - ct := new(concurrentTxStmtExecTest) - for i := 0; i < b.N; i++ { - doConcurrentTest(b, ct) - } -} - -func BenchmarkConcurrentRandom(b *testing.B) { - b.ReportAllocs() - ct := new(concurrentRandomTest) - for i := 0; i < b.N; i++ { - doConcurrentTest(b, ct) - } -} diff --git a/src/pkg/debug/dwarf/buf.go b/src/pkg/debug/dwarf/buf.go deleted file mode 100644 index 53c46eb4b..000000000 --- a/src/pkg/debug/dwarf/buf.go +++ /dev/null @@ -1,181 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Buffered reading and decoding of DWARF data streams. - -package dwarf - -import ( - "encoding/binary" - "strconv" -) - -// Data buffer being decoded. -type buf struct { - dwarf *Data - order binary.ByteOrder - format dataFormat - name string - off Offset - data []byte - err error -} - -// Data format, other than byte order. This affects the handling of -// certain field formats. -type dataFormat interface { - // DWARF version number. Zero means unknown. - version() int - - // 64-bit DWARF format? - dwarf64() (dwarf64 bool, isKnown bool) - - // Size of an address, in bytes. Zero means unknown. - addrsize() int -} - -// Some parts of DWARF have no data format, e.g., abbrevs. -type unknownFormat struct{} - -func (u unknownFormat) version() int { - return 0 -} - -func (u unknownFormat) dwarf64() (bool, bool) { - return false, false -} - -func (u unknownFormat) addrsize() int { - return 0 -} - -func makeBuf(d *Data, format dataFormat, name string, off Offset, data []byte) buf { - return buf{d, d.order, format, name, off, data, nil} -} - -func (b *buf) uint8() uint8 { - if len(b.data) < 1 { - b.error("underflow") - return 0 - } - val := b.data[0] - b.data = b.data[1:] - b.off++ - return val -} - -func (b *buf) bytes(n int) []byte { - if len(b.data) < n { - b.error("underflow") - return nil - } - data := b.data[0:n] - b.data = b.data[n:] - b.off += Offset(n) - return data -} - -func (b *buf) skip(n int) { b.bytes(n) } - -func (b *buf) string() string { - for i := 0; i < len(b.data); i++ { - if b.data[i] == 0 { - s := string(b.data[0:i]) - b.data = b.data[i+1:] - b.off += Offset(i + 1) - return s - } - } - b.error("underflow") - return "" -} - -func (b *buf) uint16() uint16 { - a := b.bytes(2) - if a == nil { - return 0 - } - return b.order.Uint16(a) -} - -func (b *buf) uint32() uint32 { - a := b.bytes(4) - if a == nil { - return 0 - } - return b.order.Uint32(a) -} - -func (b *buf) uint64() uint64 { - a := b.bytes(8) - if a == nil { - return 0 - } - return b.order.Uint64(a) -} - -// Read a varint, which is 7 bits per byte, little endian. -// the 0x80 bit means read another byte. -func (b *buf) varint() (c uint64, bits uint) { - for i := 0; i < len(b.data); i++ { - byte := b.data[i] - c |= uint64(byte&0x7F) << bits - bits += 7 - if byte&0x80 == 0 { - b.off += Offset(i + 1) - b.data = b.data[i+1:] - return c, bits - } - } - return 0, 0 -} - -// Unsigned int is just a varint. -func (b *buf) uint() uint64 { - x, _ := b.varint() - return x -} - -// Signed int is a sign-extended varint. -func (b *buf) int() int64 { - ux, bits := b.varint() - x := int64(ux) - if x&(1<<(bits-1)) != 0 { - x |= -1 << bits - } - return x -} - -// Address-sized uint. -func (b *buf) addr() uint64 { - switch b.format.addrsize() { - case 1: - return uint64(b.uint8()) - case 2: - return uint64(b.uint16()) - case 4: - return uint64(b.uint32()) - case 8: - return uint64(b.uint64()) - } - b.error("unknown address size") - return 0 -} - -func (b *buf) error(s string) { - if b.err == nil { - b.data = nil - b.err = DecodeError{b.name, b.off, s} - } -} - -type DecodeError struct { - Name string - Offset Offset - Err string -} - -func (e DecodeError) Error() string { - return "decoding dwarf section " + e.Name + " at offset 0x" + strconv.FormatInt(int64(e.Offset), 16) + ": " + e.Err -} diff --git a/src/pkg/debug/dwarf/const.go b/src/pkg/debug/dwarf/const.go deleted file mode 100644 index 93c68881a..000000000 --- a/src/pkg/debug/dwarf/const.go +++ /dev/null @@ -1,454 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Constants - -package dwarf - -import "strconv" - -// An Attr identifies the attribute type in a DWARF Entry's Field. -type Attr uint32 - -const ( - AttrSibling Attr = 0x01 - AttrLocation Attr = 0x02 - AttrName Attr = 0x03 - AttrOrdering Attr = 0x09 - AttrByteSize Attr = 0x0B - AttrBitOffset Attr = 0x0C - AttrBitSize Attr = 0x0D - AttrStmtList Attr = 0x10 - AttrLowpc Attr = 0x11 - AttrHighpc Attr = 0x12 - AttrLanguage Attr = 0x13 - AttrDiscr Attr = 0x15 - AttrDiscrValue Attr = 0x16 - AttrVisibility Attr = 0x17 - AttrImport Attr = 0x18 - AttrStringLength Attr = 0x19 - AttrCommonRef Attr = 0x1A - AttrCompDir Attr = 0x1B - AttrConstValue Attr = 0x1C - AttrContainingType Attr = 0x1D - AttrDefaultValue Attr = 0x1E - AttrInline Attr = 0x20 - AttrIsOptional Attr = 0x21 - AttrLowerBound Attr = 0x22 - AttrProducer Attr = 0x25 - AttrPrototyped Attr = 0x27 - AttrReturnAddr Attr = 0x2A - AttrStartScope Attr = 0x2C - AttrStrideSize Attr = 0x2E - AttrUpperBound Attr = 0x2F - AttrAbstractOrigin Attr = 0x31 - AttrAccessibility Attr = 0x32 - AttrAddrClass Attr = 0x33 - AttrArtificial Attr = 0x34 - AttrBaseTypes Attr = 0x35 - AttrCalling Attr = 0x36 - AttrCount Attr = 0x37 - AttrDataMemberLoc Attr = 0x38 - AttrDeclColumn Attr = 0x39 - AttrDeclFile Attr = 0x3A - AttrDeclLine Attr = 0x3B - AttrDeclaration Attr = 0x3C - AttrDiscrList Attr = 0x3D - AttrEncoding Attr = 0x3E - AttrExternal Attr = 0x3F - AttrFrameBase Attr = 0x40 - AttrFriend Attr = 0x41 - AttrIdentifierCase Attr = 0x42 - AttrMacroInfo Attr = 0x43 - AttrNamelistItem Attr = 0x44 - AttrPriority Attr = 0x45 - AttrSegment Attr = 0x46 - AttrSpecification Attr = 0x47 - AttrStaticLink Attr = 0x48 - AttrType Attr = 0x49 - AttrUseLocation Attr = 0x4A - AttrVarParam Attr = 0x4B - AttrVirtuality Attr = 0x4C - AttrVtableElemLoc Attr = 0x4D - AttrAllocated Attr = 0x4E - AttrAssociated Attr = 0x4F - AttrDataLocation Attr = 0x50 - AttrStride Attr = 0x51 - AttrEntrypc Attr = 0x52 - AttrUseUTF8 Attr = 0x53 - AttrExtension Attr = 0x54 - AttrRanges Attr = 0x55 - AttrTrampoline Attr = 0x56 - AttrCallColumn Attr = 0x57 - AttrCallFile Attr = 0x58 - AttrCallLine Attr = 0x59 - AttrDescription Attr = 0x5A -) - -var attrNames = [...]string{ - AttrSibling: "Sibling", - AttrLocation: "Location", - AttrName: "Name", - AttrOrdering: "Ordering", - AttrByteSize: "ByteSize", - AttrBitOffset: "BitOffset", - AttrBitSize: "BitSize", - AttrStmtList: "StmtList", - AttrLowpc: "Lowpc", - AttrHighpc: "Highpc", - AttrLanguage: "Language", - AttrDiscr: "Discr", - AttrDiscrValue: "DiscrValue", - AttrVisibility: "Visibility", - AttrImport: "Import", - AttrStringLength: "StringLength", - AttrCommonRef: "CommonRef", - AttrCompDir: "CompDir", - AttrConstValue: "ConstValue", - AttrContainingType: "ContainingType", - AttrDefaultValue: "DefaultValue", - AttrInline: "Inline", - AttrIsOptional: "IsOptional", - AttrLowerBound: "LowerBound", - AttrProducer: "Producer", - AttrPrototyped: "Prototyped", - AttrReturnAddr: "ReturnAddr", - AttrStartScope: "StartScope", - AttrStrideSize: "StrideSize", - AttrUpperBound: "UpperBound", - AttrAbstractOrigin: "AbstractOrigin", - AttrAccessibility: "Accessibility", - AttrAddrClass: "AddrClass", - AttrArtificial: "Artificial", - AttrBaseTypes: "BaseTypes", - AttrCalling: "Calling", - AttrCount: "Count", - AttrDataMemberLoc: "DataMemberLoc", - AttrDeclColumn: "DeclColumn", - AttrDeclFile: "DeclFile", - AttrDeclLine: "DeclLine", - AttrDeclaration: "Declaration", - AttrDiscrList: "DiscrList", - AttrEncoding: "Encoding", - AttrExternal: "External", - AttrFrameBase: "FrameBase", - AttrFriend: "Friend", - AttrIdentifierCase: "IdentifierCase", - AttrMacroInfo: "MacroInfo", - AttrNamelistItem: "NamelistItem", - AttrPriority: "Priority", - AttrSegment: "Segment", - AttrSpecification: "Specification", - AttrStaticLink: "StaticLink", - AttrType: "Type", - AttrUseLocation: "UseLocation", - AttrVarParam: "VarParam", - AttrVirtuality: "Virtuality", - AttrVtableElemLoc: "VtableElemLoc", - AttrAllocated: "Allocated", - AttrAssociated: "Associated", - AttrDataLocation: "DataLocation", - AttrStride: "Stride", - AttrEntrypc: "Entrypc", - AttrUseUTF8: "UseUTF8", - AttrExtension: "Extension", - AttrRanges: "Ranges", - AttrTrampoline: "Trampoline", - AttrCallColumn: "CallColumn", - AttrCallFile: "CallFile", - AttrCallLine: "CallLine", - AttrDescription: "Description", -} - -func (a Attr) String() string { - if int(a) < len(attrNames) { - s := attrNames[a] - if s != "" { - return s - } - } - return strconv.Itoa(int(a)) -} - -func (a Attr) GoString() string { - if int(a) < len(attrNames) { - s := attrNames[a] - if s != "" { - return "dwarf.Attr" + s - } - } - return "dwarf.Attr(" + strconv.FormatInt(int64(a), 10) + ")" -} - -// A format is a DWARF data encoding format. -type format uint32 - -const ( - // value formats - formAddr format = 0x01 - formDwarfBlock2 format = 0x03 - formDwarfBlock4 format = 0x04 - formData2 format = 0x05 - formData4 format = 0x06 - formData8 format = 0x07 - formString format = 0x08 - formDwarfBlock format = 0x09 - formDwarfBlock1 format = 0x0A - formData1 format = 0x0B - formFlag format = 0x0C - formSdata format = 0x0D - formStrp format = 0x0E - formUdata format = 0x0F - formRefAddr format = 0x10 - formRef1 format = 0x11 - formRef2 format = 0x12 - formRef4 format = 0x13 - formRef8 format = 0x14 - formRefUdata format = 0x15 - formIndirect format = 0x16 - // The following are new in DWARF 4. - formSecOffset format = 0x17 - formExprloc format = 0x18 - formFlagPresent format = 0x19 - formRefSig8 format = 0x20 - // Extensions for multi-file compression (.dwz) - // http://www.dwarfstd.org/ShowIssue.php?issue=120604.1 - formGnuRefAlt format = 0x1f20 - formGnuStrpAlt format = 0x1f21 -) - -// A Tag is the classification (the type) of an Entry. -type Tag uint32 - -const ( - TagArrayType Tag = 0x01 - TagClassType Tag = 0x02 - TagEntryPoint Tag = 0x03 - TagEnumerationType Tag = 0x04 - TagFormalParameter Tag = 0x05 - TagImportedDeclaration Tag = 0x08 - TagLabel Tag = 0x0A - TagLexDwarfBlock Tag = 0x0B - TagMember Tag = 0x0D - TagPointerType Tag = 0x0F - TagReferenceType Tag = 0x10 - TagCompileUnit Tag = 0x11 - TagStringType Tag = 0x12 - TagStructType Tag = 0x13 - TagSubroutineType Tag = 0x15 - TagTypedef Tag = 0x16 - TagUnionType Tag = 0x17 - TagUnspecifiedParameters Tag = 0x18 - TagVariant Tag = 0x19 - TagCommonDwarfBlock Tag = 0x1A - TagCommonInclusion Tag = 0x1B - TagInheritance Tag = 0x1C - TagInlinedSubroutine Tag = 0x1D - TagModule Tag = 0x1E - TagPtrToMemberType Tag = 0x1F - TagSetType Tag = 0x20 - TagSubrangeType Tag = 0x21 - TagWithStmt Tag = 0x22 - TagAccessDeclaration Tag = 0x23 - TagBaseType Tag = 0x24 - TagCatchDwarfBlock Tag = 0x25 - TagConstType Tag = 0x26 - TagConstant Tag = 0x27 - TagEnumerator Tag = 0x28 - TagFileType Tag = 0x29 - TagFriend Tag = 0x2A - TagNamelist Tag = 0x2B - TagNamelistItem Tag = 0x2C - TagPackedType Tag = 0x2D - TagSubprogram Tag = 0x2E - TagTemplateTypeParameter Tag = 0x2F - TagTemplateValueParameter Tag = 0x30 - TagThrownType Tag = 0x31 - TagTryDwarfBlock Tag = 0x32 - TagVariantPart Tag = 0x33 - TagVariable Tag = 0x34 - TagVolatileType Tag = 0x35 - // The following are new in DWARF 3. - TagDwarfProcedure Tag = 0x36 - TagRestrictType Tag = 0x37 - TagInterfaceType Tag = 0x38 - TagNamespace Tag = 0x39 - TagImportedModule Tag = 0x3A - TagUnspecifiedType Tag = 0x3B - TagPartialUnit Tag = 0x3C - TagImportedUnit Tag = 0x3D - TagMutableType Tag = 0x3E // Later removed from DWARF. - TagCondition Tag = 0x3F - TagSharedType Tag = 0x40 - // The following are new in DWARF 4. - TagTypeUnit Tag = 0x41 - TagRvalueReferenceType Tag = 0x42 - TagTemplateAlias Tag = 0x43 -) - -var tagNames = [...]string{ - TagArrayType: "ArrayType", - TagClassType: "ClassType", - TagEntryPoint: "EntryPoint", - TagEnumerationType: "EnumerationType", - TagFormalParameter: "FormalParameter", - TagImportedDeclaration: "ImportedDeclaration", - TagLabel: "Label", - TagLexDwarfBlock: "LexDwarfBlock", - TagMember: "Member", - TagPointerType: "PointerType", - TagReferenceType: "ReferenceType", - TagCompileUnit: "CompileUnit", - TagStringType: "StringType", - TagStructType: "StructType", - TagSubroutineType: "SubroutineType", - TagTypedef: "Typedef", - TagUnionType: "UnionType", - TagUnspecifiedParameters: "UnspecifiedParameters", - TagVariant: "Variant", - TagCommonDwarfBlock: "CommonDwarfBlock", - TagCommonInclusion: "CommonInclusion", - TagInheritance: "Inheritance", - TagInlinedSubroutine: "InlinedSubroutine", - TagModule: "Module", - TagPtrToMemberType: "PtrToMemberType", - TagSetType: "SetType", - TagSubrangeType: "SubrangeType", - TagWithStmt: "WithStmt", - TagAccessDeclaration: "AccessDeclaration", - TagBaseType: "BaseType", - TagCatchDwarfBlock: "CatchDwarfBlock", - TagConstType: "ConstType", - TagConstant: "Constant", - TagEnumerator: "Enumerator", - TagFileType: "FileType", - TagFriend: "Friend", - TagNamelist: "Namelist", - TagNamelistItem: "NamelistItem", - TagPackedType: "PackedType", - TagSubprogram: "Subprogram", - TagTemplateTypeParameter: "TemplateTypeParameter", - TagTemplateValueParameter: "TemplateValueParameter", - TagThrownType: "ThrownType", - TagTryDwarfBlock: "TryDwarfBlock", - TagVariantPart: "VariantPart", - TagVariable: "Variable", - TagVolatileType: "VolatileType", - TagDwarfProcedure: "DwarfProcedure", - TagRestrictType: "RestrictType", - TagInterfaceType: "InterfaceType", - TagNamespace: "Namespace", - TagImportedModule: "ImportedModule", - TagUnspecifiedType: "UnspecifiedType", - TagPartialUnit: "PartialUnit", - TagImportedUnit: "ImportedUnit", - TagMutableType: "MutableType", - TagCondition: "Condition", - TagSharedType: "SharedType", - TagTypeUnit: "TypeUnit", - TagRvalueReferenceType: "RvalueReferenceType", - TagTemplateAlias: "TemplateAlias", -} - -func (t Tag) String() string { - if int(t) < len(tagNames) { - s := tagNames[t] - if s != "" { - return s - } - } - return strconv.Itoa(int(t)) -} - -func (t Tag) GoString() string { - if int(t) < len(tagNames) { - s := tagNames[t] - if s != "" { - return "dwarf.Tag" + s - } - } - return "dwarf.Tag(" + strconv.FormatInt(int64(t), 10) + ")" -} - -// Location expression operators. -// The debug info encodes value locations like 8(R3) -// as a sequence of these op codes. -// This package does not implement full expressions; -// the opPlusUconst operator is expected by the type parser. -const ( - opAddr = 0x03 /* 1 op, const addr */ - opDeref = 0x06 - opConst1u = 0x08 /* 1 op, 1 byte const */ - opConst1s = 0x09 /* " signed */ - opConst2u = 0x0A /* 1 op, 2 byte const */ - opConst2s = 0x0B /* " signed */ - opConst4u = 0x0C /* 1 op, 4 byte const */ - opConst4s = 0x0D /* " signed */ - opConst8u = 0x0E /* 1 op, 8 byte const */ - opConst8s = 0x0F /* " signed */ - opConstu = 0x10 /* 1 op, LEB128 const */ - opConsts = 0x11 /* " signed */ - opDup = 0x12 - opDrop = 0x13 - opOver = 0x14 - opPick = 0x15 /* 1 op, 1 byte stack index */ - opSwap = 0x16 - opRot = 0x17 - opXderef = 0x18 - opAbs = 0x19 - opAnd = 0x1A - opDiv = 0x1B - opMinus = 0x1C - opMod = 0x1D - opMul = 0x1E - opNeg = 0x1F - opNot = 0x20 - opOr = 0x21 - opPlus = 0x22 - opPlusUconst = 0x23 /* 1 op, ULEB128 addend */ - opShl = 0x24 - opShr = 0x25 - opShra = 0x26 - opXor = 0x27 - opSkip = 0x2F /* 1 op, signed 2-byte constant */ - opBra = 0x28 /* 1 op, signed 2-byte constant */ - opEq = 0x29 - opGe = 0x2A - opGt = 0x2B - opLe = 0x2C - opLt = 0x2D - opNe = 0x2E - opLit0 = 0x30 - /* OpLitN = OpLit0 + N for N = 0..31 */ - opReg0 = 0x50 - /* OpRegN = OpReg0 + N for N = 0..31 */ - opBreg0 = 0x70 /* 1 op, signed LEB128 constant */ - /* OpBregN = OpBreg0 + N for N = 0..31 */ - opRegx = 0x90 /* 1 op, ULEB128 register */ - opFbreg = 0x91 /* 1 op, SLEB128 offset */ - opBregx = 0x92 /* 2 op, ULEB128 reg; SLEB128 off */ - opPiece = 0x93 /* 1 op, ULEB128 size of piece */ - opDerefSize = 0x94 /* 1-byte size of data retrieved */ - opXderefSize = 0x95 /* 1-byte size of data retrieved */ - opNop = 0x96 - /* next four new in Dwarf v3 */ - opPushObjAddr = 0x97 - opCall2 = 0x98 /* 2-byte offset of DIE */ - opCall4 = 0x99 /* 4-byte offset of DIE */ - opCallRef = 0x9A /* 4- or 8- byte offset of DIE */ - /* 0xE0-0xFF reserved for user-specific */ -) - -// Basic type encodings -- the value for AttrEncoding in a TagBaseType Entry. -const ( - encAddress = 0x01 - encBoolean = 0x02 - encComplexFloat = 0x03 - encFloat = 0x04 - encSigned = 0x05 - encSignedChar = 0x06 - encUnsigned = 0x07 - encUnsignedChar = 0x08 - encImaginaryFloat = 0x09 -) diff --git a/src/pkg/debug/dwarf/entry.go b/src/pkg/debug/dwarf/entry.go deleted file mode 100644 index 665c6840d..000000000 --- a/src/pkg/debug/dwarf/entry.go +++ /dev/null @@ -1,401 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// DWARF debug information entry parser. -// An entry is a sequence of data items of a given format. -// The first word in the entry is an index into what DWARF -// calls the ``abbreviation table.'' An abbreviation is really -// just a type descriptor: it's an array of attribute tag/value format pairs. - -package dwarf - -import ( - "errors" - "strconv" -) - -// a single entry's description: a sequence of attributes -type abbrev struct { - tag Tag - children bool - field []afield -} - -type afield struct { - attr Attr - fmt format -} - -// a map from entry format ids to their descriptions -type abbrevTable map[uint32]abbrev - -// ParseAbbrev returns the abbreviation table that starts at byte off -// in the .debug_abbrev section. -func (d *Data) parseAbbrev(off uint32) (abbrevTable, error) { - if m, ok := d.abbrevCache[off]; ok { - return m, nil - } - - data := d.abbrev - if off > uint32(len(data)) { - data = nil - } else { - data = data[off:] - } - b := makeBuf(d, unknownFormat{}, "abbrev", 0, data) - - // Error handling is simplified by the buf getters - // returning an endless stream of 0s after an error. - m := make(abbrevTable) - for { - // Table ends with id == 0. - id := uint32(b.uint()) - if id == 0 { - break - } - - // Walk over attributes, counting. - n := 0 - b1 := b // Read from copy of b. - b1.uint() - b1.uint8() - for { - tag := b1.uint() - fmt := b1.uint() - if tag == 0 && fmt == 0 { - break - } - n++ - } - if b1.err != nil { - return nil, b1.err - } - - // Walk over attributes again, this time writing them down. - var a abbrev - a.tag = Tag(b.uint()) - a.children = b.uint8() != 0 - a.field = make([]afield, n) - for i := range a.field { - a.field[i].attr = Attr(b.uint()) - a.field[i].fmt = format(b.uint()) - } - b.uint() - b.uint() - - m[id] = a - } - if b.err != nil { - return nil, b.err - } - d.abbrevCache[off] = m - return m, nil -} - -// An entry is a sequence of attribute/value pairs. -type Entry struct { - Offset Offset // offset of Entry in DWARF info - Tag Tag // tag (kind of Entry) - Children bool // whether Entry is followed by children - Field []Field -} - -// A Field is a single attribute/value pair in an Entry. -type Field struct { - Attr Attr - Val interface{} -} - -// Val returns the value associated with attribute Attr in Entry, -// or nil if there is no such attribute. -// -// A common idiom is to merge the check for nil return with -// the check that the value has the expected dynamic type, as in: -// v, ok := e.Val(AttrSibling).(int64); -// -func (e *Entry) Val(a Attr) interface{} { - for _, f := range e.Field { - if f.Attr == a { - return f.Val - } - } - return nil -} - -// An Offset represents the location of an Entry within the DWARF info. -// (See Reader.Seek.) -type Offset uint32 - -// Entry reads a single entry from buf, decoding -// according to the given abbreviation table. -func (b *buf) entry(atab abbrevTable, ubase Offset) *Entry { - off := b.off - id := uint32(b.uint()) - if id == 0 { - return &Entry{} - } - a, ok := atab[id] - if !ok { - b.error("unknown abbreviation table index") - return nil - } - e := &Entry{ - Offset: off, - Tag: a.tag, - Children: a.children, - Field: make([]Field, len(a.field)), - } - for i := range e.Field { - e.Field[i].Attr = a.field[i].attr - fmt := a.field[i].fmt - if fmt == formIndirect { - fmt = format(b.uint()) - } - var val interface{} - switch fmt { - default: - b.error("unknown entry attr format 0x" + strconv.FormatInt(int64(fmt), 16)) - - // address - case formAddr: - val = b.addr() - - // block - case formDwarfBlock1: - val = b.bytes(int(b.uint8())) - case formDwarfBlock2: - val = b.bytes(int(b.uint16())) - case formDwarfBlock4: - val = b.bytes(int(b.uint32())) - case formDwarfBlock: - val = b.bytes(int(b.uint())) - - // constant - case formData1: - val = int64(b.uint8()) - case formData2: - val = int64(b.uint16()) - case formData4: - val = int64(b.uint32()) - case formData8: - val = int64(b.uint64()) - case formSdata: - val = int64(b.int()) - case formUdata: - val = int64(b.uint()) - - // flag - case formFlag: - val = b.uint8() == 1 - // New in DWARF 4. - case formFlagPresent: - // The attribute is implicitly indicated as present, and no value is - // encoded in the debugging information entry itself. - val = true - - // reference to other entry - case formRefAddr: - vers := b.format.version() - if vers == 0 { - b.error("unknown version for DW_FORM_ref_addr") - } else if vers == 2 { - val = Offset(b.addr()) - } else { - is64, known := b.format.dwarf64() - if !known { - b.error("unknown size for DW_FORM_ref_addr") - } else if is64 { - val = Offset(b.uint64()) - } else { - val = Offset(b.uint32()) - } - } - case formRef1: - val = Offset(b.uint8()) + ubase - case formRef2: - val = Offset(b.uint16()) + ubase - case formRef4: - val = Offset(b.uint32()) + ubase - case formRef8: - val = Offset(b.uint64()) + ubase - case formRefUdata: - val = Offset(b.uint()) + ubase - - // string - case formString: - val = b.string() - case formStrp: - off := b.uint32() // offset into .debug_str - if b.err != nil { - return nil - } - b1 := makeBuf(b.dwarf, unknownFormat{}, "str", 0, b.dwarf.str) - b1.skip(int(off)) - val = b1.string() - if b1.err != nil { - b.err = b1.err - return nil - } - - // lineptr, loclistptr, macptr, rangelistptr - // New in DWARF 4, but clang can generate them with -gdwarf-2. - // Section reference, replacing use of formData4 and formData8. - case formSecOffset, formGnuRefAlt, formGnuStrpAlt: - is64, known := b.format.dwarf64() - if !known { - b.error("unknown size for form 0x" + strconv.FormatInt(int64(fmt), 16)) - } else if is64 { - val = int64(b.uint64()) - } else { - val = int64(b.uint32()) - } - - // exprloc - // New in DWARF 4. - case formExprloc: - val = b.bytes(int(b.uint())) - - // reference - // New in DWARF 4. - case formRefSig8: - // 64-bit type signature. - val = b.uint64() - } - e.Field[i].Val = val - } - if b.err != nil { - return nil - } - return e -} - -// A Reader allows reading Entry structures from a DWARF ``info'' section. -// The Entry structures are arranged in a tree. The Reader's Next function -// return successive entries from a pre-order traversal of the tree. -// If an entry has children, its Children field will be true, and the children -// follow, terminated by an Entry with Tag 0. -type Reader struct { - b buf - d *Data - err error - unit int - lastChildren bool // .Children of last entry returned by Next - lastSibling Offset // .Val(AttrSibling) of last entry returned by Next -} - -// Reader returns a new Reader for Data. -// The reader is positioned at byte offset 0 in the DWARF ``info'' section. -func (d *Data) Reader() *Reader { - r := &Reader{d: d} - r.Seek(0) - return r -} - -// Seek positions the Reader at offset off in the encoded entry stream. -// Offset 0 can be used to denote the first entry. -func (r *Reader) Seek(off Offset) { - d := r.d - r.err = nil - r.lastChildren = false - if off == 0 { - if len(d.unit) == 0 { - return - } - u := &d.unit[0] - r.unit = 0 - r.b = makeBuf(r.d, u, "info", u.off, u.data) - return - } - - // TODO(rsc): binary search (maybe a new package) - var i int - var u *unit - for i = range d.unit { - u = &d.unit[i] - if u.off <= off && off < u.off+Offset(len(u.data)) { - r.unit = i - r.b = makeBuf(r.d, u, "info", off, u.data[off-u.off:]) - return - } - } - r.err = errors.New("offset out of range") -} - -// maybeNextUnit advances to the next unit if this one is finished. -func (r *Reader) maybeNextUnit() { - for len(r.b.data) == 0 && r.unit+1 < len(r.d.unit) { - r.unit++ - u := &r.d.unit[r.unit] - r.b = makeBuf(r.d, u, "info", u.off, u.data) - } -} - -// Next reads the next entry from the encoded entry stream. -// It returns nil, nil when it reaches the end of the section. -// It returns an error if the current offset is invalid or the data at the -// offset cannot be decoded as a valid Entry. -func (r *Reader) Next() (*Entry, error) { - if r.err != nil { - return nil, r.err - } - r.maybeNextUnit() - if len(r.b.data) == 0 { - return nil, nil - } - u := &r.d.unit[r.unit] - e := r.b.entry(u.atable, u.base) - if r.b.err != nil { - r.err = r.b.err - return nil, r.err - } - if e != nil { - r.lastChildren = e.Children - if r.lastChildren { - r.lastSibling, _ = e.Val(AttrSibling).(Offset) - } - } else { - r.lastChildren = false - } - return e, nil -} - -// SkipChildren skips over the child entries associated with -// the last Entry returned by Next. If that Entry did not have -// children or Next has not been called, SkipChildren is a no-op. -func (r *Reader) SkipChildren() { - if r.err != nil || !r.lastChildren { - return - } - - // If the last entry had a sibling attribute, - // that attribute gives the offset of the next - // sibling, so we can avoid decoding the - // child subtrees. - if r.lastSibling >= r.b.off { - r.Seek(r.lastSibling) - return - } - - for { - e, err := r.Next() - if err != nil || e == nil || e.Tag == 0 { - break - } - if e.Children { - r.SkipChildren() - } - } -} - -// clone returns a copy of the reader. This is used by the typeReader -// interface. -func (r *Reader) clone() typeReader { - return r.d.Reader() -} - -// offset returns the current buffer offset. This is used by the -// typeReader interface. -func (r *Reader) offset() Offset { - return r.b.off -} diff --git a/src/pkg/debug/dwarf/open.go b/src/pkg/debug/dwarf/open.go deleted file mode 100644 index c1b3f37ac..000000000 --- a/src/pkg/debug/dwarf/open.go +++ /dev/null @@ -1,87 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package dwarf provides access to DWARF debugging information loaded from -// executable files, as defined in the DWARF 2.0 Standard at -// http://dwarfstd.org/doc/dwarf-2.0.0.pdf -package dwarf - -import "encoding/binary" - -// Data represents the DWARF debugging information -// loaded from an executable file (for example, an ELF or Mach-O executable). -type Data struct { - // raw data - abbrev []byte - aranges []byte - frame []byte - info []byte - line []byte - pubnames []byte - ranges []byte - str []byte - - // parsed data - abbrevCache map[uint32]abbrevTable - order binary.ByteOrder - typeCache map[Offset]Type - typeSigs map[uint64]*typeUnit - unit []unit -} - -// New returns a new Data object initialized from the given parameters. -// Rather than calling this function directly, clients should typically use -// the DWARF method of the File type of the appropriate package debug/elf, -// debug/macho, or debug/pe. -// -// The []byte arguments are the data from the corresponding debug section -// in the object file; for example, for an ELF object, abbrev is the contents of -// the ".debug_abbrev" section. -func New(abbrev, aranges, frame, info, line, pubnames, ranges, str []byte) (*Data, error) { - d := &Data{ - abbrev: abbrev, - aranges: aranges, - frame: frame, - info: info, - line: line, - pubnames: pubnames, - ranges: ranges, - str: str, - abbrevCache: make(map[uint32]abbrevTable), - typeCache: make(map[Offset]Type), - typeSigs: make(map[uint64]*typeUnit), - } - - // Sniff .debug_info to figure out byte order. - // bytes 4:6 are the version, a tiny 16-bit number (1, 2, 3). - if len(d.info) < 6 { - return nil, DecodeError{"info", Offset(len(d.info)), "too short"} - } - x, y := d.info[4], d.info[5] - switch { - case x == 0 && y == 0: - return nil, DecodeError{"info", 4, "unsupported version 0"} - case x == 0: - d.order = binary.BigEndian - case y == 0: - d.order = binary.LittleEndian - default: - return nil, DecodeError{"info", 4, "cannot determine byte order"} - } - - u, err := d.parseUnits() - if err != nil { - return nil, err - } - d.unit = u - return d, nil -} - -// AddTypes will add one .debug_types section to the DWARF data. A -// typical object with DWARF version 4 debug info will have multiple -// .debug_types sections. The name is used for error reporting only, -// and serves to distinguish one .debug_types section from another. -func (d *Data) AddTypes(name string, types []byte) error { - return d.parseTypes(name, types) -} diff --git a/src/pkg/debug/dwarf/testdata/typedef.c b/src/pkg/debug/dwarf/testdata/typedef.c deleted file mode 100644 index f05f01564..000000000 --- a/src/pkg/debug/dwarf/testdata/typedef.c +++ /dev/null @@ -1,85 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* -Linux ELF: -gcc -gdwarf-2 -m64 -c typedef.c && gcc -gdwarf-2 -m64 -o typedef.elf typedef.o - -OS X Mach-O: -gcc -gdwarf-2 -m64 -c typedef.c -o typedef.macho -*/ -#include - -typedef volatile int* t_ptr_volatile_int; -typedef const char *t_ptr_const_char; -typedef long t_long; -typedef unsigned short t_ushort; -typedef int t_func_int_of_float_double(float, double); -typedef int (*t_ptr_func_int_of_float_double)(float, double); -typedef int (*t_ptr_func_int_of_float_complex)(float complex); -typedef int (*t_ptr_func_int_of_double_complex)(double complex); -typedef int (*t_ptr_func_int_of_long_double_complex)(long double complex); -typedef int *t_func_ptr_int_of_char_schar_uchar(char, signed char, unsigned char); -typedef void t_func_void_of_char(char); -typedef void t_func_void_of_void(void); -typedef void t_func_void_of_ptr_char_dots(char*, ...); -typedef struct my_struct { - volatile int vi; - char x : 1; - int y : 4; - int z[0]; - long long array[40]; - int zz[0]; -} t_my_struct; -typedef struct my_struct1 { - int zz [1]; -} t_my_struct1; -typedef union my_union { - volatile int vi; - char x : 1; - int y : 4; - long long array[40]; -} t_my_union; -typedef enum my_enum { - e1 = 1, - e2 = 2, - e3 = -5, - e4 = 1000000000000000LL, -} t_my_enum; - -typedef struct list t_my_list; -struct list { - short val; - t_my_list *next; -}; - -typedef struct tree { - struct tree *left, *right; - unsigned long long val; -} t_my_tree; - -t_ptr_volatile_int *a2; -t_ptr_const_char **a3a; -t_long *a4; -t_ushort *a5; -t_func_int_of_float_double *a6; -t_ptr_func_int_of_float_double *a7; -t_func_ptr_int_of_char_schar_uchar *a8; -t_func_void_of_char *a9; -t_func_void_of_void *a10; -t_func_void_of_ptr_char_dots *a11; -t_my_struct *a12; -t_my_struct1 *a12a; -t_my_union *a12b; -t_my_enum *a13; -t_my_list *a14; -t_my_tree *a15; -t_ptr_func_int_of_float_complex *a16; -t_ptr_func_int_of_double_complex *a17; -t_ptr_func_int_of_long_double_complex *a18; - -int main() -{ - return 0; -} diff --git a/src/pkg/debug/dwarf/testdata/typedef.elf b/src/pkg/debug/dwarf/testdata/typedef.elf deleted file mode 100755 index b2062d2c4..000000000 Binary files a/src/pkg/debug/dwarf/testdata/typedef.elf and /dev/null differ diff --git a/src/pkg/debug/dwarf/testdata/typedef.elf4 b/src/pkg/debug/dwarf/testdata/typedef.elf4 deleted file mode 100644 index 3d5a5a1b1..000000000 Binary files a/src/pkg/debug/dwarf/testdata/typedef.elf4 and /dev/null differ diff --git a/src/pkg/debug/dwarf/testdata/typedef.macho b/src/pkg/debug/dwarf/testdata/typedef.macho deleted file mode 100644 index f75afcccb..000000000 Binary files a/src/pkg/debug/dwarf/testdata/typedef.macho and /dev/null differ diff --git a/src/pkg/debug/dwarf/type.go b/src/pkg/debug/dwarf/type.go deleted file mode 100644 index fa40b2bef..000000000 --- a/src/pkg/debug/dwarf/type.go +++ /dev/null @@ -1,685 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// DWARF type information structures. -// The format is heavily biased toward C, but for simplicity -// the String methods use a pseudo-Go syntax. - -package dwarf - -import "strconv" - -// A Type conventionally represents a pointer to any of the -// specific Type structures (CharType, StructType, etc.). -type Type interface { - Common() *CommonType - String() string - Size() int64 -} - -// A CommonType holds fields common to multiple types. -// If a field is not known or not applicable for a given type, -// the zero value is used. -type CommonType struct { - ByteSize int64 // size of value of this type, in bytes - Name string // name that can be used to refer to type -} - -func (c *CommonType) Common() *CommonType { return c } - -func (c *CommonType) Size() int64 { return c.ByteSize } - -// Basic types - -// A BasicType holds fields common to all basic types. -type BasicType struct { - CommonType - BitSize int64 - BitOffset int64 -} - -func (b *BasicType) Basic() *BasicType { return b } - -func (t *BasicType) String() string { - if t.Name != "" { - return t.Name - } - return "?" -} - -// A CharType represents a signed character type. -type CharType struct { - BasicType -} - -// A UcharType represents an unsigned character type. -type UcharType struct { - BasicType -} - -// An IntType represents a signed integer type. -type IntType struct { - BasicType -} - -// A UintType represents an unsigned integer type. -type UintType struct { - BasicType -} - -// A FloatType represents a floating point type. -type FloatType struct { - BasicType -} - -// A ComplexType represents a complex floating point type. -type ComplexType struct { - BasicType -} - -// A BoolType represents a boolean type. -type BoolType struct { - BasicType -} - -// An AddrType represents a machine address type. -type AddrType struct { - BasicType -} - -// An UnspecifiedType represents an implicit, unknown, ambiguous or nonexistent type. -type UnspecifiedType struct { - BasicType -} - -// qualifiers - -// A QualType represents a type that has the C/C++ "const", "restrict", or "volatile" qualifier. -type QualType struct { - CommonType - Qual string - Type Type -} - -func (t *QualType) String() string { return t.Qual + " " + t.Type.String() } - -func (t *QualType) Size() int64 { return t.Type.Size() } - -// An ArrayType represents a fixed size array type. -type ArrayType struct { - CommonType - Type Type - StrideBitSize int64 // if > 0, number of bits to hold each element - Count int64 // if == -1, an incomplete array, like char x[]. -} - -func (t *ArrayType) String() string { - return "[" + strconv.FormatInt(t.Count, 10) + "]" + t.Type.String() -} - -func (t *ArrayType) Size() int64 { - if t.Count == -1 { - return 0 - } - return t.Count * t.Type.Size() -} - -// A VoidType represents the C void type. -type VoidType struct { - CommonType -} - -func (t *VoidType) String() string { return "void" } - -// A PtrType represents a pointer type. -type PtrType struct { - CommonType - Type Type -} - -func (t *PtrType) String() string { return "*" + t.Type.String() } - -// A StructType represents a struct, union, or C++ class type. -type StructType struct { - CommonType - StructName string - Kind string // "struct", "union", or "class". - Field []*StructField - Incomplete bool // if true, struct, union, class is declared but not defined -} - -// A StructField represents a field in a struct, union, or C++ class type. -type StructField struct { - Name string - Type Type - ByteOffset int64 - ByteSize int64 - BitOffset int64 // within the ByteSize bytes at ByteOffset - BitSize int64 // zero if not a bit field -} - -func (t *StructType) String() string { - if t.StructName != "" { - return t.Kind + " " + t.StructName - } - return t.Defn() -} - -func (t *StructType) Defn() string { - s := t.Kind - if t.StructName != "" { - s += " " + t.StructName - } - if t.Incomplete { - s += " /*incomplete*/" - return s - } - s += " {" - for i, f := range t.Field { - if i > 0 { - s += "; " - } - s += f.Name + " " + f.Type.String() - s += "@" + strconv.FormatInt(f.ByteOffset, 10) - if f.BitSize > 0 { - s += " : " + strconv.FormatInt(f.BitSize, 10) - s += "@" + strconv.FormatInt(f.BitOffset, 10) - } - } - s += "}" - return s -} - -// An EnumType represents an enumerated type. -// The only indication of its native integer type is its ByteSize -// (inside CommonType). -type EnumType struct { - CommonType - EnumName string - Val []*EnumValue -} - -// An EnumValue represents a single enumeration value. -type EnumValue struct { - Name string - Val int64 -} - -func (t *EnumType) String() string { - s := "enum" - if t.EnumName != "" { - s += " " + t.EnumName - } - s += " {" - for i, v := range t.Val { - if i > 0 { - s += "; " - } - s += v.Name + "=" + strconv.FormatInt(v.Val, 10) - } - s += "}" - return s -} - -// A FuncType represents a function type. -type FuncType struct { - CommonType - ReturnType Type - ParamType []Type -} - -func (t *FuncType) String() string { - s := "func(" - for i, t := range t.ParamType { - if i > 0 { - s += ", " - } - s += t.String() - } - s += ")" - if t.ReturnType != nil { - s += " " + t.ReturnType.String() - } - return s -} - -// A DotDotDotType represents the variadic ... function parameter. -type DotDotDotType struct { - CommonType -} - -func (t *DotDotDotType) String() string { return "..." } - -// A TypedefType represents a named type. -type TypedefType struct { - CommonType - Type Type -} - -func (t *TypedefType) String() string { return t.Name } - -func (t *TypedefType) Size() int64 { return t.Type.Size() } - -// typeReader is used to read from either the info section or the -// types section. -type typeReader interface { - Seek(Offset) - Next() (*Entry, error) - clone() typeReader - offset() Offset -} - -// Type reads the type at off in the DWARF ``info'' section. -func (d *Data) Type(off Offset) (Type, error) { - return d.readType("info", d.Reader(), off, d.typeCache) -} - -// readType reads a type from r at off of name using and updating a -// type cache. -func (d *Data) readType(name string, r typeReader, off Offset, typeCache map[Offset]Type) (Type, error) { - if t, ok := typeCache[off]; ok { - return t, nil - } - r.Seek(off) - e, err := r.Next() - if err != nil { - return nil, err - } - if e == nil || e.Offset != off { - return nil, DecodeError{name, off, "no type at offset"} - } - - // Parse type from Entry. - // Must always set typeCache[off] before calling - // d.Type recursively, to handle circular types correctly. - var typ Type - - nextDepth := 0 - - // Get next child; set err if error happens. - next := func() *Entry { - if !e.Children { - return nil - } - // Only return direct children. - // Skip over composite entries that happen to be nested - // inside this one. Most DWARF generators wouldn't generate - // such a thing, but clang does. - // See golang.org/issue/6472. - for { - kid, err1 := r.Next() - if err1 != nil { - err = err1 - return nil - } - if kid == nil { - err = DecodeError{name, r.offset(), "unexpected end of DWARF entries"} - return nil - } - if kid.Tag == 0 { - if nextDepth > 0 { - nextDepth-- - continue - } - return nil - } - if kid.Children { - nextDepth++ - } - if nextDepth > 0 { - continue - } - return kid - } - } - - // Get Type referred to by Entry's AttrType field. - // Set err if error happens. Not having a type is an error. - typeOf := func(e *Entry) Type { - tval := e.Val(AttrType) - var t Type - switch toff := tval.(type) { - case Offset: - if t, err = d.readType(name, r.clone(), toff, typeCache); err != nil { - return nil - } - case uint64: - if t, err = d.sigToType(toff); err != nil { - return nil - } - default: - // It appears that no Type means "void". - return new(VoidType) - } - return t - } - - switch e.Tag { - case TagArrayType: - // Multi-dimensional array. (DWARF v2 §5.4) - // Attributes: - // AttrType:subtype [required] - // AttrStrideSize: size in bits of each element of the array - // AttrByteSize: size of entire array - // Children: - // TagSubrangeType or TagEnumerationType giving one dimension. - // dimensions are in left to right order. - t := new(ArrayType) - typ = t - typeCache[off] = t - if t.Type = typeOf(e); err != nil { - goto Error - } - t.StrideBitSize, _ = e.Val(AttrStrideSize).(int64) - - // Accumulate dimensions, - var dims []int64 - for kid := next(); kid != nil; kid = next() { - // TODO(rsc): Can also be TagEnumerationType - // but haven't seen that in the wild yet. - switch kid.Tag { - case TagSubrangeType: - count, ok := kid.Val(AttrCount).(int64) - if !ok { - // Old binaries may have an upper bound instead. - count, ok = kid.Val(AttrUpperBound).(int64) - if ok { - count++ // Length is one more than upper bound. - } else if len(dims) == 0 { - count = -1 // As in x[]. - } - } - dims = append(dims, count) - case TagEnumerationType: - err = DecodeError{name, kid.Offset, "cannot handle enumeration type as array bound"} - goto Error - } - } - if len(dims) == 0 { - // LLVM generates this for x[]. - dims = []int64{-1} - } - - t.Count = dims[0] - for i := len(dims) - 1; i >= 1; i-- { - t.Type = &ArrayType{Type: t.Type, Count: dims[i]} - } - - case TagBaseType: - // Basic type. (DWARF v2 §5.1) - // Attributes: - // AttrName: name of base type in programming language of the compilation unit [required] - // AttrEncoding: encoding value for type (encFloat etc) [required] - // AttrByteSize: size of type in bytes [required] - // AttrBitOffset: for sub-byte types, size in bits - // AttrBitSize: for sub-byte types, bit offset of high order bit in the AttrByteSize bytes - name, _ := e.Val(AttrName).(string) - enc, ok := e.Val(AttrEncoding).(int64) - if !ok { - err = DecodeError{name, e.Offset, "missing encoding attribute for " + name} - goto Error - } - switch enc { - default: - err = DecodeError{name, e.Offset, "unrecognized encoding attribute value"} - goto Error - - case encAddress: - typ = new(AddrType) - case encBoolean: - typ = new(BoolType) - case encComplexFloat: - typ = new(ComplexType) - case encFloat: - typ = new(FloatType) - case encSigned: - typ = new(IntType) - case encUnsigned: - typ = new(UintType) - case encSignedChar: - typ = new(CharType) - case encUnsignedChar: - typ = new(UcharType) - } - typeCache[off] = typ - t := typ.(interface { - Basic() *BasicType - }).Basic() - t.Name = name - t.BitSize, _ = e.Val(AttrBitSize).(int64) - t.BitOffset, _ = e.Val(AttrBitOffset).(int64) - - case TagClassType, TagStructType, TagUnionType: - // Structure, union, or class type. (DWARF v2 §5.5) - // Attributes: - // AttrName: name of struct, union, or class - // AttrByteSize: byte size [required] - // AttrDeclaration: if true, struct/union/class is incomplete - // Children: - // TagMember to describe one member. - // AttrName: name of member [required] - // AttrType: type of member [required] - // AttrByteSize: size in bytes - // AttrBitOffset: bit offset within bytes for bit fields - // AttrBitSize: bit size for bit fields - // AttrDataMemberLoc: location within struct [required for struct, class] - // There is much more to handle C++, all ignored for now. - t := new(StructType) - typ = t - typeCache[off] = t - switch e.Tag { - case TagClassType: - t.Kind = "class" - case TagStructType: - t.Kind = "struct" - case TagUnionType: - t.Kind = "union" - } - t.StructName, _ = e.Val(AttrName).(string) - t.Incomplete = e.Val(AttrDeclaration) != nil - t.Field = make([]*StructField, 0, 8) - var lastFieldType *Type - var lastFieldBitOffset int64 - for kid := next(); kid != nil; kid = next() { - if kid.Tag == TagMember { - f := new(StructField) - if f.Type = typeOf(kid); err != nil { - goto Error - } - switch loc := kid.Val(AttrDataMemberLoc).(type) { - case []byte: - // TODO: Should have original compilation - // unit here, not unknownFormat. - b := makeBuf(d, unknownFormat{}, "location", 0, loc) - if b.uint8() != opPlusUconst { - err = DecodeError{name, kid.Offset, "unexpected opcode"} - goto Error - } - f.ByteOffset = int64(b.uint()) - if b.err != nil { - err = b.err - goto Error - } - case int64: - f.ByteOffset = loc - } - - haveBitOffset := false - f.Name, _ = kid.Val(AttrName).(string) - f.ByteSize, _ = kid.Val(AttrByteSize).(int64) - f.BitOffset, haveBitOffset = kid.Val(AttrBitOffset).(int64) - f.BitSize, _ = kid.Val(AttrBitSize).(int64) - t.Field = append(t.Field, f) - - bito := f.BitOffset - if !haveBitOffset { - bito = f.ByteOffset * 8 - } - if bito == lastFieldBitOffset && t.Kind != "union" { - // Last field was zero width. Fix array length. - // (DWARF writes out 0-length arrays as if they were 1-length arrays.) - zeroArray(lastFieldType) - } - lastFieldType = &f.Type - lastFieldBitOffset = bito - } - } - if t.Kind != "union" { - b, ok := e.Val(AttrByteSize).(int64) - if ok && b*8 == lastFieldBitOffset { - // Final field must be zero width. Fix array length. - zeroArray(lastFieldType) - } - } - - case TagConstType, TagVolatileType, TagRestrictType: - // Type modifier (DWARF v2 §5.2) - // Attributes: - // AttrType: subtype - t := new(QualType) - typ = t - typeCache[off] = t - if t.Type = typeOf(e); err != nil { - goto Error - } - switch e.Tag { - case TagConstType: - t.Qual = "const" - case TagRestrictType: - t.Qual = "restrict" - case TagVolatileType: - t.Qual = "volatile" - } - - case TagEnumerationType: - // Enumeration type (DWARF v2 §5.6) - // Attributes: - // AttrName: enum name if any - // AttrByteSize: bytes required to represent largest value - // Children: - // TagEnumerator: - // AttrName: name of constant - // AttrConstValue: value of constant - t := new(EnumType) - typ = t - typeCache[off] = t - t.EnumName, _ = e.Val(AttrName).(string) - t.Val = make([]*EnumValue, 0, 8) - for kid := next(); kid != nil; kid = next() { - if kid.Tag == TagEnumerator { - f := new(EnumValue) - f.Name, _ = kid.Val(AttrName).(string) - f.Val, _ = kid.Val(AttrConstValue).(int64) - n := len(t.Val) - if n >= cap(t.Val) { - val := make([]*EnumValue, n, n*2) - copy(val, t.Val) - t.Val = val - } - t.Val = t.Val[0 : n+1] - t.Val[n] = f - } - } - - case TagPointerType: - // Type modifier (DWARF v2 §5.2) - // Attributes: - // AttrType: subtype [not required! void* has no AttrType] - // AttrAddrClass: address class [ignored] - t := new(PtrType) - typ = t - typeCache[off] = t - if e.Val(AttrType) == nil { - t.Type = &VoidType{} - break - } - t.Type = typeOf(e) - - case TagSubroutineType: - // Subroutine type. (DWARF v2 §5.7) - // Attributes: - // AttrType: type of return value if any - // AttrName: possible name of type [ignored] - // AttrPrototyped: whether used ANSI C prototype [ignored] - // Children: - // TagFormalParameter: typed parameter - // AttrType: type of parameter - // TagUnspecifiedParameter: final ... - t := new(FuncType) - typ = t - typeCache[off] = t - if t.ReturnType = typeOf(e); err != nil { - goto Error - } - t.ParamType = make([]Type, 0, 8) - for kid := next(); kid != nil; kid = next() { - var tkid Type - switch kid.Tag { - default: - continue - case TagFormalParameter: - if tkid = typeOf(kid); err != nil { - goto Error - } - case TagUnspecifiedParameters: - tkid = &DotDotDotType{} - } - t.ParamType = append(t.ParamType, tkid) - } - - case TagTypedef: - // Typedef (DWARF v2 §5.3) - // Attributes: - // AttrName: name [required] - // AttrType: type definition [required] - t := new(TypedefType) - typ = t - typeCache[off] = t - t.Name, _ = e.Val(AttrName).(string) - t.Type = typeOf(e) - - case TagUnspecifiedType: - // Unspecified type (DWARF v3 §5.2) - // Attributes: - // AttrName: name - t := new(UnspecifiedType) - typ = t - typeCache[off] = t - t.Name, _ = e.Val(AttrName).(string) - } - - if err != nil { - goto Error - } - - { - b, ok := e.Val(AttrByteSize).(int64) - if !ok { - b = -1 - } - typ.Common().ByteSize = b - } - return typ, nil - -Error: - // If the parse fails, take the type out of the cache - // so that the next call with this offset doesn't hit - // the cache and return success. - delete(typeCache, off) - return nil, err -} - -func zeroArray(t *Type) { - if t == nil { - return - } - at, ok := (*t).(*ArrayType) - if !ok || at.Type.Size() == 0 { - return - } - // Make a copy to avoid invalidating typeCache. - tt := *at - tt.Count = 0 - *t = &tt -} diff --git a/src/pkg/debug/dwarf/type_test.go b/src/pkg/debug/dwarf/type_test.go deleted file mode 100644 index 2cb85e74b..000000000 --- a/src/pkg/debug/dwarf/type_test.go +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package dwarf_test - -import ( - . "debug/dwarf" - "debug/elf" - "debug/macho" - "testing" -) - -var typedefTests = map[string]string{ - "t_ptr_volatile_int": "*volatile int", - "t_ptr_const_char": "*const char", - "t_long": "long int", - "t_ushort": "short unsigned int", - "t_func_int_of_float_double": "func(float, double) int", - "t_ptr_func_int_of_float_double": "*func(float, double) int", - "t_ptr_func_int_of_float_complex": "*func(complex float) int", - "t_ptr_func_int_of_double_complex": "*func(complex double) int", - "t_ptr_func_int_of_long_double_complex": "*func(complex long double) int", - "t_func_ptr_int_of_char_schar_uchar": "func(char, signed char, unsigned char) *int", - "t_func_void_of_char": "func(char) void", - "t_func_void_of_void": "func() void", - "t_func_void_of_ptr_char_dots": "func(*char, ...) void", - "t_my_struct": "struct my_struct {vi volatile int@0; x char@4 : 1@7; y int@4 : 4@27; z [0]int@8; array [40]long long int@8; zz [0]int@328}", - "t_my_struct1": "struct my_struct1 {zz [1]int@0}", - "t_my_union": "union my_union {vi volatile int@0; x char@0 : 1@7; y int@0 : 4@28; array [40]long long int@0}", - "t_my_enum": "enum my_enum {e1=1; e2=2; e3=-5; e4=1000000000000000}", - "t_my_list": "struct list {val short int@0; next *t_my_list@8}", - "t_my_tree": "struct tree {left *struct tree@0; right *struct tree@8; val long long unsigned int@16}", -} - -// As Apple converts gcc to a clang-based front end -// they keep breaking the DWARF output. This map lists the -// conversion from real answer to Apple answer. -var machoBug = map[string]string{ - "func(*char, ...) void": "func(*char) void", - "enum my_enum {e1=1; e2=2; e3=-5; e4=1000000000000000}": "enum my_enum {e1=1; e2=2; e3=-5; e4=-1530494976}", -} - -func elfData(t *testing.T, name string) *Data { - f, err := elf.Open(name) - if err != nil { - t.Fatal(err) - } - - d, err := f.DWARF() - if err != nil { - t.Fatal(err) - } - return d -} - -func machoData(t *testing.T, name string) *Data { - f, err := macho.Open(name) - if err != nil { - t.Fatal(err) - } - - d, err := f.DWARF() - if err != nil { - t.Fatal(err) - } - return d -} - -func TestTypedefsELF(t *testing.T) { testTypedefs(t, elfData(t, "testdata/typedef.elf"), "elf") } - -func TestTypedefsMachO(t *testing.T) { - testTypedefs(t, machoData(t, "testdata/typedef.macho"), "macho") -} - -func TestTypedefsELFDwarf4(t *testing.T) { testTypedefs(t, elfData(t, "testdata/typedef.elf4"), "elf") } - -func testTypedefs(t *testing.T, d *Data, kind string) { - r := d.Reader() - seen := make(map[string]bool) - for { - e, err := r.Next() - if err != nil { - t.Fatal("r.Next:", err) - } - if e == nil { - break - } - if e.Tag == TagTypedef { - typ, err := d.Type(e.Offset) - if err != nil { - t.Fatal("d.Type:", err) - } - t1 := typ.(*TypedefType) - var typstr string - if ts, ok := t1.Type.(*StructType); ok { - typstr = ts.Defn() - } else { - typstr = t1.Type.String() - } - - if want, ok := typedefTests[t1.Name]; ok { - if seen[t1.Name] { - t.Errorf("multiple definitions for %s", t1.Name) - } - seen[t1.Name] = true - if typstr != want && (kind != "macho" || typstr != machoBug[want]) { - t.Errorf("%s:\n\thave %s\n\twant %s", t1.Name, typstr, want) - } - } - } - if e.Tag != TagCompileUnit { - r.SkipChildren() - } - } - - for k := range typedefTests { - if !seen[k] { - t.Errorf("missing %s", k) - } - } -} diff --git a/src/pkg/debug/dwarf/typeunit.go b/src/pkg/debug/dwarf/typeunit.go deleted file mode 100644 index 3fd1c9973..000000000 --- a/src/pkg/debug/dwarf/typeunit.go +++ /dev/null @@ -1,166 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package dwarf - -import ( - "fmt" - "strconv" -) - -// Parse the type units stored in a DWARF4 .debug_types section. Each -// type unit defines a single primary type and an 8-byte signature. -// Other sections may then use formRefSig8 to refer to the type. - -// The typeUnit format is a single type with a signature. It holds -// the same data as a compilation unit. -type typeUnit struct { - unit - toff Offset // Offset to signature type within data. - name string // Name of .debug_type section. - cache Type // Cache the type, nil to start. -} - -// Parse a .debug_types section. -func (d *Data) parseTypes(name string, types []byte) error { - b := makeBuf(d, unknownFormat{}, name, 0, types) - for len(b.data) > 0 { - base := b.off - dwarf64 := false - n := b.uint32() - if n == 0xffffffff { - n64 := b.uint64() - if n64 != uint64(uint32(n64)) { - b.error("type unit length overflow") - return b.err - } - n = uint32(n64) - dwarf64 = true - } - hdroff := b.off - vers := b.uint16() - if vers != 4 { - b.error("unsupported DWARF version " + strconv.Itoa(int(vers))) - return b.err - } - var ao uint32 - if !dwarf64 { - ao = b.uint32() - } else { - ao64 := b.uint64() - if ao64 != uint64(uint32(ao64)) { - b.error("type unit abbrev offset overflow") - return b.err - } - ao = uint32(ao64) - } - atable, err := d.parseAbbrev(ao) - if err != nil { - return err - } - asize := b.uint8() - sig := b.uint64() - - var toff uint32 - if !dwarf64 { - toff = b.uint32() - } else { - to64 := b.uint64() - if to64 != uint64(uint32(to64)) { - b.error("type unit type offset overflow") - return b.err - } - toff = uint32(to64) - } - - boff := b.off - d.typeSigs[sig] = &typeUnit{ - unit: unit{ - base: base, - off: boff, - data: b.bytes(int(Offset(n) - (b.off - hdroff))), - atable: atable, - asize: int(asize), - vers: int(vers), - is64: dwarf64, - }, - toff: Offset(toff), - name: name, - } - if b.err != nil { - return b.err - } - } - return nil -} - -// Return the type for a type signature. -func (d *Data) sigToType(sig uint64) (Type, error) { - tu := d.typeSigs[sig] - if tu == nil { - return nil, fmt.Errorf("no type unit with signature %v", sig) - } - if tu.cache != nil { - return tu.cache, nil - } - - b := makeBuf(d, tu, tu.name, tu.off, tu.data) - r := &typeUnitReader{d: d, tu: tu, b: b} - t, err := d.readType(tu.name, r, Offset(tu.toff), make(map[Offset]Type)) - if err != nil { - return nil, err - } - - tu.cache = t - return t, nil -} - -// typeUnitReader is a typeReader for a tagTypeUnit. -type typeUnitReader struct { - d *Data - tu *typeUnit - b buf - err error -} - -// Seek to a new position in the type unit. -func (tur *typeUnitReader) Seek(off Offset) { - tur.err = nil - doff := off - tur.tu.off - if doff < 0 || doff >= Offset(len(tur.tu.data)) { - tur.err = fmt.Errorf("%s: offset %d out of range; max %d", tur.tu.name, doff, len(tur.tu.data)) - return - } - tur.b = makeBuf(tur.d, tur.tu, tur.tu.name, off, tur.tu.data[doff:]) -} - -// Next reads the next Entry from the type unit. -func (tur *typeUnitReader) Next() (*Entry, error) { - if tur.err != nil { - return nil, tur.err - } - if len(tur.tu.data) == 0 { - return nil, nil - } - e := tur.b.entry(tur.tu.atable, tur.tu.base) - if tur.b.err != nil { - tur.err = tur.b.err - return nil, tur.err - } - return e, nil -} - -// clone returns a new reader for the type unit. -func (tur *typeUnitReader) clone() typeReader { - return &typeUnitReader{ - d: tur.d, - tu: tur.tu, - b: makeBuf(tur.d, tur.tu, tur.tu.name, tur.tu.off, tur.tu.data), - } -} - -// offset returns the current offset. -func (tur *typeUnitReader) offset() Offset { - return tur.b.off -} diff --git a/src/pkg/debug/dwarf/unit.go b/src/pkg/debug/dwarf/unit.go deleted file mode 100644 index 0fbc8e082..000000000 --- a/src/pkg/debug/dwarf/unit.go +++ /dev/null @@ -1,90 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package dwarf - -import "strconv" - -// DWARF debug info is split into a sequence of compilation units. -// Each unit has its own abbreviation table and address size. - -type unit struct { - base Offset // byte offset of header within the aggregate info - off Offset // byte offset of data within the aggregate info - data []byte - atable abbrevTable - asize int - vers int - is64 bool // True for 64-bit DWARF format -} - -// Implement the dataFormat interface. - -func (u *unit) version() int { - return u.vers -} - -func (u *unit) dwarf64() (bool, bool) { - return u.is64, true -} - -func (u *unit) addrsize() int { - return u.asize -} - -func (d *Data) parseUnits() ([]unit, error) { - // Count units. - nunit := 0 - b := makeBuf(d, unknownFormat{}, "info", 0, d.info) - for len(b.data) > 0 { - len := b.uint32() - if len == 0xffffffff { - len64 := b.uint64() - if len64 != uint64(uint32(len64)) { - b.error("unit length overflow") - break - } - len = uint32(len64) - } - b.skip(int(len)) - nunit++ - } - if b.err != nil { - return nil, b.err - } - - // Again, this time writing them down. - b = makeBuf(d, unknownFormat{}, "info", 0, d.info) - units := make([]unit, nunit) - for i := range units { - u := &units[i] - u.base = b.off - n := b.uint32() - if n == 0xffffffff { - u.is64 = true - n = uint32(b.uint64()) - } - vers := b.uint16() - if vers != 2 && vers != 3 && vers != 4 { - b.error("unsupported DWARF version " + strconv.Itoa(int(vers))) - break - } - u.vers = int(vers) - atable, err := d.parseAbbrev(b.uint32()) - if err != nil { - if b.err == nil { - b.err = err - } - break - } - u.atable = atable - u.asize = int(b.uint8()) - u.off = b.off - u.data = b.bytes(int(n - (2 + 4 + 1))) - } - if b.err != nil { - return nil, b.err - } - return units, nil -} diff --git a/src/pkg/debug/elf/elf.go b/src/pkg/debug/elf/elf.go deleted file mode 100644 index cde296c79..000000000 --- a/src/pkg/debug/elf/elf.go +++ /dev/null @@ -1,1773 +0,0 @@ -/* - * ELF constants and data structures - * - * Derived from: - * $FreeBSD: src/sys/sys/elf32.h,v 1.8.14.1 2005/12/30 22:13:58 marcel Exp $ - * $FreeBSD: src/sys/sys/elf64.h,v 1.10.14.1 2005/12/30 22:13:58 marcel Exp $ - * $FreeBSD: src/sys/sys/elf_common.h,v 1.15.8.1 2005/12/30 22:13:58 marcel Exp $ - * $FreeBSD: src/sys/alpha/include/elf.h,v 1.14 2003/09/25 01:10:22 peter Exp $ - * $FreeBSD: src/sys/amd64/include/elf.h,v 1.18 2004/08/03 08:21:48 dfr Exp $ - * $FreeBSD: src/sys/arm/include/elf.h,v 1.5.2.1 2006/06/30 21:42:52 cognet Exp $ - * $FreeBSD: src/sys/i386/include/elf.h,v 1.16 2004/08/02 19:12:17 dfr Exp $ - * $FreeBSD: src/sys/powerpc/include/elf.h,v 1.7 2004/11/02 09:47:01 ssouhlal Exp $ - * $FreeBSD: src/sys/sparc64/include/elf.h,v 1.12 2003/09/25 01:10:26 peter Exp $ - * "ELF for the ARM® 64-bit Architecture (AArch64)" (ARM IHI 0056B) - * - * Copyright (c) 1996-1998 John D. Polstra. All rights reserved. - * Copyright (c) 2001 David E. O'Brien - * Portions Copyright 2009 The Go Authors. All rights reserved. - * - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * - * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND - * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE - * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL - * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS - * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) - * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT - * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY - * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF - * SUCH DAMAGE. - */ - -package elf - -import "strconv" - -/* - * Constants - */ - -// Indexes into the Header.Ident array. -const ( - EI_CLASS = 4 /* Class of machine. */ - EI_DATA = 5 /* Data format. */ - EI_VERSION = 6 /* ELF format version. */ - EI_OSABI = 7 /* Operating system / ABI identification */ - EI_ABIVERSION = 8 /* ABI version */ - EI_PAD = 9 /* Start of padding (per SVR4 ABI). */ - EI_NIDENT = 16 /* Size of e_ident array. */ -) - -// Initial magic number for ELF files. -const ELFMAG = "\177ELF" - -// Version is found in Header.Ident[EI_VERSION] and Header.Version. -type Version byte - -const ( - EV_NONE Version = 0 - EV_CURRENT Version = 1 -) - -var versionStrings = []intName{ - {0, "EV_NONE"}, - {1, "EV_CURRENT"}, -} - -func (i Version) String() string { return stringName(uint32(i), versionStrings, false) } -func (i Version) GoString() string { return stringName(uint32(i), versionStrings, true) } - -// Class is found in Header.Ident[EI_CLASS] and Header.Class. -type Class byte - -const ( - ELFCLASSNONE Class = 0 /* Unknown class. */ - ELFCLASS32 Class = 1 /* 32-bit architecture. */ - ELFCLASS64 Class = 2 /* 64-bit architecture. */ -) - -var classStrings = []intName{ - {0, "ELFCLASSNONE"}, - {1, "ELFCLASS32"}, - {2, "ELFCLASS64"}, -} - -func (i Class) String() string { return stringName(uint32(i), classStrings, false) } -func (i Class) GoString() string { return stringName(uint32(i), classStrings, true) } - -// Data is found in Header.Ident[EI_DATA] and Header.Data. -type Data byte - -const ( - ELFDATANONE Data = 0 /* Unknown data format. */ - ELFDATA2LSB Data = 1 /* 2's complement little-endian. */ - ELFDATA2MSB Data = 2 /* 2's complement big-endian. */ -) - -var dataStrings = []intName{ - {0, "ELFDATANONE"}, - {1, "ELFDATA2LSB"}, - {2, "ELFDATA2MSB"}, -} - -func (i Data) String() string { return stringName(uint32(i), dataStrings, false) } -func (i Data) GoString() string { return stringName(uint32(i), dataStrings, true) } - -// OSABI is found in Header.Ident[EI_OSABI] and Header.OSABI. -type OSABI byte - -const ( - ELFOSABI_NONE OSABI = 0 /* UNIX System V ABI */ - ELFOSABI_HPUX OSABI = 1 /* HP-UX operating system */ - ELFOSABI_NETBSD OSABI = 2 /* NetBSD */ - ELFOSABI_LINUX OSABI = 3 /* GNU/Linux */ - ELFOSABI_HURD OSABI = 4 /* GNU/Hurd */ - ELFOSABI_86OPEN OSABI = 5 /* 86Open common IA32 ABI */ - ELFOSABI_SOLARIS OSABI = 6 /* Solaris */ - ELFOSABI_AIX OSABI = 7 /* AIX */ - ELFOSABI_IRIX OSABI = 8 /* IRIX */ - ELFOSABI_FREEBSD OSABI = 9 /* FreeBSD */ - ELFOSABI_TRU64 OSABI = 10 /* TRU64 UNIX */ - ELFOSABI_MODESTO OSABI = 11 /* Novell Modesto */ - ELFOSABI_OPENBSD OSABI = 12 /* OpenBSD */ - ELFOSABI_OPENVMS OSABI = 13 /* Open VMS */ - ELFOSABI_NSK OSABI = 14 /* HP Non-Stop Kernel */ - ELFOSABI_ARM OSABI = 97 /* ARM */ - ELFOSABI_STANDALONE OSABI = 255 /* Standalone (embedded) application */ -) - -var osabiStrings = []intName{ - {0, "ELFOSABI_NONE"}, - {1, "ELFOSABI_HPUX"}, - {2, "ELFOSABI_NETBSD"}, - {3, "ELFOSABI_LINUX"}, - {4, "ELFOSABI_HURD"}, - {5, "ELFOSABI_86OPEN"}, - {6, "ELFOSABI_SOLARIS"}, - {7, "ELFOSABI_AIX"}, - {8, "ELFOSABI_IRIX"}, - {9, "ELFOSABI_FREEBSD"}, - {10, "ELFOSABI_TRU64"}, - {11, "ELFOSABI_MODESTO"}, - {12, "ELFOSABI_OPENBSD"}, - {13, "ELFOSABI_OPENVMS"}, - {14, "ELFOSABI_NSK"}, - {97, "ELFOSABI_ARM"}, - {255, "ELFOSABI_STANDALONE"}, -} - -func (i OSABI) String() string { return stringName(uint32(i), osabiStrings, false) } -func (i OSABI) GoString() string { return stringName(uint32(i), osabiStrings, true) } - -// Type is found in Header.Type. -type Type uint16 - -const ( - ET_NONE Type = 0 /* Unknown type. */ - ET_REL Type = 1 /* Relocatable. */ - ET_EXEC Type = 2 /* Executable. */ - ET_DYN Type = 3 /* Shared object. */ - ET_CORE Type = 4 /* Core file. */ - ET_LOOS Type = 0xfe00 /* First operating system specific. */ - ET_HIOS Type = 0xfeff /* Last operating system-specific. */ - ET_LOPROC Type = 0xff00 /* First processor-specific. */ - ET_HIPROC Type = 0xffff /* Last processor-specific. */ -) - -var typeStrings = []intName{ - {0, "ET_NONE"}, - {1, "ET_REL"}, - {2, "ET_EXEC"}, - {3, "ET_DYN"}, - {4, "ET_CORE"}, - {0xfe00, "ET_LOOS"}, - {0xfeff, "ET_HIOS"}, - {0xff00, "ET_LOPROC"}, - {0xffff, "ET_HIPROC"}, -} - -func (i Type) String() string { return stringName(uint32(i), typeStrings, false) } -func (i Type) GoString() string { return stringName(uint32(i), typeStrings, true) } - -// Machine is found in Header.Machine. -type Machine uint16 - -const ( - EM_NONE Machine = 0 /* Unknown machine. */ - EM_M32 Machine = 1 /* AT&T WE32100. */ - EM_SPARC Machine = 2 /* Sun SPARC. */ - EM_386 Machine = 3 /* Intel i386. */ - EM_68K Machine = 4 /* Motorola 68000. */ - EM_88K Machine = 5 /* Motorola 88000. */ - EM_860 Machine = 7 /* Intel i860. */ - EM_MIPS Machine = 8 /* MIPS R3000 Big-Endian only. */ - EM_S370 Machine = 9 /* IBM System/370. */ - EM_MIPS_RS3_LE Machine = 10 /* MIPS R3000 Little-Endian. */ - EM_PARISC Machine = 15 /* HP PA-RISC. */ - EM_VPP500 Machine = 17 /* Fujitsu VPP500. */ - EM_SPARC32PLUS Machine = 18 /* SPARC v8plus. */ - EM_960 Machine = 19 /* Intel 80960. */ - EM_PPC Machine = 20 /* PowerPC 32-bit. */ - EM_PPC64 Machine = 21 /* PowerPC 64-bit. */ - EM_S390 Machine = 22 /* IBM System/390. */ - EM_V800 Machine = 36 /* NEC V800. */ - EM_FR20 Machine = 37 /* Fujitsu FR20. */ - EM_RH32 Machine = 38 /* TRW RH-32. */ - EM_RCE Machine = 39 /* Motorola RCE. */ - EM_ARM Machine = 40 /* ARM. */ - EM_SH Machine = 42 /* Hitachi SH. */ - EM_SPARCV9 Machine = 43 /* SPARC v9 64-bit. */ - EM_TRICORE Machine = 44 /* Siemens TriCore embedded processor. */ - EM_ARC Machine = 45 /* Argonaut RISC Core. */ - EM_H8_300 Machine = 46 /* Hitachi H8/300. */ - EM_H8_300H Machine = 47 /* Hitachi H8/300H. */ - EM_H8S Machine = 48 /* Hitachi H8S. */ - EM_H8_500 Machine = 49 /* Hitachi H8/500. */ - EM_IA_64 Machine = 50 /* Intel IA-64 Processor. */ - EM_MIPS_X Machine = 51 /* Stanford MIPS-X. */ - EM_COLDFIRE Machine = 52 /* Motorola ColdFire. */ - EM_68HC12 Machine = 53 /* Motorola M68HC12. */ - EM_MMA Machine = 54 /* Fujitsu MMA. */ - EM_PCP Machine = 55 /* Siemens PCP. */ - EM_NCPU Machine = 56 /* Sony nCPU. */ - EM_NDR1 Machine = 57 /* Denso NDR1 microprocessor. */ - EM_STARCORE Machine = 58 /* Motorola Star*Core processor. */ - EM_ME16 Machine = 59 /* Toyota ME16 processor. */ - EM_ST100 Machine = 60 /* STMicroelectronics ST100 processor. */ - EM_TINYJ Machine = 61 /* Advanced Logic Corp. TinyJ processor. */ - EM_X86_64 Machine = 62 /* Advanced Micro Devices x86-64 */ - EM_AARCH64 Machine = 183 /* ARM 64-bit Architecture (AArch64) */ - - /* Non-standard or deprecated. */ - EM_486 Machine = 6 /* Intel i486. */ - EM_MIPS_RS4_BE Machine = 10 /* MIPS R4000 Big-Endian */ - EM_ALPHA_STD Machine = 41 /* Digital Alpha (standard value). */ - EM_ALPHA Machine = 0x9026 /* Alpha (written in the absence of an ABI) */ -) - -var machineStrings = []intName{ - {0, "EM_NONE"}, - {1, "EM_M32"}, - {2, "EM_SPARC"}, - {3, "EM_386"}, - {4, "EM_68K"}, - {5, "EM_88K"}, - {7, "EM_860"}, - {8, "EM_MIPS"}, - {9, "EM_S370"}, - {10, "EM_MIPS_RS3_LE"}, - {15, "EM_PARISC"}, - {17, "EM_VPP500"}, - {18, "EM_SPARC32PLUS"}, - {19, "EM_960"}, - {20, "EM_PPC"}, - {21, "EM_PPC64"}, - {22, "EM_S390"}, - {36, "EM_V800"}, - {37, "EM_FR20"}, - {38, "EM_RH32"}, - {39, "EM_RCE"}, - {40, "EM_ARM"}, - {42, "EM_SH"}, - {43, "EM_SPARCV9"}, - {44, "EM_TRICORE"}, - {45, "EM_ARC"}, - {46, "EM_H8_300"}, - {47, "EM_H8_300H"}, - {48, "EM_H8S"}, - {49, "EM_H8_500"}, - {50, "EM_IA_64"}, - {51, "EM_MIPS_X"}, - {52, "EM_COLDFIRE"}, - {53, "EM_68HC12"}, - {54, "EM_MMA"}, - {55, "EM_PCP"}, - {56, "EM_NCPU"}, - {57, "EM_NDR1"}, - {58, "EM_STARCORE"}, - {59, "EM_ME16"}, - {60, "EM_ST100"}, - {61, "EM_TINYJ"}, - {62, "EM_X86_64"}, - - /* Non-standard or deprecated. */ - {6, "EM_486"}, - {10, "EM_MIPS_RS4_BE"}, - {41, "EM_ALPHA_STD"}, - {0x9026, "EM_ALPHA"}, -} - -func (i Machine) String() string { return stringName(uint32(i), machineStrings, false) } -func (i Machine) GoString() string { return stringName(uint32(i), machineStrings, true) } - -// Special section indices. -type SectionIndex int - -const ( - SHN_UNDEF SectionIndex = 0 /* Undefined, missing, irrelevant. */ - SHN_LORESERVE SectionIndex = 0xff00 /* First of reserved range. */ - SHN_LOPROC SectionIndex = 0xff00 /* First processor-specific. */ - SHN_HIPROC SectionIndex = 0xff1f /* Last processor-specific. */ - SHN_LOOS SectionIndex = 0xff20 /* First operating system-specific. */ - SHN_HIOS SectionIndex = 0xff3f /* Last operating system-specific. */ - SHN_ABS SectionIndex = 0xfff1 /* Absolute values. */ - SHN_COMMON SectionIndex = 0xfff2 /* Common data. */ - SHN_XINDEX SectionIndex = 0xffff /* Escape -- index stored elsewhere. */ - SHN_HIRESERVE SectionIndex = 0xffff /* Last of reserved range. */ -) - -var shnStrings = []intName{ - {0, "SHN_UNDEF"}, - {0xff00, "SHN_LOPROC"}, - {0xff20, "SHN_LOOS"}, - {0xfff1, "SHN_ABS"}, - {0xfff2, "SHN_COMMON"}, - {0xffff, "SHN_XINDEX"}, -} - -func (i SectionIndex) String() string { return stringName(uint32(i), shnStrings, false) } -func (i SectionIndex) GoString() string { return stringName(uint32(i), shnStrings, true) } - -// Section type. -type SectionType uint32 - -const ( - SHT_NULL SectionType = 0 /* inactive */ - SHT_PROGBITS SectionType = 1 /* program defined information */ - SHT_SYMTAB SectionType = 2 /* symbol table section */ - SHT_STRTAB SectionType = 3 /* string table section */ - SHT_RELA SectionType = 4 /* relocation section with addends */ - SHT_HASH SectionType = 5 /* symbol hash table section */ - SHT_DYNAMIC SectionType = 6 /* dynamic section */ - SHT_NOTE SectionType = 7 /* note section */ - SHT_NOBITS SectionType = 8 /* no space section */ - SHT_REL SectionType = 9 /* relocation section - no addends */ - SHT_SHLIB SectionType = 10 /* reserved - purpose unknown */ - SHT_DYNSYM SectionType = 11 /* dynamic symbol table section */ - SHT_INIT_ARRAY SectionType = 14 /* Initialization function pointers. */ - SHT_FINI_ARRAY SectionType = 15 /* Termination function pointers. */ - SHT_PREINIT_ARRAY SectionType = 16 /* Pre-initialization function ptrs. */ - SHT_GROUP SectionType = 17 /* Section group. */ - SHT_SYMTAB_SHNDX SectionType = 18 /* Section indexes (see SHN_XINDEX). */ - SHT_LOOS SectionType = 0x60000000 /* First of OS specific semantics */ - SHT_GNU_ATTRIBUTES SectionType = 0x6ffffff5 /* GNU object attributes */ - SHT_GNU_HASH SectionType = 0x6ffffff6 /* GNU hash table */ - SHT_GNU_LIBLIST SectionType = 0x6ffffff7 /* GNU prelink library list */ - SHT_GNU_VERDEF SectionType = 0x6ffffffd /* GNU version definition section */ - SHT_GNU_VERNEED SectionType = 0x6ffffffe /* GNU version needs section */ - SHT_GNU_VERSYM SectionType = 0x6fffffff /* GNU version symbol table */ - SHT_HIOS SectionType = 0x6fffffff /* Last of OS specific semantics */ - SHT_LOPROC SectionType = 0x70000000 /* reserved range for processor */ - SHT_HIPROC SectionType = 0x7fffffff /* specific section header types */ - SHT_LOUSER SectionType = 0x80000000 /* reserved range for application */ - SHT_HIUSER SectionType = 0xffffffff /* specific indexes */ -) - -var shtStrings = []intName{ - {0, "SHT_NULL"}, - {1, "SHT_PROGBITS"}, - {2, "SHT_SYMTAB"}, - {3, "SHT_STRTAB"}, - {4, "SHT_RELA"}, - {5, "SHT_HASH"}, - {6, "SHT_DYNAMIC"}, - {7, "SHT_NOTE"}, - {8, "SHT_NOBITS"}, - {9, "SHT_REL"}, - {10, "SHT_SHLIB"}, - {11, "SHT_DYNSYM"}, - {14, "SHT_INIT_ARRAY"}, - {15, "SHT_FINI_ARRAY"}, - {16, "SHT_PREINIT_ARRAY"}, - {17, "SHT_GROUP"}, - {18, "SHT_SYMTAB_SHNDX"}, - {0x60000000, "SHT_LOOS"}, - {0x6ffffff5, "SHT_GNU_ATTRIBUTES"}, - {0x6ffffff6, "SHT_GNU_HASH"}, - {0x6ffffff7, "SHT_GNU_LIBLIST"}, - {0x6ffffffd, "SHT_GNU_VERDEF"}, - {0x6ffffffe, "SHT_GNU_VERNEED"}, - {0x6fffffff, "SHT_GNU_VERSYM"}, - {0x70000000, "SHT_LOPROC"}, - {0x7fffffff, "SHT_HIPROC"}, - {0x80000000, "SHT_LOUSER"}, - {0xffffffff, "SHT_HIUSER"}, -} - -func (i SectionType) String() string { return stringName(uint32(i), shtStrings, false) } -func (i SectionType) GoString() string { return stringName(uint32(i), shtStrings, true) } - -// Section flags. -type SectionFlag uint32 - -const ( - SHF_WRITE SectionFlag = 0x1 /* Section contains writable data. */ - SHF_ALLOC SectionFlag = 0x2 /* Section occupies memory. */ - SHF_EXECINSTR SectionFlag = 0x4 /* Section contains instructions. */ - SHF_MERGE SectionFlag = 0x10 /* Section may be merged. */ - SHF_STRINGS SectionFlag = 0x20 /* Section contains strings. */ - SHF_INFO_LINK SectionFlag = 0x40 /* sh_info holds section index. */ - SHF_LINK_ORDER SectionFlag = 0x80 /* Special ordering requirements. */ - SHF_OS_NONCONFORMING SectionFlag = 0x100 /* OS-specific processing required. */ - SHF_GROUP SectionFlag = 0x200 /* Member of section group. */ - SHF_TLS SectionFlag = 0x400 /* Section contains TLS data. */ - SHF_MASKOS SectionFlag = 0x0ff00000 /* OS-specific semantics. */ - SHF_MASKPROC SectionFlag = 0xf0000000 /* Processor-specific semantics. */ -) - -var shfStrings = []intName{ - {0x1, "SHF_WRITE"}, - {0x2, "SHF_ALLOC"}, - {0x4, "SHF_EXECINSTR"}, - {0x10, "SHF_MERGE"}, - {0x20, "SHF_STRINGS"}, - {0x40, "SHF_INFO_LINK"}, - {0x80, "SHF_LINK_ORDER"}, - {0x100, "SHF_OS_NONCONFORMING"}, - {0x200, "SHF_GROUP"}, - {0x400, "SHF_TLS"}, -} - -func (i SectionFlag) String() string { return flagName(uint32(i), shfStrings, false) } -func (i SectionFlag) GoString() string { return flagName(uint32(i), shfStrings, true) } - -// Prog.Type -type ProgType int - -const ( - PT_NULL ProgType = 0 /* Unused entry. */ - PT_LOAD ProgType = 1 /* Loadable segment. */ - PT_DYNAMIC ProgType = 2 /* Dynamic linking information segment. */ - PT_INTERP ProgType = 3 /* Pathname of interpreter. */ - PT_NOTE ProgType = 4 /* Auxiliary information. */ - PT_SHLIB ProgType = 5 /* Reserved (not used). */ - PT_PHDR ProgType = 6 /* Location of program header itself. */ - PT_TLS ProgType = 7 /* Thread local storage segment */ - PT_LOOS ProgType = 0x60000000 /* First OS-specific. */ - PT_HIOS ProgType = 0x6fffffff /* Last OS-specific. */ - PT_LOPROC ProgType = 0x70000000 /* First processor-specific type. */ - PT_HIPROC ProgType = 0x7fffffff /* Last processor-specific type. */ -) - -var ptStrings = []intName{ - {0, "PT_NULL"}, - {1, "PT_LOAD"}, - {2, "PT_DYNAMIC"}, - {3, "PT_INTERP"}, - {4, "PT_NOTE"}, - {5, "PT_SHLIB"}, - {6, "PT_PHDR"}, - {7, "PT_TLS"}, - {0x60000000, "PT_LOOS"}, - {0x6fffffff, "PT_HIOS"}, - {0x70000000, "PT_LOPROC"}, - {0x7fffffff, "PT_HIPROC"}, -} - -func (i ProgType) String() string { return stringName(uint32(i), ptStrings, false) } -func (i ProgType) GoString() string { return stringName(uint32(i), ptStrings, true) } - -// Prog.Flag -type ProgFlag uint32 - -const ( - PF_X ProgFlag = 0x1 /* Executable. */ - PF_W ProgFlag = 0x2 /* Writable. */ - PF_R ProgFlag = 0x4 /* Readable. */ - PF_MASKOS ProgFlag = 0x0ff00000 /* Operating system-specific. */ - PF_MASKPROC ProgFlag = 0xf0000000 /* Processor-specific. */ -) - -var pfStrings = []intName{ - {0x1, "PF_X"}, - {0x2, "PF_W"}, - {0x4, "PF_R"}, -} - -func (i ProgFlag) String() string { return flagName(uint32(i), pfStrings, false) } -func (i ProgFlag) GoString() string { return flagName(uint32(i), pfStrings, true) } - -// Dyn.Tag -type DynTag int - -const ( - DT_NULL DynTag = 0 /* Terminating entry. */ - DT_NEEDED DynTag = 1 /* String table offset of a needed shared library. */ - DT_PLTRELSZ DynTag = 2 /* Total size in bytes of PLT relocations. */ - DT_PLTGOT DynTag = 3 /* Processor-dependent address. */ - DT_HASH DynTag = 4 /* Address of symbol hash table. */ - DT_STRTAB DynTag = 5 /* Address of string table. */ - DT_SYMTAB DynTag = 6 /* Address of symbol table. */ - DT_RELA DynTag = 7 /* Address of ElfNN_Rela relocations. */ - DT_RELASZ DynTag = 8 /* Total size of ElfNN_Rela relocations. */ - DT_RELAENT DynTag = 9 /* Size of each ElfNN_Rela relocation entry. */ - DT_STRSZ DynTag = 10 /* Size of string table. */ - DT_SYMENT DynTag = 11 /* Size of each symbol table entry. */ - DT_INIT DynTag = 12 /* Address of initialization function. */ - DT_FINI DynTag = 13 /* Address of finalization function. */ - DT_SONAME DynTag = 14 /* String table offset of shared object name. */ - DT_RPATH DynTag = 15 /* String table offset of library path. [sup] */ - DT_SYMBOLIC DynTag = 16 /* Indicates "symbolic" linking. [sup] */ - DT_REL DynTag = 17 /* Address of ElfNN_Rel relocations. */ - DT_RELSZ DynTag = 18 /* Total size of ElfNN_Rel relocations. */ - DT_RELENT DynTag = 19 /* Size of each ElfNN_Rel relocation. */ - DT_PLTREL DynTag = 20 /* Type of relocation used for PLT. */ - DT_DEBUG DynTag = 21 /* Reserved (not used). */ - DT_TEXTREL DynTag = 22 /* Indicates there may be relocations in non-writable segments. [sup] */ - DT_JMPREL DynTag = 23 /* Address of PLT relocations. */ - DT_BIND_NOW DynTag = 24 /* [sup] */ - DT_INIT_ARRAY DynTag = 25 /* Address of the array of pointers to initialization functions */ - DT_FINI_ARRAY DynTag = 26 /* Address of the array of pointers to termination functions */ - DT_INIT_ARRAYSZ DynTag = 27 /* Size in bytes of the array of initialization functions. */ - DT_FINI_ARRAYSZ DynTag = 28 /* Size in bytes of the array of termination functions. */ - DT_RUNPATH DynTag = 29 /* String table offset of a null-terminated library search path string. */ - DT_FLAGS DynTag = 30 /* Object specific flag values. */ - DT_ENCODING DynTag = 32 /* Values greater than or equal to DT_ENCODING - and less than DT_LOOS follow the rules for - the interpretation of the d_un union - as follows: even == 'd_ptr', even == 'd_val' - or none */ - DT_PREINIT_ARRAY DynTag = 32 /* Address of the array of pointers to pre-initialization functions. */ - DT_PREINIT_ARRAYSZ DynTag = 33 /* Size in bytes of the array of pre-initialization functions. */ - DT_LOOS DynTag = 0x6000000d /* First OS-specific */ - DT_HIOS DynTag = 0x6ffff000 /* Last OS-specific */ - DT_VERSYM DynTag = 0x6ffffff0 - DT_VERNEED DynTag = 0x6ffffffe - DT_VERNEEDNUM DynTag = 0x6fffffff - DT_LOPROC DynTag = 0x70000000 /* First processor-specific type. */ - DT_HIPROC DynTag = 0x7fffffff /* Last processor-specific type. */ -) - -var dtStrings = []intName{ - {0, "DT_NULL"}, - {1, "DT_NEEDED"}, - {2, "DT_PLTRELSZ"}, - {3, "DT_PLTGOT"}, - {4, "DT_HASH"}, - {5, "DT_STRTAB"}, - {6, "DT_SYMTAB"}, - {7, "DT_RELA"}, - {8, "DT_RELASZ"}, - {9, "DT_RELAENT"}, - {10, "DT_STRSZ"}, - {11, "DT_SYMENT"}, - {12, "DT_INIT"}, - {13, "DT_FINI"}, - {14, "DT_SONAME"}, - {15, "DT_RPATH"}, - {16, "DT_SYMBOLIC"}, - {17, "DT_REL"}, - {18, "DT_RELSZ"}, - {19, "DT_RELENT"}, - {20, "DT_PLTREL"}, - {21, "DT_DEBUG"}, - {22, "DT_TEXTREL"}, - {23, "DT_JMPREL"}, - {24, "DT_BIND_NOW"}, - {25, "DT_INIT_ARRAY"}, - {26, "DT_FINI_ARRAY"}, - {27, "DT_INIT_ARRAYSZ"}, - {28, "DT_FINI_ARRAYSZ"}, - {29, "DT_RUNPATH"}, - {30, "DT_FLAGS"}, - {32, "DT_ENCODING"}, - {32, "DT_PREINIT_ARRAY"}, - {33, "DT_PREINIT_ARRAYSZ"}, - {0x6000000d, "DT_LOOS"}, - {0x6ffff000, "DT_HIOS"}, - {0x6ffffff0, "DT_VERSYM"}, - {0x6ffffffe, "DT_VERNEED"}, - {0x6fffffff, "DT_VERNEEDNUM"}, - {0x70000000, "DT_LOPROC"}, - {0x7fffffff, "DT_HIPROC"}, -} - -func (i DynTag) String() string { return stringName(uint32(i), dtStrings, false) } -func (i DynTag) GoString() string { return stringName(uint32(i), dtStrings, true) } - -// DT_FLAGS values. -type DynFlag int - -const ( - DF_ORIGIN DynFlag = 0x0001 /* Indicates that the object being loaded may - make reference to the - $ORIGIN substitution string */ - DF_SYMBOLIC DynFlag = 0x0002 /* Indicates "symbolic" linking. */ - DF_TEXTREL DynFlag = 0x0004 /* Indicates there may be relocations in non-writable segments. */ - DF_BIND_NOW DynFlag = 0x0008 /* Indicates that the dynamic linker should - process all relocations for the object - containing this entry before transferring - control to the program. */ - DF_STATIC_TLS DynFlag = 0x0010 /* Indicates that the shared object or - executable contains code using a static - thread-local storage scheme. */ -) - -var dflagStrings = []intName{ - {0x0001, "DF_ORIGIN"}, - {0x0002, "DF_SYMBOLIC"}, - {0x0004, "DF_TEXTREL"}, - {0x0008, "DF_BIND_NOW"}, - {0x0010, "DF_STATIC_TLS"}, -} - -func (i DynFlag) String() string { return flagName(uint32(i), dflagStrings, false) } -func (i DynFlag) GoString() string { return flagName(uint32(i), dflagStrings, true) } - -// NType values; used in core files. -type NType int - -const ( - NT_PRSTATUS NType = 1 /* Process status. */ - NT_FPREGSET NType = 2 /* Floating point registers. */ - NT_PRPSINFO NType = 3 /* Process state info. */ -) - -var ntypeStrings = []intName{ - {1, "NT_PRSTATUS"}, - {2, "NT_FPREGSET"}, - {3, "NT_PRPSINFO"}, -} - -func (i NType) String() string { return stringName(uint32(i), ntypeStrings, false) } -func (i NType) GoString() string { return stringName(uint32(i), ntypeStrings, true) } - -/* Symbol Binding - ELFNN_ST_BIND - st_info */ -type SymBind int - -const ( - STB_LOCAL SymBind = 0 /* Local symbol */ - STB_GLOBAL SymBind = 1 /* Global symbol */ - STB_WEAK SymBind = 2 /* like global - lower precedence */ - STB_LOOS SymBind = 10 /* Reserved range for operating system */ - STB_HIOS SymBind = 12 /* specific semantics. */ - STB_LOPROC SymBind = 13 /* reserved range for processor */ - STB_HIPROC SymBind = 15 /* specific semantics. */ -) - -var stbStrings = []intName{ - {0, "STB_LOCAL"}, - {1, "STB_GLOBAL"}, - {2, "STB_WEAK"}, - {10, "STB_LOOS"}, - {12, "STB_HIOS"}, - {13, "STB_LOPROC"}, - {15, "STB_HIPROC"}, -} - -func (i SymBind) String() string { return stringName(uint32(i), stbStrings, false) } -func (i SymBind) GoString() string { return stringName(uint32(i), stbStrings, true) } - -/* Symbol type - ELFNN_ST_TYPE - st_info */ -type SymType int - -const ( - STT_NOTYPE SymType = 0 /* Unspecified type. */ - STT_OBJECT SymType = 1 /* Data object. */ - STT_FUNC SymType = 2 /* Function. */ - STT_SECTION SymType = 3 /* Section. */ - STT_FILE SymType = 4 /* Source file. */ - STT_COMMON SymType = 5 /* Uninitialized common block. */ - STT_TLS SymType = 6 /* TLS object. */ - STT_LOOS SymType = 10 /* Reserved range for operating system */ - STT_HIOS SymType = 12 /* specific semantics. */ - STT_LOPROC SymType = 13 /* reserved range for processor */ - STT_HIPROC SymType = 15 /* specific semantics. */ -) - -var sttStrings = []intName{ - {0, "STT_NOTYPE"}, - {1, "STT_OBJECT"}, - {2, "STT_FUNC"}, - {3, "STT_SECTION"}, - {4, "STT_FILE"}, - {5, "STT_COMMON"}, - {6, "STT_TLS"}, - {10, "STT_LOOS"}, - {12, "STT_HIOS"}, - {13, "STT_LOPROC"}, - {15, "STT_HIPROC"}, -} - -func (i SymType) String() string { return stringName(uint32(i), sttStrings, false) } -func (i SymType) GoString() string { return stringName(uint32(i), sttStrings, true) } - -/* Symbol visibility - ELFNN_ST_VISIBILITY - st_other */ -type SymVis int - -const ( - STV_DEFAULT SymVis = 0x0 /* Default visibility (see binding). */ - STV_INTERNAL SymVis = 0x1 /* Special meaning in relocatable objects. */ - STV_HIDDEN SymVis = 0x2 /* Not visible. */ - STV_PROTECTED SymVis = 0x3 /* Visible but not preemptible. */ -) - -var stvStrings = []intName{ - {0x0, "STV_DEFAULT"}, - {0x1, "STV_INTERNAL"}, - {0x2, "STV_HIDDEN"}, - {0x3, "STV_PROTECTED"}, -} - -func (i SymVis) String() string { return stringName(uint32(i), stvStrings, false) } -func (i SymVis) GoString() string { return stringName(uint32(i), stvStrings, true) } - -/* - * Relocation types. - */ - -// Relocation types for x86-64. -type R_X86_64 int - -const ( - R_X86_64_NONE R_X86_64 = 0 /* No relocation. */ - R_X86_64_64 R_X86_64 = 1 /* Add 64 bit symbol value. */ - R_X86_64_PC32 R_X86_64 = 2 /* PC-relative 32 bit signed sym value. */ - R_X86_64_GOT32 R_X86_64 = 3 /* PC-relative 32 bit GOT offset. */ - R_X86_64_PLT32 R_X86_64 = 4 /* PC-relative 32 bit PLT offset. */ - R_X86_64_COPY R_X86_64 = 5 /* Copy data from shared object. */ - R_X86_64_GLOB_DAT R_X86_64 = 6 /* Set GOT entry to data address. */ - R_X86_64_JMP_SLOT R_X86_64 = 7 /* Set GOT entry to code address. */ - R_X86_64_RELATIVE R_X86_64 = 8 /* Add load address of shared object. */ - R_X86_64_GOTPCREL R_X86_64 = 9 /* Add 32 bit signed pcrel offset to GOT. */ - R_X86_64_32 R_X86_64 = 10 /* Add 32 bit zero extended symbol value */ - R_X86_64_32S R_X86_64 = 11 /* Add 32 bit sign extended symbol value */ - R_X86_64_16 R_X86_64 = 12 /* Add 16 bit zero extended symbol value */ - R_X86_64_PC16 R_X86_64 = 13 /* Add 16 bit signed extended pc relative symbol value */ - R_X86_64_8 R_X86_64 = 14 /* Add 8 bit zero extended symbol value */ - R_X86_64_PC8 R_X86_64 = 15 /* Add 8 bit signed extended pc relative symbol value */ - R_X86_64_DTPMOD64 R_X86_64 = 16 /* ID of module containing symbol */ - R_X86_64_DTPOFF64 R_X86_64 = 17 /* Offset in TLS block */ - R_X86_64_TPOFF64 R_X86_64 = 18 /* Offset in static TLS block */ - R_X86_64_TLSGD R_X86_64 = 19 /* PC relative offset to GD GOT entry */ - R_X86_64_TLSLD R_X86_64 = 20 /* PC relative offset to LD GOT entry */ - R_X86_64_DTPOFF32 R_X86_64 = 21 /* Offset in TLS block */ - R_X86_64_GOTTPOFF R_X86_64 = 22 /* PC relative offset to IE GOT entry */ - R_X86_64_TPOFF32 R_X86_64 = 23 /* Offset in static TLS block */ -) - -var rx86_64Strings = []intName{ - {0, "R_X86_64_NONE"}, - {1, "R_X86_64_64"}, - {2, "R_X86_64_PC32"}, - {3, "R_X86_64_GOT32"}, - {4, "R_X86_64_PLT32"}, - {5, "R_X86_64_COPY"}, - {6, "R_X86_64_GLOB_DAT"}, - {7, "R_X86_64_JMP_SLOT"}, - {8, "R_X86_64_RELATIVE"}, - {9, "R_X86_64_GOTPCREL"}, - {10, "R_X86_64_32"}, - {11, "R_X86_64_32S"}, - {12, "R_X86_64_16"}, - {13, "R_X86_64_PC16"}, - {14, "R_X86_64_8"}, - {15, "R_X86_64_PC8"}, - {16, "R_X86_64_DTPMOD64"}, - {17, "R_X86_64_DTPOFF64"}, - {18, "R_X86_64_TPOFF64"}, - {19, "R_X86_64_TLSGD"}, - {20, "R_X86_64_TLSLD"}, - {21, "R_X86_64_DTPOFF32"}, - {22, "R_X86_64_GOTTPOFF"}, - {23, "R_X86_64_TPOFF32"}, -} - -func (i R_X86_64) String() string { return stringName(uint32(i), rx86_64Strings, false) } -func (i R_X86_64) GoString() string { return stringName(uint32(i), rx86_64Strings, true) } - -// Relocation types for AArch64 (aka arm64) -type R_AARCH64 int - -const ( - R_AARCH64_NONE R_AARCH64 = 0 - R_AARCH64_P32_ABS32 R_AARCH64 = 1 - R_AARCH64_P32_ABS16 R_AARCH64 = 2 - R_AARCH64_P32_PREL32 R_AARCH64 = 3 - R_AARCH64_P32_PREL16 R_AARCH64 = 4 - R_AARCH64_P32_MOVW_UABS_G0 R_AARCH64 = 5 - R_AARCH64_P32_MOVW_UABS_G0_NC R_AARCH64 = 6 - R_AARCH64_P32_MOVW_UABS_G1 R_AARCH64 = 7 - R_AARCH64_P32_MOVW_SABS_G0 R_AARCH64 = 8 - R_AARCH64_P32_LD_PREL_LO19 R_AARCH64 = 9 - R_AARCH64_P32_ADR_PREL_LO21 R_AARCH64 = 10 - R_AARCH64_P32_ADR_PREL_PG_HI21 R_AARCH64 = 11 - R_AARCH64_P32_ADD_ABS_LO12_NC R_AARCH64 = 12 - R_AARCH64_P32_LDST8_ABS_LO12_NC R_AARCH64 = 13 - R_AARCH64_P32_LDST16_ABS_LO12_NC R_AARCH64 = 14 - R_AARCH64_P32_LDST32_ABS_LO12_NC R_AARCH64 = 15 - R_AARCH64_P32_LDST64_ABS_LO12_NC R_AARCH64 = 16 - R_AARCH64_P32_LDST128_ABS_LO12_NC R_AARCH64 = 17 - R_AARCH64_P32_TSTBR14 R_AARCH64 = 18 - R_AARCH64_P32_CONDBR19 R_AARCH64 = 19 - R_AARCH64_P32_JUMP26 R_AARCH64 = 20 - R_AARCH64_P32_CALL26 R_AARCH64 = 21 - R_AARCH64_P32_GOT_LD_PREL19 R_AARCH64 = 25 - R_AARCH64_P32_ADR_GOT_PAGE R_AARCH64 = 26 - R_AARCH64_P32_LD32_GOT_LO12_NC R_AARCH64 = 27 - R_AARCH64_P32_TLSGD_ADR_PAGE21 R_AARCH64 = 81 - R_AARCH64_P32_TLSGD_ADD_LO12_NC R_AARCH64 = 82 - R_AARCH64_P32_TLSIE_ADR_GOTTPREL_PAGE21 R_AARCH64 = 103 - R_AARCH64_P32_TLSIE_LD32_GOTTPREL_LO12_NC R_AARCH64 = 104 - R_AARCH64_P32_TLSIE_LD_GOTTPREL_PREL19 R_AARCH64 = 105 - R_AARCH64_P32_TLSLE_MOVW_TPREL_G1 R_AARCH64 = 106 - R_AARCH64_P32_TLSLE_MOVW_TPREL_G0 R_AARCH64 = 107 - R_AARCH64_P32_TLSLE_MOVW_TPREL_G0_NC R_AARCH64 = 108 - R_AARCH64_P32_TLSLE_ADD_TPREL_HI12 R_AARCH64 = 109 - R_AARCH64_P32_TLSLE_ADD_TPREL_LO12 R_AARCH64 = 110 - R_AARCH64_P32_TLSLE_ADD_TPREL_LO12_NC R_AARCH64 = 111 - R_AARCH64_P32_TLSDESC_LD_PREL19 R_AARCH64 = 122 - R_AARCH64_P32_TLSDESC_ADR_PREL21 R_AARCH64 = 123 - R_AARCH64_P32_TLSDESC_ADR_PAGE21 R_AARCH64 = 124 - R_AARCH64_P32_TLSDESC_LD32_LO12_NC R_AARCH64 = 125 - R_AARCH64_P32_TLSDESC_ADD_LO12_NC R_AARCH64 = 126 - R_AARCH64_P32_TLSDESC_CALL R_AARCH64 = 127 - R_AARCH64_P32_COPY R_AARCH64 = 180 - R_AARCH64_P32_GLOB_DAT R_AARCH64 = 181 - R_AARCH64_P32_JUMP_SLOT R_AARCH64 = 182 - R_AARCH64_P32_RELATIVE R_AARCH64 = 183 - R_AARCH64_P32_TLS_DTPMOD R_AARCH64 = 184 - R_AARCH64_P32_TLS_DTPREL R_AARCH64 = 185 - R_AARCH64_P32_TLS_TPREL R_AARCH64 = 186 - R_AARCH64_P32_TLSDESC R_AARCH64 = 187 - R_AARCH64_P32_IRELATIVE R_AARCH64 = 188 - R_AARCH64_NULL R_AARCH64 = 256 - R_AARCH64_ABS64 R_AARCH64 = 257 - R_AARCH64_ABS32 R_AARCH64 = 258 - R_AARCH64_ABS16 R_AARCH64 = 259 - R_AARCH64_PREL64 R_AARCH64 = 260 - R_AARCH64_PREL32 R_AARCH64 = 261 - R_AARCH64_PREL16 R_AARCH64 = 262 - R_AARCH64_MOVW_UABS_G0 R_AARCH64 = 263 - R_AARCH64_MOVW_UABS_G0_NC R_AARCH64 = 264 - R_AARCH64_MOVW_UABS_G1 R_AARCH64 = 265 - R_AARCH64_MOVW_UABS_G1_NC R_AARCH64 = 266 - R_AARCH64_MOVW_UABS_G2 R_AARCH64 = 267 - R_AARCH64_MOVW_UABS_G2_NC R_AARCH64 = 268 - R_AARCH64_MOVW_UABS_G3 R_AARCH64 = 269 - R_AARCH64_MOVW_SABS_G0 R_AARCH64 = 270 - R_AARCH64_MOVW_SABS_G1 R_AARCH64 = 271 - R_AARCH64_MOVW_SABS_G2 R_AARCH64 = 272 - R_AARCH64_LD_PREL_LO19 R_AARCH64 = 273 - R_AARCH64_ADR_PREL_LO21 R_AARCH64 = 274 - R_AARCH64_ADR_PREL_PG_HI21 R_AARCH64 = 275 - R_AARCH64_ADR_PREL_PG_HI21_NC R_AARCH64 = 276 - R_AARCH64_ADD_ABS_LO12_NC R_AARCH64 = 277 - R_AARCH64_LDST8_ABS_LO12_NC R_AARCH64 = 278 - R_AARCH64_TSTBR14 R_AARCH64 = 279 - R_AARCH64_CONDBR19 R_AARCH64 = 280 - R_AARCH64_JUMP26 R_AARCH64 = 282 - R_AARCH64_CALL26 R_AARCH64 = 283 - R_AARCH64_LDST16_ABS_LO12_NC R_AARCH64 = 284 - R_AARCH64_LDST32_ABS_LO12_NC R_AARCH64 = 285 - R_AARCH64_LDST64_ABS_LO12_NC R_AARCH64 = 286 - R_AARCH64_LDST128_ABS_LO12_NC R_AARCH64 = 299 - R_AARCH64_GOT_LD_PREL19 R_AARCH64 = 309 - R_AARCH64_ADR_GOT_PAGE R_AARCH64 = 311 - R_AARCH64_LD64_GOT_LO12_NC R_AARCH64 = 312 - R_AARCH64_TLSGD_ADR_PAGE21 R_AARCH64 = 513 - R_AARCH64_TLSGD_ADD_LO12_NC R_AARCH64 = 514 - R_AARCH64_TLSIE_MOVW_GOTTPREL_G1 R_AARCH64 = 539 - R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC R_AARCH64 = 540 - R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21 R_AARCH64 = 541 - R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC R_AARCH64 = 542 - R_AARCH64_TLSIE_LD_GOTTPREL_PREL19 R_AARCH64 = 543 - R_AARCH64_TLSLE_MOVW_TPREL_G2 R_AARCH64 = 544 - R_AARCH64_TLSLE_MOVW_TPREL_G1 R_AARCH64 = 545 - R_AARCH64_TLSLE_MOVW_TPREL_G1_NC R_AARCH64 = 546 - R_AARCH64_TLSLE_MOVW_TPREL_G0 R_AARCH64 = 547 - R_AARCH64_TLSLE_MOVW_TPREL_G0_NC R_AARCH64 = 548 - R_AARCH64_TLSLE_ADD_TPREL_HI12 R_AARCH64 = 549 - R_AARCH64_TLSLE_ADD_TPREL_LO12 R_AARCH64 = 550 - R_AARCH64_TLSLE_ADD_TPREL_LO12_NC R_AARCH64 = 551 - R_AARCH64_TLSDESC_LD_PREL19 R_AARCH64 = 560 - R_AARCH64_TLSDESC_ADR_PREL21 R_AARCH64 = 561 - R_AARCH64_TLSDESC_ADR_PAGE21 R_AARCH64 = 562 - R_AARCH64_TLSDESC_LD64_LO12_NC R_AARCH64 = 563 - R_AARCH64_TLSDESC_ADD_LO12_NC R_AARCH64 = 564 - R_AARCH64_TLSDESC_OFF_G1 R_AARCH64 = 565 - R_AARCH64_TLSDESC_OFF_G0_NC R_AARCH64 = 566 - R_AARCH64_TLSDESC_LDR R_AARCH64 = 567 - R_AARCH64_TLSDESC_ADD R_AARCH64 = 568 - R_AARCH64_TLSDESC_CALL R_AARCH64 = 569 - R_AARCH64_COPY R_AARCH64 = 1024 - R_AARCH64_GLOB_DAT R_AARCH64 = 1025 - R_AARCH64_JUMP_SLOT R_AARCH64 = 1026 - R_AARCH64_RELATIVE R_AARCH64 = 1027 - R_AARCH64_TLS_DTPMOD64 R_AARCH64 = 1028 - R_AARCH64_TLS_DTPREL64 R_AARCH64 = 1029 - R_AARCH64_TLS_TPREL64 R_AARCH64 = 1030 - R_AARCH64_TLSDESC R_AARCH64 = 1031 - R_AARCH64_IRELATIVE R_AARCH64 = 1032 -) - -var raarch64Strings = []intName{ - {0, "R_AARCH64_NONE"}, - {1, "R_AARCH64_P32_ABS32"}, - {2, "R_AARCH64_P32_ABS16"}, - {3, "R_AARCH64_P32_PREL32"}, - {4, "R_AARCH64_P32_PREL16"}, - {5, "R_AARCH64_P32_MOVW_UABS_G0"}, - {6, "R_AARCH64_P32_MOVW_UABS_G0_NC"}, - {7, "R_AARCH64_P32_MOVW_UABS_G1"}, - {8, "R_AARCH64_P32_MOVW_SABS_G0"}, - {9, "R_AARCH64_P32_LD_PREL_LO19"}, - {10, "R_AARCH64_P32_ADR_PREL_LO21"}, - {11, "R_AARCH64_P32_ADR_PREL_PG_HI21"}, - {12, "R_AARCH64_P32_ADD_ABS_LO12_NC"}, - {13, "R_AARCH64_P32_LDST8_ABS_LO12_NC"}, - {14, "R_AARCH64_P32_LDST16_ABS_LO12_NC"}, - {15, "R_AARCH64_P32_LDST32_ABS_LO12_NC"}, - {16, "R_AARCH64_P32_LDST64_ABS_LO12_NC"}, - {17, "R_AARCH64_P32_LDST128_ABS_LO12_NC"}, - {18, "R_AARCH64_P32_TSTBR14"}, - {19, "R_AARCH64_P32_CONDBR19"}, - {20, "R_AARCH64_P32_JUMP26"}, - {21, "R_AARCH64_P32_CALL26"}, - {25, "R_AARCH64_P32_GOT_LD_PREL19"}, - {26, "R_AARCH64_P32_ADR_GOT_PAGE"}, - {27, "R_AARCH64_P32_LD32_GOT_LO12_NC"}, - {81, "R_AARCH64_P32_TLSGD_ADR_PAGE21"}, - {82, "R_AARCH64_P32_TLSGD_ADD_LO12_NC"}, - {103, "R_AARCH64_P32_TLSIE_ADR_GOTTPREL_PAGE21"}, - {104, "R_AARCH64_P32_TLSIE_LD32_GOTTPREL_LO12_NC"}, - {105, "R_AARCH64_P32_TLSIE_LD_GOTTPREL_PREL19"}, - {106, "R_AARCH64_P32_TLSLE_MOVW_TPREL_G1"}, - {107, "R_AARCH64_P32_TLSLE_MOVW_TPREL_G0"}, - {108, "R_AARCH64_P32_TLSLE_MOVW_TPREL_G0_NC"}, - {109, "R_AARCH64_P32_TLSLE_ADD_TPREL_HI12"}, - {110, "R_AARCH64_P32_TLSLE_ADD_TPREL_LO12"}, - {111, "R_AARCH64_P32_TLSLE_ADD_TPREL_LO12_NC"}, - {122, "R_AARCH64_P32_TLSDESC_LD_PREL19"}, - {123, "R_AARCH64_P32_TLSDESC_ADR_PREL21"}, - {124, "R_AARCH64_P32_TLSDESC_ADR_PAGE21"}, - {125, "R_AARCH64_P32_TLSDESC_LD32_LO12_NC"}, - {126, "R_AARCH64_P32_TLSDESC_ADD_LO12_NC"}, - {127, "R_AARCH64_P32_TLSDESC_CALL"}, - {180, "R_AARCH64_P32_COPY"}, - {181, "R_AARCH64_P32_GLOB_DAT"}, - {182, "R_AARCH64_P32_JUMP_SLOT"}, - {183, "R_AARCH64_P32_RELATIVE"}, - {184, "R_AARCH64_P32_TLS_DTPMOD"}, - {185, "R_AARCH64_P32_TLS_DTPREL"}, - {186, "R_AARCH64_P32_TLS_TPREL"}, - {187, "R_AARCH64_P32_TLSDESC"}, - {188, "R_AARCH64_P32_IRELATIVE"}, - {256, "R_AARCH64_NULL"}, - {257, "R_AARCH64_ABS64"}, - {258, "R_AARCH64_ABS32"}, - {259, "R_AARCH64_ABS16"}, - {260, "R_AARCH64_PREL64"}, - {261, "R_AARCH64_PREL32"}, - {262, "R_AARCH64_PREL16"}, - {263, "R_AARCH64_MOVW_UABS_G0"}, - {264, "R_AARCH64_MOVW_UABS_G0_NC"}, - {265, "R_AARCH64_MOVW_UABS_G1"}, - {266, "R_AARCH64_MOVW_UABS_G1_NC"}, - {267, "R_AARCH64_MOVW_UABS_G2"}, - {268, "R_AARCH64_MOVW_UABS_G2_NC"}, - {269, "R_AARCH64_MOVW_UABS_G3"}, - {270, "R_AARCH64_MOVW_SABS_G0"}, - {271, "R_AARCH64_MOVW_SABS_G1"}, - {272, "R_AARCH64_MOVW_SABS_G2"}, - {273, "R_AARCH64_LD_PREL_LO19"}, - {274, "R_AARCH64_ADR_PREL_LO21"}, - {275, "R_AARCH64_ADR_PREL_PG_HI21"}, - {276, "R_AARCH64_ADR_PREL_PG_HI21_NC"}, - {277, "R_AARCH64_ADD_ABS_LO12_NC"}, - {278, "R_AARCH64_LDST8_ABS_LO12_NC"}, - {279, "R_AARCH64_TSTBR14"}, - {280, "R_AARCH64_CONDBR19"}, - {282, "R_AARCH64_JUMP26"}, - {283, "R_AARCH64_CALL26"}, - {284, "R_AARCH64_LDST16_ABS_LO12_NC"}, - {285, "R_AARCH64_LDST32_ABS_LO12_NC"}, - {286, "R_AARCH64_LDST64_ABS_LO12_NC"}, - {299, "R_AARCH64_LDST128_ABS_LO12_NC"}, - {309, "R_AARCH64_GOT_LD_PREL19"}, - {311, "R_AARCH64_ADR_GOT_PAGE"}, - {312, "R_AARCH64_LD64_GOT_LO12_NC"}, - {513, "R_AARCH64_TLSGD_ADR_PAGE21"}, - {514, "R_AARCH64_TLSGD_ADD_LO12_NC"}, - {539, "R_AARCH64_TLSIE_MOVW_GOTTPREL_G1"}, - {540, "R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC"}, - {541, "R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21"}, - {542, "R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC"}, - {543, "R_AARCH64_TLSIE_LD_GOTTPREL_PREL19"}, - {544, "R_AARCH64_TLSLE_MOVW_TPREL_G2"}, - {545, "R_AARCH64_TLSLE_MOVW_TPREL_G1"}, - {546, "R_AARCH64_TLSLE_MOVW_TPREL_G1_NC"}, - {547, "R_AARCH64_TLSLE_MOVW_TPREL_G0"}, - {548, "R_AARCH64_TLSLE_MOVW_TPREL_G0_NC"}, - {549, "R_AARCH64_TLSLE_ADD_TPREL_HI12"}, - {550, "R_AARCH64_TLSLE_ADD_TPREL_LO12"}, - {551, "R_AARCH64_TLSLE_ADD_TPREL_LO12_NC"}, - {560, "R_AARCH64_TLSDESC_LD_PREL19"}, - {561, "R_AARCH64_TLSDESC_ADR_PREL21"}, - {562, "R_AARCH64_TLSDESC_ADR_PAGE21"}, - {563, "R_AARCH64_TLSDESC_LD64_LO12_NC"}, - {564, "R_AARCH64_TLSDESC_ADD_LO12_NC"}, - {565, "R_AARCH64_TLSDESC_OFF_G1"}, - {566, "R_AARCH64_TLSDESC_OFF_G0_NC"}, - {567, "R_AARCH64_TLSDESC_LDR"}, - {568, "R_AARCH64_TLSDESC_ADD"}, - {569, "R_AARCH64_TLSDESC_CALL"}, - {1024, "R_AARCH64_COPY"}, - {1025, "R_AARCH64_GLOB_DAT"}, - {1026, "R_AARCH64_JUMP_SLOT"}, - {1027, "R_AARCH64_RELATIVE"}, - {1028, "R_AARCH64_TLS_DTPMOD64"}, - {1029, "R_AARCH64_TLS_DTPREL64"}, - {1030, "R_AARCH64_TLS_TPREL64"}, - {1031, "R_AARCH64_TLSDESC"}, - {1032, "R_AARCH64_IRELATIVE"}, -} - -func (i R_AARCH64) String() string { return stringName(uint32(i), raarch64Strings, false) } -func (i R_AARCH64) GoString() string { return stringName(uint32(i), raarch64Strings, true) } - -// Relocation types for Alpha. -type R_ALPHA int - -const ( - R_ALPHA_NONE R_ALPHA = 0 /* No reloc */ - R_ALPHA_REFLONG R_ALPHA = 1 /* Direct 32 bit */ - R_ALPHA_REFQUAD R_ALPHA = 2 /* Direct 64 bit */ - R_ALPHA_GPREL32 R_ALPHA = 3 /* GP relative 32 bit */ - R_ALPHA_LITERAL R_ALPHA = 4 /* GP relative 16 bit w/optimization */ - R_ALPHA_LITUSE R_ALPHA = 5 /* Optimization hint for LITERAL */ - R_ALPHA_GPDISP R_ALPHA = 6 /* Add displacement to GP */ - R_ALPHA_BRADDR R_ALPHA = 7 /* PC+4 relative 23 bit shifted */ - R_ALPHA_HINT R_ALPHA = 8 /* PC+4 relative 16 bit shifted */ - R_ALPHA_SREL16 R_ALPHA = 9 /* PC relative 16 bit */ - R_ALPHA_SREL32 R_ALPHA = 10 /* PC relative 32 bit */ - R_ALPHA_SREL64 R_ALPHA = 11 /* PC relative 64 bit */ - R_ALPHA_OP_PUSH R_ALPHA = 12 /* OP stack push */ - R_ALPHA_OP_STORE R_ALPHA = 13 /* OP stack pop and store */ - R_ALPHA_OP_PSUB R_ALPHA = 14 /* OP stack subtract */ - R_ALPHA_OP_PRSHIFT R_ALPHA = 15 /* OP stack right shift */ - R_ALPHA_GPVALUE R_ALPHA = 16 - R_ALPHA_GPRELHIGH R_ALPHA = 17 - R_ALPHA_GPRELLOW R_ALPHA = 18 - R_ALPHA_IMMED_GP_16 R_ALPHA = 19 - R_ALPHA_IMMED_GP_HI32 R_ALPHA = 20 - R_ALPHA_IMMED_SCN_HI32 R_ALPHA = 21 - R_ALPHA_IMMED_BR_HI32 R_ALPHA = 22 - R_ALPHA_IMMED_LO32 R_ALPHA = 23 - R_ALPHA_COPY R_ALPHA = 24 /* Copy symbol at runtime */ - R_ALPHA_GLOB_DAT R_ALPHA = 25 /* Create GOT entry */ - R_ALPHA_JMP_SLOT R_ALPHA = 26 /* Create PLT entry */ - R_ALPHA_RELATIVE R_ALPHA = 27 /* Adjust by program base */ -) - -var ralphaStrings = []intName{ - {0, "R_ALPHA_NONE"}, - {1, "R_ALPHA_REFLONG"}, - {2, "R_ALPHA_REFQUAD"}, - {3, "R_ALPHA_GPREL32"}, - {4, "R_ALPHA_LITERAL"}, - {5, "R_ALPHA_LITUSE"}, - {6, "R_ALPHA_GPDISP"}, - {7, "R_ALPHA_BRADDR"}, - {8, "R_ALPHA_HINT"}, - {9, "R_ALPHA_SREL16"}, - {10, "R_ALPHA_SREL32"}, - {11, "R_ALPHA_SREL64"}, - {12, "R_ALPHA_OP_PUSH"}, - {13, "R_ALPHA_OP_STORE"}, - {14, "R_ALPHA_OP_PSUB"}, - {15, "R_ALPHA_OP_PRSHIFT"}, - {16, "R_ALPHA_GPVALUE"}, - {17, "R_ALPHA_GPRELHIGH"}, - {18, "R_ALPHA_GPRELLOW"}, - {19, "R_ALPHA_IMMED_GP_16"}, - {20, "R_ALPHA_IMMED_GP_HI32"}, - {21, "R_ALPHA_IMMED_SCN_HI32"}, - {22, "R_ALPHA_IMMED_BR_HI32"}, - {23, "R_ALPHA_IMMED_LO32"}, - {24, "R_ALPHA_COPY"}, - {25, "R_ALPHA_GLOB_DAT"}, - {26, "R_ALPHA_JMP_SLOT"}, - {27, "R_ALPHA_RELATIVE"}, -} - -func (i R_ALPHA) String() string { return stringName(uint32(i), ralphaStrings, false) } -func (i R_ALPHA) GoString() string { return stringName(uint32(i), ralphaStrings, true) } - -// Relocation types for ARM. -type R_ARM int - -const ( - R_ARM_NONE R_ARM = 0 /* No relocation. */ - R_ARM_PC24 R_ARM = 1 - R_ARM_ABS32 R_ARM = 2 - R_ARM_REL32 R_ARM = 3 - R_ARM_PC13 R_ARM = 4 - R_ARM_ABS16 R_ARM = 5 - R_ARM_ABS12 R_ARM = 6 - R_ARM_THM_ABS5 R_ARM = 7 - R_ARM_ABS8 R_ARM = 8 - R_ARM_SBREL32 R_ARM = 9 - R_ARM_THM_PC22 R_ARM = 10 - R_ARM_THM_PC8 R_ARM = 11 - R_ARM_AMP_VCALL9 R_ARM = 12 - R_ARM_SWI24 R_ARM = 13 - R_ARM_THM_SWI8 R_ARM = 14 - R_ARM_XPC25 R_ARM = 15 - R_ARM_THM_XPC22 R_ARM = 16 - R_ARM_COPY R_ARM = 20 /* Copy data from shared object. */ - R_ARM_GLOB_DAT R_ARM = 21 /* Set GOT entry to data address. */ - R_ARM_JUMP_SLOT R_ARM = 22 /* Set GOT entry to code address. */ - R_ARM_RELATIVE R_ARM = 23 /* Add load address of shared object. */ - R_ARM_GOTOFF R_ARM = 24 /* Add GOT-relative symbol address. */ - R_ARM_GOTPC R_ARM = 25 /* Add PC-relative GOT table address. */ - R_ARM_GOT32 R_ARM = 26 /* Add PC-relative GOT offset. */ - R_ARM_PLT32 R_ARM = 27 /* Add PC-relative PLT offset. */ - R_ARM_GNU_VTENTRY R_ARM = 100 - R_ARM_GNU_VTINHERIT R_ARM = 101 - R_ARM_RSBREL32 R_ARM = 250 - R_ARM_THM_RPC22 R_ARM = 251 - R_ARM_RREL32 R_ARM = 252 - R_ARM_RABS32 R_ARM = 253 - R_ARM_RPC24 R_ARM = 254 - R_ARM_RBASE R_ARM = 255 -) - -var rarmStrings = []intName{ - {0, "R_ARM_NONE"}, - {1, "R_ARM_PC24"}, - {2, "R_ARM_ABS32"}, - {3, "R_ARM_REL32"}, - {4, "R_ARM_PC13"}, - {5, "R_ARM_ABS16"}, - {6, "R_ARM_ABS12"}, - {7, "R_ARM_THM_ABS5"}, - {8, "R_ARM_ABS8"}, - {9, "R_ARM_SBREL32"}, - {10, "R_ARM_THM_PC22"}, - {11, "R_ARM_THM_PC8"}, - {12, "R_ARM_AMP_VCALL9"}, - {13, "R_ARM_SWI24"}, - {14, "R_ARM_THM_SWI8"}, - {15, "R_ARM_XPC25"}, - {16, "R_ARM_THM_XPC22"}, - {20, "R_ARM_COPY"}, - {21, "R_ARM_GLOB_DAT"}, - {22, "R_ARM_JUMP_SLOT"}, - {23, "R_ARM_RELATIVE"}, - {24, "R_ARM_GOTOFF"}, - {25, "R_ARM_GOTPC"}, - {26, "R_ARM_GOT32"}, - {27, "R_ARM_PLT32"}, - {100, "R_ARM_GNU_VTENTRY"}, - {101, "R_ARM_GNU_VTINHERIT"}, - {250, "R_ARM_RSBREL32"}, - {251, "R_ARM_THM_RPC22"}, - {252, "R_ARM_RREL32"}, - {253, "R_ARM_RABS32"}, - {254, "R_ARM_RPC24"}, - {255, "R_ARM_RBASE"}, -} - -func (i R_ARM) String() string { return stringName(uint32(i), rarmStrings, false) } -func (i R_ARM) GoString() string { return stringName(uint32(i), rarmStrings, true) } - -// Relocation types for 386. -type R_386 int - -const ( - R_386_NONE R_386 = 0 /* No relocation. */ - R_386_32 R_386 = 1 /* Add symbol value. */ - R_386_PC32 R_386 = 2 /* Add PC-relative symbol value. */ - R_386_GOT32 R_386 = 3 /* Add PC-relative GOT offset. */ - R_386_PLT32 R_386 = 4 /* Add PC-relative PLT offset. */ - R_386_COPY R_386 = 5 /* Copy data from shared object. */ - R_386_GLOB_DAT R_386 = 6 /* Set GOT entry to data address. */ - R_386_JMP_SLOT R_386 = 7 /* Set GOT entry to code address. */ - R_386_RELATIVE R_386 = 8 /* Add load address of shared object. */ - R_386_GOTOFF R_386 = 9 /* Add GOT-relative symbol address. */ - R_386_GOTPC R_386 = 10 /* Add PC-relative GOT table address. */ - R_386_TLS_TPOFF R_386 = 14 /* Negative offset in static TLS block */ - R_386_TLS_IE R_386 = 15 /* Absolute address of GOT for -ve static TLS */ - R_386_TLS_GOTIE R_386 = 16 /* GOT entry for negative static TLS block */ - R_386_TLS_LE R_386 = 17 /* Negative offset relative to static TLS */ - R_386_TLS_GD R_386 = 18 /* 32 bit offset to GOT (index,off) pair */ - R_386_TLS_LDM R_386 = 19 /* 32 bit offset to GOT (index,zero) pair */ - R_386_TLS_GD_32 R_386 = 24 /* 32 bit offset to GOT (index,off) pair */ - R_386_TLS_GD_PUSH R_386 = 25 /* pushl instruction for Sun ABI GD sequence */ - R_386_TLS_GD_CALL R_386 = 26 /* call instruction for Sun ABI GD sequence */ - R_386_TLS_GD_POP R_386 = 27 /* popl instruction for Sun ABI GD sequence */ - R_386_TLS_LDM_32 R_386 = 28 /* 32 bit offset to GOT (index,zero) pair */ - R_386_TLS_LDM_PUSH R_386 = 29 /* pushl instruction for Sun ABI LD sequence */ - R_386_TLS_LDM_CALL R_386 = 30 /* call instruction for Sun ABI LD sequence */ - R_386_TLS_LDM_POP R_386 = 31 /* popl instruction for Sun ABI LD sequence */ - R_386_TLS_LDO_32 R_386 = 32 /* 32 bit offset from start of TLS block */ - R_386_TLS_IE_32 R_386 = 33 /* 32 bit offset to GOT static TLS offset entry */ - R_386_TLS_LE_32 R_386 = 34 /* 32 bit offset within static TLS block */ - R_386_TLS_DTPMOD32 R_386 = 35 /* GOT entry containing TLS index */ - R_386_TLS_DTPOFF32 R_386 = 36 /* GOT entry containing TLS offset */ - R_386_TLS_TPOFF32 R_386 = 37 /* GOT entry of -ve static TLS offset */ -) - -var r386Strings = []intName{ - {0, "R_386_NONE"}, - {1, "R_386_32"}, - {2, "R_386_PC32"}, - {3, "R_386_GOT32"}, - {4, "R_386_PLT32"}, - {5, "R_386_COPY"}, - {6, "R_386_GLOB_DAT"}, - {7, "R_386_JMP_SLOT"}, - {8, "R_386_RELATIVE"}, - {9, "R_386_GOTOFF"}, - {10, "R_386_GOTPC"}, - {14, "R_386_TLS_TPOFF"}, - {15, "R_386_TLS_IE"}, - {16, "R_386_TLS_GOTIE"}, - {17, "R_386_TLS_LE"}, - {18, "R_386_TLS_GD"}, - {19, "R_386_TLS_LDM"}, - {24, "R_386_TLS_GD_32"}, - {25, "R_386_TLS_GD_PUSH"}, - {26, "R_386_TLS_GD_CALL"}, - {27, "R_386_TLS_GD_POP"}, - {28, "R_386_TLS_LDM_32"}, - {29, "R_386_TLS_LDM_PUSH"}, - {30, "R_386_TLS_LDM_CALL"}, - {31, "R_386_TLS_LDM_POP"}, - {32, "R_386_TLS_LDO_32"}, - {33, "R_386_TLS_IE_32"}, - {34, "R_386_TLS_LE_32"}, - {35, "R_386_TLS_DTPMOD32"}, - {36, "R_386_TLS_DTPOFF32"}, - {37, "R_386_TLS_TPOFF32"}, -} - -func (i R_386) String() string { return stringName(uint32(i), r386Strings, false) } -func (i R_386) GoString() string { return stringName(uint32(i), r386Strings, true) } - -// Relocation types for PowerPC. -type R_PPC int - -const ( - R_PPC_NONE R_PPC = 0 /* No relocation. */ - R_PPC_ADDR32 R_PPC = 1 - R_PPC_ADDR24 R_PPC = 2 - R_PPC_ADDR16 R_PPC = 3 - R_PPC_ADDR16_LO R_PPC = 4 - R_PPC_ADDR16_HI R_PPC = 5 - R_PPC_ADDR16_HA R_PPC = 6 - R_PPC_ADDR14 R_PPC = 7 - R_PPC_ADDR14_BRTAKEN R_PPC = 8 - R_PPC_ADDR14_BRNTAKEN R_PPC = 9 - R_PPC_REL24 R_PPC = 10 - R_PPC_REL14 R_PPC = 11 - R_PPC_REL14_BRTAKEN R_PPC = 12 - R_PPC_REL14_BRNTAKEN R_PPC = 13 - R_PPC_GOT16 R_PPC = 14 - R_PPC_GOT16_LO R_PPC = 15 - R_PPC_GOT16_HI R_PPC = 16 - R_PPC_GOT16_HA R_PPC = 17 - R_PPC_PLTREL24 R_PPC = 18 - R_PPC_COPY R_PPC = 19 - R_PPC_GLOB_DAT R_PPC = 20 - R_PPC_JMP_SLOT R_PPC = 21 - R_PPC_RELATIVE R_PPC = 22 - R_PPC_LOCAL24PC R_PPC = 23 - R_PPC_UADDR32 R_PPC = 24 - R_PPC_UADDR16 R_PPC = 25 - R_PPC_REL32 R_PPC = 26 - R_PPC_PLT32 R_PPC = 27 - R_PPC_PLTREL32 R_PPC = 28 - R_PPC_PLT16_LO R_PPC = 29 - R_PPC_PLT16_HI R_PPC = 30 - R_PPC_PLT16_HA R_PPC = 31 - R_PPC_SDAREL16 R_PPC = 32 - R_PPC_SECTOFF R_PPC = 33 - R_PPC_SECTOFF_LO R_PPC = 34 - R_PPC_SECTOFF_HI R_PPC = 35 - R_PPC_SECTOFF_HA R_PPC = 36 - R_PPC_TLS R_PPC = 67 - R_PPC_DTPMOD32 R_PPC = 68 - R_PPC_TPREL16 R_PPC = 69 - R_PPC_TPREL16_LO R_PPC = 70 - R_PPC_TPREL16_HI R_PPC = 71 - R_PPC_TPREL16_HA R_PPC = 72 - R_PPC_TPREL32 R_PPC = 73 - R_PPC_DTPREL16 R_PPC = 74 - R_PPC_DTPREL16_LO R_PPC = 75 - R_PPC_DTPREL16_HI R_PPC = 76 - R_PPC_DTPREL16_HA R_PPC = 77 - R_PPC_DTPREL32 R_PPC = 78 - R_PPC_GOT_TLSGD16 R_PPC = 79 - R_PPC_GOT_TLSGD16_LO R_PPC = 80 - R_PPC_GOT_TLSGD16_HI R_PPC = 81 - R_PPC_GOT_TLSGD16_HA R_PPC = 82 - R_PPC_GOT_TLSLD16 R_PPC = 83 - R_PPC_GOT_TLSLD16_LO R_PPC = 84 - R_PPC_GOT_TLSLD16_HI R_PPC = 85 - R_PPC_GOT_TLSLD16_HA R_PPC = 86 - R_PPC_GOT_TPREL16 R_PPC = 87 - R_PPC_GOT_TPREL16_LO R_PPC = 88 - R_PPC_GOT_TPREL16_HI R_PPC = 89 - R_PPC_GOT_TPREL16_HA R_PPC = 90 - R_PPC_EMB_NADDR32 R_PPC = 101 - R_PPC_EMB_NADDR16 R_PPC = 102 - R_PPC_EMB_NADDR16_LO R_PPC = 103 - R_PPC_EMB_NADDR16_HI R_PPC = 104 - R_PPC_EMB_NADDR16_HA R_PPC = 105 - R_PPC_EMB_SDAI16 R_PPC = 106 - R_PPC_EMB_SDA2I16 R_PPC = 107 - R_PPC_EMB_SDA2REL R_PPC = 108 - R_PPC_EMB_SDA21 R_PPC = 109 - R_PPC_EMB_MRKREF R_PPC = 110 - R_PPC_EMB_RELSEC16 R_PPC = 111 - R_PPC_EMB_RELST_LO R_PPC = 112 - R_PPC_EMB_RELST_HI R_PPC = 113 - R_PPC_EMB_RELST_HA R_PPC = 114 - R_PPC_EMB_BIT_FLD R_PPC = 115 - R_PPC_EMB_RELSDA R_PPC = 116 -) - -var rppcStrings = []intName{ - {0, "R_PPC_NONE"}, - {1, "R_PPC_ADDR32"}, - {2, "R_PPC_ADDR24"}, - {3, "R_PPC_ADDR16"}, - {4, "R_PPC_ADDR16_LO"}, - {5, "R_PPC_ADDR16_HI"}, - {6, "R_PPC_ADDR16_HA"}, - {7, "R_PPC_ADDR14"}, - {8, "R_PPC_ADDR14_BRTAKEN"}, - {9, "R_PPC_ADDR14_BRNTAKEN"}, - {10, "R_PPC_REL24"}, - {11, "R_PPC_REL14"}, - {12, "R_PPC_REL14_BRTAKEN"}, - {13, "R_PPC_REL14_BRNTAKEN"}, - {14, "R_PPC_GOT16"}, - {15, "R_PPC_GOT16_LO"}, - {16, "R_PPC_GOT16_HI"}, - {17, "R_PPC_GOT16_HA"}, - {18, "R_PPC_PLTREL24"}, - {19, "R_PPC_COPY"}, - {20, "R_PPC_GLOB_DAT"}, - {21, "R_PPC_JMP_SLOT"}, - {22, "R_PPC_RELATIVE"}, - {23, "R_PPC_LOCAL24PC"}, - {24, "R_PPC_UADDR32"}, - {25, "R_PPC_UADDR16"}, - {26, "R_PPC_REL32"}, - {27, "R_PPC_PLT32"}, - {28, "R_PPC_PLTREL32"}, - {29, "R_PPC_PLT16_LO"}, - {30, "R_PPC_PLT16_HI"}, - {31, "R_PPC_PLT16_HA"}, - {32, "R_PPC_SDAREL16"}, - {33, "R_PPC_SECTOFF"}, - {34, "R_PPC_SECTOFF_LO"}, - {35, "R_PPC_SECTOFF_HI"}, - {36, "R_PPC_SECTOFF_HA"}, - - {67, "R_PPC_TLS"}, - {68, "R_PPC_DTPMOD32"}, - {69, "R_PPC_TPREL16"}, - {70, "R_PPC_TPREL16_LO"}, - {71, "R_PPC_TPREL16_HI"}, - {72, "R_PPC_TPREL16_HA"}, - {73, "R_PPC_TPREL32"}, - {74, "R_PPC_DTPREL16"}, - {75, "R_PPC_DTPREL16_LO"}, - {76, "R_PPC_DTPREL16_HI"}, - {77, "R_PPC_DTPREL16_HA"}, - {78, "R_PPC_DTPREL32"}, - {79, "R_PPC_GOT_TLSGD16"}, - {80, "R_PPC_GOT_TLSGD16_LO"}, - {81, "R_PPC_GOT_TLSGD16_HI"}, - {82, "R_PPC_GOT_TLSGD16_HA"}, - {83, "R_PPC_GOT_TLSLD16"}, - {84, "R_PPC_GOT_TLSLD16_LO"}, - {85, "R_PPC_GOT_TLSLD16_HI"}, - {86, "R_PPC_GOT_TLSLD16_HA"}, - {87, "R_PPC_GOT_TPREL16"}, - {88, "R_PPC_GOT_TPREL16_LO"}, - {89, "R_PPC_GOT_TPREL16_HI"}, - {90, "R_PPC_GOT_TPREL16_HA"}, - - {101, "R_PPC_EMB_NADDR32"}, - {102, "R_PPC_EMB_NADDR16"}, - {103, "R_PPC_EMB_NADDR16_LO"}, - {104, "R_PPC_EMB_NADDR16_HI"}, - {105, "R_PPC_EMB_NADDR16_HA"}, - {106, "R_PPC_EMB_SDAI16"}, - {107, "R_PPC_EMB_SDA2I16"}, - {108, "R_PPC_EMB_SDA2REL"}, - {109, "R_PPC_EMB_SDA21"}, - {110, "R_PPC_EMB_MRKREF"}, - {111, "R_PPC_EMB_RELSEC16"}, - {112, "R_PPC_EMB_RELST_LO"}, - {113, "R_PPC_EMB_RELST_HI"}, - {114, "R_PPC_EMB_RELST_HA"}, - {115, "R_PPC_EMB_BIT_FLD"}, - {116, "R_PPC_EMB_RELSDA"}, -} - -func (i R_PPC) String() string { return stringName(uint32(i), rppcStrings, false) } -func (i R_PPC) GoString() string { return stringName(uint32(i), rppcStrings, true) } - -// Relocation types for SPARC. -type R_SPARC int - -const ( - R_SPARC_NONE R_SPARC = 0 - R_SPARC_8 R_SPARC = 1 - R_SPARC_16 R_SPARC = 2 - R_SPARC_32 R_SPARC = 3 - R_SPARC_DISP8 R_SPARC = 4 - R_SPARC_DISP16 R_SPARC = 5 - R_SPARC_DISP32 R_SPARC = 6 - R_SPARC_WDISP30 R_SPARC = 7 - R_SPARC_WDISP22 R_SPARC = 8 - R_SPARC_HI22 R_SPARC = 9 - R_SPARC_22 R_SPARC = 10 - R_SPARC_13 R_SPARC = 11 - R_SPARC_LO10 R_SPARC = 12 - R_SPARC_GOT10 R_SPARC = 13 - R_SPARC_GOT13 R_SPARC = 14 - R_SPARC_GOT22 R_SPARC = 15 - R_SPARC_PC10 R_SPARC = 16 - R_SPARC_PC22 R_SPARC = 17 - R_SPARC_WPLT30 R_SPARC = 18 - R_SPARC_COPY R_SPARC = 19 - R_SPARC_GLOB_DAT R_SPARC = 20 - R_SPARC_JMP_SLOT R_SPARC = 21 - R_SPARC_RELATIVE R_SPARC = 22 - R_SPARC_UA32 R_SPARC = 23 - R_SPARC_PLT32 R_SPARC = 24 - R_SPARC_HIPLT22 R_SPARC = 25 - R_SPARC_LOPLT10 R_SPARC = 26 - R_SPARC_PCPLT32 R_SPARC = 27 - R_SPARC_PCPLT22 R_SPARC = 28 - R_SPARC_PCPLT10 R_SPARC = 29 - R_SPARC_10 R_SPARC = 30 - R_SPARC_11 R_SPARC = 31 - R_SPARC_64 R_SPARC = 32 - R_SPARC_OLO10 R_SPARC = 33 - R_SPARC_HH22 R_SPARC = 34 - R_SPARC_HM10 R_SPARC = 35 - R_SPARC_LM22 R_SPARC = 36 - R_SPARC_PC_HH22 R_SPARC = 37 - R_SPARC_PC_HM10 R_SPARC = 38 - R_SPARC_PC_LM22 R_SPARC = 39 - R_SPARC_WDISP16 R_SPARC = 40 - R_SPARC_WDISP19 R_SPARC = 41 - R_SPARC_GLOB_JMP R_SPARC = 42 - R_SPARC_7 R_SPARC = 43 - R_SPARC_5 R_SPARC = 44 - R_SPARC_6 R_SPARC = 45 - R_SPARC_DISP64 R_SPARC = 46 - R_SPARC_PLT64 R_SPARC = 47 - R_SPARC_HIX22 R_SPARC = 48 - R_SPARC_LOX10 R_SPARC = 49 - R_SPARC_H44 R_SPARC = 50 - R_SPARC_M44 R_SPARC = 51 - R_SPARC_L44 R_SPARC = 52 - R_SPARC_REGISTER R_SPARC = 53 - R_SPARC_UA64 R_SPARC = 54 - R_SPARC_UA16 R_SPARC = 55 -) - -var rsparcStrings = []intName{ - {0, "R_SPARC_NONE"}, - {1, "R_SPARC_8"}, - {2, "R_SPARC_16"}, - {3, "R_SPARC_32"}, - {4, "R_SPARC_DISP8"}, - {5, "R_SPARC_DISP16"}, - {6, "R_SPARC_DISP32"}, - {7, "R_SPARC_WDISP30"}, - {8, "R_SPARC_WDISP22"}, - {9, "R_SPARC_HI22"}, - {10, "R_SPARC_22"}, - {11, "R_SPARC_13"}, - {12, "R_SPARC_LO10"}, - {13, "R_SPARC_GOT10"}, - {14, "R_SPARC_GOT13"}, - {15, "R_SPARC_GOT22"}, - {16, "R_SPARC_PC10"}, - {17, "R_SPARC_PC22"}, - {18, "R_SPARC_WPLT30"}, - {19, "R_SPARC_COPY"}, - {20, "R_SPARC_GLOB_DAT"}, - {21, "R_SPARC_JMP_SLOT"}, - {22, "R_SPARC_RELATIVE"}, - {23, "R_SPARC_UA32"}, - {24, "R_SPARC_PLT32"}, - {25, "R_SPARC_HIPLT22"}, - {26, "R_SPARC_LOPLT10"}, - {27, "R_SPARC_PCPLT32"}, - {28, "R_SPARC_PCPLT22"}, - {29, "R_SPARC_PCPLT10"}, - {30, "R_SPARC_10"}, - {31, "R_SPARC_11"}, - {32, "R_SPARC_64"}, - {33, "R_SPARC_OLO10"}, - {34, "R_SPARC_HH22"}, - {35, "R_SPARC_HM10"}, - {36, "R_SPARC_LM22"}, - {37, "R_SPARC_PC_HH22"}, - {38, "R_SPARC_PC_HM10"}, - {39, "R_SPARC_PC_LM22"}, - {40, "R_SPARC_WDISP16"}, - {41, "R_SPARC_WDISP19"}, - {42, "R_SPARC_GLOB_JMP"}, - {43, "R_SPARC_7"}, - {44, "R_SPARC_5"}, - {45, "R_SPARC_6"}, - {46, "R_SPARC_DISP64"}, - {47, "R_SPARC_PLT64"}, - {48, "R_SPARC_HIX22"}, - {49, "R_SPARC_LOX10"}, - {50, "R_SPARC_H44"}, - {51, "R_SPARC_M44"}, - {52, "R_SPARC_L44"}, - {53, "R_SPARC_REGISTER"}, - {54, "R_SPARC_UA64"}, - {55, "R_SPARC_UA16"}, -} - -func (i R_SPARC) String() string { return stringName(uint32(i), rsparcStrings, false) } -func (i R_SPARC) GoString() string { return stringName(uint32(i), rsparcStrings, true) } - -// Magic number for the elf trampoline, chosen wisely to be an immediate value. -const ARM_MAGIC_TRAMP_NUMBER = 0x5c000003 - -// ELF32 File header. -type Header32 struct { - Ident [EI_NIDENT]byte /* File identification. */ - Type uint16 /* File type. */ - Machine uint16 /* Machine architecture. */ - Version uint32 /* ELF format version. */ - Entry uint32 /* Entry point. */ - Phoff uint32 /* Program header file offset. */ - Shoff uint32 /* Section header file offset. */ - Flags uint32 /* Architecture-specific flags. */ - Ehsize uint16 /* Size of ELF header in bytes. */ - Phentsize uint16 /* Size of program header entry. */ - Phnum uint16 /* Number of program header entries. */ - Shentsize uint16 /* Size of section header entry. */ - Shnum uint16 /* Number of section header entries. */ - Shstrndx uint16 /* Section name strings section. */ -} - -// ELF32 Section header. -type Section32 struct { - Name uint32 /* Section name (index into the section header string table). */ - Type uint32 /* Section type. */ - Flags uint32 /* Section flags. */ - Addr uint32 /* Address in memory image. */ - Off uint32 /* Offset in file. */ - Size uint32 /* Size in bytes. */ - Link uint32 /* Index of a related section. */ - Info uint32 /* Depends on section type. */ - Addralign uint32 /* Alignment in bytes. */ - Entsize uint32 /* Size of each entry in section. */ -} - -// ELF32 Program header. -type Prog32 struct { - Type uint32 /* Entry type. */ - Off uint32 /* File offset of contents. */ - Vaddr uint32 /* Virtual address in memory image. */ - Paddr uint32 /* Physical address (not used). */ - Filesz uint32 /* Size of contents in file. */ - Memsz uint32 /* Size of contents in memory. */ - Flags uint32 /* Access permission flags. */ - Align uint32 /* Alignment in memory and file. */ -} - -// ELF32 Dynamic structure. The ".dynamic" section contains an array of them. -type Dyn32 struct { - Tag int32 /* Entry type. */ - Val uint32 /* Integer/Address value. */ -} - -/* - * Relocation entries. - */ - -// ELF32 Relocations that don't need an addend field. -type Rel32 struct { - Off uint32 /* Location to be relocated. */ - Info uint32 /* Relocation type and symbol index. */ -} - -// ELF32 Relocations that need an addend field. -type Rela32 struct { - Off uint32 /* Location to be relocated. */ - Info uint32 /* Relocation type and symbol index. */ - Addend int32 /* Addend. */ -} - -func R_SYM32(info uint32) uint32 { return uint32(info >> 8) } -func R_TYPE32(info uint32) uint32 { return uint32(info & 0xff) } -func R_INFO32(sym, typ uint32) uint32 { return sym<<8 | typ } - -// ELF32 Symbol. -type Sym32 struct { - Name uint32 - Value uint32 - Size uint32 - Info uint8 - Other uint8 - Shndx uint16 -} - -const Sym32Size = 16 - -func ST_BIND(info uint8) SymBind { return SymBind(info >> 4) } -func ST_TYPE(info uint8) SymType { return SymType(info & 0xF) } -func ST_INFO(bind SymBind, typ SymType) uint8 { - return uint8(bind)<<4 | uint8(typ)&0xf -} -func ST_VISIBILITY(other uint8) SymVis { return SymVis(other & 3) } - -/* - * ELF64 - */ - -// ELF64 file header. -type Header64 struct { - Ident [EI_NIDENT]byte /* File identification. */ - Type uint16 /* File type. */ - Machine uint16 /* Machine architecture. */ - Version uint32 /* ELF format version. */ - Entry uint64 /* Entry point. */ - Phoff uint64 /* Program header file offset. */ - Shoff uint64 /* Section header file offset. */ - Flags uint32 /* Architecture-specific flags. */ - Ehsize uint16 /* Size of ELF header in bytes. */ - Phentsize uint16 /* Size of program header entry. */ - Phnum uint16 /* Number of program header entries. */ - Shentsize uint16 /* Size of section header entry. */ - Shnum uint16 /* Number of section header entries. */ - Shstrndx uint16 /* Section name strings section. */ -} - -// ELF64 Section header. -type Section64 struct { - Name uint32 /* Section name (index into the section header string table). */ - Type uint32 /* Section type. */ - Flags uint64 /* Section flags. */ - Addr uint64 /* Address in memory image. */ - Off uint64 /* Offset in file. */ - Size uint64 /* Size in bytes. */ - Link uint32 /* Index of a related section. */ - Info uint32 /* Depends on section type. */ - Addralign uint64 /* Alignment in bytes. */ - Entsize uint64 /* Size of each entry in section. */ -} - -// ELF64 Program header. -type Prog64 struct { - Type uint32 /* Entry type. */ - Flags uint32 /* Access permission flags. */ - Off uint64 /* File offset of contents. */ - Vaddr uint64 /* Virtual address in memory image. */ - Paddr uint64 /* Physical address (not used). */ - Filesz uint64 /* Size of contents in file. */ - Memsz uint64 /* Size of contents in memory. */ - Align uint64 /* Alignment in memory and file. */ -} - -// ELF64 Dynamic structure. The ".dynamic" section contains an array of them. -type Dyn64 struct { - Tag int64 /* Entry type. */ - Val uint64 /* Integer/address value */ -} - -/* - * Relocation entries. - */ - -/* ELF64 relocations that don't need an addend field. */ -type Rel64 struct { - Off uint64 /* Location to be relocated. */ - Info uint64 /* Relocation type and symbol index. */ -} - -/* ELF64 relocations that need an addend field. */ -type Rela64 struct { - Off uint64 /* Location to be relocated. */ - Info uint64 /* Relocation type and symbol index. */ - Addend int64 /* Addend. */ -} - -func R_SYM64(info uint64) uint32 { return uint32(info >> 32) } -func R_TYPE64(info uint64) uint32 { return uint32(info) } -func R_INFO(sym, typ uint32) uint64 { return uint64(sym)<<32 | uint64(typ) } - -// ELF64 symbol table entries. -type Sym64 struct { - Name uint32 /* String table index of name. */ - Info uint8 /* Type and binding information. */ - Other uint8 /* Reserved (not used). */ - Shndx uint16 /* Section index of symbol. */ - Value uint64 /* Symbol value. */ - Size uint64 /* Size of associated object. */ -} - -const Sym64Size = 24 - -type intName struct { - i uint32 - s string -} - -func stringName(i uint32, names []intName, goSyntax bool) string { - for _, n := range names { - if n.i == i { - if goSyntax { - return "elf." + n.s - } - return n.s - } - } - - // second pass - look for smaller to add with. - // assume sorted already - for j := len(names) - 1; j >= 0; j-- { - n := names[j] - if n.i < i { - s := n.s - if goSyntax { - s = "elf." + s - } - return s + "+" + strconv.FormatUint(uint64(i-n.i), 10) - } - } - - return strconv.FormatUint(uint64(i), 10) -} - -func flagName(i uint32, names []intName, goSyntax bool) string { - s := "" - for _, n := range names { - if n.i&i == n.i { - if len(s) > 0 { - s += "+" - } - if goSyntax { - s += "elf." - } - s += n.s - i -= n.i - } - } - if len(s) == 0 { - return "0x" + strconv.FormatUint(uint64(i), 16) - } - if i != 0 { - s += "+0x" + strconv.FormatUint(uint64(i), 16) - } - return s -} diff --git a/src/pkg/debug/elf/elf_test.go b/src/pkg/debug/elf/elf_test.go deleted file mode 100644 index e3c51bb71..000000000 --- a/src/pkg/debug/elf/elf_test.go +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package elf - -import ( - "fmt" - "testing" -) - -type nameTest struct { - val interface{} - str string -} - -var nameTests = []nameTest{ - {ELFOSABI_LINUX, "ELFOSABI_LINUX"}, - {ET_EXEC, "ET_EXEC"}, - {EM_860, "EM_860"}, - {SHN_LOPROC, "SHN_LOPROC"}, - {SHT_PROGBITS, "SHT_PROGBITS"}, - {SHF_MERGE + SHF_TLS, "SHF_MERGE+SHF_TLS"}, - {PT_LOAD, "PT_LOAD"}, - {PF_W + PF_R + 0x50, "PF_W+PF_R+0x50"}, - {DT_SYMBOLIC, "DT_SYMBOLIC"}, - {DF_BIND_NOW, "DF_BIND_NOW"}, - {NT_FPREGSET, "NT_FPREGSET"}, - {STB_GLOBAL, "STB_GLOBAL"}, - {STT_COMMON, "STT_COMMON"}, - {STV_HIDDEN, "STV_HIDDEN"}, - {R_X86_64_PC32, "R_X86_64_PC32"}, - {R_ALPHA_OP_PUSH, "R_ALPHA_OP_PUSH"}, - {R_ARM_THM_ABS5, "R_ARM_THM_ABS5"}, - {R_386_GOT32, "R_386_GOT32"}, - {R_PPC_GOT16_HI, "R_PPC_GOT16_HI"}, - {R_SPARC_GOT22, "R_SPARC_GOT22"}, - {ET_LOOS + 5, "ET_LOOS+5"}, - {ProgFlag(0x50), "0x50"}, -} - -func TestNames(t *testing.T) { - for i, tt := range nameTests { - s := fmt.Sprint(tt.val) - if s != tt.str { - t.Errorf("#%d: Sprint(%d) = %q, want %q", i, tt.val, s, tt.str) - } - } -} diff --git a/src/pkg/debug/elf/file.go b/src/pkg/debug/elf/file.go deleted file mode 100644 index c908e7a88..000000000 --- a/src/pkg/debug/elf/file.go +++ /dev/null @@ -1,945 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package elf implements access to ELF object files. -package elf - -import ( - "bytes" - "debug/dwarf" - "encoding/binary" - "errors" - "fmt" - "io" - "os" -) - -// TODO: error reporting detail - -/* - * Internal ELF representation - */ - -// A FileHeader represents an ELF file header. -type FileHeader struct { - Class Class - Data Data - Version Version - OSABI OSABI - ABIVersion uint8 - ByteOrder binary.ByteOrder - Type Type - Machine Machine - Entry uint64 -} - -// A File represents an open ELF file. -type File struct { - FileHeader - Sections []*Section - Progs []*Prog - closer io.Closer - gnuNeed []verneed - gnuVersym []byte -} - -// A SectionHeader represents a single ELF section header. -type SectionHeader struct { - Name string - Type SectionType - Flags SectionFlag - Addr uint64 - Offset uint64 - Size uint64 - Link uint32 - Info uint32 - Addralign uint64 - Entsize uint64 -} - -// A Section represents a single section in an ELF file. -type Section struct { - SectionHeader - - // Embed ReaderAt for ReadAt method. - // Do not embed SectionReader directly - // to avoid having Read and Seek. - // If a client wants Read and Seek it must use - // Open() to avoid fighting over the seek offset - // with other clients. - io.ReaderAt - sr *io.SectionReader -} - -// Data reads and returns the contents of the ELF section. -func (s *Section) Data() ([]byte, error) { - dat := make([]byte, s.sr.Size()) - n, err := s.sr.ReadAt(dat, 0) - if n == len(dat) { - err = nil - } - return dat[0:n], err -} - -// stringTable reads and returns the string table given by the -// specified link value. -func (f *File) stringTable(link uint32) ([]byte, error) { - if link <= 0 || link >= uint32(len(f.Sections)) { - return nil, errors.New("section has invalid string table link") - } - return f.Sections[link].Data() -} - -// Open returns a new ReadSeeker reading the ELF section. -func (s *Section) Open() io.ReadSeeker { return io.NewSectionReader(s.sr, 0, 1<<63-1) } - -// A ProgHeader represents a single ELF program header. -type ProgHeader struct { - Type ProgType - Flags ProgFlag - Off uint64 - Vaddr uint64 - Paddr uint64 - Filesz uint64 - Memsz uint64 - Align uint64 -} - -// A Prog represents a single ELF program header in an ELF binary. -type Prog struct { - ProgHeader - - // Embed ReaderAt for ReadAt method. - // Do not embed SectionReader directly - // to avoid having Read and Seek. - // If a client wants Read and Seek it must use - // Open() to avoid fighting over the seek offset - // with other clients. - io.ReaderAt - sr *io.SectionReader -} - -// Open returns a new ReadSeeker reading the ELF program body. -func (p *Prog) Open() io.ReadSeeker { return io.NewSectionReader(p.sr, 0, 1<<63-1) } - -// A Symbol represents an entry in an ELF symbol table section. -type Symbol struct { - Name string - Info, Other byte - Section SectionIndex - Value, Size uint64 -} - -/* - * ELF reader - */ - -type FormatError struct { - off int64 - msg string - val interface{} -} - -func (e *FormatError) Error() string { - msg := e.msg - if e.val != nil { - msg += fmt.Sprintf(" '%v' ", e.val) - } - msg += fmt.Sprintf("in record at byte %#x", e.off) - return msg -} - -// Open opens the named file using os.Open and prepares it for use as an ELF binary. -func Open(name string) (*File, error) { - f, err := os.Open(name) - if err != nil { - return nil, err - } - ff, err := NewFile(f) - if err != nil { - f.Close() - return nil, err - } - ff.closer = f - return ff, nil -} - -// Close closes the File. -// If the File was created using NewFile directly instead of Open, -// Close has no effect. -func (f *File) Close() error { - var err error - if f.closer != nil { - err = f.closer.Close() - f.closer = nil - } - return err -} - -// SectionByType returns the first section in f with the -// given type, or nil if there is no such section. -func (f *File) SectionByType(typ SectionType) *Section { - for _, s := range f.Sections { - if s.Type == typ { - return s - } - } - return nil -} - -// NewFile creates a new File for accessing an ELF binary in an underlying reader. -// The ELF binary is expected to start at position 0 in the ReaderAt. -func NewFile(r io.ReaderAt) (*File, error) { - sr := io.NewSectionReader(r, 0, 1<<63-1) - // Read and decode ELF identifier - var ident [16]uint8 - if _, err := r.ReadAt(ident[0:], 0); err != nil { - return nil, err - } - if ident[0] != '\x7f' || ident[1] != 'E' || ident[2] != 'L' || ident[3] != 'F' { - return nil, &FormatError{0, "bad magic number", ident[0:4]} - } - - f := new(File) - f.Class = Class(ident[EI_CLASS]) - switch f.Class { - case ELFCLASS32: - case ELFCLASS64: - // ok - default: - return nil, &FormatError{0, "unknown ELF class", f.Class} - } - - f.Data = Data(ident[EI_DATA]) - switch f.Data { - case ELFDATA2LSB: - f.ByteOrder = binary.LittleEndian - case ELFDATA2MSB: - f.ByteOrder = binary.BigEndian - default: - return nil, &FormatError{0, "unknown ELF data encoding", f.Data} - } - - f.Version = Version(ident[EI_VERSION]) - if f.Version != EV_CURRENT { - return nil, &FormatError{0, "unknown ELF version", f.Version} - } - - f.OSABI = OSABI(ident[EI_OSABI]) - f.ABIVersion = ident[EI_ABIVERSION] - - // Read ELF file header - var phoff int64 - var phentsize, phnum int - var shoff int64 - var shentsize, shnum, shstrndx int - shstrndx = -1 - switch f.Class { - case ELFCLASS32: - hdr := new(Header32) - sr.Seek(0, os.SEEK_SET) - if err := binary.Read(sr, f.ByteOrder, hdr); err != nil { - return nil, err - } - f.Type = Type(hdr.Type) - f.Machine = Machine(hdr.Machine) - f.Entry = uint64(hdr.Entry) - if v := Version(hdr.Version); v != f.Version { - return nil, &FormatError{0, "mismatched ELF version", v} - } - phoff = int64(hdr.Phoff) - phentsize = int(hdr.Phentsize) - phnum = int(hdr.Phnum) - shoff = int64(hdr.Shoff) - shentsize = int(hdr.Shentsize) - shnum = int(hdr.Shnum) - shstrndx = int(hdr.Shstrndx) - case ELFCLASS64: - hdr := new(Header64) - sr.Seek(0, os.SEEK_SET) - if err := binary.Read(sr, f.ByteOrder, hdr); err != nil { - return nil, err - } - f.Type = Type(hdr.Type) - f.Machine = Machine(hdr.Machine) - f.Entry = uint64(hdr.Entry) - if v := Version(hdr.Version); v != f.Version { - return nil, &FormatError{0, "mismatched ELF version", v} - } - phoff = int64(hdr.Phoff) - phentsize = int(hdr.Phentsize) - phnum = int(hdr.Phnum) - shoff = int64(hdr.Shoff) - shentsize = int(hdr.Shentsize) - shnum = int(hdr.Shnum) - shstrndx = int(hdr.Shstrndx) - } - - if shnum > 0 && shoff > 0 && (shstrndx < 0 || shstrndx >= shnum) { - return nil, &FormatError{0, "invalid ELF shstrndx", shstrndx} - } - - // Read program headers - f.Progs = make([]*Prog, phnum) - for i := 0; i < phnum; i++ { - off := phoff + int64(i)*int64(phentsize) - sr.Seek(off, os.SEEK_SET) - p := new(Prog) - switch f.Class { - case ELFCLASS32: - ph := new(Prog32) - if err := binary.Read(sr, f.ByteOrder, ph); err != nil { - return nil, err - } - p.ProgHeader = ProgHeader{ - Type: ProgType(ph.Type), - Flags: ProgFlag(ph.Flags), - Off: uint64(ph.Off), - Vaddr: uint64(ph.Vaddr), - Paddr: uint64(ph.Paddr), - Filesz: uint64(ph.Filesz), - Memsz: uint64(ph.Memsz), - Align: uint64(ph.Align), - } - case ELFCLASS64: - ph := new(Prog64) - if err := binary.Read(sr, f.ByteOrder, ph); err != nil { - return nil, err - } - p.ProgHeader = ProgHeader{ - Type: ProgType(ph.Type), - Flags: ProgFlag(ph.Flags), - Off: uint64(ph.Off), - Vaddr: uint64(ph.Vaddr), - Paddr: uint64(ph.Paddr), - Filesz: uint64(ph.Filesz), - Memsz: uint64(ph.Memsz), - Align: uint64(ph.Align), - } - } - p.sr = io.NewSectionReader(r, int64(p.Off), int64(p.Filesz)) - p.ReaderAt = p.sr - f.Progs[i] = p - } - - // Read section headers - f.Sections = make([]*Section, shnum) - names := make([]uint32, shnum) - for i := 0; i < shnum; i++ { - off := shoff + int64(i)*int64(shentsize) - sr.Seek(off, os.SEEK_SET) - s := new(Section) - switch f.Class { - case ELFCLASS32: - sh := new(Section32) - if err := binary.Read(sr, f.ByteOrder, sh); err != nil { - return nil, err - } - names[i] = sh.Name - s.SectionHeader = SectionHeader{ - Type: SectionType(sh.Type), - Flags: SectionFlag(sh.Flags), - Addr: uint64(sh.Addr), - Offset: uint64(sh.Off), - Size: uint64(sh.Size), - Link: uint32(sh.Link), - Info: uint32(sh.Info), - Addralign: uint64(sh.Addralign), - Entsize: uint64(sh.Entsize), - } - case ELFCLASS64: - sh := new(Section64) - if err := binary.Read(sr, f.ByteOrder, sh); err != nil { - return nil, err - } - names[i] = sh.Name - s.SectionHeader = SectionHeader{ - Type: SectionType(sh.Type), - Flags: SectionFlag(sh.Flags), - Offset: uint64(sh.Off), - Size: uint64(sh.Size), - Addr: uint64(sh.Addr), - Link: uint32(sh.Link), - Info: uint32(sh.Info), - Addralign: uint64(sh.Addralign), - Entsize: uint64(sh.Entsize), - } - } - s.sr = io.NewSectionReader(r, int64(s.Offset), int64(s.Size)) - s.ReaderAt = s.sr - f.Sections[i] = s - } - - if len(f.Sections) == 0 { - return f, nil - } - - // Load section header string table. - shstrtab, err := f.Sections[shstrndx].Data() - if err != nil { - return nil, err - } - for i, s := range f.Sections { - var ok bool - s.Name, ok = getString(shstrtab, int(names[i])) - if !ok { - return nil, &FormatError{shoff + int64(i*shentsize), "bad section name index", names[i]} - } - } - - return f, nil -} - -// getSymbols returns a slice of Symbols from parsing the symbol table -// with the given type, along with the associated string table. -func (f *File) getSymbols(typ SectionType) ([]Symbol, []byte, error) { - switch f.Class { - case ELFCLASS64: - return f.getSymbols64(typ) - - case ELFCLASS32: - return f.getSymbols32(typ) - } - - return nil, nil, errors.New("not implemented") -} - -// ErrNoSymbols is returned by File.Symbols and File.DynamicSymbols -// if there is no such section in the File. -var ErrNoSymbols = errors.New("no symbol section") - -func (f *File) getSymbols32(typ SectionType) ([]Symbol, []byte, error) { - symtabSection := f.SectionByType(typ) - if symtabSection == nil { - return nil, nil, ErrNoSymbols - } - - data, err := symtabSection.Data() - if err != nil { - return nil, nil, errors.New("cannot load symbol section") - } - symtab := bytes.NewReader(data) - if symtab.Len()%Sym32Size != 0 { - return nil, nil, errors.New("length of symbol section is not a multiple of SymSize") - } - - strdata, err := f.stringTable(symtabSection.Link) - if err != nil { - return nil, nil, errors.New("cannot load string table section") - } - - // The first entry is all zeros. - var skip [Sym32Size]byte - symtab.Read(skip[:]) - - symbols := make([]Symbol, symtab.Len()/Sym32Size) - - i := 0 - var sym Sym32 - for symtab.Len() > 0 { - binary.Read(symtab, f.ByteOrder, &sym) - str, _ := getString(strdata, int(sym.Name)) - symbols[i].Name = str - symbols[i].Info = sym.Info - symbols[i].Other = sym.Other - symbols[i].Section = SectionIndex(sym.Shndx) - symbols[i].Value = uint64(sym.Value) - symbols[i].Size = uint64(sym.Size) - i++ - } - - return symbols, strdata, nil -} - -func (f *File) getSymbols64(typ SectionType) ([]Symbol, []byte, error) { - symtabSection := f.SectionByType(typ) - if symtabSection == nil { - return nil, nil, ErrNoSymbols - } - - data, err := symtabSection.Data() - if err != nil { - return nil, nil, errors.New("cannot load symbol section") - } - symtab := bytes.NewReader(data) - if symtab.Len()%Sym64Size != 0 { - return nil, nil, errors.New("length of symbol section is not a multiple of Sym64Size") - } - - strdata, err := f.stringTable(symtabSection.Link) - if err != nil { - return nil, nil, errors.New("cannot load string table section") - } - - // The first entry is all zeros. - var skip [Sym64Size]byte - symtab.Read(skip[:]) - - symbols := make([]Symbol, symtab.Len()/Sym64Size) - - i := 0 - var sym Sym64 - for symtab.Len() > 0 { - binary.Read(symtab, f.ByteOrder, &sym) - str, _ := getString(strdata, int(sym.Name)) - symbols[i].Name = str - symbols[i].Info = sym.Info - symbols[i].Other = sym.Other - symbols[i].Section = SectionIndex(sym.Shndx) - symbols[i].Value = sym.Value - symbols[i].Size = sym.Size - i++ - } - - return symbols, strdata, nil -} - -// getString extracts a string from an ELF string table. -func getString(section []byte, start int) (string, bool) { - if start < 0 || start >= len(section) { - return "", false - } - - for end := start; end < len(section); end++ { - if section[end] == 0 { - return string(section[start:end]), true - } - } - return "", false -} - -// Section returns a section with the given name, or nil if no such -// section exists. -func (f *File) Section(name string) *Section { - for _, s := range f.Sections { - if s.Name == name { - return s - } - } - return nil -} - -// applyRelocations applies relocations to dst. rels is a relocations section -// in RELA format. -func (f *File) applyRelocations(dst []byte, rels []byte) error { - if f.Class == ELFCLASS64 && f.Machine == EM_X86_64 { - return f.applyRelocationsAMD64(dst, rels) - } - if f.Class == ELFCLASS32 && f.Machine == EM_386 { - return f.applyRelocations386(dst, rels) - } - if f.Class == ELFCLASS64 && f.Machine == EM_AARCH64 { - return f.applyRelocationsARM64(dst, rels) - } - - return errors.New("not implemented") -} - -func (f *File) applyRelocationsAMD64(dst []byte, rels []byte) error { - // 24 is the size of Rela64. - if len(rels)%24 != 0 { - return errors.New("length of relocation section is not a multiple of 24") - } - - symbols, _, err := f.getSymbols(SHT_SYMTAB) - if err != nil { - return err - } - - b := bytes.NewReader(rels) - var rela Rela64 - - for b.Len() > 0 { - binary.Read(b, f.ByteOrder, &rela) - symNo := rela.Info >> 32 - t := R_X86_64(rela.Info & 0xffff) - - if symNo == 0 || symNo > uint64(len(symbols)) { - continue - } - sym := &symbols[symNo-1] - if SymType(sym.Info&0xf) != STT_SECTION { - // We don't handle non-section relocations for now. - continue - } - - switch t { - case R_X86_64_64: - if rela.Off+8 >= uint64(len(dst)) || rela.Addend < 0 { - continue - } - f.ByteOrder.PutUint64(dst[rela.Off:rela.Off+8], uint64(rela.Addend)) - case R_X86_64_32: - if rela.Off+4 >= uint64(len(dst)) || rela.Addend < 0 { - continue - } - f.ByteOrder.PutUint32(dst[rela.Off:rela.Off+4], uint32(rela.Addend)) - } - } - - return nil -} - -func (f *File) applyRelocations386(dst []byte, rels []byte) error { - // 8 is the size of Rel32. - if len(rels)%8 != 0 { - return errors.New("length of relocation section is not a multiple of 8") - } - - symbols, _, err := f.getSymbols(SHT_SYMTAB) - if err != nil { - return err - } - - b := bytes.NewReader(rels) - var rel Rel32 - - for b.Len() > 0 { - binary.Read(b, f.ByteOrder, &rel) - symNo := rel.Info >> 8 - t := R_386(rel.Info & 0xff) - - if symNo == 0 || symNo > uint32(len(symbols)) { - continue - } - sym := &symbols[symNo-1] - - if t == R_386_32 { - if rel.Off+4 >= uint32(len(dst)) { - continue - } - val := f.ByteOrder.Uint32(dst[rel.Off : rel.Off+4]) - val += uint32(sym.Value) - f.ByteOrder.PutUint32(dst[rel.Off:rel.Off+4], val) - } - } - - return nil -} - -func (f *File) applyRelocationsARM64(dst []byte, rels []byte) error { - // 24 is the size of Rela64. - if len(rels)%24 != 0 { - return errors.New("length of relocation section is not a multiple of 24") - } - - symbols, _, err := f.getSymbols(SHT_SYMTAB) - if err != nil { - return err - } - - b := bytes.NewReader(rels) - var rela Rela64 - - for b.Len() > 0 { - binary.Read(b, f.ByteOrder, &rela) - symNo := rela.Info >> 32 - t := R_AARCH64(rela.Info & 0xffff) - - if symNo == 0 || symNo > uint64(len(symbols)) { - continue - } - sym := &symbols[symNo-1] - if SymType(sym.Info&0xf) != STT_SECTION { - // We don't handle non-section relocations for now. - continue - } - - switch t { - case R_AARCH64_ABS64: - if rela.Off+8 >= uint64(len(dst)) || rela.Addend < 0 { - continue - } - f.ByteOrder.PutUint64(dst[rela.Off:rela.Off+8], uint64(rela.Addend)) - case R_AARCH64_ABS32: - if rela.Off+4 >= uint64(len(dst)) || rela.Addend < 0 { - continue - } - f.ByteOrder.PutUint32(dst[rela.Off:rela.Off+4], uint32(rela.Addend)) - } - } - - return nil -} - -func (f *File) DWARF() (*dwarf.Data, error) { - // There are many other DWARF sections, but these - // are the required ones, and the debug/dwarf package - // does not use the others, so don't bother loading them. - var names = [...]string{"abbrev", "info", "str"} - var dat [len(names)][]byte - for i, name := range names { - name = ".debug_" + name - s := f.Section(name) - if s == nil { - continue - } - b, err := s.Data() - if err != nil && uint64(len(b)) < s.Size { - return nil, err - } - dat[i] = b - } - - // If there's a relocation table for .debug_info, we have to process it - // now otherwise the data in .debug_info is invalid for x86-64 objects. - rela := f.Section(".rela.debug_info") - if rela != nil && rela.Type == SHT_RELA && (f.Machine == EM_X86_64 || f.Machine == EM_AARCH64) { - data, err := rela.Data() - if err != nil { - return nil, err - } - err = f.applyRelocations(dat[1], data) - if err != nil { - return nil, err - } - } - - // When using clang we need to process relocations even for 386. - rel := f.Section(".rel.debug_info") - if rel != nil && rel.Type == SHT_REL && f.Machine == EM_386 { - data, err := rel.Data() - if err != nil { - return nil, err - } - err = f.applyRelocations(dat[1], data) - if err != nil { - return nil, err - } - } - - abbrev, info, str := dat[0], dat[1], dat[2] - d, err := dwarf.New(abbrev, nil, nil, info, nil, nil, nil, str) - if err != nil { - return nil, err - } - - // Look for DWARF4 .debug_types sections. - for i, s := range f.Sections { - if s.Name == ".debug_types" { - b, err := s.Data() - if err != nil && uint64(len(b)) < s.Size { - return nil, err - } - - for _, r := range f.Sections { - if r.Type != SHT_RELA && r.Type != SHT_REL { - continue - } - if int(r.Info) != i { - continue - } - rd, err := r.Data() - if err != nil { - return nil, err - } - err = f.applyRelocations(b, rd) - if err != nil { - return nil, err - } - } - - err = d.AddTypes(fmt.Sprintf("types-%d", i), b) - if err != nil { - return nil, err - } - } - } - - return d, nil -} - -// Symbols returns the symbol table for f. The symbols will be listed in the order -// they appear in f. -// -// For compatibility with Go 1.0, Symbols omits the null symbol at index 0. -// After retrieving the symbols as symtab, an externally supplied index x -// corresponds to symtab[x-1], not symtab[x]. -func (f *File) Symbols() ([]Symbol, error) { - sym, _, err := f.getSymbols(SHT_SYMTAB) - return sym, err -} - -// DynamicSymbols returns the dynamic symbol table for f. The symbols -// will be listed in the order they appear in f. -// -// For compatibility with Symbols, DynamicSymbols omits the null symbol at index 0. -// After retrieving the symbols as symtab, an externally supplied index x -// corresponds to symtab[x-1], not symtab[x]. -func (f *File) DynamicSymbols() ([]Symbol, error) { - sym, _, err := f.getSymbols(SHT_DYNSYM) - return sym, err -} - -type ImportedSymbol struct { - Name string - Version string - Library string -} - -// ImportedSymbols returns the names of all symbols -// referred to by the binary f that are expected to be -// satisfied by other libraries at dynamic load time. -// It does not return weak symbols. -func (f *File) ImportedSymbols() ([]ImportedSymbol, error) { - sym, str, err := f.getSymbols(SHT_DYNSYM) - if err != nil { - return nil, err - } - f.gnuVersionInit(str) - var all []ImportedSymbol - for i, s := range sym { - if ST_BIND(s.Info) == STB_GLOBAL && s.Section == SHN_UNDEF { - all = append(all, ImportedSymbol{Name: s.Name}) - f.gnuVersion(i, &all[len(all)-1]) - } - } - return all, nil -} - -type verneed struct { - File string - Name string -} - -// gnuVersionInit parses the GNU version tables -// for use by calls to gnuVersion. -func (f *File) gnuVersionInit(str []byte) { - // Accumulate verneed information. - vn := f.SectionByType(SHT_GNU_VERNEED) - if vn == nil { - return - } - d, _ := vn.Data() - - var need []verneed - i := 0 - for { - if i+16 > len(d) { - break - } - vers := f.ByteOrder.Uint16(d[i : i+2]) - if vers != 1 { - break - } - cnt := f.ByteOrder.Uint16(d[i+2 : i+4]) - fileoff := f.ByteOrder.Uint32(d[i+4 : i+8]) - aux := f.ByteOrder.Uint32(d[i+8 : i+12]) - next := f.ByteOrder.Uint32(d[i+12 : i+16]) - file, _ := getString(str, int(fileoff)) - - var name string - j := i + int(aux) - for c := 0; c < int(cnt); c++ { - if j+16 > len(d) { - break - } - // hash := f.ByteOrder.Uint32(d[j:j+4]) - // flags := f.ByteOrder.Uint16(d[j+4:j+6]) - other := f.ByteOrder.Uint16(d[j+6 : j+8]) - nameoff := f.ByteOrder.Uint32(d[j+8 : j+12]) - next := f.ByteOrder.Uint32(d[j+12 : j+16]) - name, _ = getString(str, int(nameoff)) - ndx := int(other) - if ndx >= len(need) { - a := make([]verneed, 2*(ndx+1)) - copy(a, need) - need = a - } - - need[ndx] = verneed{file, name} - if next == 0 { - break - } - j += int(next) - } - - if next == 0 { - break - } - i += int(next) - } - - // Versym parallels symbol table, indexing into verneed. - vs := f.SectionByType(SHT_GNU_VERSYM) - if vs == nil { - return - } - d, _ = vs.Data() - - f.gnuNeed = need - f.gnuVersym = d -} - -// gnuVersion adds Library and Version information to sym, -// which came from offset i of the symbol table. -func (f *File) gnuVersion(i int, sym *ImportedSymbol) { - // Each entry is two bytes. - i = (i + 1) * 2 - if i >= len(f.gnuVersym) { - return - } - j := int(f.ByteOrder.Uint16(f.gnuVersym[i:])) - if j < 2 || j >= len(f.gnuNeed) { - return - } - n := &f.gnuNeed[j] - sym.Library = n.File - sym.Version = n.Name -} - -// ImportedLibraries returns the names of all libraries -// referred to by the binary f that are expected to be -// linked with the binary at dynamic link time. -func (f *File) ImportedLibraries() ([]string, error) { - return f.DynString(DT_NEEDED) -} - -// DynString returns the strings listed for the given tag in the file's dynamic -// section. -// -// The tag must be one that takes string values: DT_NEEDED, DT_SONAME, DT_RPATH, or -// DT_RUNPATH. -func (f *File) DynString(tag DynTag) ([]string, error) { - switch tag { - case DT_NEEDED, DT_SONAME, DT_RPATH, DT_RUNPATH: - default: - return nil, fmt.Errorf("non-string-valued tag %v", tag) - } - ds := f.SectionByType(SHT_DYNAMIC) - if ds == nil { - // not dynamic, so no libraries - return nil, nil - } - d, err := ds.Data() - if err != nil { - return nil, err - } - str, err := f.stringTable(ds.Link) - if err != nil { - return nil, err - } - var all []string - for len(d) > 0 { - var t DynTag - var v uint64 - switch f.Class { - case ELFCLASS32: - t = DynTag(f.ByteOrder.Uint32(d[0:4])) - v = uint64(f.ByteOrder.Uint32(d[4:8])) - d = d[8:] - case ELFCLASS64: - t = DynTag(f.ByteOrder.Uint64(d[0:8])) - v = f.ByteOrder.Uint64(d[8:16]) - d = d[16:] - } - if t == tag { - s, ok := getString(str, int(v)) - if ok { - all = append(all, s) - } - } - } - return all, nil -} diff --git a/src/pkg/debug/elf/file_test.go b/src/pkg/debug/elf/file_test.go deleted file mode 100644 index 5e5ba52f3..000000000 --- a/src/pkg/debug/elf/file_test.go +++ /dev/null @@ -1,345 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package elf - -import ( - "bytes" - "compress/gzip" - "debug/dwarf" - "encoding/binary" - "io" - "net" - "os" - "path" - "reflect" - "runtime" - "testing" -) - -type fileTest struct { - file string - hdr FileHeader - sections []SectionHeader - progs []ProgHeader - needed []string -} - -var fileTests = []fileTest{ - { - "testdata/gcc-386-freebsd-exec", - FileHeader{ELFCLASS32, ELFDATA2LSB, EV_CURRENT, ELFOSABI_FREEBSD, 0, binary.LittleEndian, ET_EXEC, EM_386, 0x80483cc}, - []SectionHeader{ - {"", SHT_NULL, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, - {".interp", SHT_PROGBITS, SHF_ALLOC, 0x80480d4, 0xd4, 0x15, 0x0, 0x0, 0x1, 0x0}, - {".hash", SHT_HASH, SHF_ALLOC, 0x80480ec, 0xec, 0x90, 0x3, 0x0, 0x4, 0x4}, - {".dynsym", SHT_DYNSYM, SHF_ALLOC, 0x804817c, 0x17c, 0x110, 0x4, 0x1, 0x4, 0x10}, - {".dynstr", SHT_STRTAB, SHF_ALLOC, 0x804828c, 0x28c, 0xbb, 0x0, 0x0, 0x1, 0x0}, - {".rel.plt", SHT_REL, SHF_ALLOC, 0x8048348, 0x348, 0x20, 0x3, 0x7, 0x4, 0x8}, - {".init", SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR, 0x8048368, 0x368, 0x11, 0x0, 0x0, 0x4, 0x0}, - {".plt", SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR, 0x804837c, 0x37c, 0x50, 0x0, 0x0, 0x4, 0x4}, - {".text", SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR, 0x80483cc, 0x3cc, 0x180, 0x0, 0x0, 0x4, 0x0}, - {".fini", SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR, 0x804854c, 0x54c, 0xc, 0x0, 0x0, 0x4, 0x0}, - {".rodata", SHT_PROGBITS, SHF_ALLOC, 0x8048558, 0x558, 0xa3, 0x0, 0x0, 0x1, 0x0}, - {".data", SHT_PROGBITS, SHF_WRITE + SHF_ALLOC, 0x80495fc, 0x5fc, 0xc, 0x0, 0x0, 0x4, 0x0}, - {".eh_frame", SHT_PROGBITS, SHF_ALLOC, 0x8049608, 0x608, 0x4, 0x0, 0x0, 0x4, 0x0}, - {".dynamic", SHT_DYNAMIC, SHF_WRITE + SHF_ALLOC, 0x804960c, 0x60c, 0x98, 0x4, 0x0, 0x4, 0x8}, - {".ctors", SHT_PROGBITS, SHF_WRITE + SHF_ALLOC, 0x80496a4, 0x6a4, 0x8, 0x0, 0x0, 0x4, 0x0}, - {".dtors", SHT_PROGBITS, SHF_WRITE + SHF_ALLOC, 0x80496ac, 0x6ac, 0x8, 0x0, 0x0, 0x4, 0x0}, - {".jcr", SHT_PROGBITS, SHF_WRITE + SHF_ALLOC, 0x80496b4, 0x6b4, 0x4, 0x0, 0x0, 0x4, 0x0}, - {".got", SHT_PROGBITS, SHF_WRITE + SHF_ALLOC, 0x80496b8, 0x6b8, 0x1c, 0x0, 0x0, 0x4, 0x4}, - {".bss", SHT_NOBITS, SHF_WRITE + SHF_ALLOC, 0x80496d4, 0x6d4, 0x20, 0x0, 0x0, 0x4, 0x0}, - {".comment", SHT_PROGBITS, 0x0, 0x0, 0x6d4, 0x12d, 0x0, 0x0, 0x1, 0x0}, - {".debug_aranges", SHT_PROGBITS, 0x0, 0x0, 0x801, 0x20, 0x0, 0x0, 0x1, 0x0}, - {".debug_pubnames", SHT_PROGBITS, 0x0, 0x0, 0x821, 0x1b, 0x0, 0x0, 0x1, 0x0}, - {".debug_info", SHT_PROGBITS, 0x0, 0x0, 0x83c, 0x11d, 0x0, 0x0, 0x1, 0x0}, - {".debug_abbrev", SHT_PROGBITS, 0x0, 0x0, 0x959, 0x41, 0x0, 0x0, 0x1, 0x0}, - {".debug_line", SHT_PROGBITS, 0x0, 0x0, 0x99a, 0x35, 0x0, 0x0, 0x1, 0x0}, - {".debug_frame", SHT_PROGBITS, 0x0, 0x0, 0x9d0, 0x30, 0x0, 0x0, 0x4, 0x0}, - {".debug_str", SHT_PROGBITS, 0x0, 0x0, 0xa00, 0xd, 0x0, 0x0, 0x1, 0x0}, - {".shstrtab", SHT_STRTAB, 0x0, 0x0, 0xa0d, 0xf8, 0x0, 0x0, 0x1, 0x0}, - {".symtab", SHT_SYMTAB, 0x0, 0x0, 0xfb8, 0x4b0, 0x1d, 0x38, 0x4, 0x10}, - {".strtab", SHT_STRTAB, 0x0, 0x0, 0x1468, 0x206, 0x0, 0x0, 0x1, 0x0}, - }, - []ProgHeader{ - {PT_PHDR, PF_R + PF_X, 0x34, 0x8048034, 0x8048034, 0xa0, 0xa0, 0x4}, - {PT_INTERP, PF_R, 0xd4, 0x80480d4, 0x80480d4, 0x15, 0x15, 0x1}, - {PT_LOAD, PF_R + PF_X, 0x0, 0x8048000, 0x8048000, 0x5fb, 0x5fb, 0x1000}, - {PT_LOAD, PF_R + PF_W, 0x5fc, 0x80495fc, 0x80495fc, 0xd8, 0xf8, 0x1000}, - {PT_DYNAMIC, PF_R + PF_W, 0x60c, 0x804960c, 0x804960c, 0x98, 0x98, 0x4}, - }, - []string{"libc.so.6"}, - }, - { - "testdata/gcc-amd64-linux-exec", - FileHeader{ELFCLASS64, ELFDATA2LSB, EV_CURRENT, ELFOSABI_NONE, 0, binary.LittleEndian, ET_EXEC, EM_X86_64, 0x4003e0}, - []SectionHeader{ - {"", SHT_NULL, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, - {".interp", SHT_PROGBITS, SHF_ALLOC, 0x400200, 0x200, 0x1c, 0x0, 0x0, 0x1, 0x0}, - {".note.ABI-tag", SHT_NOTE, SHF_ALLOC, 0x40021c, 0x21c, 0x20, 0x0, 0x0, 0x4, 0x0}, - {".hash", SHT_HASH, SHF_ALLOC, 0x400240, 0x240, 0x24, 0x5, 0x0, 0x8, 0x4}, - {".gnu.hash", SHT_LOOS + 268435446, SHF_ALLOC, 0x400268, 0x268, 0x1c, 0x5, 0x0, 0x8, 0x0}, - {".dynsym", SHT_DYNSYM, SHF_ALLOC, 0x400288, 0x288, 0x60, 0x6, 0x1, 0x8, 0x18}, - {".dynstr", SHT_STRTAB, SHF_ALLOC, 0x4002e8, 0x2e8, 0x3d, 0x0, 0x0, 0x1, 0x0}, - {".gnu.version", SHT_HIOS, SHF_ALLOC, 0x400326, 0x326, 0x8, 0x5, 0x0, 0x2, 0x2}, - {".gnu.version_r", SHT_LOOS + 268435454, SHF_ALLOC, 0x400330, 0x330, 0x20, 0x6, 0x1, 0x8, 0x0}, - {".rela.dyn", SHT_RELA, SHF_ALLOC, 0x400350, 0x350, 0x18, 0x5, 0x0, 0x8, 0x18}, - {".rela.plt", SHT_RELA, SHF_ALLOC, 0x400368, 0x368, 0x30, 0x5, 0xc, 0x8, 0x18}, - {".init", SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR, 0x400398, 0x398, 0x18, 0x0, 0x0, 0x4, 0x0}, - {".plt", SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR, 0x4003b0, 0x3b0, 0x30, 0x0, 0x0, 0x4, 0x10}, - {".text", SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR, 0x4003e0, 0x3e0, 0x1b4, 0x0, 0x0, 0x10, 0x0}, - {".fini", SHT_PROGBITS, SHF_ALLOC + SHF_EXECINSTR, 0x400594, 0x594, 0xe, 0x0, 0x0, 0x4, 0x0}, - {".rodata", SHT_PROGBITS, SHF_ALLOC, 0x4005a4, 0x5a4, 0x11, 0x0, 0x0, 0x4, 0x0}, - {".eh_frame_hdr", SHT_PROGBITS, SHF_ALLOC, 0x4005b8, 0x5b8, 0x24, 0x0, 0x0, 0x4, 0x0}, - {".eh_frame", SHT_PROGBITS, SHF_ALLOC, 0x4005e0, 0x5e0, 0xa4, 0x0, 0x0, 0x8, 0x0}, - {".ctors", SHT_PROGBITS, SHF_WRITE + SHF_ALLOC, 0x600688, 0x688, 0x10, 0x0, 0x0, 0x8, 0x0}, - {".dtors", SHT_PROGBITS, SHF_WRITE + SHF_ALLOC, 0x600698, 0x698, 0x10, 0x0, 0x0, 0x8, 0x0}, - {".jcr", SHT_PROGBITS, SHF_WRITE + SHF_ALLOC, 0x6006a8, 0x6a8, 0x8, 0x0, 0x0, 0x8, 0x0}, - {".dynamic", SHT_DYNAMIC, SHF_WRITE + SHF_ALLOC, 0x6006b0, 0x6b0, 0x1a0, 0x6, 0x0, 0x8, 0x10}, - {".got", SHT_PROGBITS, SHF_WRITE + SHF_ALLOC, 0x600850, 0x850, 0x8, 0x0, 0x0, 0x8, 0x8}, - {".got.plt", SHT_PROGBITS, SHF_WRITE + SHF_ALLOC, 0x600858, 0x858, 0x28, 0x0, 0x0, 0x8, 0x8}, - {".data", SHT_PROGBITS, SHF_WRITE + SHF_ALLOC, 0x600880, 0x880, 0x18, 0x0, 0x0, 0x8, 0x0}, - {".bss", SHT_NOBITS, SHF_WRITE + SHF_ALLOC, 0x600898, 0x898, 0x8, 0x0, 0x0, 0x4, 0x0}, - {".comment", SHT_PROGBITS, 0x0, 0x0, 0x898, 0x126, 0x0, 0x0, 0x1, 0x0}, - {".debug_aranges", SHT_PROGBITS, 0x0, 0x0, 0x9c0, 0x90, 0x0, 0x0, 0x10, 0x0}, - {".debug_pubnames", SHT_PROGBITS, 0x0, 0x0, 0xa50, 0x25, 0x0, 0x0, 0x1, 0x0}, - {".debug_info", SHT_PROGBITS, 0x0, 0x0, 0xa75, 0x1a7, 0x0, 0x0, 0x1, 0x0}, - {".debug_abbrev", SHT_PROGBITS, 0x0, 0x0, 0xc1c, 0x6f, 0x0, 0x0, 0x1, 0x0}, - {".debug_line", SHT_PROGBITS, 0x0, 0x0, 0xc8b, 0x13f, 0x0, 0x0, 0x1, 0x0}, - {".debug_str", SHT_PROGBITS, SHF_MERGE + SHF_STRINGS, 0x0, 0xdca, 0xb1, 0x0, 0x0, 0x1, 0x1}, - {".debug_ranges", SHT_PROGBITS, 0x0, 0x0, 0xe80, 0x90, 0x0, 0x0, 0x10, 0x0}, - {".shstrtab", SHT_STRTAB, 0x0, 0x0, 0xf10, 0x149, 0x0, 0x0, 0x1, 0x0}, - {".symtab", SHT_SYMTAB, 0x0, 0x0, 0x19a0, 0x6f0, 0x24, 0x39, 0x8, 0x18}, - {".strtab", SHT_STRTAB, 0x0, 0x0, 0x2090, 0x1fc, 0x0, 0x0, 0x1, 0x0}, - }, - []ProgHeader{ - {PT_PHDR, PF_R + PF_X, 0x40, 0x400040, 0x400040, 0x1c0, 0x1c0, 0x8}, - {PT_INTERP, PF_R, 0x200, 0x400200, 0x400200, 0x1c, 0x1c, 1}, - {PT_LOAD, PF_R + PF_X, 0x0, 0x400000, 0x400000, 0x684, 0x684, 0x200000}, - {PT_LOAD, PF_R + PF_W, 0x688, 0x600688, 0x600688, 0x210, 0x218, 0x200000}, - {PT_DYNAMIC, PF_R + PF_W, 0x6b0, 0x6006b0, 0x6006b0, 0x1a0, 0x1a0, 0x8}, - {PT_NOTE, PF_R, 0x21c, 0x40021c, 0x40021c, 0x20, 0x20, 0x4}, - {PT_LOOS + 0x474E550, PF_R, 0x5b8, 0x4005b8, 0x4005b8, 0x24, 0x24, 0x4}, - {PT_LOOS + 0x474E551, PF_R + PF_W, 0x0, 0x0, 0x0, 0x0, 0x0, 0x8}, - }, - []string{"libc.so.6"}, - }, - { - "testdata/hello-world-core.gz", - FileHeader{ELFCLASS64, ELFDATA2LSB, EV_CURRENT, ELFOSABI_NONE, 0x0, binary.LittleEndian, ET_CORE, EM_X86_64, 0x0}, - []SectionHeader{}, - []ProgHeader{ - {Type: PT_NOTE, Flags: 0x0, Off: 0x3f8, Vaddr: 0x0, Paddr: 0x0, Filesz: 0x8ac, Memsz: 0x0, Align: 0x0}, - {Type: PT_LOAD, Flags: PF_X + PF_R, Off: 0x1000, Vaddr: 0x400000, Paddr: 0x0, Filesz: 0x0, Memsz: 0x1000, Align: 0x1000}, - {Type: PT_LOAD, Flags: PF_R, Off: 0x1000, Vaddr: 0x401000, Paddr: 0x0, Filesz: 0x1000, Memsz: 0x1000, Align: 0x1000}, - {Type: PT_LOAD, Flags: PF_W + PF_R, Off: 0x2000, Vaddr: 0x402000, Paddr: 0x0, Filesz: 0x1000, Memsz: 0x1000, Align: 0x1000}, - {Type: PT_LOAD, Flags: PF_X + PF_R, Off: 0x3000, Vaddr: 0x7f54078b8000, Paddr: 0x0, Filesz: 0x0, Memsz: 0x1b5000, Align: 0x1000}, - {Type: PT_LOAD, Flags: 0x0, Off: 0x3000, Vaddr: 0x7f5407a6d000, Paddr: 0x0, Filesz: 0x0, Memsz: 0x1ff000, Align: 0x1000}, - {Type: PT_LOAD, Flags: PF_R, Off: 0x3000, Vaddr: 0x7f5407c6c000, Paddr: 0x0, Filesz: 0x4000, Memsz: 0x4000, Align: 0x1000}, - {Type: PT_LOAD, Flags: PF_W + PF_R, Off: 0x7000, Vaddr: 0x7f5407c70000, Paddr: 0x0, Filesz: 0x2000, Memsz: 0x2000, Align: 0x1000}, - {Type: PT_LOAD, Flags: PF_W + PF_R, Off: 0x9000, Vaddr: 0x7f5407c72000, Paddr: 0x0, Filesz: 0x5000, Memsz: 0x5000, Align: 0x1000}, - {Type: PT_LOAD, Flags: PF_X + PF_R, Off: 0xe000, Vaddr: 0x7f5407c77000, Paddr: 0x0, Filesz: 0x0, Memsz: 0x22000, Align: 0x1000}, - {Type: PT_LOAD, Flags: PF_W + PF_R, Off: 0xe000, Vaddr: 0x7f5407e81000, Paddr: 0x0, Filesz: 0x3000, Memsz: 0x3000, Align: 0x1000}, - {Type: PT_LOAD, Flags: PF_W + PF_R, Off: 0x11000, Vaddr: 0x7f5407e96000, Paddr: 0x0, Filesz: 0x3000, Memsz: 0x3000, Align: 0x1000}, - {Type: PT_LOAD, Flags: PF_R, Off: 0x14000, Vaddr: 0x7f5407e99000, Paddr: 0x0, Filesz: 0x1000, Memsz: 0x1000, Align: 0x1000}, - {Type: PT_LOAD, Flags: PF_W + PF_R, Off: 0x15000, Vaddr: 0x7f5407e9a000, Paddr: 0x0, Filesz: 0x2000, Memsz: 0x2000, Align: 0x1000}, - {Type: PT_LOAD, Flags: PF_W + PF_R, Off: 0x17000, Vaddr: 0x7fff79972000, Paddr: 0x0, Filesz: 0x23000, Memsz: 0x23000, Align: 0x1000}, - {Type: PT_LOAD, Flags: PF_X + PF_R, Off: 0x3a000, Vaddr: 0x7fff799f8000, Paddr: 0x0, Filesz: 0x1000, Memsz: 0x1000, Align: 0x1000}, - {Type: PT_LOAD, Flags: PF_X + PF_R, Off: 0x3b000, Vaddr: 0xffffffffff600000, Paddr: 0x0, Filesz: 0x1000, Memsz: 0x1000, Align: 0x1000}, - }, - nil, - }, -} - -func TestOpen(t *testing.T) { - for i := range fileTests { - tt := &fileTests[i] - - var f *File - var err error - if path.Ext(tt.file) == ".gz" { - var r io.ReaderAt - if r, err = decompress(tt.file); err == nil { - f, err = NewFile(r) - } - } else { - f, err = Open(tt.file) - } - if err != nil { - t.Errorf("cannot open file %s: %v", tt.file, err) - continue - } - defer f.Close() - if !reflect.DeepEqual(f.FileHeader, tt.hdr) { - t.Errorf("open %s:\n\thave %#v\n\twant %#v\n", tt.file, f.FileHeader, tt.hdr) - continue - } - for i, s := range f.Sections { - if i >= len(tt.sections) { - break - } - sh := &tt.sections[i] - if !reflect.DeepEqual(&s.SectionHeader, sh) { - t.Errorf("open %s, section %d:\n\thave %#v\n\twant %#v\n", tt.file, i, &s.SectionHeader, sh) - } - } - for i, p := range f.Progs { - if i >= len(tt.progs) { - break - } - ph := &tt.progs[i] - if !reflect.DeepEqual(&p.ProgHeader, ph) { - t.Errorf("open %s, program %d:\n\thave %#v\n\twant %#v\n", tt.file, i, &p.ProgHeader, ph) - } - } - tn := len(tt.sections) - fn := len(f.Sections) - if tn != fn { - t.Errorf("open %s: len(Sections) = %d, want %d", tt.file, fn, tn) - } - tn = len(tt.progs) - fn = len(f.Progs) - if tn != fn { - t.Errorf("open %s: len(Progs) = %d, want %d", tt.file, fn, tn) - } - tl := tt.needed - fl, err := f.ImportedLibraries() - if err != nil { - t.Error(err) - } - if !reflect.DeepEqual(tl, fl) { - t.Errorf("open %s: DT_NEEDED = %v, want %v", tt.file, tl, fl) - } - } -} - -// elf.NewFile requires io.ReaderAt, which compress/gzip cannot -// provide. Decompress the file to a bytes.Reader. -func decompress(gz string) (io.ReaderAt, error) { - in, err := os.Open(gz) - if err != nil { - return nil, err - } - defer in.Close() - r, err := gzip.NewReader(in) - if err != nil { - return nil, err - } - var out bytes.Buffer - _, err = io.Copy(&out, r) - return bytes.NewReader(out.Bytes()), err -} - -type relocationTestEntry struct { - entryNumber int - entry *dwarf.Entry -} - -type relocationTest struct { - file string - entries []relocationTestEntry -} - -var relocationTests = []relocationTest{ - { - "testdata/go-relocation-test-gcc441-x86-64.obj", - []relocationTestEntry{ - {0, &dwarf.Entry{Offset: 0xb, Tag: dwarf.TagCompileUnit, Children: true, Field: []dwarf.Field{{Attr: dwarf.AttrProducer, Val: "GNU C 4.4.1"}, {Attr: dwarf.AttrLanguage, Val: int64(1)}, {Attr: dwarf.AttrName, Val: "go-relocation-test.c"}, {Attr: dwarf.AttrCompDir, Val: "/tmp"}, {Attr: dwarf.AttrLowpc, Val: uint64(0x0)}, {Attr: dwarf.AttrHighpc, Val: uint64(0x6)}, {Attr: dwarf.AttrStmtList, Val: int64(0)}}}}, - }, - }, - { - "testdata/go-relocation-test-gcc441-x86.obj", - []relocationTestEntry{ - {0, &dwarf.Entry{Offset: 0xb, Tag: dwarf.TagCompileUnit, Children: true, Field: []dwarf.Field{{Attr: dwarf.AttrProducer, Val: "GNU C 4.4.1"}, {Attr: dwarf.AttrLanguage, Val: int64(1)}, {Attr: dwarf.AttrName, Val: "t.c"}, {Attr: dwarf.AttrCompDir, Val: "/tmp"}, {Attr: dwarf.AttrLowpc, Val: uint64(0x0)}, {Attr: dwarf.AttrHighpc, Val: uint64(0x5)}, {Attr: dwarf.AttrStmtList, Val: int64(0)}}}}, - }, - }, - { - "testdata/go-relocation-test-gcc424-x86-64.obj", - []relocationTestEntry{ - {0, &dwarf.Entry{Offset: 0xb, Tag: dwarf.TagCompileUnit, Children: true, Field: []dwarf.Field{{Attr: dwarf.AttrProducer, Val: "GNU C 4.2.4 (Ubuntu 4.2.4-1ubuntu4)"}, {Attr: dwarf.AttrLanguage, Val: int64(1)}, {Attr: dwarf.AttrName, Val: "go-relocation-test-gcc424.c"}, {Attr: dwarf.AttrCompDir, Val: "/tmp"}, {Attr: dwarf.AttrLowpc, Val: uint64(0x0)}, {Attr: dwarf.AttrHighpc, Val: uint64(0x6)}, {Attr: dwarf.AttrStmtList, Val: int64(0)}}}}, - }, - }, - { - "testdata/go-relocation-test-gcc482-aarch64.obj", - []relocationTestEntry{ - {0, &dwarf.Entry{Offset: 0xb, Tag: dwarf.TagCompileUnit, Children: true, Field: []dwarf.Field{{Attr: dwarf.AttrProducer, Val: "GNU C 4.8.2 -g -fstack-protector"}, {Attr: dwarf.AttrLanguage, Val: int64(1)}, {Attr: dwarf.AttrName, Val: "go-relocation-test-gcc482.c"}, {Attr: dwarf.AttrCompDir, Val: "/tmp"}, {Attr: dwarf.AttrLowpc, Val: uint64(0x0)}, {Attr: dwarf.AttrHighpc, Val: int64(0x24)}, {Attr: dwarf.AttrStmtList, Val: int64(0)}}}}, - }, - }, - { - "testdata/go-relocation-test-clang-x86.obj", - []relocationTestEntry{ - {0, &dwarf.Entry{Offset: 0xb, Tag: dwarf.TagCompileUnit, Children: true, Field: []dwarf.Field{{Attr: dwarf.AttrProducer, Val: "clang version google3-trunk (trunk r209387)"}, {Attr: dwarf.AttrLanguage, Val: int64(12)}, {Attr: dwarf.AttrName, Val: "go-relocation-test-clang.c"}, {Attr: dwarf.AttrStmtList, Val: int64(0)}, {Attr: dwarf.AttrCompDir, Val: "/tmp"}}}}, - }, - }, - { - "testdata/gcc-amd64-openbsd-debug-with-rela.obj", - []relocationTestEntry{ - {203, &dwarf.Entry{Offset: 0xc62, Tag: dwarf.TagMember, Children: false, Field: []dwarf.Field{{Attr: dwarf.AttrName, Val: "it_interval"}, {Attr: dwarf.AttrDeclFile, Val: int64(7)}, {Attr: dwarf.AttrDeclLine, Val: int64(236)}, {Attr: dwarf.AttrType, Val: dwarf.Offset(0xb7f)}, {Attr: dwarf.AttrDataMemberLoc, Val: []byte{0x23, 0x0}}}}}, - {204, &dwarf.Entry{Offset: 0xc70, Tag: dwarf.TagMember, Children: false, Field: []dwarf.Field{{Attr: dwarf.AttrName, Val: "it_value"}, {Attr: dwarf.AttrDeclFile, Val: int64(7)}, {Attr: dwarf.AttrDeclLine, Val: int64(237)}, {Attr: dwarf.AttrType, Val: dwarf.Offset(0xb7f)}, {Attr: dwarf.AttrDataMemberLoc, Val: []byte{0x23, 0x10}}}}}, - }, - }, -} - -func TestDWARFRelocations(t *testing.T) { - for i, test := range relocationTests { - f, err := Open(test.file) - if err != nil { - t.Error(err) - continue - } - dwarf, err := f.DWARF() - if err != nil { - t.Error(err) - continue - } - for _, testEntry := range test.entries { - reader := dwarf.Reader() - for j := 0; j < testEntry.entryNumber; j++ { - entry, err := reader.Next() - if entry == nil || err != nil { - t.Errorf("Failed to skip to entry %d: %v", testEntry.entryNumber, err) - continue - } - } - entry, err := reader.Next() - if err != nil { - t.Error(err) - continue - } - if !reflect.DeepEqual(testEntry.entry, entry) { - t.Errorf("#%d/%d: mismatch: got:%#v want:%#v", i, testEntry.entryNumber, entry, testEntry.entry) - continue - } - } - } -} - -func TestNoSectionOverlaps(t *testing.T) { - // Ensure 6l outputs sections without overlaps. - if runtime.GOOS != "linux" && runtime.GOOS != "freebsd" { - return // not ELF - } - _ = net.ResolveIPAddr // force dynamic linkage - f, err := Open(os.Args[0]) - if err != nil { - t.Error(err) - return - } - for i, si := range f.Sections { - sih := si.SectionHeader - if sih.Type == SHT_NOBITS { - continue - } - for j, sj := range f.Sections { - sjh := sj.SectionHeader - if i == j || sjh.Type == SHT_NOBITS || sih.Offset == sjh.Offset && sih.Size == 0 { - continue - } - if sih.Offset >= sjh.Offset && sih.Offset < sjh.Offset+sjh.Size { - t.Errorf("ld produced ELF with section %s within %s: 0x%x <= 0x%x..0x%x < 0x%x", - sih.Name, sjh.Name, sjh.Offset, sih.Offset, sih.Offset+sih.Size, sjh.Offset+sjh.Size) - } - } - } -} diff --git a/src/pkg/debug/elf/symbols_test.go b/src/pkg/debug/elf/symbols_test.go deleted file mode 100644 index 1b79520e3..000000000 --- a/src/pkg/debug/elf/symbols_test.go +++ /dev/null @@ -1,834 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package elf - -import ( - "io" - "path" - "reflect" - "testing" -) - -// TODO: remove duplicate code -func TestSymbols(t *testing.T) { - do := func(file string, ts []Symbol, getfunc func(*File) ([]Symbol, error)) { - var f *File - var err error - if path.Ext(file) == ".gz" { - var r io.ReaderAt - if r, err = decompress(file); err == nil { - f, err = NewFile(r) - } - } else { - f, err = Open(file) - } - if err != nil { - t.Errorf("TestSymbols: cannot open file %s: %v", file, err) - return - } - defer f.Close() - fs, err := getfunc(f) - if err != nil && err != ErrNoSymbols { - t.Error(err) - return - } else if err == ErrNoSymbols { - fs = []Symbol{} - } - if !reflect.DeepEqual(ts, fs) { - t.Errorf("%s: Symbols = %v, want %v", file, ts, fs) - } - } - for file, ts := range symbolsGolden { - do(file, ts, (*File).Symbols) - } - for file, ts := range dynamicSymbolsGolden { - do(file, ts, (*File).DynamicSymbols) - } -} - -// golden symbol table data generated by testdata/getgoldsym.c - -var symbolsGolden = map[string][]Symbol{ - "testdata/gcc-amd64-linux-exec": { - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x1, - Value: 0x400200, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x2, - Value: 0x40021C, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x3, - Value: 0x400240, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x4, - Value: 0x400268, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x5, - Value: 0x400288, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x6, - Value: 0x4002E8, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x7, - Value: 0x400326, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x8, - Value: 0x400330, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x9, - Value: 0x400350, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0xA, - Value: 0x400368, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0xB, - Value: 0x400398, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0xC, - Value: 0x4003B0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0xD, - Value: 0x4003E0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0xE, - Value: 0x400594, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0xF, - Value: 0x4005A4, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x10, - Value: 0x4005B8, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x11, - Value: 0x4005E0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x12, - Value: 0x600688, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x13, - Value: 0x600698, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x14, - Value: 0x6006A8, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x15, - Value: 0x6006B0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x16, - Value: 0x600850, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x17, - Value: 0x600858, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x18, - Value: 0x600880, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x19, - Value: 0x600898, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x1A, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x1B, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x1C, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x1D, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x1E, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x1F, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x20, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x21, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "init.c", - Info: 0x4, - Other: 0x0, - Section: 0xFFF1, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "initfini.c", - Info: 0x4, - Other: 0x0, - Section: 0xFFF1, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "call_gmon_start", - Info: 0x2, - Other: 0x0, - Section: 0xD, - Value: 0x40040C, - Size: 0x0, - }, - Symbol{ - Name: "crtstuff.c", - Info: 0x4, - Other: 0x0, - Section: 0xFFF1, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "__CTOR_LIST__", - Info: 0x1, - Other: 0x0, - Section: 0x12, - Value: 0x600688, - Size: 0x0, - }, - Symbol{ - Name: "__DTOR_LIST__", - Info: 0x1, - Other: 0x0, - Section: 0x13, - Value: 0x600698, - Size: 0x0, - }, - Symbol{ - Name: "__JCR_LIST__", - Info: 0x1, - Other: 0x0, - Section: 0x14, - Value: 0x6006A8, - Size: 0x0, - }, - Symbol{ - Name: "__do_global_dtors_aux", - Info: 0x2, - Other: 0x0, - Section: 0xD, - Value: 0x400430, - Size: 0x0, - }, - Symbol{ - Name: "completed.6183", - Info: 0x1, - Other: 0x0, - Section: 0x19, - Value: 0x600898, - Size: 0x1, - }, - Symbol{ - Name: "p.6181", - Info: 0x1, - Other: 0x0, - Section: 0x18, - Value: 0x600890, - Size: 0x0, - }, - Symbol{ - Name: "frame_dummy", - Info: 0x2, - Other: 0x0, - Section: 0xD, - Value: 0x400470, - Size: 0x0, - }, - Symbol{ - Name: "crtstuff.c", - Info: 0x4, - Other: 0x0, - Section: 0xFFF1, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "__CTOR_END__", - Info: 0x1, - Other: 0x0, - Section: 0x12, - Value: 0x600690, - Size: 0x0, - }, - Symbol{ - Name: "__DTOR_END__", - Info: 0x1, - Other: 0x0, - Section: 0x13, - Value: 0x6006A0, - Size: 0x0, - }, - Symbol{ - Name: "__FRAME_END__", - Info: 0x1, - Other: 0x0, - Section: 0x11, - Value: 0x400680, - Size: 0x0, - }, - Symbol{ - Name: "__JCR_END__", - Info: 0x1, - Other: 0x0, - Section: 0x14, - Value: 0x6006A8, - Size: 0x0, - }, - Symbol{ - Name: "__do_global_ctors_aux", - Info: 0x2, - Other: 0x0, - Section: 0xD, - Value: 0x400560, - Size: 0x0, - }, - Symbol{ - Name: "initfini.c", - Info: 0x4, - Other: 0x0, - Section: 0xFFF1, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "hello.c", - Info: 0x4, - Other: 0x0, - Section: 0xFFF1, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "_GLOBAL_OFFSET_TABLE_", - Info: 0x1, - Other: 0x2, - Section: 0x17, - Value: 0x600858, - Size: 0x0, - }, - Symbol{ - Name: "__init_array_end", - Info: 0x0, - Other: 0x2, - Section: 0x12, - Value: 0x600684, - Size: 0x0, - }, - Symbol{ - Name: "__init_array_start", - Info: 0x0, - Other: 0x2, - Section: 0x12, - Value: 0x600684, - Size: 0x0, - }, - Symbol{ - Name: "_DYNAMIC", - Info: 0x1, - Other: 0x2, - Section: 0x15, - Value: 0x6006B0, - Size: 0x0, - }, - Symbol{ - Name: "data_start", - Info: 0x20, - Other: 0x0, - Section: 0x18, - Value: 0x600880, - Size: 0x0, - }, - Symbol{ - Name: "__libc_csu_fini", - Info: 0x12, - Other: 0x0, - Section: 0xD, - Value: 0x4004C0, - Size: 0x2, - }, - Symbol{ - Name: "_start", - Info: 0x12, - Other: 0x0, - Section: 0xD, - Value: 0x4003E0, - Size: 0x0, - }, - Symbol{ - Name: "__gmon_start__", - Info: 0x20, - Other: 0x0, - Section: 0x0, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "_Jv_RegisterClasses", - Info: 0x20, - Other: 0x0, - Section: 0x0, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "puts@@GLIBC_2.2.5", - Info: 0x12, - Other: 0x0, - Section: 0x0, - Value: 0x0, - Size: 0x18C, - }, - Symbol{ - Name: "_fini", - Info: 0x12, - Other: 0x0, - Section: 0xE, - Value: 0x400594, - Size: 0x0, - }, - Symbol{ - Name: "__libc_start_main@@GLIBC_2.2.5", - Info: 0x12, - Other: 0x0, - Section: 0x0, - Value: 0x0, - Size: 0x1C2, - }, - Symbol{ - Name: "_IO_stdin_used", - Info: 0x11, - Other: 0x0, - Section: 0xF, - Value: 0x4005A4, - Size: 0x4, - }, - Symbol{ - Name: "__data_start", - Info: 0x10, - Other: 0x0, - Section: 0x18, - Value: 0x600880, - Size: 0x0, - }, - Symbol{ - Name: "__dso_handle", - Info: 0x11, - Other: 0x2, - Section: 0x18, - Value: 0x600888, - Size: 0x0, - }, - Symbol{ - Name: "__libc_csu_init", - Info: 0x12, - Other: 0x0, - Section: 0xD, - Value: 0x4004D0, - Size: 0x89, - }, - Symbol{ - Name: "__bss_start", - Info: 0x10, - Other: 0x0, - Section: 0xFFF1, - Value: 0x600898, - Size: 0x0, - }, - Symbol{ - Name: "_end", - Info: 0x10, - Other: 0x0, - Section: 0xFFF1, - Value: 0x6008A0, - Size: 0x0, - }, - Symbol{ - Name: "_edata", - Info: 0x10, - Other: 0x0, - Section: 0xFFF1, - Value: 0x600898, - Size: 0x0, - }, - Symbol{ - Name: "main", - Info: 0x12, - Other: 0x0, - Section: 0xD, - Value: 0x400498, - Size: 0x1B, - }, - Symbol{ - Name: "_init", - Info: 0x12, - Other: 0x0, - Section: 0xB, - Value: 0x400398, - Size: 0x0, - }, - }, - "testdata/go-relocation-test-clang-x86.obj": { - Symbol{ - Name: "go-relocation-test-clang.c", - Info: 0x4, - Other: 0x0, - Section: 0xFFF1, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: ".Linfo_string0", - Info: 0x0, - Other: 0x0, - Section: 0xC, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: ".Linfo_string1", - Info: 0x0, - Other: 0x0, - Section: 0xC, - Value: 0x2C, - Size: 0x0, - }, - Symbol{ - Name: ".Linfo_string2", - Info: 0x0, - Other: 0x0, - Section: 0xC, - Value: 0x47, - Size: 0x0, - }, - Symbol{ - Name: ".Linfo_string3", - Info: 0x0, - Other: 0x0, - Section: 0xC, - Value: 0x4C, - Size: 0x0, - }, - Symbol{ - Name: ".Linfo_string4", - Info: 0x0, - Other: 0x0, - Section: 0xC, - Value: 0x4E, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x1, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x2, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x3, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x4, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x6, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x7, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x8, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0xA, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0xC, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0xD, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0xE, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0xF, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "", - Info: 0x3, - Other: 0x0, - Section: 0x10, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "v", - Info: 0x11, - Other: 0x0, - Section: 0xFFF2, - Value: 0x4, - Size: 0x4, - }, - }, - "testdata/hello-world-core.gz": {}, -} - -var dynamicSymbolsGolden = map[string][]Symbol{ - "testdata/gcc-amd64-linux-exec": { - Symbol{ - Name: "__gmon_start__", - Info: 0x20, - Other: 0x0, - Section: 0x0, - Value: 0x0, - Size: 0x0, - }, - Symbol{ - Name: "puts", - Info: 0x12, - Other: 0x0, - Section: 0x0, - Value: 0x0, - Size: 0x18C, - }, - Symbol{ - Name: "__libc_start_main", - Info: 0x12, - Other: 0x0, - Section: 0x0, - Value: 0x0, - Size: 0x1C2, - }, - }, - "testdata/go-relocation-test-clang-x86.obj": {}, - "testdata/hello-world-core.gz": {}, -} diff --git a/src/pkg/debug/elf/testdata/gcc-386-freebsd-exec b/src/pkg/debug/elf/testdata/gcc-386-freebsd-exec deleted file mode 100755 index 7af9c58ca..000000000 Binary files a/src/pkg/debug/elf/testdata/gcc-386-freebsd-exec and /dev/null differ diff --git a/src/pkg/debug/elf/testdata/gcc-amd64-linux-exec b/src/pkg/debug/elf/testdata/gcc-amd64-linux-exec deleted file mode 100755 index c6cb1de28..000000000 Binary files a/src/pkg/debug/elf/testdata/gcc-amd64-linux-exec and /dev/null differ diff --git a/src/pkg/debug/elf/testdata/gcc-amd64-openbsd-debug-with-rela.obj b/src/pkg/debug/elf/testdata/gcc-amd64-openbsd-debug-with-rela.obj deleted file mode 100644 index f62b1ea1c..000000000 Binary files a/src/pkg/debug/elf/testdata/gcc-amd64-openbsd-debug-with-rela.obj and /dev/null differ diff --git a/src/pkg/debug/elf/testdata/go-relocation-test-clang-x86.obj b/src/pkg/debug/elf/testdata/go-relocation-test-clang-x86.obj deleted file mode 100644 index e909cf4e6..000000000 Binary files a/src/pkg/debug/elf/testdata/go-relocation-test-clang-x86.obj and /dev/null differ diff --git a/src/pkg/debug/elf/testdata/go-relocation-test-gcc424-x86-64.obj b/src/pkg/debug/elf/testdata/go-relocation-test-gcc424-x86-64.obj deleted file mode 100644 index a7c6d6e56..000000000 Binary files a/src/pkg/debug/elf/testdata/go-relocation-test-gcc424-x86-64.obj and /dev/null differ diff --git a/src/pkg/debug/elf/testdata/go-relocation-test-gcc441-x86-64.obj b/src/pkg/debug/elf/testdata/go-relocation-test-gcc441-x86-64.obj deleted file mode 100644 index 2d37ab6e6..000000000 Binary files a/src/pkg/debug/elf/testdata/go-relocation-test-gcc441-x86-64.obj and /dev/null differ diff --git a/src/pkg/debug/elf/testdata/go-relocation-test-gcc441-x86.obj b/src/pkg/debug/elf/testdata/go-relocation-test-gcc441-x86.obj deleted file mode 100644 index 0d59fe303..000000000 Binary files a/src/pkg/debug/elf/testdata/go-relocation-test-gcc441-x86.obj and /dev/null differ diff --git a/src/pkg/debug/elf/testdata/go-relocation-test-gcc482-aarch64.obj b/src/pkg/debug/elf/testdata/go-relocation-test-gcc482-aarch64.obj deleted file mode 100644 index 849e2644e..000000000 Binary files a/src/pkg/debug/elf/testdata/go-relocation-test-gcc482-aarch64.obj and /dev/null differ diff --git a/src/pkg/debug/elf/testdata/hello-world-core.gz b/src/pkg/debug/elf/testdata/hello-world-core.gz deleted file mode 100644 index 806af6edb..000000000 Binary files a/src/pkg/debug/elf/testdata/hello-world-core.gz and /dev/null differ diff --git a/src/pkg/debug/elf/testdata/hello.c b/src/pkg/debug/elf/testdata/hello.c deleted file mode 100644 index 34d9ee792..000000000 --- a/src/pkg/debug/elf/testdata/hello.c +++ /dev/null @@ -1,7 +0,0 @@ -#include - -void -main(int argc, char *argv[]) -{ - printf("hello, world\n"); -} diff --git a/src/pkg/debug/goobj/read.go b/src/pkg/debug/goobj/read.go deleted file mode 100644 index 79a83e59a..000000000 --- a/src/pkg/debug/goobj/read.go +++ /dev/null @@ -1,666 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package goobj implements reading of Go object files and archives. -// -// TODO(rsc): Decide where this package should live. (golang.org/issue/6932) -// TODO(rsc): Decide the appropriate integer types for various fields. -// TODO(rsc): Write tests. (File format still up in the air a little.) -package goobj - -import ( - "bufio" - "bytes" - "errors" - "fmt" - "io" - "strconv" - "strings" -) - -// A SymKind describes the kind of memory represented by a symbol. -type SymKind int - -// This list is taken from include/link.h. - -// Defined SymKind values. -// TODO(rsc): Give idiomatic Go names. -// TODO(rsc): Reduce the number of symbol types in the object files. -const ( - _ SymKind = iota - - // readonly, executable - STEXT - SELFRXSECT - - // readonly, non-executable - STYPE - SSTRING - SGOSTRING - SGOFUNC - SRODATA - SFUNCTAB - STYPELINK - SSYMTAB // TODO: move to unmapped section - SPCLNTAB - SELFROSECT - - // writable, non-executable - SMACHOPLT - SELFSECT - SMACHO // Mach-O __nl_symbol_ptr - SMACHOGOT - SNOPTRDATA - SINITARR - SDATA - SWINDOWS - SBSS - SNOPTRBSS - STLSBSS - - // not mapped - SXREF - SMACHOSYMSTR - SMACHOSYMTAB - SMACHOINDIRECTPLT - SMACHOINDIRECTGOT - SFILE - SFILEPATH - SCONST - SDYNIMPORT - SHOSTOBJ -) - -var symKindStrings = []string{ - SBSS: "SBSS", - SCONST: "SCONST", - SDATA: "SDATA", - SDYNIMPORT: "SDYNIMPORT", - SELFROSECT: "SELFROSECT", - SELFRXSECT: "SELFRXSECT", - SELFSECT: "SELFSECT", - SFILE: "SFILE", - SFILEPATH: "SFILEPATH", - SFUNCTAB: "SFUNCTAB", - SGOFUNC: "SGOFUNC", - SGOSTRING: "SGOSTRING", - SHOSTOBJ: "SHOSTOBJ", - SINITARR: "SINITARR", - SMACHO: "SMACHO", - SMACHOGOT: "SMACHOGOT", - SMACHOINDIRECTGOT: "SMACHOINDIRECTGOT", - SMACHOINDIRECTPLT: "SMACHOINDIRECTPLT", - SMACHOPLT: "SMACHOPLT", - SMACHOSYMSTR: "SMACHOSYMSTR", - SMACHOSYMTAB: "SMACHOSYMTAB", - SNOPTRBSS: "SNOPTRBSS", - SNOPTRDATA: "SNOPTRDATA", - SPCLNTAB: "SPCLNTAB", - SRODATA: "SRODATA", - SSTRING: "SSTRING", - SSYMTAB: "SSYMTAB", - STEXT: "STEXT", - STLSBSS: "STLSBSS", - STYPE: "STYPE", - STYPELINK: "STYPELINK", - SWINDOWS: "SWINDOWS", - SXREF: "SXREF", -} - -func (k SymKind) String() string { - if k < 0 || int(k) >= len(symKindStrings) { - return fmt.Sprintf("SymKind(%d)", k) - } - return symKindStrings[k] -} - -// A Sym is a named symbol in an object file. -type Sym struct { - SymID // symbol identifier (name and version) - Kind SymKind // kind of symbol - DupOK bool // are duplicate definitions okay? - Size int // size of corresponding data - Type SymID // symbol for Go type information - Data Data // memory image of symbol - Reloc []Reloc // relocations to apply to Data - Func *Func // additional data for functions -} - -// A SymID - the combination of Name and Version - uniquely identifies -// a symbol within a package. -type SymID struct { - // Name is the name of a symbol. - Name string - - // Version is zero for symbols with global visibility. - // Symbols with only file visibility (such as file-level static - // declarations in C) have a non-zero version distinguishing - // a symbol in one file from a symbol of the same name - // in another file - Version int -} - -func (s SymID) String() string { - if s.Version == 0 { - return s.Name - } - return fmt.Sprintf("%s<%d>", s.Name, s.Version) -} - -// A Data is a reference to data stored in an object file. -// It records the offset and size of the data, so that a client can -// read the data only if necessary. -type Data struct { - Offset int64 - Size int64 -} - -// A Reloc describes a relocation applied to a memory image to refer -// to an address within a particular symbol. -type Reloc struct { - // The bytes at [Offset, Offset+Size) within the memory image - // should be updated to refer to the address Add bytes after the start - // of the symbol Sym. - Offset int - Size int - Sym SymID - Add int - - // The Type records the form of address expected in the bytes - // described by the previous fields: absolute, PC-relative, and so on. - // TODO(rsc): The interpretation of Type is not exposed by this package. - Type int -} - -// A Var describes a variable in a function stack frame: a declared -// local variable, an input argument, or an output result. -type Var struct { - // The combination of Name, Kind, and Offset uniquely - // identifies a variable in a function stack frame. - // Using fewer of these - in particular, using only Name - does not. - Name string // Name of variable. - Kind int // TODO(rsc): Define meaning. - Offset int // Frame offset. TODO(rsc): Define meaning. - - Type SymID // Go type for variable. -} - -// Func contains additional per-symbol information specific to functions. -type Func struct { - Args int // size in bytes of argument frame: inputs and outputs - Frame int // size in bytes of local variable frame - Leaf bool // function omits save of link register (ARM) - NoSplit bool // function omits stack split prologue - Var []Var // detail about local variables - PCSP Data // PC → SP offset map - PCFile Data // PC → file number map (index into File) - PCLine Data // PC → line number map - PCData []Data // PC → runtime support data map - FuncData []FuncData // non-PC-specific runtime support data - File []string // paths indexed by PCFile -} - -// TODO: Add PCData []byte and PCDataIter (similar to liblink). - -// A FuncData is a single function-specific data value. -type FuncData struct { - Sym SymID // symbol holding data - Offset int64 // offset into symbol for funcdata pointer -} - -// A Package is a parsed Go object file or archive defining a Go package. -type Package struct { - ImportPath string // import path denoting this package - Imports []string // packages imported by this package - Syms []*Sym // symbols defined by this package - MaxVersion int // maximum Version in any SymID in Syms -} - -var ( - archiveHeader = []byte("!\n") - archiveMagic = []byte("`\n") - goobjHeader = []byte("go objec") // truncated to size of archiveHeader - - errCorruptArchive = errors.New("corrupt archive") - errTruncatedArchive = errors.New("truncated archive") - errNotArchive = errors.New("unrecognized archive format") - - errCorruptObject = errors.New("corrupt object file") - errTruncatedObject = errors.New("truncated object file") - errNotObject = errors.New("unrecognized object file format") -) - -// An objReader is an object file reader. -type objReader struct { - p *Package - b *bufio.Reader - f io.ReadSeeker - err error - offset int64 - limit int64 - tmp [256]byte - pkg string - pkgprefix string -} - -// importPathToPrefix returns the prefix that will be used in the -// final symbol table for the given import path. -// We escape '%', '"', all control characters and non-ASCII bytes, -// and any '.' after the final slash. -// -// See ../../../cmd/ld/lib.c:/^pathtoprefix and -// ../../../cmd/gc/subr.c:/^pathtoprefix. -func importPathToPrefix(s string) string { - // find index of last slash, if any, or else -1. - // used for determining whether an index is after the last slash. - slash := strings.LastIndex(s, "/") - - // check for chars that need escaping - n := 0 - for r := 0; r < len(s); r++ { - if c := s[r]; c <= ' ' || (c == '.' && r > slash) || c == '%' || c == '"' || c >= 0x7F { - n++ - } - } - - // quick exit - if n == 0 { - return s - } - - // escape - const hex = "0123456789abcdef" - p := make([]byte, 0, len(s)+2*n) - for r := 0; r < len(s); r++ { - if c := s[r]; c <= ' ' || (c == '.' && r > slash) || c == '%' || c == '"' || c >= 0x7F { - p = append(p, '%', hex[c>>4], hex[c&0xF]) - } else { - p = append(p, c) - } - } - - return string(p) -} - -// init initializes r to read package p from f. -func (r *objReader) init(f io.ReadSeeker, p *Package) { - r.f = f - r.p = p - r.offset, _ = f.Seek(0, 1) - r.limit, _ = f.Seek(0, 2) - f.Seek(r.offset, 0) - r.b = bufio.NewReader(f) - r.pkgprefix = importPathToPrefix(p.ImportPath) + "." -} - -// error records that an error occurred. -// It returns only the first error, so that an error -// caused by an earlier error does not discard information -// about the earlier error. -func (r *objReader) error(err error) error { - if r.err == nil { - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - r.err = err - } - // panic("corrupt") // useful for debugging - return r.err -} - -// readByte reads and returns a byte from the input file. -// On I/O error or EOF, it records the error but returns byte 0. -// A sequence of 0 bytes will eventually terminate any -// parsing state in the object file. In particular, it ends the -// reading of a varint. -func (r *objReader) readByte() byte { - if r.err != nil { - return 0 - } - if r.offset >= r.limit { - r.error(io.ErrUnexpectedEOF) - return 0 - } - b, err := r.b.ReadByte() - if err != nil { - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - r.error(err) - b = 0 - } else { - r.offset++ - } - return b -} - -// read reads exactly len(b) bytes from the input file. -// If an error occurs, read returns the error but also -// records it, so it is safe for callers to ignore the result -// as long as delaying the report is not a problem. -func (r *objReader) readFull(b []byte) error { - if r.err != nil { - return r.err - } - if r.offset+int64(len(b)) > r.limit { - return r.error(io.ErrUnexpectedEOF) - } - n, err := io.ReadFull(r.b, b) - r.offset += int64(n) - if err != nil { - return r.error(err) - } - return nil -} - -// readInt reads a zigzag varint from the input file. -func (r *objReader) readInt() int { - var u uint64 - - for shift := uint(0); ; shift += 7 { - if shift >= 64 { - r.error(errCorruptObject) - return 0 - } - c := r.readByte() - u |= uint64(c&0x7F) << shift - if c&0x80 == 0 { - break - } - } - - v := int64(u>>1) ^ (int64(u) << 63 >> 63) - if int64(int(v)) != v { - r.error(errCorruptObject) // TODO - return 0 - } - return int(v) -} - -// readString reads a length-delimited string from the input file. -func (r *objReader) readString() string { - n := r.readInt() - buf := make([]byte, n) - r.readFull(buf) - return string(buf) -} - -// readSymID reads a SymID from the input file. -func (r *objReader) readSymID() SymID { - name, vers := r.readString(), r.readInt() - - // In a symbol name in an object file, "". denotes the - // prefix for the package in which the object file has been found. - // Expand it. - name = strings.Replace(name, `"".`, r.pkgprefix, -1) - - // An individual object file only records version 0 (extern) or 1 (static). - // To make static symbols unique across all files being read, we - // replace version 1 with the version corresponding to the current - // file number. The number is incremented on each call to parseObject. - if vers != 0 { - vers = r.p.MaxVersion - } - - return SymID{name, vers} -} - -// readData reads a data reference from the input file. -func (r *objReader) readData() Data { - n := r.readInt() - d := Data{Offset: r.offset, Size: int64(n)} - r.skip(int64(n)) - return d -} - -// skip skips n bytes in the input. -func (r *objReader) skip(n int64) { - if n < 0 { - r.error(fmt.Errorf("debug/goobj: internal error: misuse of skip")) - } - if n < int64(len(r.tmp)) { - // Since the data is so small, a just reading from the buffered - // reader is better than flushing the buffer and seeking. - r.readFull(r.tmp[:n]) - } else if n <= int64(r.b.Buffered()) { - // Even though the data is not small, it has already been read. - // Advance the buffer instead of seeking. - for n > int64(len(r.tmp)) { - r.readFull(r.tmp[:]) - n -= int64(len(r.tmp)) - } - r.readFull(r.tmp[:n]) - } else { - // Seek, giving up buffered data. - _, err := r.f.Seek(r.offset+n, 0) - if err != nil { - r.error(err) - } - r.offset += n - r.b.Reset(r.f) - } -} - -// Parse parses an object file or archive from r, -// assuming that its import path is pkgpath. -func Parse(r io.ReadSeeker, pkgpath string) (*Package, error) { - if pkgpath == "" { - pkgpath = `""` - } - p := new(Package) - p.ImportPath = pkgpath - - var rd objReader - rd.init(r, p) - err := rd.readFull(rd.tmp[:8]) - if err != nil { - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - return nil, err - } - - switch { - default: - return nil, errNotObject - - case bytes.Equal(rd.tmp[:8], archiveHeader): - if err := rd.parseArchive(); err != nil { - return nil, err - } - case bytes.Equal(rd.tmp[:8], goobjHeader): - if err := rd.parseObject(goobjHeader); err != nil { - return nil, err - } - } - - return p, nil -} - -// trimSpace removes trailing spaces from b and returns the corresponding string. -// This effectively parses the form used in archive headers. -func trimSpace(b []byte) string { - return string(bytes.TrimRight(b, " ")) -} - -// parseArchive parses a Unix archive of Go object files. -// TODO(rsc): Need to skip non-Go object files. -// TODO(rsc): Maybe record table of contents in r.p so that -// linker can avoid having code to parse archives too. -func (r *objReader) parseArchive() error { - for r.offset < r.limit { - if err := r.readFull(r.tmp[:60]); err != nil { - return err - } - data := r.tmp[:60] - - // Each file is preceded by this text header (slice indices in first column): - // 0:16 name - // 16:28 date - // 28:34 uid - // 34:40 gid - // 40:48 mode - // 48:58 size - // 58:60 magic - `\n - // We only care about name, size, and magic. - // The fields are space-padded on the right. - // The size is in decimal. - // The file data - size bytes - follows the header. - // Headers are 2-byte aligned, so if size is odd, an extra padding - // byte sits between the file data and the next header. - // The file data that follows is padded to an even number of bytes: - // if size is odd, an extra padding byte is inserted betw the next header. - if len(data) < 60 { - return errTruncatedArchive - } - if !bytes.Equal(data[58:60], archiveMagic) { - return errCorruptArchive - } - name := trimSpace(data[0:16]) - size, err := strconv.ParseInt(trimSpace(data[48:58]), 10, 64) - if err != nil { - return errCorruptArchive - } - data = data[60:] - fsize := size + size&1 - if fsize < 0 || fsize < size { - return errCorruptArchive - } - switch name { - case "__.SYMDEF", "__.GOSYMDEF", "__.PKGDEF": - r.skip(size) - default: - oldLimit := r.limit - r.limit = r.offset + size - if err := r.parseObject(nil); err != nil { - return fmt.Errorf("parsing archive member %q: %v", name, err) - } - r.skip(r.limit - r.offset) - r.limit = oldLimit - } - if size&1 != 0 { - r.skip(1) - } - } - return nil -} - -// parseObject parses a single Go object file. -// The prefix is the bytes already read from the file, -// typically in order to detect that this is an object file. -// The object file consists of a textual header ending in "\n!\n" -// and then the part we want to parse begins. -// The format of that part is defined in a comment at the top -// of src/liblink/objfile.c. -func (r *objReader) parseObject(prefix []byte) error { - // TODO(rsc): Maybe use prefix and the initial input to - // record the header line from the file, which would - // give the architecture and other version information. - - r.p.MaxVersion++ - var c1, c2, c3 byte - for { - c1, c2, c3 = c2, c3, r.readByte() - if c3 == 0 { // NUL or EOF, either is bad - return errCorruptObject - } - if c1 == '\n' && c2 == '!' && c3 == '\n' { - break - } - } - - r.readFull(r.tmp[:8]) - if !bytes.Equal(r.tmp[:8], []byte("\x00\x00go13ld")) { - return r.error(errCorruptObject) - } - - b := r.readByte() - if b != 1 { - return r.error(errCorruptObject) - } - - // Direct package dependencies. - for { - s := r.readString() - if s == "" { - break - } - r.p.Imports = append(r.p.Imports, s) - } - - // Symbols. - for { - if b := r.readByte(); b != 0xfe { - if b != 0xff { - return r.error(errCorruptObject) - } - break - } - - typ := r.readInt() - s := &Sym{SymID: r.readSymID()} - r.p.Syms = append(r.p.Syms, s) - s.Kind = SymKind(typ) - flags := r.readInt() - s.DupOK = flags&1 != 0 - s.Size = r.readInt() - s.Type = r.readSymID() - s.Data = r.readData() - s.Reloc = make([]Reloc, r.readInt()) - for i := range s.Reloc { - rel := &s.Reloc[i] - rel.Offset = r.readInt() - rel.Size = r.readInt() - rel.Type = r.readInt() - rel.Add = r.readInt() - r.readInt() // Xadd - ignored - rel.Sym = r.readSymID() - r.readSymID() // Xsym - ignored - } - - if s.Kind == STEXT { - f := new(Func) - s.Func = f - f.Args = r.readInt() - f.Frame = r.readInt() - flags := r.readInt() - f.Leaf = flags&1 != 0 - f.NoSplit = r.readInt() != 0 - f.Var = make([]Var, r.readInt()) - for i := range f.Var { - v := &f.Var[i] - v.Name = r.readSymID().Name - v.Offset = r.readInt() - v.Kind = r.readInt() - v.Type = r.readSymID() - } - - f.PCSP = r.readData() - f.PCFile = r.readData() - f.PCLine = r.readData() - f.PCData = make([]Data, r.readInt()) - for i := range f.PCData { - f.PCData[i] = r.readData() - } - f.FuncData = make([]FuncData, r.readInt()) - for i := range f.FuncData { - f.FuncData[i].Sym = r.readSymID() - } - for i := range f.FuncData { - f.FuncData[i].Offset = int64(r.readInt()) // TODO - } - f.File = make([]string, r.readInt()) - for i := range f.File { - f.File[i] = r.readSymID().Name - } - } - } - - r.readFull(r.tmp[:7]) - if !bytes.Equal(r.tmp[:7], []byte("\xffgo13ld")) { - return r.error(errCorruptObject) - } - - return nil -} diff --git a/src/pkg/debug/goobj/read_test.go b/src/pkg/debug/goobj/read_test.go deleted file mode 100644 index dee140533..000000000 --- a/src/pkg/debug/goobj/read_test.go +++ /dev/null @@ -1,28 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package goobj - -import "testing" - -var importPathToPrefixTests = []struct { - in string - out string -}{ - {"runtime", "runtime"}, - {"sync/atomic", "sync/atomic"}, - {"code.google.com/p/go.tools/godoc", "code.google.com/p/go.tools/godoc"}, - {"foo.bar/baz.quux", "foo.bar/baz%2equux"}, - {"", ""}, - {"%foo%bar", "%25foo%25bar"}, - {"\x01\x00\x7F☺", "%01%00%7f%e2%98%ba"}, -} - -func TestImportPathToPrefix(t *testing.T) { - for _, tt := range importPathToPrefixTests { - if out := importPathToPrefix(tt.in); out != tt.out { - t.Errorf("importPathToPrefix(%q) = %q, want %q", tt.in, out, tt.out) - } - } -} diff --git a/src/pkg/debug/gosym/pclinetest.asm b/src/pkg/debug/gosym/pclinetest.asm deleted file mode 100644 index b9ee9c0a5..000000000 --- a/src/pkg/debug/gosym/pclinetest.asm +++ /dev/null @@ -1,58 +0,0 @@ -TEXT linefrompc(SB),4,$0 // Each byte stores its line delta -BYTE $2; -BYTE $1; -BYTE $1; BYTE $0; -BYTE $1; BYTE $0; BYTE $0; -BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; -BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; -BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; -BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; -BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; -BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; -BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; -BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; -BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; -BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; -BYTE $1; -BYTE $1; -BYTE $1; BYTE $0; -BYTE $1; BYTE $0; BYTE $0; -BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; -BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; -BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; -BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; -BYTE $1; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; BYTE $0; -#include "pclinetest.h" -BYTE $2; -#include "pclinetest.h" -BYTE $2; -BYTE $255; - -TEXT pcfromline(SB),4,$0 // Each record stores its line delta, then n, then n more bytes -BYTE $32; BYTE $0; -BYTE $1; BYTE $1; BYTE $0; -BYTE $1; BYTE $0; - -BYTE $2; BYTE $4; BYTE $0; BYTE $0; BYTE $0; BYTE $0; - - -#include "pclinetest.h" -BYTE $4; BYTE $0; - - -BYTE $3; BYTE $3; BYTE $0; BYTE $0; BYTE $0; -#include "pclinetest.h" - - -BYTE $4; BYTE $3; BYTE $0; BYTE $0; BYTE $0; -BYTE $255; - -// Keep the linker happy -TEXT main·main(SB),4,$0 - RET - -TEXT main·init(SB),4,$0 - // Prevent GC of our test symbols - CALL linefrompc(SB) - CALL pcfromline(SB) - RET diff --git a/src/pkg/debug/gosym/pclinetest.h b/src/pkg/debug/gosym/pclinetest.h deleted file mode 100644 index 156c0b87b..000000000 --- a/src/pkg/debug/gosym/pclinetest.h +++ /dev/null @@ -1,9 +0,0 @@ -// +build ignore - -// Empty include file to generate z symbols - - - - - -// EOF diff --git a/src/pkg/debug/gosym/pclntab.go b/src/pkg/debug/gosym/pclntab.go deleted file mode 100644 index 6620aefb0..000000000 --- a/src/pkg/debug/gosym/pclntab.go +++ /dev/null @@ -1,453 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* - * Line tables - */ - -package gosym - -import ( - "encoding/binary" - "sync" -) - -// A LineTable is a data structure mapping program counters to line numbers. -// -// In Go 1.1 and earlier, each function (represented by a Func) had its own LineTable, -// and the line number corresponded to a numbering of all source lines in the -// program, across all files. That absolute line number would then have to be -// converted separately to a file name and line number within the file. -// -// In Go 1.2, the format of the data changed so that there is a single LineTable -// for the entire program, shared by all Funcs, and there are no absolute line -// numbers, just line numbers within specific files. -// -// For the most part, LineTable's methods should be treated as an internal -// detail of the package; callers should use the methods on Table instead. -type LineTable struct { - Data []byte - PC uint64 - Line int - - // Go 1.2 state - mu sync.Mutex - go12 int // is this in Go 1.2 format? -1 no, 0 unknown, 1 yes - binary binary.ByteOrder - quantum uint32 - ptrsize uint32 - functab []byte - nfunctab uint32 - filetab []byte - nfiletab uint32 - fileMap map[string]uint32 -} - -// NOTE(rsc): This is wrong for GOARCH=arm, which uses a quantum of 4, -// but we have no idea whether we're using arm or not. This only -// matters in the old (pre-Go 1.2) symbol table format, so it's not worth -// fixing. -const oldQuantum = 1 - -func (t *LineTable) parse(targetPC uint64, targetLine int) (b []byte, pc uint64, line int) { - // The PC/line table can be thought of as a sequence of - // * - // batches. Each update batch results in a (pc, line) pair, - // where line applies to every PC from pc up to but not - // including the pc of the next pair. - // - // Here we process each update individually, which simplifies - // the code, but makes the corner cases more confusing. - b, pc, line = t.Data, t.PC, t.Line - for pc <= targetPC && line != targetLine && len(b) > 0 { - code := b[0] - b = b[1:] - switch { - case code == 0: - if len(b) < 4 { - b = b[0:0] - break - } - val := binary.BigEndian.Uint32(b) - b = b[4:] - line += int(val) - case code <= 64: - line += int(code) - case code <= 128: - line -= int(code - 64) - default: - pc += oldQuantum * uint64(code-128) - continue - } - pc += oldQuantum - } - return b, pc, line -} - -func (t *LineTable) slice(pc uint64) *LineTable { - data, pc, line := t.parse(pc, -1) - return &LineTable{Data: data, PC: pc, Line: line} -} - -// PCToLine returns the line number for the given program counter. -// Callers should use Table's PCToLine method instead. -func (t *LineTable) PCToLine(pc uint64) int { - if t.isGo12() { - return t.go12PCToLine(pc) - } - _, _, line := t.parse(pc, -1) - return line -} - -// LineToPC returns the program counter for the given line number, -// considering only program counters before maxpc. -// Callers should use Table's LineToPC method instead. -func (t *LineTable) LineToPC(line int, maxpc uint64) uint64 { - if t.isGo12() { - return 0 - } - _, pc, line1 := t.parse(maxpc, line) - if line1 != line { - return 0 - } - // Subtract quantum from PC to account for post-line increment - return pc - oldQuantum -} - -// NewLineTable returns a new PC/line table -// corresponding to the encoded data. -// Text must be the start address of the -// corresponding text segment. -func NewLineTable(data []byte, text uint64) *LineTable { - return &LineTable{Data: data, PC: text, Line: 0} -} - -// Go 1.2 symbol table format. -// See golang.org/s/go12symtab. -// -// A general note about the methods here: rather than try to avoid -// index out of bounds errors, we trust Go to detect them, and then -// we recover from the panics and treat them as indicative of a malformed -// or incomplete table. -// -// The methods called by symtab.go, which begin with "go12" prefixes, -// are expected to have that recovery logic. - -// isGo12 reports whether this is a Go 1.2 (or later) symbol table. -func (t *LineTable) isGo12() bool { - t.go12Init() - return t.go12 == 1 -} - -const go12magic = 0xfffffffb - -// uintptr returns the pointer-sized value encoded at b. -// The pointer size is dictated by the table being read. -func (t *LineTable) uintptr(b []byte) uint64 { - if t.ptrsize == 4 { - return uint64(t.binary.Uint32(b)) - } - return t.binary.Uint64(b) -} - -// go12init initializes the Go 1.2 metadata if t is a Go 1.2 symbol table. -func (t *LineTable) go12Init() { - t.mu.Lock() - defer t.mu.Unlock() - if t.go12 != 0 { - return - } - - defer func() { - // If we panic parsing, assume it's not a Go 1.2 symbol table. - recover() - }() - - // Check header: 4-byte magic, two zeros, pc quantum, pointer size. - t.go12 = -1 // not Go 1.2 until proven otherwise - if len(t.Data) < 16 || t.Data[4] != 0 || t.Data[5] != 0 || - (t.Data[6] != 1 && t.Data[6] != 4) || // pc quantum - (t.Data[7] != 4 && t.Data[7] != 8) { // pointer size - return - } - - switch uint32(go12magic) { - case binary.LittleEndian.Uint32(t.Data): - t.binary = binary.LittleEndian - case binary.BigEndian.Uint32(t.Data): - t.binary = binary.BigEndian - default: - return - } - - t.quantum = uint32(t.Data[6]) - t.ptrsize = uint32(t.Data[7]) - - t.nfunctab = uint32(t.uintptr(t.Data[8:])) - t.functab = t.Data[8+t.ptrsize:] - functabsize := t.nfunctab*2*t.ptrsize + t.ptrsize - fileoff := t.binary.Uint32(t.functab[functabsize:]) - t.functab = t.functab[:functabsize] - t.filetab = t.Data[fileoff:] - t.nfiletab = t.binary.Uint32(t.filetab) - t.filetab = t.filetab[:t.nfiletab*4] - - t.go12 = 1 // so far so good -} - -// go12Funcs returns a slice of Funcs derived from the Go 1.2 pcln table. -func (t *LineTable) go12Funcs() []Func { - // Assume it is malformed and return nil on error. - defer func() { - recover() - }() - - n := len(t.functab) / int(t.ptrsize) / 2 - funcs := make([]Func, n) - for i := range funcs { - f := &funcs[i] - f.Entry = uint64(t.uintptr(t.functab[2*i*int(t.ptrsize):])) - f.End = uint64(t.uintptr(t.functab[(2*i+2)*int(t.ptrsize):])) - info := t.Data[t.uintptr(t.functab[(2*i+1)*int(t.ptrsize):]):] - f.LineTable = t - f.FrameSize = int(t.binary.Uint32(info[t.ptrsize+2*4:])) - f.Sym = &Sym{ - Value: f.Entry, - Type: 'T', - Name: t.string(t.binary.Uint32(info[t.ptrsize:])), - GoType: 0, - Func: f, - } - } - return funcs -} - -// findFunc returns the func corresponding to the given program counter. -func (t *LineTable) findFunc(pc uint64) []byte { - if pc < t.uintptr(t.functab) || pc >= t.uintptr(t.functab[len(t.functab)-int(t.ptrsize):]) { - return nil - } - - // The function table is a list of 2*nfunctab+1 uintptrs, - // alternating program counters and offsets to func structures. - f := t.functab - nf := t.nfunctab - for nf > 0 { - m := nf / 2 - fm := f[2*t.ptrsize*m:] - if t.uintptr(fm) <= pc && pc < t.uintptr(fm[2*t.ptrsize:]) { - return t.Data[t.uintptr(fm[t.ptrsize:]):] - } else if pc < t.uintptr(fm) { - nf = m - } else { - f = f[(m+1)*2*t.ptrsize:] - nf -= m + 1 - } - } - return nil -} - -// readvarint reads, removes, and returns a varint from *pp. -func (t *LineTable) readvarint(pp *[]byte) uint32 { - var v, shift uint32 - p := *pp - for shift = 0; ; shift += 7 { - b := p[0] - p = p[1:] - v |= (uint32(b) & 0x7F) << shift - if b&0x80 == 0 { - break - } - } - *pp = p - return v -} - -// string returns a Go string found at off. -func (t *LineTable) string(off uint32) string { - for i := off; ; i++ { - if t.Data[i] == 0 { - return string(t.Data[off:i]) - } - } -} - -// step advances to the next pc, value pair in the encoded table. -func (t *LineTable) step(p *[]byte, pc *uint64, val *int32, first bool) bool { - uvdelta := t.readvarint(p) - if uvdelta == 0 && !first { - return false - } - if uvdelta&1 != 0 { - uvdelta = ^(uvdelta >> 1) - } else { - uvdelta >>= 1 - } - vdelta := int32(uvdelta) - pcdelta := t.readvarint(p) * t.quantum - *pc += uint64(pcdelta) - *val += vdelta - return true -} - -// pcvalue reports the value associated with the target pc. -// off is the offset to the beginning of the pc-value table, -// and entry is the start PC for the corresponding function. -func (t *LineTable) pcvalue(off uint32, entry, targetpc uint64) int32 { - if off == 0 { - return -1 - } - p := t.Data[off:] - - val := int32(-1) - pc := entry - for t.step(&p, &pc, &val, pc == entry) { - if targetpc < pc { - return val - } - } - return -1 -} - -// findFileLine scans one function in the binary looking for a -// program counter in the given file on the given line. -// It does so by running the pc-value tables mapping program counter -// to file number. Since most functions come from a single file, these -// are usually short and quick to scan. If a file match is found, then the -// code goes to the expense of looking for a simultaneous line number match. -func (t *LineTable) findFileLine(entry uint64, filetab, linetab uint32, filenum, line int32) uint64 { - if filetab == 0 || linetab == 0 { - return 0 - } - - fp := t.Data[filetab:] - fl := t.Data[linetab:] - fileVal := int32(-1) - filePC := entry - lineVal := int32(-1) - linePC := entry - fileStartPC := filePC - for t.step(&fp, &filePC, &fileVal, filePC == entry) { - if fileVal == filenum && fileStartPC < filePC { - // fileVal is in effect starting at fileStartPC up to - // but not including filePC, and it's the file we want. - // Run the PC table looking for a matching line number - // or until we reach filePC. - lineStartPC := linePC - for linePC < filePC && t.step(&fl, &linePC, &lineVal, linePC == entry) { - // lineVal is in effect until linePC, and lineStartPC < filePC. - if lineVal == line { - if fileStartPC <= lineStartPC { - return lineStartPC - } - if fileStartPC < linePC { - return fileStartPC - } - } - lineStartPC = linePC - } - } - fileStartPC = filePC - } - return 0 -} - -// go12PCToLine maps program counter to line number for the Go 1.2 pcln table. -func (t *LineTable) go12PCToLine(pc uint64) (line int) { - defer func() { - if recover() != nil { - line = -1 - } - }() - - f := t.findFunc(pc) - if f == nil { - return -1 - } - entry := t.uintptr(f) - linetab := t.binary.Uint32(f[t.ptrsize+5*4:]) - return int(t.pcvalue(linetab, entry, pc)) -} - -// go12PCToFile maps program counter to file name for the Go 1.2 pcln table. -func (t *LineTable) go12PCToFile(pc uint64) (file string) { - defer func() { - if recover() != nil { - file = "" - } - }() - - f := t.findFunc(pc) - if f == nil { - return "" - } - entry := t.uintptr(f) - filetab := t.binary.Uint32(f[t.ptrsize+4*4:]) - fno := t.pcvalue(filetab, entry, pc) - if fno <= 0 { - return "" - } - return t.string(t.binary.Uint32(t.filetab[4*fno:])) -} - -// go12LineToPC maps a (file, line) pair to a program counter for the Go 1.2 pcln table. -func (t *LineTable) go12LineToPC(file string, line int) (pc uint64) { - defer func() { - if recover() != nil { - pc = 0 - } - }() - - t.initFileMap() - filenum := t.fileMap[file] - if filenum == 0 { - return 0 - } - - // Scan all functions. - // If this turns out to be a bottleneck, we could build a map[int32][]int32 - // mapping file number to a list of functions with code from that file. - for i := uint32(0); i < t.nfunctab; i++ { - f := t.Data[t.uintptr(t.functab[2*t.ptrsize*i+t.ptrsize:]):] - entry := t.uintptr(f) - filetab := t.binary.Uint32(f[t.ptrsize+4*4:]) - linetab := t.binary.Uint32(f[t.ptrsize+5*4:]) - pc := t.findFileLine(entry, filetab, linetab, int32(filenum), int32(line)) - if pc != 0 { - return pc - } - } - return 0 -} - -// initFileMap initializes the map from file name to file number. -func (t *LineTable) initFileMap() { - t.mu.Lock() - defer t.mu.Unlock() - - if t.fileMap != nil { - return - } - m := make(map[string]uint32) - - for i := uint32(1); i < t.nfiletab; i++ { - s := t.string(t.binary.Uint32(t.filetab[4*i:])) - m[s] = i - } - t.fileMap = m -} - -// go12MapFiles adds to m a key for every file in the Go 1.2 LineTable. -// Every key maps to obj. That's not a very interesting map, but it provides -// a way for callers to obtain the list of files in the program. -func (t *LineTable) go12MapFiles(m map[string]*Obj, obj *Obj) { - defer func() { - recover() - }() - - t.initFileMap() - for file := range t.fileMap { - m[file] = obj - } -} diff --git a/src/pkg/debug/gosym/pclntab_test.go b/src/pkg/debug/gosym/pclntab_test.go deleted file mode 100644 index 35502e8c3..000000000 --- a/src/pkg/debug/gosym/pclntab_test.go +++ /dev/null @@ -1,274 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gosym - -import ( - "debug/elf" - "fmt" - "io/ioutil" - "os" - "os/exec" - "path/filepath" - "runtime" - "strings" - "testing" -) - -var ( - pclineTempDir string - pclinetestBinary string -) - -func dotest(self bool) bool { - // For now, only works on amd64 platforms. - if runtime.GOARCH != "amd64" { - return false - } - // Self test reads test binary; only works on Linux. - if self && runtime.GOOS != "linux" { - return false - } - // Command below expects "sh", so Unix. - if runtime.GOOS == "windows" || runtime.GOOS == "plan9" { - return false - } - if pclinetestBinary != "" { - return true - } - var err error - pclineTempDir, err = ioutil.TempDir("", "pclinetest") - if err != nil { - panic(err) - } - if strings.Contains(pclineTempDir, " ") { - panic("unexpected space in tempdir") - } - // This command builds pclinetest from pclinetest.asm; - // the resulting binary looks like it was built from pclinetest.s, - // but we have renamed it to keep it away from the go tool. - pclinetestBinary = filepath.Join(pclineTempDir, "pclinetest") - command := fmt.Sprintf("go tool 6a -o %s.6 pclinetest.asm && go tool 6l -H linux -E main -o %s %s.6", - pclinetestBinary, pclinetestBinary, pclinetestBinary) - cmd := exec.Command("sh", "-c", command) - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - if err := cmd.Run(); err != nil { - panic(err) - } - return true -} - -func endtest() { - if pclineTempDir != "" { - os.RemoveAll(pclineTempDir) - pclineTempDir = "" - pclinetestBinary = "" - } -} - -func getTable(t *testing.T) *Table { - f, tab := crack(os.Args[0], t) - f.Close() - return tab -} - -func crack(file string, t *testing.T) (*elf.File, *Table) { - // Open self - f, err := elf.Open(file) - if err != nil { - t.Fatal(err) - } - return parse(file, f, t) -} - -func parse(file string, f *elf.File, t *testing.T) (*elf.File, *Table) { - symdat, err := f.Section(".gosymtab").Data() - if err != nil { - f.Close() - t.Fatalf("reading %s gosymtab: %v", file, err) - } - pclndat, err := f.Section(".gopclntab").Data() - if err != nil { - f.Close() - t.Fatalf("reading %s gopclntab: %v", file, err) - } - - pcln := NewLineTable(pclndat, f.Section(".text").Addr) - tab, err := NewTable(symdat, pcln) - if err != nil { - f.Close() - t.Fatalf("parsing %s gosymtab: %v", file, err) - } - - return f, tab -} - -var goarch = os.Getenv("O") - -func TestLineFromAline(t *testing.T) { - if !dotest(true) { - return - } - defer endtest() - - tab := getTable(t) - if tab.go12line != nil { - // aline's don't exist in the Go 1.2 table. - t.Skip("not relevant to Go 1.2 symbol table") - } - - // Find the sym package - pkg := tab.LookupFunc("debug/gosym.TestLineFromAline").Obj - if pkg == nil { - t.Fatalf("nil pkg") - } - - // Walk every absolute line and ensure that we hit every - // source line monotonically - lastline := make(map[string]int) - final := -1 - for i := 0; i < 10000; i++ { - path, line := pkg.lineFromAline(i) - // Check for end of object - if path == "" { - if final == -1 { - final = i - 1 - } - continue - } else if final != -1 { - t.Fatalf("reached end of package at absolute line %d, but absolute line %d mapped to %s:%d", final, i, path, line) - } - // It's okay to see files multiple times (e.g., sys.a) - if line == 1 { - lastline[path] = 1 - continue - } - // Check that the is the next line in path - ll, ok := lastline[path] - if !ok { - t.Errorf("file %s starts on line %d", path, line) - } else if line != ll+1 { - t.Fatalf("expected next line of file %s to be %d, got %d", path, ll+1, line) - } - lastline[path] = line - } - if final == -1 { - t.Errorf("never reached end of object") - } -} - -func TestLineAline(t *testing.T) { - if !dotest(true) { - return - } - defer endtest() - - tab := getTable(t) - if tab.go12line != nil { - // aline's don't exist in the Go 1.2 table. - t.Skip("not relevant to Go 1.2 symbol table") - } - - for _, o := range tab.Files { - // A source file can appear multiple times in a - // object. alineFromLine will always return alines in - // the first file, so track which lines we've seen. - found := make(map[string]int) - for i := 0; i < 1000; i++ { - path, line := o.lineFromAline(i) - if path == "" { - break - } - - // cgo files are full of 'Z' symbols, which we don't handle - if len(path) > 4 && path[len(path)-4:] == ".cgo" { - continue - } - - if minline, ok := found[path]; path != "" && ok { - if minline >= line { - // We've already covered this file - continue - } - } - found[path] = line - - a, err := o.alineFromLine(path, line) - if err != nil { - t.Errorf("absolute line %d in object %s maps to %s:%d, but mapping that back gives error %s", i, o.Paths[0].Name, path, line, err) - } else if a != i { - t.Errorf("absolute line %d in object %s maps to %s:%d, which maps back to absolute line %d\n", i, o.Paths[0].Name, path, line, a) - } - } - } -} - -func TestPCLine(t *testing.T) { - if !dotest(false) { - return - } - defer endtest() - - f, tab := crack(pclinetestBinary, t) - text := f.Section(".text") - textdat, err := text.Data() - if err != nil { - t.Fatalf("reading .text: %v", err) - } - - // Test PCToLine - sym := tab.LookupFunc("linefrompc") - wantLine := 0 - for pc := sym.Entry; pc < sym.End; pc++ { - off := pc - text.Addr // TODO(rsc): should not need off; bug in 8g - if textdat[off] == 255 { - break - } - wantLine += int(textdat[off]) - t.Logf("off is %d %#x (max %d)", off, textdat[off], sym.End-pc) - file, line, fn := tab.PCToLine(pc) - if fn == nil { - t.Errorf("failed to get line of PC %#x", pc) - } else if !strings.HasSuffix(file, "pclinetest.asm") || line != wantLine || fn != sym { - t.Errorf("PCToLine(%#x) = %s:%d (%s), want %s:%d (%s)", pc, file, line, fn.Name, "pclinetest.asm", wantLine, sym.Name) - } - } - - // Test LineToPC - sym = tab.LookupFunc("pcfromline") - lookupline := -1 - wantLine = 0 - off := uint64(0) // TODO(rsc): should not need off; bug in 8g - for pc := sym.Value; pc < sym.End; pc += 2 + uint64(textdat[off]) { - file, line, fn := tab.PCToLine(pc) - off = pc - text.Addr - if textdat[off] == 255 { - break - } - wantLine += int(textdat[off]) - if line != wantLine { - t.Errorf("expected line %d at PC %#x in pcfromline, got %d", wantLine, pc, line) - off = pc + 1 - text.Addr - continue - } - if lookupline == -1 { - lookupline = line - } - for ; lookupline <= line; lookupline++ { - pc2, fn2, err := tab.LineToPC(file, lookupline) - if lookupline != line { - // Should be nothing on this line - if err == nil { - t.Errorf("expected no PC at line %d, got %#x (%s)", lookupline, pc2, fn2.Name) - } - } else if err != nil { - t.Errorf("failed to get PC of line %d: %s", lookupline, err) - } else if pc != pc2 { - t.Errorf("expected PC %#x (%s) at line %d, got PC %#x (%s)", pc, fn.Name, line, pc2, fn2.Name) - } - } - off = pc + 1 - text.Addr - } -} diff --git a/src/pkg/debug/gosym/symtab.go b/src/pkg/debug/gosym/symtab.go deleted file mode 100644 index ee18499d1..000000000 --- a/src/pkg/debug/gosym/symtab.go +++ /dev/null @@ -1,710 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package gosym implements access to the Go symbol -// and line number tables embedded in Go binaries generated -// by the gc compilers. -package gosym - -// The table format is a variant of the format used in Plan 9's a.out -// format, documented at http://plan9.bell-labs.com/magic/man2html/6/a.out. -// The best reference for the differences between the Plan 9 format -// and the Go format is the runtime source, specifically ../../runtime/symtab.c. - -import ( - "bytes" - "encoding/binary" - "fmt" - "strconv" - "strings" -) - -/* - * Symbols - */ - -// A Sym represents a single symbol table entry. -type Sym struct { - Value uint64 - Type byte - Name string - GoType uint64 - // If this symbol if a function symbol, the corresponding Func - Func *Func -} - -// Static reports whether this symbol is static (not visible outside its file). -func (s *Sym) Static() bool { return s.Type >= 'a' } - -// PackageName returns the package part of the symbol name, -// or the empty string if there is none. -func (s *Sym) PackageName() string { - if i := strings.Index(s.Name, "."); i != -1 { - return s.Name[0:i] - } - return "" -} - -// ReceiverName returns the receiver type name of this symbol, -// or the empty string if there is none. -func (s *Sym) ReceiverName() string { - l := strings.Index(s.Name, ".") - r := strings.LastIndex(s.Name, ".") - if l == -1 || r == -1 || l == r { - return "" - } - return s.Name[l+1 : r] -} - -// BaseName returns the symbol name without the package or receiver name. -func (s *Sym) BaseName() string { - if i := strings.LastIndex(s.Name, "."); i != -1 { - return s.Name[i+1:] - } - return s.Name -} - -// A Func collects information about a single function. -type Func struct { - Entry uint64 - *Sym - End uint64 - Params []*Sym - Locals []*Sym - FrameSize int - LineTable *LineTable - Obj *Obj -} - -// An Obj represents a collection of functions in a symbol table. -// -// The exact method of division of a binary into separate Objs is an internal detail -// of the symbol table format. -// -// In early versions of Go each source file became a different Obj. -// -// In Go 1 and Go 1.1, each package produced one Obj for all Go sources -// and one Obj per C source file. -// -// In Go 1.2, there is a single Obj for the entire program. -type Obj struct { - // Funcs is a list of functions in the Obj. - Funcs []Func - - // In Go 1.1 and earlier, Paths is a list of symbols corresponding - // to the source file names that produced the Obj. - // In Go 1.2, Paths is nil. - // Use the keys of Table.Files to obtain a list of source files. - Paths []Sym // meta -} - -/* - * Symbol tables - */ - -// Table represents a Go symbol table. It stores all of the -// symbols decoded from the program and provides methods to translate -// between symbols, names, and addresses. -type Table struct { - Syms []Sym - Funcs []Func - Files map[string]*Obj // nil for Go 1.2 and later binaries - Objs []Obj // nil for Go 1.2 and later binaries - - go12line *LineTable // Go 1.2 line number table -} - -type sym struct { - value uint64 - gotype uint64 - typ byte - name []byte -} - -var ( - littleEndianSymtab = []byte{0xFD, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00} - bigEndianSymtab = []byte{0xFF, 0xFF, 0xFF, 0xFD, 0x00, 0x00, 0x00} - oldLittleEndianSymtab = []byte{0xFE, 0xFF, 0xFF, 0xFF, 0x00, 0x00} -) - -func walksymtab(data []byte, fn func(sym) error) error { - if len(data) == 0 { // missing symtab is okay - return nil - } - var order binary.ByteOrder = binary.BigEndian - newTable := false - switch { - case bytes.HasPrefix(data, oldLittleEndianSymtab): - // Same as Go 1.0, but little endian. - // Format was used during interim development between Go 1.0 and Go 1.1. - // Should not be widespread, but easy to support. - data = data[6:] - order = binary.LittleEndian - case bytes.HasPrefix(data, bigEndianSymtab): - newTable = true - case bytes.HasPrefix(data, littleEndianSymtab): - newTable = true - order = binary.LittleEndian - } - var ptrsz int - if newTable { - if len(data) < 8 { - return &DecodingError{len(data), "unexpected EOF", nil} - } - ptrsz = int(data[7]) - if ptrsz != 4 && ptrsz != 8 { - return &DecodingError{7, "invalid pointer size", ptrsz} - } - data = data[8:] - } - var s sym - p := data - for len(p) >= 4 { - var typ byte - if newTable { - // Symbol type, value, Go type. - typ = p[0] & 0x3F - wideValue := p[0]&0x40 != 0 - goType := p[0]&0x80 != 0 - if typ < 26 { - typ += 'A' - } else { - typ += 'a' - 26 - } - s.typ = typ - p = p[1:] - if wideValue { - if len(p) < ptrsz { - return &DecodingError{len(data), "unexpected EOF", nil} - } - // fixed-width value - if ptrsz == 8 { - s.value = order.Uint64(p[0:8]) - p = p[8:] - } else { - s.value = uint64(order.Uint32(p[0:4])) - p = p[4:] - } - } else { - // varint value - s.value = 0 - shift := uint(0) - for len(p) > 0 && p[0]&0x80 != 0 { - s.value |= uint64(p[0]&0x7F) << shift - shift += 7 - p = p[1:] - } - if len(p) == 0 { - return &DecodingError{len(data), "unexpected EOF", nil} - } - s.value |= uint64(p[0]) << shift - p = p[1:] - } - if goType { - if len(p) < ptrsz { - return &DecodingError{len(data), "unexpected EOF", nil} - } - // fixed-width go type - if ptrsz == 8 { - s.gotype = order.Uint64(p[0:8]) - p = p[8:] - } else { - s.gotype = uint64(order.Uint32(p[0:4])) - p = p[4:] - } - } - } else { - // Value, symbol type. - s.value = uint64(order.Uint32(p[0:4])) - if len(p) < 5 { - return &DecodingError{len(data), "unexpected EOF", nil} - } - typ = p[4] - if typ&0x80 == 0 { - return &DecodingError{len(data) - len(p) + 4, "bad symbol type", typ} - } - typ &^= 0x80 - s.typ = typ - p = p[5:] - } - - // Name. - var i int - var nnul int - for i = 0; i < len(p); i++ { - if p[i] == 0 { - nnul = 1 - break - } - } - switch typ { - case 'z', 'Z': - p = p[i+nnul:] - for i = 0; i+2 <= len(p); i += 2 { - if p[i] == 0 && p[i+1] == 0 { - nnul = 2 - break - } - } - } - if len(p) < i+nnul { - return &DecodingError{len(data), "unexpected EOF", nil} - } - s.name = p[0:i] - i += nnul - p = p[i:] - - if !newTable { - if len(p) < 4 { - return &DecodingError{len(data), "unexpected EOF", nil} - } - // Go type. - s.gotype = uint64(order.Uint32(p[:4])) - p = p[4:] - } - fn(s) - } - return nil -} - -// NewTable decodes the Go symbol table in data, -// returning an in-memory representation. -func NewTable(symtab []byte, pcln *LineTable) (*Table, error) { - var n int - err := walksymtab(symtab, func(s sym) error { - n++ - return nil - }) - if err != nil { - return nil, err - } - - var t Table - if pcln.isGo12() { - t.go12line = pcln - } - fname := make(map[uint16]string) - t.Syms = make([]Sym, 0, n) - nf := 0 - nz := 0 - lasttyp := uint8(0) - err = walksymtab(symtab, func(s sym) error { - n := len(t.Syms) - t.Syms = t.Syms[0 : n+1] - ts := &t.Syms[n] - ts.Type = s.typ - ts.Value = uint64(s.value) - ts.GoType = uint64(s.gotype) - switch s.typ { - default: - // rewrite name to use . instead of · (c2 b7) - w := 0 - b := s.name - for i := 0; i < len(b); i++ { - if b[i] == 0xc2 && i+1 < len(b) && b[i+1] == 0xb7 { - i++ - b[i] = '.' - } - b[w] = b[i] - w++ - } - ts.Name = string(s.name[0:w]) - case 'z', 'Z': - if lasttyp != 'z' && lasttyp != 'Z' { - nz++ - } - for i := 0; i < len(s.name); i += 2 { - eltIdx := binary.BigEndian.Uint16(s.name[i : i+2]) - elt, ok := fname[eltIdx] - if !ok { - return &DecodingError{-1, "bad filename code", eltIdx} - } - if n := len(ts.Name); n > 0 && ts.Name[n-1] != '/' { - ts.Name += "/" - } - ts.Name += elt - } - } - switch s.typ { - case 'T', 't', 'L', 'l': - nf++ - case 'f': - fname[uint16(s.value)] = ts.Name - } - lasttyp = s.typ - return nil - }) - if err != nil { - return nil, err - } - - t.Funcs = make([]Func, 0, nf) - t.Files = make(map[string]*Obj) - - var obj *Obj - if t.go12line != nil { - // Put all functions into one Obj. - t.Objs = make([]Obj, 1) - obj = &t.Objs[0] - t.go12line.go12MapFiles(t.Files, obj) - } else { - t.Objs = make([]Obj, 0, nz) - } - - // Count text symbols and attach frame sizes, parameters, and - // locals to them. Also, find object file boundaries. - lastf := 0 - for i := 0; i < len(t.Syms); i++ { - sym := &t.Syms[i] - switch sym.Type { - case 'Z', 'z': // path symbol - if t.go12line != nil { - // Go 1.2 binaries have the file information elsewhere. Ignore. - break - } - // Finish the current object - if obj != nil { - obj.Funcs = t.Funcs[lastf:] - } - lastf = len(t.Funcs) - - // Start new object - n := len(t.Objs) - t.Objs = t.Objs[0 : n+1] - obj = &t.Objs[n] - - // Count & copy path symbols - var end int - for end = i + 1; end < len(t.Syms); end++ { - if c := t.Syms[end].Type; c != 'Z' && c != 'z' { - break - } - } - obj.Paths = t.Syms[i:end] - i = end - 1 // loop will i++ - - // Record file names - depth := 0 - for j := range obj.Paths { - s := &obj.Paths[j] - if s.Name == "" { - depth-- - } else { - if depth == 0 { - t.Files[s.Name] = obj - } - depth++ - } - } - - case 'T', 't', 'L', 'l': // text symbol - if n := len(t.Funcs); n > 0 { - t.Funcs[n-1].End = sym.Value - } - if sym.Name == "runtime.etext" || sym.Name == "etext" { - continue - } - - // Count parameter and local (auto) syms - var np, na int - var end int - countloop: - for end = i + 1; end < len(t.Syms); end++ { - switch t.Syms[end].Type { - case 'T', 't', 'L', 'l', 'Z', 'z': - break countloop - case 'p': - np++ - case 'a': - na++ - } - } - - // Fill in the function symbol - n := len(t.Funcs) - t.Funcs = t.Funcs[0 : n+1] - fn := &t.Funcs[n] - sym.Func = fn - fn.Params = make([]*Sym, 0, np) - fn.Locals = make([]*Sym, 0, na) - fn.Sym = sym - fn.Entry = sym.Value - fn.Obj = obj - if t.go12line != nil { - // All functions share the same line table. - // It knows how to narrow down to a specific - // function quickly. - fn.LineTable = t.go12line - } else if pcln != nil { - fn.LineTable = pcln.slice(fn.Entry) - pcln = fn.LineTable - } - for j := i; j < end; j++ { - s := &t.Syms[j] - switch s.Type { - case 'm': - fn.FrameSize = int(s.Value) - case 'p': - n := len(fn.Params) - fn.Params = fn.Params[0 : n+1] - fn.Params[n] = s - case 'a': - n := len(fn.Locals) - fn.Locals = fn.Locals[0 : n+1] - fn.Locals[n] = s - } - } - i = end - 1 // loop will i++ - } - } - - if t.go12line != nil && nf == 0 { - t.Funcs = t.go12line.go12Funcs() - } - if obj != nil { - obj.Funcs = t.Funcs[lastf:] - } - return &t, nil -} - -// PCToFunc returns the function containing the program counter pc, -// or nil if there is no such function. -func (t *Table) PCToFunc(pc uint64) *Func { - funcs := t.Funcs - for len(funcs) > 0 { - m := len(funcs) / 2 - fn := &funcs[m] - switch { - case pc < fn.Entry: - funcs = funcs[0:m] - case fn.Entry <= pc && pc < fn.End: - return fn - default: - funcs = funcs[m+1:] - } - } - return nil -} - -// PCToLine looks up line number information for a program counter. -// If there is no information, it returns fn == nil. -func (t *Table) PCToLine(pc uint64) (file string, line int, fn *Func) { - if fn = t.PCToFunc(pc); fn == nil { - return - } - if t.go12line != nil { - file = t.go12line.go12PCToFile(pc) - line = t.go12line.go12PCToLine(pc) - } else { - file, line = fn.Obj.lineFromAline(fn.LineTable.PCToLine(pc)) - } - return -} - -// LineToPC looks up the first program counter on the given line in -// the named file. It returns UnknownPathError or UnknownLineError if -// there is an error looking up this line. -func (t *Table) LineToPC(file string, line int) (pc uint64, fn *Func, err error) { - obj, ok := t.Files[file] - if !ok { - return 0, nil, UnknownFileError(file) - } - - if t.go12line != nil { - pc := t.go12line.go12LineToPC(file, line) - if pc == 0 { - return 0, nil, &UnknownLineError{file, line} - } - return pc, t.PCToFunc(pc), nil - } - - abs, err := obj.alineFromLine(file, line) - if err != nil { - return - } - for i := range obj.Funcs { - f := &obj.Funcs[i] - pc := f.LineTable.LineToPC(abs, f.End) - if pc != 0 { - return pc, f, nil - } - } - return 0, nil, &UnknownLineError{file, line} -} - -// LookupSym returns the text, data, or bss symbol with the given name, -// or nil if no such symbol is found. -func (t *Table) LookupSym(name string) *Sym { - // TODO(austin) Maybe make a map - for i := range t.Syms { - s := &t.Syms[i] - switch s.Type { - case 'T', 't', 'L', 'l', 'D', 'd', 'B', 'b': - if s.Name == name { - return s - } - } - } - return nil -} - -// LookupFunc returns the text, data, or bss symbol with the given name, -// or nil if no such symbol is found. -func (t *Table) LookupFunc(name string) *Func { - for i := range t.Funcs { - f := &t.Funcs[i] - if f.Sym.Name == name { - return f - } - } - return nil -} - -// SymByAddr returns the text, data, or bss symbol starting at the given address. -func (t *Table) SymByAddr(addr uint64) *Sym { - for i := range t.Syms { - s := &t.Syms[i] - switch s.Type { - case 'T', 't', 'L', 'l', 'D', 'd', 'B', 'b': - if s.Value == addr { - return s - } - } - } - return nil -} - -/* - * Object files - */ - -// This is legacy code for Go 1.1 and earlier, which used the -// Plan 9 format for pc-line tables. This code was never quite -// correct. It's probably very close, and it's usually correct, but -// we never quite found all the corner cases. -// -// Go 1.2 and later use a simpler format, documented at golang.org/s/go12symtab. - -func (o *Obj) lineFromAline(aline int) (string, int) { - type stackEnt struct { - path string - start int - offset int - prev *stackEnt - } - - noPath := &stackEnt{"", 0, 0, nil} - tos := noPath - -pathloop: - for _, s := range o.Paths { - val := int(s.Value) - switch { - case val > aline: - break pathloop - - case val == 1: - // Start a new stack - tos = &stackEnt{s.Name, val, 0, noPath} - - case s.Name == "": - // Pop - if tos == noPath { - return "", 0 - } - tos.prev.offset += val - tos.start - tos = tos.prev - - default: - // Push - tos = &stackEnt{s.Name, val, 0, tos} - } - } - - if tos == noPath { - return "", 0 - } - return tos.path, aline - tos.start - tos.offset + 1 -} - -func (o *Obj) alineFromLine(path string, line int) (int, error) { - if line < 1 { - return 0, &UnknownLineError{path, line} - } - - for i, s := range o.Paths { - // Find this path - if s.Name != path { - continue - } - - // Find this line at this stack level - depth := 0 - var incstart int - line += int(s.Value) - pathloop: - for _, s := range o.Paths[i:] { - val := int(s.Value) - switch { - case depth == 1 && val >= line: - return line - 1, nil - - case s.Name == "": - depth-- - if depth == 0 { - break pathloop - } else if depth == 1 { - line += val - incstart - } - - default: - if depth == 1 { - incstart = val - } - depth++ - } - } - return 0, &UnknownLineError{path, line} - } - return 0, UnknownFileError(path) -} - -/* - * Errors - */ - -// UnknownFileError represents a failure to find the specific file in -// the symbol table. -type UnknownFileError string - -func (e UnknownFileError) Error() string { return "unknown file: " + string(e) } - -// UnknownLineError represents a failure to map a line to a program -// counter, either because the line is beyond the bounds of the file -// or because there is no code on the given line. -type UnknownLineError struct { - File string - Line int -} - -func (e *UnknownLineError) Error() string { - return "no code at " + e.File + ":" + strconv.Itoa(e.Line) -} - -// DecodingError represents an error during the decoding of -// the symbol table. -type DecodingError struct { - off int - msg string - val interface{} -} - -func (e *DecodingError) Error() string { - msg := e.msg - if e.val != nil { - msg += fmt.Sprintf(" '%v'", e.val) - } - msg += fmt.Sprintf(" at byte %#x", e.off) - return msg -} diff --git a/src/pkg/debug/macho/fat.go b/src/pkg/debug/macho/fat.go deleted file mode 100644 index 93b831526..000000000 --- a/src/pkg/debug/macho/fat.go +++ /dev/null @@ -1,146 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package macho - -import ( - "encoding/binary" - "fmt" - "io" - "os" -) - -// A FatFile is a Mach-O universal binary that contains at least one architecture. -type FatFile struct { - Magic uint32 - Arches []FatArch - closer io.Closer -} - -// A FatArchHeader represents a fat header for a specific image architecture. -type FatArchHeader struct { - Cpu Cpu - SubCpu uint32 - Offset uint32 - Size uint32 - Align uint32 -} - -const fatArchHeaderSize = 5 * 4 - -// A FatArch is a Mach-O File inside a FatFile. -type FatArch struct { - FatArchHeader - *File -} - -// ErrNotFat is returned from NewFatFile or OpenFat when the file is not a -// universal binary but may be a thin binary, based on its magic number. -var ErrNotFat = &FormatError{0, "not a fat Mach-O file", nil} - -// NewFatFile creates a new FatFile for accessing all the Mach-O images in a -// universal binary. The Mach-O binary is expected to start at position 0 in -// the ReaderAt. -func NewFatFile(r io.ReaderAt) (*FatFile, error) { - var ff FatFile - sr := io.NewSectionReader(r, 0, 1<<63-1) - - // Read the fat_header struct, which is always in big endian. - // Start with the magic number. - err := binary.Read(sr, binary.BigEndian, &ff.Magic) - if err != nil { - return nil, &FormatError{0, "error reading magic number", nil} - } else if ff.Magic != MagicFat { - // See if this is a Mach-O file via its magic number. The magic - // must be converted to little endian first though. - var buf [4]byte - binary.BigEndian.PutUint32(buf[:], ff.Magic) - leMagic := binary.LittleEndian.Uint32(buf[:]) - if leMagic == Magic32 || leMagic == Magic64 { - return nil, ErrNotFat - } else { - return nil, &FormatError{0, "invalid magic number", nil} - } - } - offset := int64(4) - - // Read the number of FatArchHeaders that come after the fat_header. - var narch uint32 - err = binary.Read(sr, binary.BigEndian, &narch) - if err != nil { - return nil, &FormatError{offset, "invalid fat_header", nil} - } - offset += 4 - - if narch < 1 { - return nil, &FormatError{offset, "file contains no images", nil} - } - - // Combine the Cpu and SubCpu (both uint32) into a uint64 to make sure - // there are not duplicate architectures. - seenArches := make(map[uint64]bool, narch) - // Make sure that all images are for the same MH_ type. - var machoType Type - - // Following the fat_header comes narch fat_arch structs that index - // Mach-O images further in the file. - ff.Arches = make([]FatArch, narch) - for i := uint32(0); i < narch; i++ { - fa := &ff.Arches[i] - err = binary.Read(sr, binary.BigEndian, &fa.FatArchHeader) - if err != nil { - return nil, &FormatError{offset, "invalid fat_arch header", nil} - } - offset += fatArchHeaderSize - - fr := io.NewSectionReader(r, int64(fa.Offset), int64(fa.Size)) - fa.File, err = NewFile(fr) - if err != nil { - return nil, err - } - - // Make sure the architecture for this image is not duplicate. - seenArch := (uint64(fa.Cpu) << 32) | uint64(fa.SubCpu) - if o, k := seenArches[seenArch]; o || k { - return nil, &FormatError{offset, fmt.Sprintf("duplicate architecture cpu=%v, subcpu=%#x", fa.Cpu, fa.SubCpu), nil} - } - seenArches[seenArch] = true - - // Make sure the Mach-O type matches that of the first image. - if i == 0 { - machoType = fa.Type - } else { - if fa.Type != machoType { - return nil, &FormatError{offset, fmt.Sprintf("Mach-O type for architecture #%d (type=%#x) does not match first (type=%#x)", i, fa.Type, machoType), nil} - } - } - } - - return &ff, nil -} - -// OpenFat opens the named file using os.Open and prepares it for use as a Mach-O -// universal binary. -func OpenFat(name string) (ff *FatFile, err error) { - f, err := os.Open(name) - if err != nil { - return nil, err - } - ff, err = NewFatFile(f) - if err != nil { - f.Close() - return nil, err - } - ff.closer = f - return -} - -func (ff *FatFile) Close() error { - var err error - if ff.closer != nil { - err = ff.closer.Close() - ff.closer = nil - } - return err -} diff --git a/src/pkg/debug/macho/file.go b/src/pkg/debug/macho/file.go deleted file mode 100644 index eefb74444..000000000 --- a/src/pkg/debug/macho/file.go +++ /dev/null @@ -1,524 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package macho implements access to Mach-O object files. -package macho - -// High level access to low level data structures. - -import ( - "bytes" - "debug/dwarf" - "encoding/binary" - "fmt" - "io" - "os" -) - -// A File represents an open Mach-O file. -type File struct { - FileHeader - ByteOrder binary.ByteOrder - Loads []Load - Sections []*Section - - Symtab *Symtab - Dysymtab *Dysymtab - - closer io.Closer -} - -// A Load represents any Mach-O load command. -type Load interface { - Raw() []byte -} - -// A LoadBytes is the uninterpreted bytes of a Mach-O load command. -type LoadBytes []byte - -func (b LoadBytes) Raw() []byte { return b } - -// A SegmentHeader is the header for a Mach-O 32-bit or 64-bit load segment command. -type SegmentHeader struct { - Cmd LoadCmd - Len uint32 - Name string - Addr uint64 - Memsz uint64 - Offset uint64 - Filesz uint64 - Maxprot uint32 - Prot uint32 - Nsect uint32 - Flag uint32 -} - -// A Segment represents a Mach-O 32-bit or 64-bit load segment command. -type Segment struct { - LoadBytes - SegmentHeader - - // Embed ReaderAt for ReadAt method. - // Do not embed SectionReader directly - // to avoid having Read and Seek. - // If a client wants Read and Seek it must use - // Open() to avoid fighting over the seek offset - // with other clients. - io.ReaderAt - sr *io.SectionReader -} - -// Data reads and returns the contents of the segment. -func (s *Segment) Data() ([]byte, error) { - dat := make([]byte, s.sr.Size()) - n, err := s.sr.ReadAt(dat, 0) - if n == len(dat) { - err = nil - } - return dat[0:n], err -} - -// Open returns a new ReadSeeker reading the segment. -func (s *Segment) Open() io.ReadSeeker { return io.NewSectionReader(s.sr, 0, 1<<63-1) } - -type SectionHeader struct { - Name string - Seg string - Addr uint64 - Size uint64 - Offset uint32 - Align uint32 - Reloff uint32 - Nreloc uint32 - Flags uint32 -} - -type Section struct { - SectionHeader - - // Embed ReaderAt for ReadAt method. - // Do not embed SectionReader directly - // to avoid having Read and Seek. - // If a client wants Read and Seek it must use - // Open() to avoid fighting over the seek offset - // with other clients. - io.ReaderAt - sr *io.SectionReader -} - -// Data reads and returns the contents of the Mach-O section. -func (s *Section) Data() ([]byte, error) { - dat := make([]byte, s.sr.Size()) - n, err := s.sr.ReadAt(dat, 0) - if n == len(dat) { - err = nil - } - return dat[0:n], err -} - -// Open returns a new ReadSeeker reading the Mach-O section. -func (s *Section) Open() io.ReadSeeker { return io.NewSectionReader(s.sr, 0, 1<<63-1) } - -// A Dylib represents a Mach-O load dynamic library command. -type Dylib struct { - LoadBytes - Name string - Time uint32 - CurrentVersion uint32 - CompatVersion uint32 -} - -// A Symtab represents a Mach-O symbol table command. -type Symtab struct { - LoadBytes - SymtabCmd - Syms []Symbol -} - -// A Dysymtab represents a Mach-O dynamic symbol table command. -type Dysymtab struct { - LoadBytes - DysymtabCmd - IndirectSyms []uint32 // indices into Symtab.Syms -} - -/* - * Mach-O reader - */ - -// FormatError is returned by some operations if the data does -// not have the correct format for an object file. -type FormatError struct { - off int64 - msg string - val interface{} -} - -func (e *FormatError) Error() string { - msg := e.msg - if e.val != nil { - msg += fmt.Sprintf(" '%v'", e.val) - } - msg += fmt.Sprintf(" in record at byte %#x", e.off) - return msg -} - -// Open opens the named file using os.Open and prepares it for use as a Mach-O binary. -func Open(name string) (*File, error) { - f, err := os.Open(name) - if err != nil { - return nil, err - } - ff, err := NewFile(f) - if err != nil { - f.Close() - return nil, err - } - ff.closer = f - return ff, nil -} - -// Close closes the File. -// If the File was created using NewFile directly instead of Open, -// Close has no effect. -func (f *File) Close() error { - var err error - if f.closer != nil { - err = f.closer.Close() - f.closer = nil - } - return err -} - -// NewFile creates a new File for accessing a Mach-O binary in an underlying reader. -// The Mach-O binary is expected to start at position 0 in the ReaderAt. -func NewFile(r io.ReaderAt) (*File, error) { - f := new(File) - sr := io.NewSectionReader(r, 0, 1<<63-1) - - // Read and decode Mach magic to determine byte order, size. - // Magic32 and Magic64 differ only in the bottom bit. - var ident [4]byte - if _, err := r.ReadAt(ident[0:], 0); err != nil { - return nil, err - } - be := binary.BigEndian.Uint32(ident[0:]) - le := binary.LittleEndian.Uint32(ident[0:]) - switch Magic32 &^ 1 { - case be &^ 1: - f.ByteOrder = binary.BigEndian - f.Magic = be - case le &^ 1: - f.ByteOrder = binary.LittleEndian - f.Magic = le - default: - return nil, &FormatError{0, "invalid magic number", nil} - } - - // Read entire file header. - if err := binary.Read(sr, f.ByteOrder, &f.FileHeader); err != nil { - return nil, err - } - - // Then load commands. - offset := int64(fileHeaderSize32) - if f.Magic == Magic64 { - offset = fileHeaderSize64 - } - dat := make([]byte, f.Cmdsz) - if _, err := r.ReadAt(dat, offset); err != nil { - return nil, err - } - f.Loads = make([]Load, f.Ncmd) - bo := f.ByteOrder - for i := range f.Loads { - // Each load command begins with uint32 command and length. - if len(dat) < 8 { - return nil, &FormatError{offset, "command block too small", nil} - } - cmd, siz := LoadCmd(bo.Uint32(dat[0:4])), bo.Uint32(dat[4:8]) - if siz < 8 || siz > uint32(len(dat)) { - return nil, &FormatError{offset, "invalid command block size", nil} - } - var cmddat []byte - cmddat, dat = dat[0:siz], dat[siz:] - offset += int64(siz) - var s *Segment - switch cmd { - default: - f.Loads[i] = LoadBytes(cmddat) - - case LoadCmdDylib: - var hdr DylibCmd - b := bytes.NewReader(cmddat) - if err := binary.Read(b, bo, &hdr); err != nil { - return nil, err - } - l := new(Dylib) - if hdr.Name >= uint32(len(cmddat)) { - return nil, &FormatError{offset, "invalid name in dynamic library command", hdr.Name} - } - l.Name = cstring(cmddat[hdr.Name:]) - l.Time = hdr.Time - l.CurrentVersion = hdr.CurrentVersion - l.CompatVersion = hdr.CompatVersion - l.LoadBytes = LoadBytes(cmddat) - f.Loads[i] = l - - case LoadCmdSymtab: - var hdr SymtabCmd - b := bytes.NewReader(cmddat) - if err := binary.Read(b, bo, &hdr); err != nil { - return nil, err - } - strtab := make([]byte, hdr.Strsize) - if _, err := r.ReadAt(strtab, int64(hdr.Stroff)); err != nil { - return nil, err - } - var symsz int - if f.Magic == Magic64 { - symsz = 16 - } else { - symsz = 12 - } - symdat := make([]byte, int(hdr.Nsyms)*symsz) - if _, err := r.ReadAt(symdat, int64(hdr.Symoff)); err != nil { - return nil, err - } - st, err := f.parseSymtab(symdat, strtab, cmddat, &hdr, offset) - if err != nil { - return nil, err - } - f.Loads[i] = st - f.Symtab = st - - case LoadCmdDysymtab: - var hdr DysymtabCmd - b := bytes.NewReader(cmddat) - if err := binary.Read(b, bo, &hdr); err != nil { - return nil, err - } - dat := make([]byte, hdr.Nindirectsyms*4) - if _, err := r.ReadAt(dat, int64(hdr.Indirectsymoff)); err != nil { - return nil, err - } - x := make([]uint32, hdr.Nindirectsyms) - if err := binary.Read(bytes.NewReader(dat), bo, x); err != nil { - return nil, err - } - st := new(Dysymtab) - st.LoadBytes = LoadBytes(cmddat) - st.DysymtabCmd = hdr - st.IndirectSyms = x - f.Loads[i] = st - f.Dysymtab = st - - case LoadCmdSegment: - var seg32 Segment32 - b := bytes.NewReader(cmddat) - if err := binary.Read(b, bo, &seg32); err != nil { - return nil, err - } - s = new(Segment) - s.LoadBytes = cmddat - s.Cmd = cmd - s.Len = siz - s.Name = cstring(seg32.Name[0:]) - s.Addr = uint64(seg32.Addr) - s.Memsz = uint64(seg32.Memsz) - s.Offset = uint64(seg32.Offset) - s.Filesz = uint64(seg32.Filesz) - s.Maxprot = seg32.Maxprot - s.Prot = seg32.Prot - s.Nsect = seg32.Nsect - s.Flag = seg32.Flag - f.Loads[i] = s - for i := 0; i < int(s.Nsect); i++ { - var sh32 Section32 - if err := binary.Read(b, bo, &sh32); err != nil { - return nil, err - } - sh := new(Section) - sh.Name = cstring(sh32.Name[0:]) - sh.Seg = cstring(sh32.Seg[0:]) - sh.Addr = uint64(sh32.Addr) - sh.Size = uint64(sh32.Size) - sh.Offset = sh32.Offset - sh.Align = sh32.Align - sh.Reloff = sh32.Reloff - sh.Nreloc = sh32.Nreloc - sh.Flags = sh32.Flags - f.pushSection(sh, r) - } - - case LoadCmdSegment64: - var seg64 Segment64 - b := bytes.NewReader(cmddat) - if err := binary.Read(b, bo, &seg64); err != nil { - return nil, err - } - s = new(Segment) - s.LoadBytes = cmddat - s.Cmd = cmd - s.Len = siz - s.Name = cstring(seg64.Name[0:]) - s.Addr = seg64.Addr - s.Memsz = seg64.Memsz - s.Offset = seg64.Offset - s.Filesz = seg64.Filesz - s.Maxprot = seg64.Maxprot - s.Prot = seg64.Prot - s.Nsect = seg64.Nsect - s.Flag = seg64.Flag - f.Loads[i] = s - for i := 0; i < int(s.Nsect); i++ { - var sh64 Section64 - if err := binary.Read(b, bo, &sh64); err != nil { - return nil, err - } - sh := new(Section) - sh.Name = cstring(sh64.Name[0:]) - sh.Seg = cstring(sh64.Seg[0:]) - sh.Addr = sh64.Addr - sh.Size = sh64.Size - sh.Offset = sh64.Offset - sh.Align = sh64.Align - sh.Reloff = sh64.Reloff - sh.Nreloc = sh64.Nreloc - sh.Flags = sh64.Flags - f.pushSection(sh, r) - } - } - if s != nil { - s.sr = io.NewSectionReader(r, int64(s.Offset), int64(s.Filesz)) - s.ReaderAt = s.sr - } - } - return f, nil -} - -func (f *File) parseSymtab(symdat, strtab, cmddat []byte, hdr *SymtabCmd, offset int64) (*Symtab, error) { - bo := f.ByteOrder - symtab := make([]Symbol, hdr.Nsyms) - b := bytes.NewReader(symdat) - for i := range symtab { - var n Nlist64 - if f.Magic == Magic64 { - if err := binary.Read(b, bo, &n); err != nil { - return nil, err - } - } else { - var n32 Nlist32 - if err := binary.Read(b, bo, &n32); err != nil { - return nil, err - } - n.Name = n32.Name - n.Type = n32.Type - n.Sect = n32.Sect - n.Desc = n32.Desc - n.Value = uint64(n32.Value) - } - sym := &symtab[i] - if n.Name >= uint32(len(strtab)) { - return nil, &FormatError{offset, "invalid name in symbol table", n.Name} - } - sym.Name = cstring(strtab[n.Name:]) - sym.Type = n.Type - sym.Sect = n.Sect - sym.Desc = n.Desc - sym.Value = n.Value - } - st := new(Symtab) - st.LoadBytes = LoadBytes(cmddat) - st.Syms = symtab - return st, nil -} - -func (f *File) pushSection(sh *Section, r io.ReaderAt) { - f.Sections = append(f.Sections, sh) - sh.sr = io.NewSectionReader(r, int64(sh.Offset), int64(sh.Size)) - sh.ReaderAt = sh.sr -} - -func cstring(b []byte) string { - var i int - for i = 0; i < len(b) && b[i] != 0; i++ { - } - return string(b[0:i]) -} - -// Segment returns the first Segment with the given name, or nil if no such segment exists. -func (f *File) Segment(name string) *Segment { - for _, l := range f.Loads { - if s, ok := l.(*Segment); ok && s.Name == name { - return s - } - } - return nil -} - -// Section returns the first section with the given name, or nil if no such -// section exists. -func (f *File) Section(name string) *Section { - for _, s := range f.Sections { - if s.Name == name { - return s - } - } - return nil -} - -// DWARF returns the DWARF debug information for the Mach-O file. -func (f *File) DWARF() (*dwarf.Data, error) { - // There are many other DWARF sections, but these - // are the required ones, and the debug/dwarf package - // does not use the others, so don't bother loading them. - var names = [...]string{"abbrev", "info", "str"} - var dat [len(names)][]byte - for i, name := range names { - name = "__debug_" + name - s := f.Section(name) - if s == nil { - continue - } - b, err := s.Data() - if err != nil && uint64(len(b)) < s.Size { - return nil, err - } - dat[i] = b - } - - abbrev, info, str := dat[0], dat[1], dat[2] - return dwarf.New(abbrev, nil, nil, info, nil, nil, nil, str) -} - -// ImportedSymbols returns the names of all symbols -// referred to by the binary f that are expected to be -// satisfied by other libraries at dynamic load time. -func (f *File) ImportedSymbols() ([]string, error) { - if f.Dysymtab == nil || f.Symtab == nil { - return nil, &FormatError{0, "missing symbol table", nil} - } - - st := f.Symtab - dt := f.Dysymtab - var all []string - for _, s := range st.Syms[dt.Iundefsym : dt.Iundefsym+dt.Nundefsym] { - all = append(all, s.Name) - } - return all, nil -} - -// ImportedLibraries returns the paths of all libraries -// referred to by the binary f that are expected to be -// linked with the binary at dynamic link time. -func (f *File) ImportedLibraries() ([]string, error) { - var all []string - for _, l := range f.Loads { - if lib, ok := l.(*Dylib); ok { - all = append(all, lib.Name) - } - } - return all, nil -} diff --git a/src/pkg/debug/macho/file_test.go b/src/pkg/debug/macho/file_test.go deleted file mode 100644 index 4797780ce..000000000 --- a/src/pkg/debug/macho/file_test.go +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package macho - -import ( - "reflect" - "testing" -) - -type fileTest struct { - file string - hdr FileHeader - segments []*SegmentHeader - sections []*SectionHeader -} - -var fileTests = []fileTest{ - { - "testdata/gcc-386-darwin-exec", - FileHeader{0xfeedface, Cpu386, 0x3, 0x2, 0xc, 0x3c0, 0x85}, - []*SegmentHeader{ - {LoadCmdSegment, 0x38, "__PAGEZERO", 0x0, 0x1000, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, - {LoadCmdSegment, 0xc0, "__TEXT", 0x1000, 0x1000, 0x0, 0x1000, 0x7, 0x5, 0x2, 0x0}, - {LoadCmdSegment, 0xc0, "__DATA", 0x2000, 0x1000, 0x1000, 0x1000, 0x7, 0x3, 0x2, 0x0}, - {LoadCmdSegment, 0x7c, "__IMPORT", 0x3000, 0x1000, 0x2000, 0x1000, 0x7, 0x7, 0x1, 0x0}, - {LoadCmdSegment, 0x38, "__LINKEDIT", 0x4000, 0x1000, 0x3000, 0x12c, 0x7, 0x1, 0x0, 0x0}, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - }, - []*SectionHeader{ - {"__text", "__TEXT", 0x1f68, 0x88, 0xf68, 0x2, 0x0, 0x0, 0x80000400}, - {"__cstring", "__TEXT", 0x1ff0, 0xd, 0xff0, 0x0, 0x0, 0x0, 0x2}, - {"__data", "__DATA", 0x2000, 0x14, 0x1000, 0x2, 0x0, 0x0, 0x0}, - {"__dyld", "__DATA", 0x2014, 0x1c, 0x1014, 0x2, 0x0, 0x0, 0x0}, - {"__jump_table", "__IMPORT", 0x3000, 0xa, 0x2000, 0x6, 0x0, 0x0, 0x4000008}, - }, - }, - { - "testdata/gcc-amd64-darwin-exec", - FileHeader{0xfeedfacf, CpuAmd64, 0x80000003, 0x2, 0xb, 0x568, 0x85}, - []*SegmentHeader{ - {LoadCmdSegment64, 0x48, "__PAGEZERO", 0x0, 0x100000000, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}, - {LoadCmdSegment64, 0x1d8, "__TEXT", 0x100000000, 0x1000, 0x0, 0x1000, 0x7, 0x5, 0x5, 0x0}, - {LoadCmdSegment64, 0x138, "__DATA", 0x100001000, 0x1000, 0x1000, 0x1000, 0x7, 0x3, 0x3, 0x0}, - {LoadCmdSegment64, 0x48, "__LINKEDIT", 0x100002000, 0x1000, 0x2000, 0x140, 0x7, 0x1, 0x0, 0x0}, - nil, - nil, - nil, - nil, - nil, - nil, - nil, - }, - []*SectionHeader{ - {"__text", "__TEXT", 0x100000f14, 0x6d, 0xf14, 0x2, 0x0, 0x0, 0x80000400}, - {"__symbol_stub1", "__TEXT", 0x100000f81, 0xc, 0xf81, 0x0, 0x0, 0x0, 0x80000408}, - {"__stub_helper", "__TEXT", 0x100000f90, 0x18, 0xf90, 0x2, 0x0, 0x0, 0x0}, - {"__cstring", "__TEXT", 0x100000fa8, 0xd, 0xfa8, 0x0, 0x0, 0x0, 0x2}, - {"__eh_frame", "__TEXT", 0x100000fb8, 0x48, 0xfb8, 0x3, 0x0, 0x0, 0x6000000b}, - {"__data", "__DATA", 0x100001000, 0x1c, 0x1000, 0x3, 0x0, 0x0, 0x0}, - {"__dyld", "__DATA", 0x100001020, 0x38, 0x1020, 0x3, 0x0, 0x0, 0x0}, - {"__la_symbol_ptr", "__DATA", 0x100001058, 0x10, 0x1058, 0x2, 0x0, 0x0, 0x7}, - }, - }, - { - "testdata/gcc-amd64-darwin-exec-debug", - FileHeader{0xfeedfacf, CpuAmd64, 0x80000003, 0xa, 0x4, 0x5a0, 0}, - []*SegmentHeader{ - nil, - {LoadCmdSegment64, 0x1d8, "__TEXT", 0x100000000, 0x1000, 0x0, 0x0, 0x7, 0x5, 0x5, 0x0}, - {LoadCmdSegment64, 0x138, "__DATA", 0x100001000, 0x1000, 0x0, 0x0, 0x7, 0x3, 0x3, 0x0}, - {LoadCmdSegment64, 0x278, "__DWARF", 0x100002000, 0x1000, 0x1000, 0x1bc, 0x7, 0x3, 0x7, 0x0}, - }, - []*SectionHeader{ - {"__text", "__TEXT", 0x100000f14, 0x0, 0x0, 0x2, 0x0, 0x0, 0x80000400}, - {"__symbol_stub1", "__TEXT", 0x100000f81, 0x0, 0x0, 0x0, 0x0, 0x0, 0x80000408}, - {"__stub_helper", "__TEXT", 0x100000f90, 0x0, 0x0, 0x2, 0x0, 0x0, 0x0}, - {"__cstring", "__TEXT", 0x100000fa8, 0x0, 0x0, 0x0, 0x0, 0x0, 0x2}, - {"__eh_frame", "__TEXT", 0x100000fb8, 0x0, 0x0, 0x3, 0x0, 0x0, 0x6000000b}, - {"__data", "__DATA", 0x100001000, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0}, - {"__dyld", "__DATA", 0x100001020, 0x0, 0x0, 0x3, 0x0, 0x0, 0x0}, - {"__la_symbol_ptr", "__DATA", 0x100001058, 0x0, 0x0, 0x2, 0x0, 0x0, 0x7}, - {"__debug_abbrev", "__DWARF", 0x100002000, 0x36, 0x1000, 0x0, 0x0, 0x0, 0x0}, - {"__debug_aranges", "__DWARF", 0x100002036, 0x30, 0x1036, 0x0, 0x0, 0x0, 0x0}, - {"__debug_frame", "__DWARF", 0x100002066, 0x40, 0x1066, 0x0, 0x0, 0x0, 0x0}, - {"__debug_info", "__DWARF", 0x1000020a6, 0x54, 0x10a6, 0x0, 0x0, 0x0, 0x0}, - {"__debug_line", "__DWARF", 0x1000020fa, 0x47, 0x10fa, 0x0, 0x0, 0x0, 0x0}, - {"__debug_pubnames", "__DWARF", 0x100002141, 0x1b, 0x1141, 0x0, 0x0, 0x0, 0x0}, - {"__debug_str", "__DWARF", 0x10000215c, 0x60, 0x115c, 0x0, 0x0, 0x0, 0x0}, - }, - }, -} - -func TestOpen(t *testing.T) { - for i := range fileTests { - tt := &fileTests[i] - - f, err := Open(tt.file) - if err != nil { - t.Error(err) - continue - } - if !reflect.DeepEqual(f.FileHeader, tt.hdr) { - t.Errorf("open %s:\n\thave %#v\n\twant %#v\n", tt.file, f.FileHeader, tt.hdr) - continue - } - for i, l := range f.Loads { - if i >= len(tt.segments) { - break - } - sh := tt.segments[i] - s, ok := l.(*Segment) - if sh == nil { - if ok { - t.Errorf("open %s, section %d: skipping %#v\n", tt.file, i, &s.SegmentHeader) - } - continue - } - if !ok { - t.Errorf("open %s, section %d: not *Segment\n", tt.file, i) - continue - } - have := &s.SegmentHeader - want := sh - if !reflect.DeepEqual(have, want) { - t.Errorf("open %s, segment %d:\n\thave %#v\n\twant %#v\n", tt.file, i, have, want) - } - } - tn := len(tt.segments) - fn := len(f.Loads) - if tn != fn { - t.Errorf("open %s: len(Loads) = %d, want %d", tt.file, fn, tn) - } - - for i, sh := range f.Sections { - if i >= len(tt.sections) { - break - } - have := &sh.SectionHeader - want := tt.sections[i] - if !reflect.DeepEqual(have, want) { - t.Errorf("open %s, section %d:\n\thave %#v\n\twant %#v\n", tt.file, i, have, want) - } - } - tn = len(tt.sections) - fn = len(f.Sections) - if tn != fn { - t.Errorf("open %s: len(Sections) = %d, want %d", tt.file, fn, tn) - } - - } -} - -func TestOpenFailure(t *testing.T) { - filename := "file.go" // not a Mach-O file - _, err := Open(filename) // don't crash - if err == nil { - t.Errorf("open %s: succeeded unexpectedly", filename) - } -} - -func TestOpenFat(t *testing.T) { - ff, err := OpenFat("testdata/fat-gcc-386-amd64-darwin-exec") - if err != nil { - t.Fatal(err) - } - - if ff.Magic != MagicFat { - t.Errorf("OpenFat: got magic number %#x, want %#x", ff.Magic, MagicFat) - } - if len(ff.Arches) != 2 { - t.Errorf("OpenFat: got %d architectures, want 2", len(ff.Arches)) - } - - for i := range ff.Arches { - arch := &ff.Arches[i] - ftArch := &fileTests[i] - - if arch.Cpu != ftArch.hdr.Cpu || arch.SubCpu != ftArch.hdr.SubCpu { - t.Errorf("OpenFat: architecture #%d got cpu=%#x subtype=%#x, expected cpu=%#x, subtype=%#x", i, arch.Cpu, arch.SubCpu, ftArch.hdr.Cpu, ftArch.hdr.SubCpu) - } - - if !reflect.DeepEqual(arch.FileHeader, ftArch.hdr) { - t.Errorf("OpenFat header:\n\tgot %#v\n\twant %#v\n", arch.FileHeader, ftArch.hdr) - } - } -} - -func TestOpenFatFailure(t *testing.T) { - filename := "file.go" // not a Mach-O file - if _, err := OpenFat(filename); err == nil { - t.Errorf("OpenFat %s: succeeded unexpectedly", filename) - } - - filename = "testdata/gcc-386-darwin-exec" // not a fat Mach-O - ff, err := OpenFat(filename) - if err != ErrNotFat { - t.Errorf("OpenFat %s: got %v, want ErrNotFat", filename, err) - } - if ff != nil { - t.Errorf("OpenFat %s: got %v, want nil", filename, ff) - } -} diff --git a/src/pkg/debug/macho/macho.go b/src/pkg/debug/macho/macho.go deleted file mode 100644 index d9678c8ed..000000000 --- a/src/pkg/debug/macho/macho.go +++ /dev/null @@ -1,316 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Mach-O header data structures -// http://developer.apple.com/mac/library/documentation/DeveloperTools/Conceptual/MachORuntime/Reference/reference.html - -package macho - -import "strconv" - -// A FileHeader represents a Mach-O file header. -type FileHeader struct { - Magic uint32 - Cpu Cpu - SubCpu uint32 - Type Type - Ncmd uint32 - Cmdsz uint32 - Flags uint32 -} - -const ( - fileHeaderSize32 = 7 * 4 - fileHeaderSize64 = 8 * 4 -) - -const ( - Magic32 uint32 = 0xfeedface - Magic64 uint32 = 0xfeedfacf - MagicFat uint32 = 0xcafebabe -) - -// A Type is the Mach-O file type, e.g. an object file, executable, or dynamic library. -type Type uint32 - -const ( - TypeObj Type = 1 - TypeExec Type = 2 - TypeDylib Type = 6 - TypeBundle Type = 8 -) - -// A Cpu is a Mach-O cpu type. -type Cpu uint32 - -const cpuArch64 = 0x01000000 - -const ( - Cpu386 Cpu = 7 - CpuAmd64 Cpu = Cpu386 | cpuArch64 - CpuArm Cpu = 12 - CpuPpc Cpu = 18 - CpuPpc64 Cpu = CpuPpc | cpuArch64 -) - -var cpuStrings = []intName{ - {uint32(Cpu386), "Cpu386"}, - {uint32(CpuAmd64), "CpuAmd64"}, - {uint32(CpuArm), "CpuArm"}, - {uint32(CpuPpc), "CpuPpc"}, - {uint32(CpuPpc64), "CpuPpc64"}, -} - -func (i Cpu) String() string { return stringName(uint32(i), cpuStrings, false) } -func (i Cpu) GoString() string { return stringName(uint32(i), cpuStrings, true) } - -// A LoadCmd is a Mach-O load command. -type LoadCmd uint32 - -const ( - LoadCmdSegment LoadCmd = 1 - LoadCmdSymtab LoadCmd = 2 - LoadCmdThread LoadCmd = 4 - LoadCmdUnixThread LoadCmd = 5 // thread+stack - LoadCmdDysymtab LoadCmd = 11 - LoadCmdDylib LoadCmd = 12 - LoadCmdDylinker LoadCmd = 15 - LoadCmdSegment64 LoadCmd = 25 -) - -var cmdStrings = []intName{ - {uint32(LoadCmdSegment), "LoadCmdSegment"}, - {uint32(LoadCmdThread), "LoadCmdThread"}, - {uint32(LoadCmdUnixThread), "LoadCmdUnixThread"}, - {uint32(LoadCmdDylib), "LoadCmdDylib"}, - {uint32(LoadCmdSegment64), "LoadCmdSegment64"}, -} - -func (i LoadCmd) String() string { return stringName(uint32(i), cmdStrings, false) } -func (i LoadCmd) GoString() string { return stringName(uint32(i), cmdStrings, true) } - -// A Segment64 is a 64-bit Mach-O segment load command. -type Segment64 struct { - Cmd LoadCmd - Len uint32 - Name [16]byte - Addr uint64 - Memsz uint64 - Offset uint64 - Filesz uint64 - Maxprot uint32 - Prot uint32 - Nsect uint32 - Flag uint32 -} - -// A Segment32 is a 32-bit Mach-O segment load command. -type Segment32 struct { - Cmd LoadCmd - Len uint32 - Name [16]byte - Addr uint32 - Memsz uint32 - Offset uint32 - Filesz uint32 - Maxprot uint32 - Prot uint32 - Nsect uint32 - Flag uint32 -} - -// A DylibCmd is a Mach-O load dynamic library command. -type DylibCmd struct { - Cmd LoadCmd - Len uint32 - Name uint32 - Time uint32 - CurrentVersion uint32 - CompatVersion uint32 -} - -// A Section32 is a 32-bit Mach-O section header. -type Section32 struct { - Name [16]byte - Seg [16]byte - Addr uint32 - Size uint32 - Offset uint32 - Align uint32 - Reloff uint32 - Nreloc uint32 - Flags uint32 - Reserve1 uint32 - Reserve2 uint32 -} - -// A Section32 is a 64-bit Mach-O section header. -type Section64 struct { - Name [16]byte - Seg [16]byte - Addr uint64 - Size uint64 - Offset uint32 - Align uint32 - Reloff uint32 - Nreloc uint32 - Flags uint32 - Reserve1 uint32 - Reserve2 uint32 - Reserve3 uint32 -} - -// A SymtabCmd is a Mach-O symbol table command. -type SymtabCmd struct { - Cmd LoadCmd - Len uint32 - Symoff uint32 - Nsyms uint32 - Stroff uint32 - Strsize uint32 -} - -// A DysymtabCmd is a Mach-O dynamic symbol table command. -type DysymtabCmd struct { - Cmd LoadCmd - Len uint32 - Ilocalsym uint32 - Nlocalsym uint32 - Iextdefsym uint32 - Nextdefsym uint32 - Iundefsym uint32 - Nundefsym uint32 - Tocoffset uint32 - Ntoc uint32 - Modtaboff uint32 - Nmodtab uint32 - Extrefsymoff uint32 - Nextrefsyms uint32 - Indirectsymoff uint32 - Nindirectsyms uint32 - Extreloff uint32 - Nextrel uint32 - Locreloff uint32 - Nlocrel uint32 -} - -// An Nlist32 is a Mach-O 32-bit symbol table entry. -type Nlist32 struct { - Name uint32 - Type uint8 - Sect uint8 - Desc uint16 - Value uint32 -} - -// An Nlist64 is a Mach-O 64-bit symbol table entry. -type Nlist64 struct { - Name uint32 - Type uint8 - Sect uint8 - Desc uint16 - Value uint64 -} - -// A Symbol is a Mach-O 32-bit or 64-bit symbol table entry. -type Symbol struct { - Name string - Type uint8 - Sect uint8 - Desc uint16 - Value uint64 -} - -// A Thread is a Mach-O thread state command. -type Thread struct { - Cmd LoadCmd - Len uint32 - Type uint32 - Data []uint32 -} - -// Regs386 is the Mach-O 386 register structure. -type Regs386 struct { - AX uint32 - BX uint32 - CX uint32 - DX uint32 - DI uint32 - SI uint32 - BP uint32 - SP uint32 - SS uint32 - FLAGS uint32 - IP uint32 - CS uint32 - DS uint32 - ES uint32 - FS uint32 - GS uint32 -} - -// RegsAMD64 is the Mach-O AMD64 register structure. -type RegsAMD64 struct { - AX uint64 - BX uint64 - CX uint64 - DX uint64 - DI uint64 - SI uint64 - BP uint64 - SP uint64 - R8 uint64 - R9 uint64 - R10 uint64 - R11 uint64 - R12 uint64 - R13 uint64 - R14 uint64 - R15 uint64 - IP uint64 - FLAGS uint64 - CS uint64 - FS uint64 - GS uint64 -} - -type intName struct { - i uint32 - s string -} - -func stringName(i uint32, names []intName, goSyntax bool) string { - for _, n := range names { - if n.i == i { - if goSyntax { - return "macho." + n.s - } - return n.s - } - } - return strconv.FormatUint(uint64(i), 10) -} - -func flagName(i uint32, names []intName, goSyntax bool) string { - s := "" - for _, n := range names { - if n.i&i == n.i { - if len(s) > 0 { - s += "+" - } - if goSyntax { - s += "macho." - } - s += n.s - i -= n.i - } - } - if len(s) == 0 { - return "0x" + strconv.FormatUint(uint64(i), 16) - } - if i != 0 { - s += "+0x" + strconv.FormatUint(uint64(i), 16) - } - return s -} diff --git a/src/pkg/debug/macho/testdata/fat-gcc-386-amd64-darwin-exec b/src/pkg/debug/macho/testdata/fat-gcc-386-amd64-darwin-exec deleted file mode 100644 index 7efd19300..000000000 Binary files a/src/pkg/debug/macho/testdata/fat-gcc-386-amd64-darwin-exec and /dev/null differ diff --git a/src/pkg/debug/macho/testdata/gcc-386-darwin-exec b/src/pkg/debug/macho/testdata/gcc-386-darwin-exec deleted file mode 100755 index 03ba1bafa..000000000 Binary files a/src/pkg/debug/macho/testdata/gcc-386-darwin-exec and /dev/null differ diff --git a/src/pkg/debug/macho/testdata/gcc-amd64-darwin-exec b/src/pkg/debug/macho/testdata/gcc-amd64-darwin-exec deleted file mode 100755 index 5155a5a26..000000000 Binary files a/src/pkg/debug/macho/testdata/gcc-amd64-darwin-exec and /dev/null differ diff --git a/src/pkg/debug/macho/testdata/gcc-amd64-darwin-exec-debug b/src/pkg/debug/macho/testdata/gcc-amd64-darwin-exec-debug deleted file mode 100644 index a47d3aef7..000000000 Binary files a/src/pkg/debug/macho/testdata/gcc-amd64-darwin-exec-debug and /dev/null differ diff --git a/src/pkg/debug/macho/testdata/hello.c b/src/pkg/debug/macho/testdata/hello.c deleted file mode 100644 index a689d3644..000000000 --- a/src/pkg/debug/macho/testdata/hello.c +++ /dev/null @@ -1,8 +0,0 @@ -#include - -int -main(void) -{ - printf("hello, world\n"); - return 0; -} diff --git a/src/pkg/debug/pe/file.go b/src/pkg/debug/pe/file.go deleted file mode 100644 index ce6f1408f..000000000 --- a/src/pkg/debug/pe/file.go +++ /dev/null @@ -1,390 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package pe implements access to PE (Microsoft Windows Portable Executable) files. -package pe - -import ( - "debug/dwarf" - "encoding/binary" - "errors" - "fmt" - "io" - "os" - "strconv" - "unsafe" -) - -// A File represents an open PE file. -type File struct { - FileHeader - OptionalHeader interface{} // of type *OptionalHeader32 or *OptionalHeader64 - Sections []*Section - Symbols []*Symbol - - closer io.Closer -} - -type SectionHeader struct { - Name string - VirtualSize uint32 - VirtualAddress uint32 - Size uint32 - Offset uint32 - PointerToRelocations uint32 - PointerToLineNumbers uint32 - NumberOfRelocations uint16 - NumberOfLineNumbers uint16 - Characteristics uint32 -} - -type Section struct { - SectionHeader - - // Embed ReaderAt for ReadAt method. - // Do not embed SectionReader directly - // to avoid having Read and Seek. - // If a client wants Read and Seek it must use - // Open() to avoid fighting over the seek offset - // with other clients. - io.ReaderAt - sr *io.SectionReader -} - -type Symbol struct { - Name string - Value uint32 - SectionNumber int16 - Type uint16 - StorageClass uint8 -} - -type ImportDirectory struct { - OriginalFirstThunk uint32 - TimeDateStamp uint32 - ForwarderChain uint32 - Name uint32 - FirstThunk uint32 - - dll string -} - -// Data reads and returns the contents of the PE section. -func (s *Section) Data() ([]byte, error) { - dat := make([]byte, s.sr.Size()) - n, err := s.sr.ReadAt(dat, 0) - if n == len(dat) { - err = nil - } - return dat[0:n], err -} - -// Open returns a new ReadSeeker reading the PE section. -func (s *Section) Open() io.ReadSeeker { return io.NewSectionReader(s.sr, 0, 1<<63-1) } - -type FormatError struct { - off int64 - msg string - val interface{} -} - -func (e *FormatError) Error() string { - msg := e.msg - if e.val != nil { - msg += fmt.Sprintf(" '%v'", e.val) - } - msg += fmt.Sprintf(" in record at byte %#x", e.off) - return msg -} - -// Open opens the named file using os.Open and prepares it for use as a PE binary. -func Open(name string) (*File, error) { - f, err := os.Open(name) - if err != nil { - return nil, err - } - ff, err := NewFile(f) - if err != nil { - f.Close() - return nil, err - } - ff.closer = f - return ff, nil -} - -// Close closes the File. -// If the File was created using NewFile directly instead of Open, -// Close has no effect. -func (f *File) Close() error { - var err error - if f.closer != nil { - err = f.closer.Close() - f.closer = nil - } - return err -} - -// NewFile creates a new File for accessing a PE binary in an underlying reader. -func NewFile(r io.ReaderAt) (*File, error) { - f := new(File) - sr := io.NewSectionReader(r, 0, 1<<63-1) - - var dosheader [96]byte - if _, err := r.ReadAt(dosheader[0:], 0); err != nil { - return nil, err - } - var base int64 - if dosheader[0] == 'M' && dosheader[1] == 'Z' { - signoff := int64(binary.LittleEndian.Uint32(dosheader[0x3c:])) - var sign [4]byte - r.ReadAt(sign[:], signoff) - if !(sign[0] == 'P' && sign[1] == 'E' && sign[2] == 0 && sign[3] == 0) { - return nil, errors.New("Invalid PE File Format.") - } - base = signoff + 4 - } else { - base = int64(0) - } - sr.Seek(base, os.SEEK_SET) - if err := binary.Read(sr, binary.LittleEndian, &f.FileHeader); err != nil { - return nil, err - } - if f.FileHeader.Machine != IMAGE_FILE_MACHINE_UNKNOWN && f.FileHeader.Machine != IMAGE_FILE_MACHINE_AMD64 && f.FileHeader.Machine != IMAGE_FILE_MACHINE_I386 { - return nil, errors.New("Invalid PE File Format.") - } - - var ss []byte - if f.FileHeader.NumberOfSymbols > 0 { - // Get COFF string table, which is located at the end of the COFF symbol table. - sr.Seek(int64(f.FileHeader.PointerToSymbolTable+COFFSymbolSize*f.FileHeader.NumberOfSymbols), os.SEEK_SET) - var l uint32 - if err := binary.Read(sr, binary.LittleEndian, &l); err != nil { - return nil, err - } - ss = make([]byte, l) - if _, err := r.ReadAt(ss, int64(f.FileHeader.PointerToSymbolTable+COFFSymbolSize*f.FileHeader.NumberOfSymbols)); err != nil { - return nil, err - } - - // Process COFF symbol table. - sr.Seek(int64(f.FileHeader.PointerToSymbolTable), os.SEEK_SET) - aux := uint8(0) - for i := 0; i < int(f.FileHeader.NumberOfSymbols); i++ { - cs := new(COFFSymbol) - if err := binary.Read(sr, binary.LittleEndian, cs); err != nil { - return nil, err - } - if aux > 0 { - aux-- - continue - } - var name string - if cs.Name[0] == 0 && cs.Name[1] == 0 && cs.Name[2] == 0 && cs.Name[3] == 0 { - si := int(binary.LittleEndian.Uint32(cs.Name[4:])) - name, _ = getString(ss, si) - } else { - name = cstring(cs.Name[:]) - } - aux = cs.NumberOfAuxSymbols - s := &Symbol{ - Name: name, - Value: cs.Value, - SectionNumber: cs.SectionNumber, - Type: cs.Type, - StorageClass: cs.StorageClass, - } - f.Symbols = append(f.Symbols, s) - } - } - - // Read optional header. - sr.Seek(base, os.SEEK_SET) - if err := binary.Read(sr, binary.LittleEndian, &f.FileHeader); err != nil { - return nil, err - } - var oh32 OptionalHeader32 - var oh64 OptionalHeader64 - switch uintptr(f.FileHeader.SizeOfOptionalHeader) { - case unsafe.Sizeof(oh32): - if err := binary.Read(sr, binary.LittleEndian, &oh32); err != nil { - return nil, err - } - if oh32.Magic != 0x10b { // PE32 - return nil, fmt.Errorf("pe32 optional header has unexpected Magic of 0x%x", oh32.Magic) - } - f.OptionalHeader = &oh32 - case unsafe.Sizeof(oh64): - if err := binary.Read(sr, binary.LittleEndian, &oh64); err != nil { - return nil, err - } - if oh64.Magic != 0x20b { // PE32+ - return nil, fmt.Errorf("pe32+ optional header has unexpected Magic of 0x%x", oh64.Magic) - } - f.OptionalHeader = &oh64 - } - - // Process sections. - f.Sections = make([]*Section, f.FileHeader.NumberOfSections) - for i := 0; i < int(f.FileHeader.NumberOfSections); i++ { - sh := new(SectionHeader32) - if err := binary.Read(sr, binary.LittleEndian, sh); err != nil { - return nil, err - } - var name string - if sh.Name[0] == '\x2F' { - si, _ := strconv.Atoi(cstring(sh.Name[1:])) - name, _ = getString(ss, si) - } else { - name = cstring(sh.Name[0:]) - } - s := new(Section) - s.SectionHeader = SectionHeader{ - Name: name, - VirtualSize: sh.VirtualSize, - VirtualAddress: sh.VirtualAddress, - Size: sh.SizeOfRawData, - Offset: sh.PointerToRawData, - PointerToRelocations: sh.PointerToRelocations, - PointerToLineNumbers: sh.PointerToLineNumbers, - NumberOfRelocations: sh.NumberOfRelocations, - NumberOfLineNumbers: sh.NumberOfLineNumbers, - Characteristics: sh.Characteristics, - } - s.sr = io.NewSectionReader(r, int64(s.SectionHeader.Offset), int64(s.SectionHeader.Size)) - s.ReaderAt = s.sr - f.Sections[i] = s - } - return f, nil -} - -func cstring(b []byte) string { - var i int - for i = 0; i < len(b) && b[i] != 0; i++ { - } - return string(b[0:i]) -} - -// getString extracts a string from symbol string table. -func getString(section []byte, start int) (string, bool) { - if start < 0 || start >= len(section) { - return "", false - } - - for end := start; end < len(section); end++ { - if section[end] == 0 { - return string(section[start:end]), true - } - } - return "", false -} - -// Section returns the first section with the given name, or nil if no such -// section exists. -func (f *File) Section(name string) *Section { - for _, s := range f.Sections { - if s.Name == name { - return s - } - } - return nil -} - -func (f *File) DWARF() (*dwarf.Data, error) { - // There are many other DWARF sections, but these - // are the required ones, and the debug/dwarf package - // does not use the others, so don't bother loading them. - var names = [...]string{"abbrev", "info", "str"} - var dat [len(names)][]byte - for i, name := range names { - name = ".debug_" + name - s := f.Section(name) - if s == nil { - continue - } - b, err := s.Data() - if err != nil && uint32(len(b)) < s.Size { - return nil, err - } - dat[i] = b - } - - abbrev, info, str := dat[0], dat[1], dat[2] - return dwarf.New(abbrev, nil, nil, info, nil, nil, nil, str) -} - -// ImportedSymbols returns the names of all symbols -// referred to by the binary f that are expected to be -// satisfied by other libraries at dynamic load time. -// It does not return weak symbols. -func (f *File) ImportedSymbols() ([]string, error) { - pe64 := f.Machine == IMAGE_FILE_MACHINE_AMD64 - ds := f.Section(".idata") - if ds == nil { - // not dynamic, so no libraries - return nil, nil - } - d, err := ds.Data() - if err != nil { - return nil, err - } - var ida []ImportDirectory - for len(d) > 0 { - var dt ImportDirectory - dt.OriginalFirstThunk = binary.LittleEndian.Uint32(d[0:4]) - dt.Name = binary.LittleEndian.Uint32(d[12:16]) - dt.FirstThunk = binary.LittleEndian.Uint32(d[16:20]) - d = d[20:] - if dt.OriginalFirstThunk == 0 { - break - } - ida = append(ida, dt) - } - names, _ := ds.Data() - var all []string - for _, dt := range ida { - dt.dll, _ = getString(names, int(dt.Name-ds.VirtualAddress)) - d, _ = ds.Data() - // seek to OriginalFirstThunk - d = d[dt.OriginalFirstThunk-ds.VirtualAddress:] - for len(d) > 0 { - if pe64 { // 64bit - va := binary.LittleEndian.Uint64(d[0:8]) - d = d[8:] - if va == 0 { - break - } - if va&0x8000000000000000 > 0 { // is Ordinal - // TODO add dynimport ordinal support. - } else { - fn, _ := getString(names, int(uint32(va)-ds.VirtualAddress+2)) - all = append(all, fn+":"+dt.dll) - } - } else { // 32bit - va := binary.LittleEndian.Uint32(d[0:4]) - d = d[4:] - if va == 0 { - break - } - if va&0x80000000 > 0 { // is Ordinal - // TODO add dynimport ordinal support. - //ord := va&0x0000FFFF - } else { - fn, _ := getString(names, int(va-ds.VirtualAddress+2)) - all = append(all, fn+":"+dt.dll) - } - } - } - } - - return all, nil -} - -// ImportedLibraries returns the names of all libraries -// referred to by the binary f that are expected to be -// linked with the binary at dynamic link time. -func (f *File) ImportedLibraries() ([]string, error) { - // TODO - // cgo -dynimport don't use this for windows PE, so just return. - return nil, nil -} diff --git a/src/pkg/debug/pe/file_test.go b/src/pkg/debug/pe/file_test.go deleted file mode 100644 index 0d73969bc..000000000 --- a/src/pkg/debug/pe/file_test.go +++ /dev/null @@ -1,243 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pe - -import ( - "reflect" - "testing" -) - -type fileTest struct { - file string - hdr FileHeader - opthdr interface{} - sections []*SectionHeader - symbols []*Symbol -} - -var fileTests = []fileTest{ - { - "testdata/gcc-386-mingw-obj", - FileHeader{0x014c, 0x000c, 0x0, 0x64a, 0x1e, 0x0, 0x104}, - nil, - []*SectionHeader{ - {".text", 0, 0, 36, 500, 1440, 0, 3, 0, 0x60300020}, - {".data", 0, 0, 0, 0, 0, 0, 0, 0, 3224371264}, - {".bss", 0, 0, 0, 0, 0, 0, 0, 0, 3224371328}, - {".debug_abbrev", 0, 0, 137, 536, 0, 0, 0, 0, 0x42100000}, - {".debug_info", 0, 0, 418, 673, 1470, 0, 7, 0, 1108344832}, - {".debug_line", 0, 0, 128, 1091, 1540, 0, 1, 0, 1108344832}, - {".rdata", 0, 0, 16, 1219, 0, 0, 0, 0, 1076887616}, - {".debug_frame", 0, 0, 52, 1235, 1550, 0, 2, 0, 1110441984}, - {".debug_loc", 0, 0, 56, 1287, 0, 0, 0, 0, 1108344832}, - {".debug_pubnames", 0, 0, 27, 1343, 1570, 0, 1, 0, 1108344832}, - {".debug_pubtypes", 0, 0, 38, 1370, 1580, 0, 1, 0, 1108344832}, - {".debug_aranges", 0, 0, 32, 1408, 1590, 0, 2, 0, 1108344832}, - }, - []*Symbol{ - {".file", 0x0, -2, 0x0, 0x67}, - {"_main", 0x0, 1, 0x20, 0x2}, - {".text", 0x0, 1, 0x0, 0x3}, - {".data", 0x0, 2, 0x0, 0x3}, - {".bss", 0x0, 3, 0x0, 0x3}, - {".debug_abbrev", 0x0, 4, 0x0, 0x3}, - {".debug_info", 0x0, 5, 0x0, 0x3}, - {".debug_line", 0x0, 6, 0x0, 0x3}, - {".rdata", 0x0, 7, 0x0, 0x3}, - {".debug_frame", 0x0, 8, 0x0, 0x3}, - {".debug_loc", 0x0, 9, 0x0, 0x3}, - {".debug_pubnames", 0x0, 10, 0x0, 0x3}, - {".debug_pubtypes", 0x0, 11, 0x0, 0x3}, - {".debug_aranges", 0x0, 12, 0x0, 0x3}, - {"___main", 0x0, 0, 0x20, 0x2}, - {"_puts", 0x0, 0, 0x20, 0x2}, - }, - }, - { - "testdata/gcc-386-mingw-exec", - FileHeader{0x014c, 0x000f, 0x4c6a1b60, 0x3c00, 0x282, 0xe0, 0x107}, - &OptionalHeader32{ - 0x10b, 0x2, 0x38, 0xe00, 0x1a00, 0x200, 0x1160, 0x1000, 0x2000, 0x400000, 0x1000, 0x200, 0x4, 0x0, 0x1, 0x0, 0x4, 0x0, 0x0, 0x10000, 0x400, 0x14abb, 0x3, 0x0, 0x200000, 0x1000, 0x100000, 0x1000, 0x0, 0x10, - [16]DataDirectory{ - {0x0, 0x0}, - {0x5000, 0x3c8}, - {0x0, 0x0}, - {0x0, 0x0}, - {0x0, 0x0}, - {0x0, 0x0}, - {0x0, 0x0}, - {0x0, 0x0}, - {0x0, 0x0}, - {0x7000, 0x18}, - {0x0, 0x0}, - {0x0, 0x0}, - {0x0, 0x0}, - {0x0, 0x0}, - {0x0, 0x0}, - {0x0, 0x0}, - }, - }, - []*SectionHeader{ - {".text", 0xcd8, 0x1000, 0xe00, 0x400, 0x0, 0x0, 0x0, 0x0, 0x60500060}, - {".data", 0x10, 0x2000, 0x200, 0x1200, 0x0, 0x0, 0x0, 0x0, 0xc0300040}, - {".rdata", 0x120, 0x3000, 0x200, 0x1400, 0x0, 0x0, 0x0, 0x0, 0x40300040}, - {".bss", 0xdc, 0x4000, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xc0400080}, - {".idata", 0x3c8, 0x5000, 0x400, 0x1600, 0x0, 0x0, 0x0, 0x0, 0xc0300040}, - {".CRT", 0x18, 0x6000, 0x200, 0x1a00, 0x0, 0x0, 0x0, 0x0, 0xc0300040}, - {".tls", 0x20, 0x7000, 0x200, 0x1c00, 0x0, 0x0, 0x0, 0x0, 0xc0300040}, - {".debug_aranges", 0x20, 0x8000, 0x200, 0x1e00, 0x0, 0x0, 0x0, 0x0, 0x42100000}, - {".debug_pubnames", 0x51, 0x9000, 0x200, 0x2000, 0x0, 0x0, 0x0, 0x0, 0x42100000}, - {".debug_pubtypes", 0x91, 0xa000, 0x200, 0x2200, 0x0, 0x0, 0x0, 0x0, 0x42100000}, - {".debug_info", 0xe22, 0xb000, 0x1000, 0x2400, 0x0, 0x0, 0x0, 0x0, 0x42100000}, - {".debug_abbrev", 0x157, 0xc000, 0x200, 0x3400, 0x0, 0x0, 0x0, 0x0, 0x42100000}, - {".debug_line", 0x144, 0xd000, 0x200, 0x3600, 0x0, 0x0, 0x0, 0x0, 0x42100000}, - {".debug_frame", 0x34, 0xe000, 0x200, 0x3800, 0x0, 0x0, 0x0, 0x0, 0x42300000}, - {".debug_loc", 0x38, 0xf000, 0x200, 0x3a00, 0x0, 0x0, 0x0, 0x0, 0x42100000}, - }, - []*Symbol{}, - }, - { - "testdata/gcc-amd64-mingw-obj", - FileHeader{0x8664, 0x6, 0x0, 0x198, 0x12, 0x0, 0x4}, - nil, - []*SectionHeader{ - {".text", 0x0, 0x0, 0x30, 0x104, 0x15c, 0x0, 0x3, 0x0, 0x60500020}, - {".data", 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xc0500040}, - {".bss", 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xc0500080}, - {".rdata", 0x0, 0x0, 0x10, 0x134, 0x0, 0x0, 0x0, 0x0, 0x40500040}, - {".xdata", 0x0, 0x0, 0xc, 0x144, 0x0, 0x0, 0x0, 0x0, 0x40300040}, - {".pdata", 0x0, 0x0, 0xc, 0x150, 0x17a, 0x0, 0x3, 0x0, 0x40300040}, - }, - []*Symbol{ - {".file", 0x0, -2, 0x0, 0x67}, - {"main", 0x0, 1, 0x20, 0x2}, - {".text", 0x0, 1, 0x0, 0x3}, - {".data", 0x0, 2, 0x0, 0x3}, - {".bss", 0x0, 3, 0x0, 0x3}, - {".rdata", 0x0, 4, 0x0, 0x3}, - {".xdata", 0x0, 5, 0x0, 0x3}, - {".pdata", 0x0, 6, 0x0, 0x3}, - {"__main", 0x0, 0, 0x20, 0x2}, - {"puts", 0x0, 0, 0x20, 0x2}, - }, - }, - { - "testdata/gcc-amd64-mingw-exec", - FileHeader{0x8664, 0x11, 0x53e4364f, 0x39600, 0x6fc, 0xf0, 0x27}, - &OptionalHeader64{ - 0x20b, 0x2, 0x16, 0x6a00, 0x2400, 0x1600, 0x14e0, 0x1000, 0x400000, 0x1000, 0x200, 0x4, 0x0, 0x0, 0x0, 0x5, 0x2, 0x0, 0x45000, 0x600, 0x46f19, 0x3, 0x0, 0x200000, 0x1000, 0x100000, 0x1000, 0x0, 0x10, - [16]DataDirectory{ - {0x0, 0x0}, - {0xe000, 0x990}, - {0x0, 0x0}, - {0xa000, 0x498}, - {0x0, 0x0}, - {0x0, 0x0}, - {0x0, 0x0}, - {0x0, 0x0}, - {0x0, 0x0}, - {0x10000, 0x28}, - {0x0, 0x0}, - {0x0, 0x0}, - {0xe254, 0x218}, - {0x0, 0x0}, - {0x0, 0x0}, - {0x0, 0x0}, - }}, - []*SectionHeader{ - {".text", 0x6860, 0x1000, 0x6a00, 0x600, 0x0, 0x0, 0x0, 0x0, 0x60500020}, - {".data", 0xe0, 0x8000, 0x200, 0x7000, 0x0, 0x0, 0x0, 0x0, 0xc0500040}, - {".rdata", 0x6b0, 0x9000, 0x800, 0x7200, 0x0, 0x0, 0x0, 0x0, 0x40600040}, - {".pdata", 0x498, 0xa000, 0x600, 0x7a00, 0x0, 0x0, 0x0, 0x0, 0x40300040}, - {".xdata", 0x488, 0xb000, 0x600, 0x8000, 0x0, 0x0, 0x0, 0x0, 0x40300040}, - {".bss", 0x1410, 0xc000, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0xc0600080}, - {".idata", 0x990, 0xe000, 0xa00, 0x8600, 0x0, 0x0, 0x0, 0x0, 0xc0300040}, - {".CRT", 0x68, 0xf000, 0x200, 0x9000, 0x0, 0x0, 0x0, 0x0, 0xc0400040}, - {".tls", 0x48, 0x10000, 0x200, 0x9200, 0x0, 0x0, 0x0, 0x0, 0xc0600040}, - {".debug_aranges", 0x600, 0x11000, 0x600, 0x9400, 0x0, 0x0, 0x0, 0x0, 0x42500040}, - {".debug_info", 0x1316e, 0x12000, 0x13200, 0x9a00, 0x0, 0x0, 0x0, 0x0, 0x42100040}, - {".debug_abbrev", 0x2ccb, 0x26000, 0x2e00, 0x1cc00, 0x0, 0x0, 0x0, 0x0, 0x42100040}, - {".debug_line", 0x3c4d, 0x29000, 0x3e00, 0x1fa00, 0x0, 0x0, 0x0, 0x0, 0x42100040}, - {".debug_frame", 0x18b8, 0x2d000, 0x1a00, 0x23800, 0x0, 0x0, 0x0, 0x0, 0x42400040}, - {".debug_str", 0x396, 0x2f000, 0x400, 0x25200, 0x0, 0x0, 0x0, 0x0, 0x42100040}, - {".debug_loc", 0x13240, 0x30000, 0x13400, 0x25600, 0x0, 0x0, 0x0, 0x0, 0x42100040}, - {".debug_ranges", 0xa70, 0x44000, 0xc00, 0x38a00, 0x0, 0x0, 0x0, 0x0, 0x42100040}, - }, - []*Symbol{}, - }, -} - -func isOptHdrEq(a, b interface{}) bool { - switch va := a.(type) { - case *OptionalHeader32: - vb, ok := b.(*OptionalHeader32) - if !ok { - return false - } - return *vb == *va - case *OptionalHeader64: - vb, ok := b.(*OptionalHeader64) - if !ok { - return false - } - return *vb == *va - case nil: - return b == nil - } - return false -} - -func TestOpen(t *testing.T) { - for i := range fileTests { - tt := &fileTests[i] - - f, err := Open(tt.file) - if err != nil { - t.Error(err) - continue - } - if !reflect.DeepEqual(f.FileHeader, tt.hdr) { - t.Errorf("open %s:\n\thave %#v\n\twant %#v\n", tt.file, f.FileHeader, tt.hdr) - continue - } - if !isOptHdrEq(tt.opthdr, f.OptionalHeader) { - t.Errorf("open %s:\n\thave %#v\n\twant %#v\n", tt.file, f.OptionalHeader, tt.opthdr) - continue - } - - for i, sh := range f.Sections { - if i >= len(tt.sections) { - break - } - have := &sh.SectionHeader - want := tt.sections[i] - if !reflect.DeepEqual(have, want) { - t.Errorf("open %s, section %d:\n\thave %#v\n\twant %#v\n", tt.file, i, have, want) - } - } - tn := len(tt.sections) - fn := len(f.Sections) - if tn != fn { - t.Errorf("open %s: len(Sections) = %d, want %d", tt.file, fn, tn) - } - for i, have := range f.Symbols { - if i >= len(tt.symbols) { - break - } - want := tt.symbols[i] - if !reflect.DeepEqual(have, want) { - t.Errorf("open %s, symbol %d:\n\thave %#v\n\twant %#v\n", tt.file, i, have, want) - } - } - } -} - -func TestOpenFailure(t *testing.T) { - filename := "file.go" // not a PE file - _, err := Open(filename) // don't crash - if err == nil { - t.Errorf("open %s: succeeded unexpectedly", filename) - } -} diff --git a/src/pkg/debug/pe/pe.go b/src/pkg/debug/pe/pe.go deleted file mode 100644 index 8e90b1b51..000000000 --- a/src/pkg/debug/pe/pe.go +++ /dev/null @@ -1,134 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package pe - -type FileHeader struct { - Machine uint16 - NumberOfSections uint16 - TimeDateStamp uint32 - PointerToSymbolTable uint32 - NumberOfSymbols uint32 - SizeOfOptionalHeader uint16 - Characteristics uint16 -} - -type DataDirectory struct { - VirtualAddress uint32 - Size uint32 -} - -type OptionalHeader32 struct { - Magic uint16 - MajorLinkerVersion uint8 - MinorLinkerVersion uint8 - SizeOfCode uint32 - SizeOfInitializedData uint32 - SizeOfUninitializedData uint32 - AddressOfEntryPoint uint32 - BaseOfCode uint32 - BaseOfData uint32 - ImageBase uint32 - SectionAlignment uint32 - FileAlignment uint32 - MajorOperatingSystemVersion uint16 - MinorOperatingSystemVersion uint16 - MajorImageVersion uint16 - MinorImageVersion uint16 - MajorSubsystemVersion uint16 - MinorSubsystemVersion uint16 - Win32VersionValue uint32 - SizeOfImage uint32 - SizeOfHeaders uint32 - CheckSum uint32 - Subsystem uint16 - DllCharacteristics uint16 - SizeOfStackReserve uint32 - SizeOfStackCommit uint32 - SizeOfHeapReserve uint32 - SizeOfHeapCommit uint32 - LoaderFlags uint32 - NumberOfRvaAndSizes uint32 - DataDirectory [16]DataDirectory -} - -type OptionalHeader64 struct { - Magic uint16 - MajorLinkerVersion uint8 - MinorLinkerVersion uint8 - SizeOfCode uint32 - SizeOfInitializedData uint32 - SizeOfUninitializedData uint32 - AddressOfEntryPoint uint32 - BaseOfCode uint32 - ImageBase uint64 - SectionAlignment uint32 - FileAlignment uint32 - MajorOperatingSystemVersion uint16 - MinorOperatingSystemVersion uint16 - MajorImageVersion uint16 - MinorImageVersion uint16 - MajorSubsystemVersion uint16 - MinorSubsystemVersion uint16 - Win32VersionValue uint32 - SizeOfImage uint32 - SizeOfHeaders uint32 - CheckSum uint32 - Subsystem uint16 - DllCharacteristics uint16 - SizeOfStackReserve uint64 - SizeOfStackCommit uint64 - SizeOfHeapReserve uint64 - SizeOfHeapCommit uint64 - LoaderFlags uint32 - NumberOfRvaAndSizes uint32 - DataDirectory [16]DataDirectory -} - -type SectionHeader32 struct { - Name [8]uint8 - VirtualSize uint32 - VirtualAddress uint32 - SizeOfRawData uint32 - PointerToRawData uint32 - PointerToRelocations uint32 - PointerToLineNumbers uint32 - NumberOfRelocations uint16 - NumberOfLineNumbers uint16 - Characteristics uint32 -} - -const COFFSymbolSize = 18 - -type COFFSymbol struct { - Name [8]uint8 - Value uint32 - SectionNumber int16 - Type uint16 - StorageClass uint8 - NumberOfAuxSymbols uint8 -} - -const ( - IMAGE_FILE_MACHINE_UNKNOWN = 0x0 - IMAGE_FILE_MACHINE_AM33 = 0x1d3 - IMAGE_FILE_MACHINE_AMD64 = 0x8664 - IMAGE_FILE_MACHINE_ARM = 0x1c0 - IMAGE_FILE_MACHINE_EBC = 0xebc - IMAGE_FILE_MACHINE_I386 = 0x14c - IMAGE_FILE_MACHINE_IA64 = 0x200 - IMAGE_FILE_MACHINE_M32R = 0x9041 - IMAGE_FILE_MACHINE_MIPS16 = 0x266 - IMAGE_FILE_MACHINE_MIPSFPU = 0x366 - IMAGE_FILE_MACHINE_MIPSFPU16 = 0x466 - IMAGE_FILE_MACHINE_POWERPC = 0x1f0 - IMAGE_FILE_MACHINE_POWERPCFP = 0x1f1 - IMAGE_FILE_MACHINE_R4000 = 0x166 - IMAGE_FILE_MACHINE_SH3 = 0x1a2 - IMAGE_FILE_MACHINE_SH3DSP = 0x1a3 - IMAGE_FILE_MACHINE_SH4 = 0x1a6 - IMAGE_FILE_MACHINE_SH5 = 0x1a8 - IMAGE_FILE_MACHINE_THUMB = 0x1c2 - IMAGE_FILE_MACHINE_WCEMIPSV2 = 0x169 -) diff --git a/src/pkg/debug/pe/testdata/gcc-386-mingw-exec b/src/pkg/debug/pe/testdata/gcc-386-mingw-exec deleted file mode 100644 index 4b808d043..000000000 Binary files a/src/pkg/debug/pe/testdata/gcc-386-mingw-exec and /dev/null differ diff --git a/src/pkg/debug/pe/testdata/gcc-386-mingw-obj b/src/pkg/debug/pe/testdata/gcc-386-mingw-obj deleted file mode 100644 index 0c84d898d..000000000 Binary files a/src/pkg/debug/pe/testdata/gcc-386-mingw-obj and /dev/null differ diff --git a/src/pkg/debug/pe/testdata/gcc-amd64-mingw-exec b/src/pkg/debug/pe/testdata/gcc-amd64-mingw-exec deleted file mode 100644 index ce6feb6b7..000000000 Binary files a/src/pkg/debug/pe/testdata/gcc-amd64-mingw-exec and /dev/null differ diff --git a/src/pkg/debug/pe/testdata/gcc-amd64-mingw-obj b/src/pkg/debug/pe/testdata/gcc-amd64-mingw-obj deleted file mode 100644 index 48ae7921f..000000000 Binary files a/src/pkg/debug/pe/testdata/gcc-amd64-mingw-obj and /dev/null differ diff --git a/src/pkg/debug/pe/testdata/hello.c b/src/pkg/debug/pe/testdata/hello.c deleted file mode 100644 index a689d3644..000000000 --- a/src/pkg/debug/pe/testdata/hello.c +++ /dev/null @@ -1,8 +0,0 @@ -#include - -int -main(void) -{ - printf("hello, world\n"); - return 0; -} diff --git a/src/pkg/debug/plan9obj/file.go b/src/pkg/debug/plan9obj/file.go deleted file mode 100644 index b11ed86f1..000000000 --- a/src/pkg/debug/plan9obj/file.go +++ /dev/null @@ -1,328 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package plan9obj implements access to Plan 9 a.out object files. -package plan9obj - -import ( - "encoding/binary" - "errors" - "fmt" - "io" - "os" -) - -// A FileHeader represents a Plan 9 a.out file header. -type FileHeader struct { - Magic uint32 - Bss uint32 - Entry uint64 - PtrSize int - LoadAddress uint64 - HdrSize uint64 -} - -// A File represents an open Plan 9 a.out file. -type File struct { - FileHeader - Sections []*Section - closer io.Closer -} - -// A SectionHeader represents a single Plan 9 a.out section header. -// This structure doesn't exist on-disk, but eases navigation -// through the object file. -type SectionHeader struct { - Name string - Size uint32 - Offset uint32 -} - -// A Section represents a single section in a Plan 9 a.out file. -type Section struct { - SectionHeader - - // Embed ReaderAt for ReadAt method. - // Do not embed SectionReader directly - // to avoid having Read and Seek. - // If a client wants Read and Seek it must use - // Open() to avoid fighting over the seek offset - // with other clients. - io.ReaderAt - sr *io.SectionReader -} - -// Data reads and returns the contents of the Plan 9 a.out section. -func (s *Section) Data() ([]byte, error) { - dat := make([]byte, s.sr.Size()) - n, err := s.sr.ReadAt(dat, 0) - if n == len(dat) { - err = nil - } - return dat[0:n], err -} - -// Open returns a new ReadSeeker reading the Plan 9 a.out section. -func (s *Section) Open() io.ReadSeeker { return io.NewSectionReader(s.sr, 0, 1<<63-1) } - -// A Symbol represents an entry in a Plan 9 a.out symbol table section. -type Sym struct { - Value uint64 - Type rune - Name string -} - -/* - * Plan 9 a.out reader - */ - -// formatError is returned by some operations if the data does -// not have the correct format for an object file. -type formatError struct { - off int - msg string - val interface{} -} - -func (e *formatError) Error() string { - msg := e.msg - if e.val != nil { - msg += fmt.Sprintf(" '%v'", e.val) - } - msg += fmt.Sprintf(" in record at byte %#x", e.off) - return msg -} - -// Open opens the named file using os.Open and prepares it for use as a Plan 9 a.out binary. -func Open(name string) (*File, error) { - f, err := os.Open(name) - if err != nil { - return nil, err - } - ff, err := NewFile(f) - if err != nil { - f.Close() - return nil, err - } - ff.closer = f - return ff, nil -} - -// Close closes the File. -// If the File was created using NewFile directly instead of Open, -// Close has no effect. -func (f *File) Close() error { - var err error - if f.closer != nil { - err = f.closer.Close() - f.closer = nil - } - return err -} - -func parseMagic(magic []byte) (uint32, error) { - m := binary.BigEndian.Uint32(magic) - switch m { - case Magic386, MagicAMD64, MagicARM: - return m, nil - } - return 0, &formatError{0, "bad magic number", magic} -} - -// NewFile creates a new File for accessing a Plan 9 binary in an underlying reader. -// The Plan 9 binary is expected to start at position 0 in the ReaderAt. -func NewFile(r io.ReaderAt) (*File, error) { - sr := io.NewSectionReader(r, 0, 1<<63-1) - // Read and decode Plan 9 magic - var magic [4]byte - if _, err := r.ReadAt(magic[:], 0); err != nil { - return nil, err - } - _, err := parseMagic(magic[:]) - if err != nil { - return nil, err - } - - ph := new(prog) - if err := binary.Read(sr, binary.BigEndian, ph); err != nil { - return nil, err - } - - f := &File{FileHeader: FileHeader{ - Magic: ph.Magic, - Bss: ph.Bss, - Entry: uint64(ph.Entry), - PtrSize: 4, - LoadAddress: 0x1000, - HdrSize: 4 * 8, - }} - - if ph.Magic&Magic64 != 0 { - if err := binary.Read(sr, binary.BigEndian, &f.Entry); err != nil { - return nil, err - } - f.PtrSize = 8 - f.LoadAddress = 0x200000 - f.HdrSize += 8 - } - - var sects = []struct { - name string - size uint32 - }{ - {"text", ph.Text}, - {"data", ph.Data}, - {"syms", ph.Syms}, - {"spsz", ph.Spsz}, - {"pcsz", ph.Pcsz}, - } - - f.Sections = make([]*Section, 5) - - off := uint32(f.HdrSize) - - for i, sect := range sects { - s := new(Section) - s.SectionHeader = SectionHeader{ - Name: sect.name, - Size: sect.size, - Offset: off, - } - off += sect.size - s.sr = io.NewSectionReader(r, int64(s.Offset), int64(s.Size)) - s.ReaderAt = s.sr - f.Sections[i] = s - } - - return f, nil -} - -func walksymtab(data []byte, ptrsz int, fn func(sym) error) error { - var order binary.ByteOrder = binary.BigEndian - var s sym - p := data - for len(p) >= 4 { - // Symbol type, value. - if len(p) < ptrsz { - return &formatError{len(data), "unexpected EOF", nil} - } - // fixed-width value - if ptrsz == 8 { - s.value = order.Uint64(p[0:8]) - p = p[8:] - } else { - s.value = uint64(order.Uint32(p[0:4])) - p = p[4:] - } - - var typ byte - typ = p[0] & 0x7F - s.typ = typ - p = p[1:] - - // Name. - var i int - var nnul int - for i = 0; i < len(p); i++ { - if p[i] == 0 { - nnul = 1 - break - } - } - switch typ { - case 'z', 'Z': - p = p[i+nnul:] - for i = 0; i+2 <= len(p); i += 2 { - if p[i] == 0 && p[i+1] == 0 { - nnul = 2 - break - } - } - } - if len(p) < i+nnul { - return &formatError{len(data), "unexpected EOF", nil} - } - s.name = p[0:i] - i += nnul - p = p[i:] - - fn(s) - } - return nil -} - -// NewTable decodes the Go symbol table in data, -// returning an in-memory representation. -func newTable(symtab []byte, ptrsz int) ([]Sym, error) { - var n int - err := walksymtab(symtab, ptrsz, func(s sym) error { - n++ - return nil - }) - if err != nil { - return nil, err - } - - fname := make(map[uint16]string) - syms := make([]Sym, 0, n) - err = walksymtab(symtab, ptrsz, func(s sym) error { - n := len(syms) - syms = syms[0 : n+1] - ts := &syms[n] - ts.Type = rune(s.typ) - ts.Value = s.value - switch s.typ { - default: - ts.Name = string(s.name[:]) - case 'z', 'Z': - for i := 0; i < len(s.name); i += 2 { - eltIdx := binary.BigEndian.Uint16(s.name[i : i+2]) - elt, ok := fname[eltIdx] - if !ok { - return &formatError{-1, "bad filename code", eltIdx} - } - if n := len(ts.Name); n > 0 && ts.Name[n-1] != '/' { - ts.Name += "/" - } - ts.Name += elt - } - } - switch s.typ { - case 'f': - fname[uint16(s.value)] = ts.Name - } - return nil - }) - if err != nil { - return nil, err - } - - return syms, nil -} - -// Symbols returns the symbol table for f. -func (f *File) Symbols() ([]Sym, error) { - symtabSection := f.Section("syms") - if symtabSection == nil { - return nil, errors.New("no symbol section") - } - - symtab, err := symtabSection.Data() - if err != nil { - return nil, errors.New("cannot load symbol section") - } - - return newTable(symtab, f.PtrSize) -} - -// Section returns a section with the given name, or nil if no such -// section exists. -func (f *File) Section(name string) *Section { - for _, s := range f.Sections { - if s.Name == name { - return s - } - } - return nil -} diff --git a/src/pkg/debug/plan9obj/file_test.go b/src/pkg/debug/plan9obj/file_test.go deleted file mode 100644 index cfd7a61d1..000000000 --- a/src/pkg/debug/plan9obj/file_test.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package plan9obj - -import ( - "reflect" - "testing" -) - -type fileTest struct { - file string - hdr FileHeader - sections []*SectionHeader -} - -var fileTests = []fileTest{ - { - "testdata/386-plan9-exec", - FileHeader{Magic386, 0x324, 0x14, 4, 0x1000, 32}, - []*SectionHeader{ - {"text", 0x4c5f, 0x20}, - {"data", 0x94c, 0x4c7f}, - {"syms", 0x2c2b, 0x55cb}, - {"spsz", 0x0, 0x81f6}, - {"pcsz", 0xf7a, 0x81f6}, - }, - }, - { - "testdata/amd64-plan9-exec", - FileHeader{MagicAMD64, 0x618, 0x13, 8, 0x200000, 40}, - []*SectionHeader{ - {"text", 0x4213, 0x28}, - {"data", 0xa80, 0x423b}, - {"syms", 0x2c8c, 0x4cbb}, - {"spsz", 0x0, 0x7947}, - {"pcsz", 0xca0, 0x7947}, - }, - }, -} - -func TestOpen(t *testing.T) { - for i := range fileTests { - tt := &fileTests[i] - - f, err := Open(tt.file) - if err != nil { - t.Error(err) - continue - } - if !reflect.DeepEqual(f.FileHeader, tt.hdr) { - t.Errorf("open %s:\n\thave %#v\n\twant %#v\n", tt.file, f.FileHeader, tt.hdr) - continue - } - - for i, sh := range f.Sections { - if i >= len(tt.sections) { - break - } - have := &sh.SectionHeader - want := tt.sections[i] - if !reflect.DeepEqual(have, want) { - t.Errorf("open %s, section %d:\n\thave %#v\n\twant %#v\n", tt.file, i, have, want) - } - } - tn := len(tt.sections) - fn := len(f.Sections) - if tn != fn { - t.Errorf("open %s: len(Sections) = %d, want %d", tt.file, fn, tn) - } - } -} - -func TestOpenFailure(t *testing.T) { - filename := "file.go" // not a Plan 9 a.out file - _, err := Open(filename) // don't crash - if err == nil { - t.Errorf("open %s: succeeded unexpectedly", filename) - } -} diff --git a/src/pkg/debug/plan9obj/plan9obj.go b/src/pkg/debug/plan9obj/plan9obj.go deleted file mode 100644 index af9858562..000000000 --- a/src/pkg/debug/plan9obj/plan9obj.go +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright 2014 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* - * Plan 9 a.out constants and data structures - */ - -package plan9obj - -// Plan 9 Program header. -type prog struct { - Magic uint32 /* magic number */ - Text uint32 /* size of text segment */ - Data uint32 /* size of initialized data */ - Bss uint32 /* size of uninitialized data */ - Syms uint32 /* size of symbol table */ - Entry uint32 /* entry point */ - Spsz uint32 /* size of pc/sp offset table */ - Pcsz uint32 /* size of pc/line number table */ -} - -// Plan 9 symbol table entries. -type sym struct { - value uint64 - typ byte - name []byte -} - -const ( - Magic64 = 0x8000 // 64-bit expanded header - - Magic386 = (4*11+0)*11 + 7 - MagicAMD64 = (4*26+0)*26 + 7 + Magic64 - MagicARM = (4*20+0)*20 + 7 -) diff --git a/src/pkg/debug/plan9obj/testdata/386-plan9-exec b/src/pkg/debug/plan9obj/testdata/386-plan9-exec deleted file mode 100755 index 748e83f8e..000000000 Binary files a/src/pkg/debug/plan9obj/testdata/386-plan9-exec and /dev/null differ diff --git a/src/pkg/debug/plan9obj/testdata/amd64-plan9-exec b/src/pkg/debug/plan9obj/testdata/amd64-plan9-exec deleted file mode 100755 index 3e257dd8f..000000000 Binary files a/src/pkg/debug/plan9obj/testdata/amd64-plan9-exec and /dev/null differ diff --git a/src/pkg/debug/plan9obj/testdata/hello.c b/src/pkg/debug/plan9obj/testdata/hello.c deleted file mode 100644 index c0d633e29..000000000 --- a/src/pkg/debug/plan9obj/testdata/hello.c +++ /dev/null @@ -1,8 +0,0 @@ -#include -#include - -void -main(void) -{ - print("hello, world\n"); -} diff --git a/src/pkg/encoding/ascii85/ascii85.go b/src/pkg/encoding/ascii85/ascii85.go deleted file mode 100644 index 4d7193873..000000000 --- a/src/pkg/encoding/ascii85/ascii85.go +++ /dev/null @@ -1,310 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package ascii85 implements the ascii85 data encoding -// as used in the btoa tool and Adobe's PostScript and PDF document formats. -package ascii85 - -import ( - "io" - "strconv" -) - -/* - * Encoder - */ - -// Encode encodes src into at most MaxEncodedLen(len(src)) -// bytes of dst, returning the actual number of bytes written. -// -// The encoding handles 4-byte chunks, using a special encoding -// for the last fragment, so Encode is not appropriate for use on -// individual blocks of a large data stream. Use NewEncoder() instead. -// -// Often, ascii85-encoded data is wrapped in <~ and ~> symbols. -// Encode does not add these. -func Encode(dst, src []byte) int { - if len(src) == 0 { - return 0 - } - - n := 0 - for len(src) > 0 { - dst[0] = 0 - dst[1] = 0 - dst[2] = 0 - dst[3] = 0 - dst[4] = 0 - - // Unpack 4 bytes into uint32 to repack into base 85 5-byte. - var v uint32 - switch len(src) { - default: - v |= uint32(src[3]) - fallthrough - case 3: - v |= uint32(src[2]) << 8 - fallthrough - case 2: - v |= uint32(src[1]) << 16 - fallthrough - case 1: - v |= uint32(src[0]) << 24 - } - - // Special case: zero (!!!!!) shortens to z. - if v == 0 && len(src) >= 4 { - dst[0] = 'z' - dst = dst[1:] - src = src[4:] - n++ - continue - } - - // Otherwise, 5 base 85 digits starting at !. - for i := 4; i >= 0; i-- { - dst[i] = '!' + byte(v%85) - v /= 85 - } - - // If src was short, discard the low destination bytes. - m := 5 - if len(src) < 4 { - m -= 4 - len(src) - src = nil - } else { - src = src[4:] - } - dst = dst[m:] - n += m - } - return n -} - -// MaxEncodedLen returns the maximum length of an encoding of n source bytes. -func MaxEncodedLen(n int) int { return (n + 3) / 4 * 5 } - -// NewEncoder returns a new ascii85 stream encoder. Data written to -// the returned writer will be encoded and then written to w. -// Ascii85 encodings operate in 32-bit blocks; when finished -// writing, the caller must Close the returned encoder to flush any -// trailing partial block. -func NewEncoder(w io.Writer) io.WriteCloser { return &encoder{w: w} } - -type encoder struct { - err error - w io.Writer - buf [4]byte // buffered data waiting to be encoded - nbuf int // number of bytes in buf - out [1024]byte // output buffer -} - -func (e *encoder) Write(p []byte) (n int, err error) { - if e.err != nil { - return 0, e.err - } - - // Leading fringe. - if e.nbuf > 0 { - var i int - for i = 0; i < len(p) && e.nbuf < 4; i++ { - e.buf[e.nbuf] = p[i] - e.nbuf++ - } - n += i - p = p[i:] - if e.nbuf < 4 { - return - } - nout := Encode(e.out[0:], e.buf[0:]) - if _, e.err = e.w.Write(e.out[0:nout]); e.err != nil { - return n, e.err - } - e.nbuf = 0 - } - - // Large interior chunks. - for len(p) >= 4 { - nn := len(e.out) / 5 * 4 - if nn > len(p) { - nn = len(p) - } - nn -= nn % 4 - if nn > 0 { - nout := Encode(e.out[0:], p[0:nn]) - if _, e.err = e.w.Write(e.out[0:nout]); e.err != nil { - return n, e.err - } - } - n += nn - p = p[nn:] - } - - // Trailing fringe. - for i := 0; i < len(p); i++ { - e.buf[i] = p[i] - } - e.nbuf = len(p) - n += len(p) - return -} - -// Close flushes any pending output from the encoder. -// It is an error to call Write after calling Close. -func (e *encoder) Close() error { - // If there's anything left in the buffer, flush it out - if e.err == nil && e.nbuf > 0 { - nout := Encode(e.out[0:], e.buf[0:e.nbuf]) - e.nbuf = 0 - _, e.err = e.w.Write(e.out[0:nout]) - } - return e.err -} - -/* - * Decoder - */ - -type CorruptInputError int64 - -func (e CorruptInputError) Error() string { - return "illegal ascii85 data at input byte " + strconv.FormatInt(int64(e), 10) -} - -// Decode decodes src into dst, returning both the number -// of bytes written to dst and the number consumed from src. -// If src contains invalid ascii85 data, Decode will return the -// number of bytes successfully written and a CorruptInputError. -// Decode ignores space and control characters in src. -// Often, ascii85-encoded data is wrapped in <~ and ~> symbols. -// Decode expects these to have been stripped by the caller. -// -// If flush is true, Decode assumes that src represents the -// end of the input stream and processes it completely rather -// than wait for the completion of another 32-bit block. -// -// NewDecoder wraps an io.Reader interface around Decode. -// -func Decode(dst, src []byte, flush bool) (ndst, nsrc int, err error) { - var v uint32 - var nb int - for i, b := range src { - if len(dst)-ndst < 4 { - return - } - switch { - case b <= ' ': - continue - case b == 'z' && nb == 0: - nb = 5 - v = 0 - case '!' <= b && b <= 'u': - v = v*85 + uint32(b-'!') - nb++ - default: - return 0, 0, CorruptInputError(i) - } - if nb == 5 { - nsrc = i + 1 - dst[ndst] = byte(v >> 24) - dst[ndst+1] = byte(v >> 16) - dst[ndst+2] = byte(v >> 8) - dst[ndst+3] = byte(v) - ndst += 4 - nb = 0 - v = 0 - } - } - if flush { - nsrc = len(src) - if nb > 0 { - // The number of output bytes in the last fragment - // is the number of leftover input bytes - 1: - // the extra byte provides enough bits to cover - // the inefficiency of the encoding for the block. - if nb == 1 { - return 0, 0, CorruptInputError(len(src)) - } - for i := nb; i < 5; i++ { - // The short encoding truncated the output value. - // We have to assume the worst case values (digit 84) - // in order to ensure that the top bits are correct. - v = v*85 + 84 - } - for i := 0; i < nb-1; i++ { - dst[ndst] = byte(v >> 24) - v <<= 8 - ndst++ - } - } - } - return -} - -// NewDecoder constructs a new ascii85 stream decoder. -func NewDecoder(r io.Reader) io.Reader { return &decoder{r: r} } - -type decoder struct { - err error - readErr error - r io.Reader - buf [1024]byte // leftover input - nbuf int - out []byte // leftover decoded output - outbuf [1024]byte -} - -func (d *decoder) Read(p []byte) (n int, err error) { - if len(p) == 0 { - return 0, nil - } - if d.err != nil { - return 0, d.err - } - - for { - // Copy leftover output from last decode. - if len(d.out) > 0 { - n = copy(p, d.out) - d.out = d.out[n:] - return - } - - // Decode leftover input from last read. - var nn, nsrc, ndst int - if d.nbuf > 0 { - ndst, nsrc, d.err = Decode(d.outbuf[0:], d.buf[0:d.nbuf], d.readErr != nil) - if ndst > 0 { - d.out = d.outbuf[0:ndst] - d.nbuf = copy(d.buf[0:], d.buf[nsrc:d.nbuf]) - continue // copy out and return - } - if ndst == 0 && d.err == nil { - // Special case: input buffer is mostly filled with non-data bytes. - // Filter out such bytes to make room for more input. - off := 0 - for i := 0; i < d.nbuf; i++ { - if d.buf[i] > ' ' { - d.buf[off] = d.buf[i] - off++ - } - } - d.nbuf = off - } - } - - // Out of input, out of decoded output. Check errors. - if d.err != nil { - return 0, d.err - } - if d.readErr != nil { - d.err = d.readErr - return 0, d.err - } - - // Read more data. - nn, d.readErr = d.r.Read(d.buf[d.nbuf:]) - d.nbuf += nn - } -} diff --git a/src/pkg/encoding/ascii85/ascii85_test.go b/src/pkg/encoding/ascii85/ascii85_test.go deleted file mode 100644 index aad199b4f..000000000 --- a/src/pkg/encoding/ascii85/ascii85_test.go +++ /dev/null @@ -1,210 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package ascii85 - -import ( - "bytes" - "io" - "io/ioutil" - "strings" - "testing" -) - -type testpair struct { - decoded, encoded string -} - -var pairs = []testpair{ - // Encode returns 0 when len(src) is 0 - { - "", - "", - }, - // Wikipedia example - { - "Man is distinguished, not only by his reason, but by this singular passion from " + - "other animals, which is a lust of the mind, that by a perseverance of delight in " + - "the continued and indefatigable generation of knowledge, exceeds the short " + - "vehemence of any carnal pleasure.", - "9jqo^BlbD-BleB1DJ+*+F(f,q/0JhKFCj@.4Gp$d7F!,L7@<6@)/0JDEF@3BB/F*&OCAfu2/AKY\n" + - "i(DIb:@FD,*)+C]U=@3BN#EcYf8ATD3s@q?d$AftVqCh[NqF-FD5W8ARlolDIa\n" + - "l(DIduD.RTpAKYo'+CT/5+Cei#DII?(E,9)oF*2M7/c\n", - }, - // Special case when shortening !!!!! to z. - { - "\000\000\000\000", - "z", - }, -} - -var bigtest = pairs[len(pairs)-1] - -func testEqual(t *testing.T, msg string, args ...interface{}) bool { - if args[len(args)-2] != args[len(args)-1] { - t.Errorf(msg, args...) - return false - } - return true -} - -func strip85(s string) string { - t := make([]byte, len(s)) - w := 0 - for r := 0; r < len(s); r++ { - c := s[r] - if c > ' ' { - t[w] = c - w++ - } - } - return string(t[0:w]) -} - -func TestEncode(t *testing.T) { - for _, p := range pairs { - buf := make([]byte, MaxEncodedLen(len(p.decoded))) - n := Encode(buf, []byte(p.decoded)) - buf = buf[0:n] - testEqual(t, "Encode(%q) = %q, want %q", p.decoded, strip85(string(buf)), strip85(p.encoded)) - } -} - -func TestEncoder(t *testing.T) { - for _, p := range pairs { - bb := &bytes.Buffer{} - encoder := NewEncoder(bb) - encoder.Write([]byte(p.decoded)) - encoder.Close() - testEqual(t, "Encode(%q) = %q, want %q", p.decoded, strip85(bb.String()), strip85(p.encoded)) - } -} - -func TestEncoderBuffering(t *testing.T) { - input := []byte(bigtest.decoded) - for bs := 1; bs <= 12; bs++ { - bb := &bytes.Buffer{} - encoder := NewEncoder(bb) - for pos := 0; pos < len(input); pos += bs { - end := pos + bs - if end > len(input) { - end = len(input) - } - n, err := encoder.Write(input[pos:end]) - testEqual(t, "Write(%q) gave error %v, want %v", input[pos:end], err, error(nil)) - testEqual(t, "Write(%q) gave length %v, want %v", input[pos:end], n, end-pos) - } - err := encoder.Close() - testEqual(t, "Close gave error %v, want %v", err, error(nil)) - testEqual(t, "Encoding/%d of %q = %q, want %q", bs, bigtest.decoded, strip85(bb.String()), strip85(bigtest.encoded)) - } -} - -func TestDecode(t *testing.T) { - for _, p := range pairs { - dbuf := make([]byte, 4*len(p.encoded)) - ndst, nsrc, err := Decode(dbuf, []byte(p.encoded), true) - testEqual(t, "Decode(%q) = error %v, want %v", p.encoded, err, error(nil)) - testEqual(t, "Decode(%q) = nsrc %v, want %v", p.encoded, nsrc, len(p.encoded)) - testEqual(t, "Decode(%q) = ndst %v, want %v", p.encoded, ndst, len(p.decoded)) - testEqual(t, "Decode(%q) = %q, want %q", p.encoded, string(dbuf[0:ndst]), p.decoded) - } -} - -func TestDecoder(t *testing.T) { - for _, p := range pairs { - decoder := NewDecoder(strings.NewReader(p.encoded)) - dbuf, err := ioutil.ReadAll(decoder) - if err != nil { - t.Fatal("Read failed", err) - } - testEqual(t, "Read from %q = length %v, want %v", p.encoded, len(dbuf), len(p.decoded)) - testEqual(t, "Decoding of %q = %q, want %q", p.encoded, string(dbuf), p.decoded) - if err != nil { - testEqual(t, "Read from %q = %v, want %v", p.encoded, err, io.EOF) - } - } -} - -func TestDecoderBuffering(t *testing.T) { - for bs := 1; bs <= 12; bs++ { - decoder := NewDecoder(strings.NewReader(bigtest.encoded)) - buf := make([]byte, len(bigtest.decoded)+12) - var total int - for total = 0; total < len(bigtest.decoded); { - n, err := decoder.Read(buf[total : total+bs]) - testEqual(t, "Read from %q at pos %d = %d, %v, want _, %v", bigtest.encoded, total, n, err, error(nil)) - total += n - } - testEqual(t, "Decoding/%d of %q = %q, want %q", bs, bigtest.encoded, string(buf[0:total]), bigtest.decoded) - } -} - -func TestDecodeCorrupt(t *testing.T) { - type corrupt struct { - e string - p int - } - examples := []corrupt{ - {"v", 0}, - {"!z!!!!!!!!!", 1}, - } - - for _, e := range examples { - dbuf := make([]byte, 4*len(e.e)) - _, _, err := Decode(dbuf, []byte(e.e), true) - switch err := err.(type) { - case CorruptInputError: - testEqual(t, "Corruption in %q at offset %v, want %v", e.e, int(err), e.p) - default: - t.Error("Decoder failed to detect corruption in", e) - } - } -} - -func TestBig(t *testing.T) { - n := 3*1000 + 1 - raw := make([]byte, n) - const alpha = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" - for i := 0; i < n; i++ { - raw[i] = alpha[i%len(alpha)] - } - encoded := new(bytes.Buffer) - w := NewEncoder(encoded) - nn, err := w.Write(raw) - if nn != n || err != nil { - t.Fatalf("Encoder.Write(raw) = %d, %v want %d, nil", nn, err, n) - } - err = w.Close() - if err != nil { - t.Fatalf("Encoder.Close() = %v want nil", err) - } - decoded, err := ioutil.ReadAll(NewDecoder(encoded)) - if err != nil { - t.Fatalf("io.ReadAll(NewDecoder(...)): %v", err) - } - - if !bytes.Equal(raw, decoded) { - var i int - for i = 0; i < len(decoded) && i < len(raw); i++ { - if decoded[i] != raw[i] { - break - } - } - t.Errorf("Decode(Encode(%d-byte string)) failed at offset %d", n, i) - } -} - -func TestDecoderInternalWhitespace(t *testing.T) { - s := strings.Repeat(" ", 2048) + "z" - decoded, err := ioutil.ReadAll(NewDecoder(strings.NewReader(s))) - if err != nil { - t.Errorf("Decode gave error %v", err) - } - if want := []byte("\000\000\000\000"); !bytes.Equal(want, decoded) { - t.Errorf("Decode failed: got %v, want %v", decoded, want) - } -} diff --git a/src/pkg/encoding/asn1/asn1.go b/src/pkg/encoding/asn1/asn1.go deleted file mode 100644 index b06aec3e4..000000000 --- a/src/pkg/encoding/asn1/asn1.go +++ /dev/null @@ -1,918 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package asn1 implements parsing of DER-encoded ASN.1 data structures, -// as defined in ITU-T Rec X.690. -// -// See also ``A Layman's Guide to a Subset of ASN.1, BER, and DER,'' -// http://luca.ntop.org/Teaching/Appunti/asn1.html. -package asn1 - -// ASN.1 is a syntax for specifying abstract objects and BER, DER, PER, XER etc -// are different encoding formats for those objects. Here, we'll be dealing -// with DER, the Distinguished Encoding Rules. DER is used in X.509 because -// it's fast to parse and, unlike BER, has a unique encoding for every object. -// When calculating hashes over objects, it's important that the resulting -// bytes be the same at both ends and DER removes this margin of error. -// -// ASN.1 is very complex and this package doesn't attempt to implement -// everything by any means. - -import ( - "fmt" - "math/big" - "reflect" - "strconv" - "time" -) - -// A StructuralError suggests that the ASN.1 data is valid, but the Go type -// which is receiving it doesn't match. -type StructuralError struct { - Msg string -} - -func (e StructuralError) Error() string { return "asn1: structure error: " + e.Msg } - -// A SyntaxError suggests that the ASN.1 data is invalid. -type SyntaxError struct { - Msg string -} - -func (e SyntaxError) Error() string { return "asn1: syntax error: " + e.Msg } - -// We start by dealing with each of the primitive types in turn. - -// BOOLEAN - -func parseBool(bytes []byte) (ret bool, err error) { - if len(bytes) != 1 { - err = SyntaxError{"invalid boolean"} - return - } - - // DER demands that "If the encoding represents the boolean value TRUE, - // its single contents octet shall have all eight bits set to one." - // Thus only 0 and 255 are valid encoded values. - switch bytes[0] { - case 0: - ret = false - case 0xff: - ret = true - default: - err = SyntaxError{"invalid boolean"} - } - - return -} - -// INTEGER - -// parseInt64 treats the given bytes as a big-endian, signed integer and -// returns the result. -func parseInt64(bytes []byte) (ret int64, err error) { - if len(bytes) > 8 { - // We'll overflow an int64 in this case. - err = StructuralError{"integer too large"} - return - } - for bytesRead := 0; bytesRead < len(bytes); bytesRead++ { - ret <<= 8 - ret |= int64(bytes[bytesRead]) - } - - // Shift up and down in order to sign extend the result. - ret <<= 64 - uint8(len(bytes))*8 - ret >>= 64 - uint8(len(bytes))*8 - return -} - -// parseInt treats the given bytes as a big-endian, signed integer and returns -// the result. -func parseInt32(bytes []byte) (int32, error) { - ret64, err := parseInt64(bytes) - if err != nil { - return 0, err - } - if ret64 != int64(int32(ret64)) { - return 0, StructuralError{"integer too large"} - } - return int32(ret64), nil -} - -var bigOne = big.NewInt(1) - -// parseBigInt treats the given bytes as a big-endian, signed integer and returns -// the result. -func parseBigInt(bytes []byte) *big.Int { - ret := new(big.Int) - if len(bytes) > 0 && bytes[0]&0x80 == 0x80 { - // This is a negative number. - notBytes := make([]byte, len(bytes)) - for i := range notBytes { - notBytes[i] = ^bytes[i] - } - ret.SetBytes(notBytes) - ret.Add(ret, bigOne) - ret.Neg(ret) - return ret - } - ret.SetBytes(bytes) - return ret -} - -// BIT STRING - -// BitString is the structure to use when you want an ASN.1 BIT STRING type. A -// bit string is padded up to the nearest byte in memory and the number of -// valid bits is recorded. Padding bits will be zero. -type BitString struct { - Bytes []byte // bits packed into bytes. - BitLength int // length in bits. -} - -// At returns the bit at the given index. If the index is out of range it -// returns false. -func (b BitString) At(i int) int { - if i < 0 || i >= b.BitLength { - return 0 - } - x := i / 8 - y := 7 - uint(i%8) - return int(b.Bytes[x]>>y) & 1 -} - -// RightAlign returns a slice where the padding bits are at the beginning. The -// slice may share memory with the BitString. -func (b BitString) RightAlign() []byte { - shift := uint(8 - (b.BitLength % 8)) - if shift == 8 || len(b.Bytes) == 0 { - return b.Bytes - } - - a := make([]byte, len(b.Bytes)) - a[0] = b.Bytes[0] >> shift - for i := 1; i < len(b.Bytes); i++ { - a[i] = b.Bytes[i-1] << (8 - shift) - a[i] |= b.Bytes[i] >> shift - } - - return a -} - -// parseBitString parses an ASN.1 bit string from the given byte slice and returns it. -func parseBitString(bytes []byte) (ret BitString, err error) { - if len(bytes) == 0 { - err = SyntaxError{"zero length BIT STRING"} - return - } - paddingBits := int(bytes[0]) - if paddingBits > 7 || - len(bytes) == 1 && paddingBits > 0 || - bytes[len(bytes)-1]&((1< 0 { - s += "." - } - s += strconv.Itoa(v) - } - - return s -} - -// parseObjectIdentifier parses an OBJECT IDENTIFIER from the given bytes and -// returns it. An object identifier is a sequence of variable length integers -// that are assigned in a hierarchy. -func parseObjectIdentifier(bytes []byte) (s []int, err error) { - if len(bytes) == 0 { - err = SyntaxError{"zero length OBJECT IDENTIFIER"} - return - } - - // In the worst case, we get two elements from the first byte (which is - // encoded differently) and then every varint is a single byte long. - s = make([]int, len(bytes)+1) - - // The first varint is 40*value1 + value2: - // According to this packing, value1 can take the values 0, 1 and 2 only. - // When value1 = 0 or value1 = 1, then value2 is <= 39. When value1 = 2, - // then there are no restrictions on value2. - v, offset, err := parseBase128Int(bytes, 0) - if err != nil { - return - } - if v < 80 { - s[0] = v / 40 - s[1] = v % 40 - } else { - s[0] = 2 - s[1] = v - 80 - } - - i := 2 - for ; offset < len(bytes); i++ { - v, offset, err = parseBase128Int(bytes, offset) - if err != nil { - return - } - s[i] = v - } - s = s[0:i] - return -} - -// ENUMERATED - -// An Enumerated is represented as a plain int. -type Enumerated int - -// FLAG - -// A Flag accepts any data and is set to true if present. -type Flag bool - -// parseBase128Int parses a base-128 encoded int from the given offset in the -// given byte slice. It returns the value and the new offset. -func parseBase128Int(bytes []byte, initOffset int) (ret, offset int, err error) { - offset = initOffset - for shifted := 0; offset < len(bytes); shifted++ { - if shifted > 4 { - err = StructuralError{"base 128 integer too large"} - return - } - ret <<= 7 - b := bytes[offset] - ret |= int(b & 0x7f) - offset++ - if b&0x80 == 0 { - return - } - } - err = SyntaxError{"truncated base 128 integer"} - return -} - -// UTCTime - -func parseUTCTime(bytes []byte) (ret time.Time, err error) { - s := string(bytes) - ret, err = time.Parse("0601021504Z0700", s) - if err != nil { - ret, err = time.Parse("060102150405Z0700", s) - } - if err == nil && ret.Year() >= 2050 { - // UTCTime only encodes times prior to 2050. See https://tools.ietf.org/html/rfc5280#section-4.1.2.5.1 - ret = ret.AddDate(-100, 0, 0) - } - - return -} - -// parseGeneralizedTime parses the GeneralizedTime from the given byte slice -// and returns the resulting time. -func parseGeneralizedTime(bytes []byte) (ret time.Time, err error) { - return time.Parse("20060102150405Z0700", string(bytes)) -} - -// PrintableString - -// parsePrintableString parses a ASN.1 PrintableString from the given byte -// array and returns it. -func parsePrintableString(bytes []byte) (ret string, err error) { - for _, b := range bytes { - if !isPrintable(b) { - err = SyntaxError{"PrintableString contains invalid character"} - return - } - } - ret = string(bytes) - return -} - -// isPrintable returns true iff the given b is in the ASN.1 PrintableString set. -func isPrintable(b byte) bool { - return 'a' <= b && b <= 'z' || - 'A' <= b && b <= 'Z' || - '0' <= b && b <= '9' || - '\'' <= b && b <= ')' || - '+' <= b && b <= '/' || - b == ' ' || - b == ':' || - b == '=' || - b == '?' || - // This is technically not allowed in a PrintableString. - // However, x509 certificates with wildcard strings don't - // always use the correct string type so we permit it. - b == '*' -} - -// IA5String - -// parseIA5String parses a ASN.1 IA5String (ASCII string) from the given -// byte slice and returns it. -func parseIA5String(bytes []byte) (ret string, err error) { - for _, b := range bytes { - if b >= 0x80 { - err = SyntaxError{"IA5String contains invalid character"} - return - } - } - ret = string(bytes) - return -} - -// T61String - -// parseT61String parses a ASN.1 T61String (8-bit clean string) from the given -// byte slice and returns it. -func parseT61String(bytes []byte) (ret string, err error) { - return string(bytes), nil -} - -// UTF8String - -// parseUTF8String parses a ASN.1 UTF8String (raw UTF-8) from the given byte -// array and returns it. -func parseUTF8String(bytes []byte) (ret string, err error) { - return string(bytes), nil -} - -// A RawValue represents an undecoded ASN.1 object. -type RawValue struct { - Class, Tag int - IsCompound bool - Bytes []byte - FullBytes []byte // includes the tag and length -} - -// RawContent is used to signal that the undecoded, DER data needs to be -// preserved for a struct. To use it, the first field of the struct must have -// this type. It's an error for any of the other fields to have this type. -type RawContent []byte - -// Tagging - -// parseTagAndLength parses an ASN.1 tag and length pair from the given offset -// into a byte slice. It returns the parsed data and the new offset. SET and -// SET OF (tag 17) are mapped to SEQUENCE and SEQUENCE OF (tag 16) since we -// don't distinguish between ordered and unordered objects in this code. -func parseTagAndLength(bytes []byte, initOffset int) (ret tagAndLength, offset int, err error) { - offset = initOffset - b := bytes[offset] - offset++ - ret.class = int(b >> 6) - ret.isCompound = b&0x20 == 0x20 - ret.tag = int(b & 0x1f) - - // If the bottom five bits are set, then the tag number is actually base 128 - // encoded afterwards - if ret.tag == 0x1f { - ret.tag, offset, err = parseBase128Int(bytes, offset) - if err != nil { - return - } - } - if offset >= len(bytes) { - err = SyntaxError{"truncated tag or length"} - return - } - b = bytes[offset] - offset++ - if b&0x80 == 0 { - // The length is encoded in the bottom 7 bits. - ret.length = int(b & 0x7f) - } else { - // Bottom 7 bits give the number of length bytes to follow. - numBytes := int(b & 0x7f) - if numBytes == 0 { - err = SyntaxError{"indefinite length found (not DER)"} - return - } - ret.length = 0 - for i := 0; i < numBytes; i++ { - if offset >= len(bytes) { - err = SyntaxError{"truncated tag or length"} - return - } - b = bytes[offset] - offset++ - if ret.length >= 1<<23 { - // We can't shift ret.length up without - // overflowing. - err = StructuralError{"length too large"} - return - } - ret.length <<= 8 - ret.length |= int(b) - if ret.length == 0 { - // DER requires that lengths be minimal. - err = StructuralError{"superfluous leading zeros in length"} - return - } - } - } - - return -} - -// parseSequenceOf is used for SEQUENCE OF and SET OF values. It tries to parse -// a number of ASN.1 values from the given byte slice and returns them as a -// slice of Go values of the given type. -func parseSequenceOf(bytes []byte, sliceType reflect.Type, elemType reflect.Type) (ret reflect.Value, err error) { - expectedTag, compoundType, ok := getUniversalType(elemType) - if !ok { - err = StructuralError{"unknown Go type for slice"} - return - } - - // First we iterate over the input and count the number of elements, - // checking that the types are correct in each case. - numElements := 0 - for offset := 0; offset < len(bytes); { - var t tagAndLength - t, offset, err = parseTagAndLength(bytes, offset) - if err != nil { - return - } - switch t.tag { - case tagIA5String, tagGeneralString, tagT61String, tagUTF8String: - // We pretend that various other string types are - // PRINTABLE STRINGs so that a sequence of them can be - // parsed into a []string. - t.tag = tagPrintableString - case tagGeneralizedTime, tagUTCTime: - // Likewise, both time types are treated the same. - t.tag = tagUTCTime - } - - if t.class != classUniversal || t.isCompound != compoundType || t.tag != expectedTag { - err = StructuralError{"sequence tag mismatch"} - return - } - if invalidLength(offset, t.length, len(bytes)) { - err = SyntaxError{"truncated sequence"} - return - } - offset += t.length - numElements++ - } - ret = reflect.MakeSlice(sliceType, numElements, numElements) - params := fieldParameters{} - offset := 0 - for i := 0; i < numElements; i++ { - offset, err = parseField(ret.Index(i), bytes, offset, params) - if err != nil { - return - } - } - return -} - -var ( - bitStringType = reflect.TypeOf(BitString{}) - objectIdentifierType = reflect.TypeOf(ObjectIdentifier{}) - enumeratedType = reflect.TypeOf(Enumerated(0)) - flagType = reflect.TypeOf(Flag(false)) - timeType = reflect.TypeOf(time.Time{}) - rawValueType = reflect.TypeOf(RawValue{}) - rawContentsType = reflect.TypeOf(RawContent(nil)) - bigIntType = reflect.TypeOf(new(big.Int)) -) - -// invalidLength returns true iff offset + length > sliceLength, or if the -// addition would overflow. -func invalidLength(offset, length, sliceLength int) bool { - return offset+length < offset || offset+length > sliceLength -} - -// parseField is the main parsing function. Given a byte slice and an offset -// into the array, it will try to parse a suitable ASN.1 value out and store it -// in the given Value. -func parseField(v reflect.Value, bytes []byte, initOffset int, params fieldParameters) (offset int, err error) { - offset = initOffset - fieldType := v.Type() - - // If we have run out of data, it may be that there are optional elements at the end. - if offset == len(bytes) { - if !setDefaultValue(v, params) { - err = SyntaxError{"sequence truncated"} - } - return - } - - // Deal with raw values. - if fieldType == rawValueType { - var t tagAndLength - t, offset, err = parseTagAndLength(bytes, offset) - if err != nil { - return - } - if invalidLength(offset, t.length, len(bytes)) { - err = SyntaxError{"data truncated"} - return - } - result := RawValue{t.class, t.tag, t.isCompound, bytes[offset : offset+t.length], bytes[initOffset : offset+t.length]} - offset += t.length - v.Set(reflect.ValueOf(result)) - return - } - - // Deal with the ANY type. - if ifaceType := fieldType; ifaceType.Kind() == reflect.Interface && ifaceType.NumMethod() == 0 { - var t tagAndLength - t, offset, err = parseTagAndLength(bytes, offset) - if err != nil { - return - } - if invalidLength(offset, t.length, len(bytes)) { - err = SyntaxError{"data truncated"} - return - } - var result interface{} - if !t.isCompound && t.class == classUniversal { - innerBytes := bytes[offset : offset+t.length] - switch t.tag { - case tagPrintableString: - result, err = parsePrintableString(innerBytes) - case tagIA5String: - result, err = parseIA5String(innerBytes) - case tagT61String: - result, err = parseT61String(innerBytes) - case tagUTF8String: - result, err = parseUTF8String(innerBytes) - case tagInteger: - result, err = parseInt64(innerBytes) - case tagBitString: - result, err = parseBitString(innerBytes) - case tagOID: - result, err = parseObjectIdentifier(innerBytes) - case tagUTCTime: - result, err = parseUTCTime(innerBytes) - case tagOctetString: - result = innerBytes - default: - // If we don't know how to handle the type, we just leave Value as nil. - } - } - offset += t.length - if err != nil { - return - } - if result != nil { - v.Set(reflect.ValueOf(result)) - } - return - } - universalTag, compoundType, ok1 := getUniversalType(fieldType) - if !ok1 { - err = StructuralError{fmt.Sprintf("unknown Go type: %v", fieldType)} - return - } - - t, offset, err := parseTagAndLength(bytes, offset) - if err != nil { - return - } - if params.explicit { - expectedClass := classContextSpecific - if params.application { - expectedClass = classApplication - } - if t.class == expectedClass && t.tag == *params.tag && (t.length == 0 || t.isCompound) { - if t.length > 0 { - t, offset, err = parseTagAndLength(bytes, offset) - if err != nil { - return - } - } else { - if fieldType != flagType { - err = StructuralError{"zero length explicit tag was not an asn1.Flag"} - return - } - v.SetBool(true) - return - } - } else { - // The tags didn't match, it might be an optional element. - ok := setDefaultValue(v, params) - if ok { - offset = initOffset - } else { - err = StructuralError{"explicitly tagged member didn't match"} - } - return - } - } - - // Special case for strings: all the ASN.1 string types map to the Go - // type string. getUniversalType returns the tag for PrintableString - // when it sees a string, so if we see a different string type on the - // wire, we change the universal type to match. - if universalTag == tagPrintableString { - switch t.tag { - case tagIA5String, tagGeneralString, tagT61String, tagUTF8String: - universalTag = t.tag - } - } - - // Special case for time: UTCTime and GeneralizedTime both map to the - // Go type time.Time. - if universalTag == tagUTCTime && t.tag == tagGeneralizedTime { - universalTag = tagGeneralizedTime - } - - if params.set { - universalTag = tagSet - } - - expectedClass := classUniversal - expectedTag := universalTag - - if !params.explicit && params.tag != nil { - expectedClass = classContextSpecific - expectedTag = *params.tag - } - - if !params.explicit && params.application && params.tag != nil { - expectedClass = classApplication - expectedTag = *params.tag - } - - // We have unwrapped any explicit tagging at this point. - if t.class != expectedClass || t.tag != expectedTag || t.isCompound != compoundType { - // Tags don't match. Again, it could be an optional element. - ok := setDefaultValue(v, params) - if ok { - offset = initOffset - } else { - err = StructuralError{fmt.Sprintf("tags don't match (%d vs %+v) %+v %s @%d", expectedTag, t, params, fieldType.Name(), offset)} - } - return - } - if invalidLength(offset, t.length, len(bytes)) { - err = SyntaxError{"data truncated"} - return - } - innerBytes := bytes[offset : offset+t.length] - offset += t.length - - // We deal with the structures defined in this package first. - switch fieldType { - case objectIdentifierType: - newSlice, err1 := parseObjectIdentifier(innerBytes) - v.Set(reflect.MakeSlice(v.Type(), len(newSlice), len(newSlice))) - if err1 == nil { - reflect.Copy(v, reflect.ValueOf(newSlice)) - } - err = err1 - return - case bitStringType: - bs, err1 := parseBitString(innerBytes) - if err1 == nil { - v.Set(reflect.ValueOf(bs)) - } - err = err1 - return - case timeType: - var time time.Time - var err1 error - if universalTag == tagUTCTime { - time, err1 = parseUTCTime(innerBytes) - } else { - time, err1 = parseGeneralizedTime(innerBytes) - } - if err1 == nil { - v.Set(reflect.ValueOf(time)) - } - err = err1 - return - case enumeratedType: - parsedInt, err1 := parseInt32(innerBytes) - if err1 == nil { - v.SetInt(int64(parsedInt)) - } - err = err1 - return - case flagType: - v.SetBool(true) - return - case bigIntType: - parsedInt := parseBigInt(innerBytes) - v.Set(reflect.ValueOf(parsedInt)) - return - } - switch val := v; val.Kind() { - case reflect.Bool: - parsedBool, err1 := parseBool(innerBytes) - if err1 == nil { - val.SetBool(parsedBool) - } - err = err1 - return - case reflect.Int, reflect.Int32, reflect.Int64: - if val.Type().Size() == 4 { - parsedInt, err1 := parseInt32(innerBytes) - if err1 == nil { - val.SetInt(int64(parsedInt)) - } - err = err1 - } else { - parsedInt, err1 := parseInt64(innerBytes) - if err1 == nil { - val.SetInt(parsedInt) - } - err = err1 - } - return - // TODO(dfc) Add support for the remaining integer types - case reflect.Struct: - structType := fieldType - - if structType.NumField() > 0 && - structType.Field(0).Type == rawContentsType { - bytes := bytes[initOffset:offset] - val.Field(0).Set(reflect.ValueOf(RawContent(bytes))) - } - - innerOffset := 0 - for i := 0; i < structType.NumField(); i++ { - field := structType.Field(i) - if i == 0 && field.Type == rawContentsType { - continue - } - innerOffset, err = parseField(val.Field(i), innerBytes, innerOffset, parseFieldParameters(field.Tag.Get("asn1"))) - if err != nil { - return - } - } - // We allow extra bytes at the end of the SEQUENCE because - // adding elements to the end has been used in X.509 as the - // version numbers have increased. - return - case reflect.Slice: - sliceType := fieldType - if sliceType.Elem().Kind() == reflect.Uint8 { - val.Set(reflect.MakeSlice(sliceType, len(innerBytes), len(innerBytes))) - reflect.Copy(val, reflect.ValueOf(innerBytes)) - return - } - newSlice, err1 := parseSequenceOf(innerBytes, sliceType, sliceType.Elem()) - if err1 == nil { - val.Set(newSlice) - } - err = err1 - return - case reflect.String: - var v string - switch universalTag { - case tagPrintableString: - v, err = parsePrintableString(innerBytes) - case tagIA5String: - v, err = parseIA5String(innerBytes) - case tagT61String: - v, err = parseT61String(innerBytes) - case tagUTF8String: - v, err = parseUTF8String(innerBytes) - case tagGeneralString: - // GeneralString is specified in ISO-2022/ECMA-35, - // A brief review suggests that it includes structures - // that allow the encoding to change midstring and - // such. We give up and pass it as an 8-bit string. - v, err = parseT61String(innerBytes) - default: - err = SyntaxError{fmt.Sprintf("internal error: unknown string type %d", universalTag)} - } - if err == nil { - val.SetString(v) - } - return - } - err = StructuralError{"unsupported: " + v.Type().String()} - return -} - -// canHaveDefaultValue reports whether k is a Kind that we will set a default -// value for. (A signed integer, essentially.) -func canHaveDefaultValue(k reflect.Kind) bool { - switch k { - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return true - } - - return false -} - -// setDefaultValue is used to install a default value, from a tag string, into -// a Value. It is successful if the field was optional, even if a default value -// wasn't provided or it failed to install it into the Value. -func setDefaultValue(v reflect.Value, params fieldParameters) (ok bool) { - if !params.optional { - return - } - ok = true - if params.defaultValue == nil { - return - } - if canHaveDefaultValue(v.Kind()) { - v.SetInt(*params.defaultValue) - } - return -} - -// Unmarshal parses the DER-encoded ASN.1 data structure b -// and uses the reflect package to fill in an arbitrary value pointed at by val. -// Because Unmarshal uses the reflect package, the structs -// being written to must use upper case field names. -// -// An ASN.1 INTEGER can be written to an int, int32, int64, -// or *big.Int (from the math/big package). -// If the encoded value does not fit in the Go type, -// Unmarshal returns a parse error. -// -// An ASN.1 BIT STRING can be written to a BitString. -// -// An ASN.1 OCTET STRING can be written to a []byte. -// -// An ASN.1 OBJECT IDENTIFIER can be written to an -// ObjectIdentifier. -// -// An ASN.1 ENUMERATED can be written to an Enumerated. -// -// An ASN.1 UTCTIME or GENERALIZEDTIME can be written to a time.Time. -// -// An ASN.1 PrintableString or IA5String can be written to a string. -// -// Any of the above ASN.1 values can be written to an interface{}. -// The value stored in the interface has the corresponding Go type. -// For integers, that type is int64. -// -// An ASN.1 SEQUENCE OF x or SET OF x can be written -// to a slice if an x can be written to the slice's element type. -// -// An ASN.1 SEQUENCE or SET can be written to a struct -// if each of the elements in the sequence can be -// written to the corresponding element in the struct. -// -// The following tags on struct fields have special meaning to Unmarshal: -// -// application specifies that a APPLICATION tag is used -// default:x sets the default value for optional integer fields -// explicit specifies that an additional, explicit tag wraps the implicit one -// optional marks the field as ASN.1 OPTIONAL -// set causes a SET, rather than a SEQUENCE type to be expected -// tag:x specifies the ASN.1 tag number; implies ASN.1 CONTEXT SPECIFIC -// -// If the type of the first field of a structure is RawContent then the raw -// ASN1 contents of the struct will be stored in it. -// -// If the type name of a slice element ends with "SET" then it's treated as if -// the "set" tag was set on it. This can be used with nested slices where a -// struct tag cannot be given. -// -// Other ASN.1 types are not supported; if it encounters them, -// Unmarshal returns a parse error. -func Unmarshal(b []byte, val interface{}) (rest []byte, err error) { - return UnmarshalWithParams(b, val, "") -} - -// UnmarshalWithParams allows field parameters to be specified for the -// top-level element. The form of the params is the same as the field tags. -func UnmarshalWithParams(b []byte, val interface{}, params string) (rest []byte, err error) { - v := reflect.ValueOf(val).Elem() - offset, err := parseField(v, b, 0, parseFieldParameters(params)) - if err != nil { - return nil, err - } - return b[offset:], nil -} diff --git a/src/pkg/encoding/asn1/asn1_test.go b/src/pkg/encoding/asn1/asn1_test.go deleted file mode 100644 index b553f78e0..000000000 --- a/src/pkg/encoding/asn1/asn1_test.go +++ /dev/null @@ -1,814 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package asn1 - -import ( - "bytes" - "fmt" - "math/big" - "reflect" - "testing" - "time" -) - -type boolTest struct { - in []byte - ok bool - out bool -} - -var boolTestData = []boolTest{ - {[]byte{0x00}, true, false}, - {[]byte{0xff}, true, true}, - {[]byte{0x00, 0x00}, false, false}, - {[]byte{0xff, 0xff}, false, false}, - {[]byte{0x01}, false, false}, -} - -func TestParseBool(t *testing.T) { - for i, test := range boolTestData { - ret, err := parseBool(test.in) - if (err == nil) != test.ok { - t.Errorf("#%d: Incorrect error result (did fail? %v, expected: %v)", i, err == nil, test.ok) - } - if test.ok && ret != test.out { - t.Errorf("#%d: Bad result: %v (expected %v)", i, ret, test.out) - } - } -} - -type int64Test struct { - in []byte - ok bool - out int64 -} - -var int64TestData = []int64Test{ - {[]byte{0x00}, true, 0}, - {[]byte{0x7f}, true, 127}, - {[]byte{0x00, 0x80}, true, 128}, - {[]byte{0x01, 0x00}, true, 256}, - {[]byte{0x80}, true, -128}, - {[]byte{0xff, 0x7f}, true, -129}, - {[]byte{0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff}, true, -1}, - {[]byte{0xff}, true, -1}, - {[]byte{0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, true, -9223372036854775808}, - {[]byte{0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, false, 0}, -} - -func TestParseInt64(t *testing.T) { - for i, test := range int64TestData { - ret, err := parseInt64(test.in) - if (err == nil) != test.ok { - t.Errorf("#%d: Incorrect error result (did fail? %v, expected: %v)", i, err == nil, test.ok) - } - if test.ok && ret != test.out { - t.Errorf("#%d: Bad result: %v (expected %v)", i, ret, test.out) - } - } -} - -type int32Test struct { - in []byte - ok bool - out int32 -} - -var int32TestData = []int32Test{ - {[]byte{0x00}, true, 0}, - {[]byte{0x7f}, true, 127}, - {[]byte{0x00, 0x80}, true, 128}, - {[]byte{0x01, 0x00}, true, 256}, - {[]byte{0x80}, true, -128}, - {[]byte{0xff, 0x7f}, true, -129}, - {[]byte{0xff, 0xff, 0xff, 0xff}, true, -1}, - {[]byte{0xff}, true, -1}, - {[]byte{0x80, 0x00, 0x00, 0x00}, true, -2147483648}, - {[]byte{0x80, 0x00, 0x00, 0x00, 0x00}, false, 0}, -} - -func TestParseInt32(t *testing.T) { - for i, test := range int32TestData { - ret, err := parseInt32(test.in) - if (err == nil) != test.ok { - t.Errorf("#%d: Incorrect error result (did fail? %v, expected: %v)", i, err == nil, test.ok) - } - if test.ok && int32(ret) != test.out { - t.Errorf("#%d: Bad result: %v (expected %v)", i, ret, test.out) - } - } -} - -var bigIntTests = []struct { - in []byte - base10 string -}{ - {[]byte{0xff}, "-1"}, - {[]byte{0x00}, "0"}, - {[]byte{0x01}, "1"}, - {[]byte{0x00, 0xff}, "255"}, - {[]byte{0xff, 0x00}, "-256"}, - {[]byte{0x01, 0x00}, "256"}, -} - -func TestParseBigInt(t *testing.T) { - for i, test := range bigIntTests { - ret := parseBigInt(test.in) - if ret.String() != test.base10 { - t.Errorf("#%d: bad result from %x, got %s want %s", i, test.in, ret.String(), test.base10) - } - fw := newForkableWriter() - marshalBigInt(fw, ret) - result := fw.Bytes() - if !bytes.Equal(result, test.in) { - t.Errorf("#%d: got %x from marshaling %s, want %x", i, result, ret, test.in) - } - } -} - -type bitStringTest struct { - in []byte - ok bool - out []byte - bitLength int -} - -var bitStringTestData = []bitStringTest{ - {[]byte{}, false, []byte{}, 0}, - {[]byte{0x00}, true, []byte{}, 0}, - {[]byte{0x07, 0x00}, true, []byte{0x00}, 1}, - {[]byte{0x07, 0x01}, false, []byte{}, 0}, - {[]byte{0x07, 0x40}, false, []byte{}, 0}, - {[]byte{0x08, 0x00}, false, []byte{}, 0}, -} - -func TestBitString(t *testing.T) { - for i, test := range bitStringTestData { - ret, err := parseBitString(test.in) - if (err == nil) != test.ok { - t.Errorf("#%d: Incorrect error result (did fail? %v, expected: %v)", i, err == nil, test.ok) - } - if err == nil { - if test.bitLength != ret.BitLength || !bytes.Equal(ret.Bytes, test.out) { - t.Errorf("#%d: Bad result: %v (expected %v %v)", i, ret, test.out, test.bitLength) - } - } - } -} - -func TestBitStringAt(t *testing.T) { - bs := BitString{[]byte{0x82, 0x40}, 16} - if bs.At(0) != 1 { - t.Error("#1: Failed") - } - if bs.At(1) != 0 { - t.Error("#2: Failed") - } - if bs.At(6) != 1 { - t.Error("#3: Failed") - } - if bs.At(9) != 1 { - t.Error("#4: Failed") - } - if bs.At(-1) != 0 { - t.Error("#5: Failed") - } - if bs.At(17) != 0 { - t.Error("#6: Failed") - } -} - -type bitStringRightAlignTest struct { - in []byte - inlen int - out []byte -} - -var bitStringRightAlignTests = []bitStringRightAlignTest{ - {[]byte{0x80}, 1, []byte{0x01}}, - {[]byte{0x80, 0x80}, 9, []byte{0x01, 0x01}}, - {[]byte{}, 0, []byte{}}, - {[]byte{0xce}, 8, []byte{0xce}}, - {[]byte{0xce, 0x47}, 16, []byte{0xce, 0x47}}, - {[]byte{0x34, 0x50}, 12, []byte{0x03, 0x45}}, -} - -func TestBitStringRightAlign(t *testing.T) { - for i, test := range bitStringRightAlignTests { - bs := BitString{test.in, test.inlen} - out := bs.RightAlign() - if !bytes.Equal(out, test.out) { - t.Errorf("#%d got: %x want: %x", i, out, test.out) - } - } -} - -type objectIdentifierTest struct { - in []byte - ok bool - out []int -} - -var objectIdentifierTestData = []objectIdentifierTest{ - {[]byte{}, false, []int{}}, - {[]byte{85}, true, []int{2, 5}}, - {[]byte{85, 0x02}, true, []int{2, 5, 2}}, - {[]byte{85, 0x02, 0xc0, 0x00}, true, []int{2, 5, 2, 0x2000}}, - {[]byte{0x81, 0x34, 0x03}, true, []int{2, 100, 3}}, - {[]byte{85, 0x02, 0xc0, 0x80, 0x80, 0x80, 0x80}, false, []int{}}, -} - -func TestObjectIdentifier(t *testing.T) { - for i, test := range objectIdentifierTestData { - ret, err := parseObjectIdentifier(test.in) - if (err == nil) != test.ok { - t.Errorf("#%d: Incorrect error result (did fail? %v, expected: %v)", i, err == nil, test.ok) - } - if err == nil { - if !reflect.DeepEqual(test.out, ret) { - t.Errorf("#%d: Bad result: %v (expected %v)", i, ret, test.out) - } - } - } - - if s := ObjectIdentifier([]int{1, 2, 3, 4}).String(); s != "1.2.3.4" { - t.Errorf("bad ObjectIdentifier.String(). Got %s, want 1.2.3.4", s) - } -} - -type timeTest struct { - in string - ok bool - out time.Time -} - -var utcTestData = []timeTest{ - {"910506164540-0700", true, time.Date(1991, 05, 06, 16, 45, 40, 0, time.FixedZone("", -7*60*60))}, - {"910506164540+0730", true, time.Date(1991, 05, 06, 16, 45, 40, 0, time.FixedZone("", 7*60*60+30*60))}, - {"910506234540Z", true, time.Date(1991, 05, 06, 23, 45, 40, 0, time.UTC)}, - {"9105062345Z", true, time.Date(1991, 05, 06, 23, 45, 0, 0, time.UTC)}, - {"5105062345Z", true, time.Date(1951, 05, 06, 23, 45, 0, 0, time.UTC)}, - {"a10506234540Z", false, time.Time{}}, - {"91a506234540Z", false, time.Time{}}, - {"9105a6234540Z", false, time.Time{}}, - {"910506a34540Z", false, time.Time{}}, - {"910506334a40Z", false, time.Time{}}, - {"91050633444aZ", false, time.Time{}}, - {"910506334461Z", false, time.Time{}}, - {"910506334400Za", false, time.Time{}}, -} - -func TestUTCTime(t *testing.T) { - for i, test := range utcTestData { - ret, err := parseUTCTime([]byte(test.in)) - if err != nil { - if test.ok { - t.Errorf("#%d: parseUTCTime(%q) = error %v", i, test.in, err) - } - continue - } - if !test.ok { - t.Errorf("#%d: parseUTCTime(%q) succeeded, should have failed", i, test.in) - continue - } - const format = "Jan _2 15:04:05 -0700 2006" // ignore zone name, just offset - have := ret.Format(format) - want := test.out.Format(format) - if have != want { - t.Errorf("#%d: parseUTCTime(%q) = %s, want %s", i, test.in, have, want) - } - } -} - -var generalizedTimeTestData = []timeTest{ - {"20100102030405Z", true, time.Date(2010, 01, 02, 03, 04, 05, 0, time.UTC)}, - {"20100102030405", false, time.Time{}}, - {"20100102030405+0607", true, time.Date(2010, 01, 02, 03, 04, 05, 0, time.FixedZone("", 6*60*60+7*60))}, - {"20100102030405-0607", true, time.Date(2010, 01, 02, 03, 04, 05, 0, time.FixedZone("", -6*60*60-7*60))}, -} - -func TestGeneralizedTime(t *testing.T) { - for i, test := range generalizedTimeTestData { - ret, err := parseGeneralizedTime([]byte(test.in)) - if (err == nil) != test.ok { - t.Errorf("#%d: Incorrect error result (did fail? %v, expected: %v)", i, err == nil, test.ok) - } - if err == nil { - if !reflect.DeepEqual(test.out, ret) { - t.Errorf("#%d: Bad result: %v (expected %v)", i, ret, test.out) - } - } - } -} - -type tagAndLengthTest struct { - in []byte - ok bool - out tagAndLength -} - -var tagAndLengthData = []tagAndLengthTest{ - {[]byte{0x80, 0x01}, true, tagAndLength{2, 0, 1, false}}, - {[]byte{0xa0, 0x01}, true, tagAndLength{2, 0, 1, true}}, - {[]byte{0x02, 0x00}, true, tagAndLength{0, 2, 0, false}}, - {[]byte{0xfe, 0x00}, true, tagAndLength{3, 30, 0, true}}, - {[]byte{0x1f, 0x01, 0x00}, true, tagAndLength{0, 1, 0, false}}, - {[]byte{0x1f, 0x81, 0x00, 0x00}, true, tagAndLength{0, 128, 0, false}}, - {[]byte{0x1f, 0x81, 0x80, 0x01, 0x00}, true, tagAndLength{0, 0x4001, 0, false}}, - {[]byte{0x00, 0x81, 0x01}, true, tagAndLength{0, 0, 1, false}}, - {[]byte{0x00, 0x82, 0x01, 0x00}, true, tagAndLength{0, 0, 256, false}}, - {[]byte{0x00, 0x83, 0x01, 0x00}, false, tagAndLength{}}, - {[]byte{0x1f, 0x85}, false, tagAndLength{}}, - {[]byte{0x30, 0x80}, false, tagAndLength{}}, - // Superfluous zeros in the length should be an error. - {[]byte{0xa0, 0x82, 0x00, 0x01}, false, tagAndLength{}}, - // Lengths up to the maximum size of an int should work. - {[]byte{0xa0, 0x84, 0x7f, 0xff, 0xff, 0xff}, true, tagAndLength{2, 0, 0x7fffffff, true}}, - // Lengths that would overflow an int should be rejected. - {[]byte{0xa0, 0x84, 0x80, 0x00, 0x00, 0x00}, false, tagAndLength{}}, -} - -func TestParseTagAndLength(t *testing.T) { - for i, test := range tagAndLengthData { - tagAndLength, _, err := parseTagAndLength(test.in, 0) - if (err == nil) != test.ok { - t.Errorf("#%d: Incorrect error result (did pass? %v, expected: %v)", i, err == nil, test.ok) - } - if err == nil && !reflect.DeepEqual(test.out, tagAndLength) { - t.Errorf("#%d: Bad result: %v (expected %v)", i, tagAndLength, test.out) - } - } -} - -type parseFieldParametersTest struct { - in string - out fieldParameters -} - -func newInt(n int) *int { return &n } - -func newInt64(n int64) *int64 { return &n } - -func newString(s string) *string { return &s } - -func newBool(b bool) *bool { return &b } - -var parseFieldParametersTestData []parseFieldParametersTest = []parseFieldParametersTest{ - {"", fieldParameters{}}, - {"ia5", fieldParameters{stringType: tagIA5String}}, - {"printable", fieldParameters{stringType: tagPrintableString}}, - {"optional", fieldParameters{optional: true}}, - {"explicit", fieldParameters{explicit: true, tag: new(int)}}, - {"application", fieldParameters{application: true, tag: new(int)}}, - {"optional,explicit", fieldParameters{optional: true, explicit: true, tag: new(int)}}, - {"default:42", fieldParameters{defaultValue: newInt64(42)}}, - {"tag:17", fieldParameters{tag: newInt(17)}}, - {"optional,explicit,default:42,tag:17", fieldParameters{optional: true, explicit: true, defaultValue: newInt64(42), tag: newInt(17)}}, - {"optional,explicit,default:42,tag:17,rubbish1", fieldParameters{true, true, false, newInt64(42), newInt(17), 0, false, false}}, - {"set", fieldParameters{set: true}}, -} - -func TestParseFieldParameters(t *testing.T) { - for i, test := range parseFieldParametersTestData { - f := parseFieldParameters(test.in) - if !reflect.DeepEqual(f, test.out) { - t.Errorf("#%d: Bad result: %v (expected %v)", i, f, test.out) - } - } -} - -type TestObjectIdentifierStruct struct { - OID ObjectIdentifier -} - -type TestContextSpecificTags struct { - A int `asn1:"tag:1"` -} - -type TestContextSpecificTags2 struct { - A int `asn1:"explicit,tag:1"` - B int -} - -type TestElementsAfterString struct { - S string - A, B int -} - -type TestBigInt struct { - X *big.Int -} - -type TestSet struct { - Ints []int `asn1:"set"` -} - -var unmarshalTestData = []struct { - in []byte - out interface{} -}{ - {[]byte{0x02, 0x01, 0x42}, newInt(0x42)}, - {[]byte{0x30, 0x08, 0x06, 0x06, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d}, &TestObjectIdentifierStruct{[]int{1, 2, 840, 113549}}}, - {[]byte{0x03, 0x04, 0x06, 0x6e, 0x5d, 0xc0}, &BitString{[]byte{110, 93, 192}, 18}}, - {[]byte{0x30, 0x09, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02, 0x02, 0x01, 0x03}, &[]int{1, 2, 3}}, - {[]byte{0x02, 0x01, 0x10}, newInt(16)}, - {[]byte{0x13, 0x04, 't', 'e', 's', 't'}, newString("test")}, - {[]byte{0x16, 0x04, 't', 'e', 's', 't'}, newString("test")}, - {[]byte{0x16, 0x04, 't', 'e', 's', 't'}, &RawValue{0, 22, false, []byte("test"), []byte("\x16\x04test")}}, - {[]byte{0x04, 0x04, 1, 2, 3, 4}, &RawValue{0, 4, false, []byte{1, 2, 3, 4}, []byte{4, 4, 1, 2, 3, 4}}}, - {[]byte{0x30, 0x03, 0x81, 0x01, 0x01}, &TestContextSpecificTags{1}}, - {[]byte{0x30, 0x08, 0xa1, 0x03, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02}, &TestContextSpecificTags2{1, 2}}, - {[]byte{0x01, 0x01, 0x00}, newBool(false)}, - {[]byte{0x01, 0x01, 0xff}, newBool(true)}, - {[]byte{0x30, 0x0b, 0x13, 0x03, 0x66, 0x6f, 0x6f, 0x02, 0x01, 0x22, 0x02, 0x01, 0x33}, &TestElementsAfterString{"foo", 0x22, 0x33}}, - {[]byte{0x30, 0x05, 0x02, 0x03, 0x12, 0x34, 0x56}, &TestBigInt{big.NewInt(0x123456)}}, - {[]byte{0x30, 0x0b, 0x31, 0x09, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02, 0x02, 0x01, 0x03}, &TestSet{Ints: []int{1, 2, 3}}}, -} - -func TestUnmarshal(t *testing.T) { - for i, test := range unmarshalTestData { - pv := reflect.New(reflect.TypeOf(test.out).Elem()) - val := pv.Interface() - _, err := Unmarshal(test.in, val) - if err != nil { - t.Errorf("Unmarshal failed at index %d %v", i, err) - } - if !reflect.DeepEqual(val, test.out) { - t.Errorf("#%d:\nhave %#v\nwant %#v", i, val, test.out) - } - } -} - -type Certificate struct { - TBSCertificate TBSCertificate - SignatureAlgorithm AlgorithmIdentifier - SignatureValue BitString -} - -type TBSCertificate struct { - Version int `asn1:"optional,explicit,default:0,tag:0"` - SerialNumber RawValue - SignatureAlgorithm AlgorithmIdentifier - Issuer RDNSequence - Validity Validity - Subject RDNSequence - PublicKey PublicKeyInfo -} - -type AlgorithmIdentifier struct { - Algorithm ObjectIdentifier -} - -type RDNSequence []RelativeDistinguishedNameSET - -type RelativeDistinguishedNameSET []AttributeTypeAndValue - -type AttributeTypeAndValue struct { - Type ObjectIdentifier - Value interface{} -} - -type Validity struct { - NotBefore, NotAfter time.Time -} - -type PublicKeyInfo struct { - Algorithm AlgorithmIdentifier - PublicKey BitString -} - -func TestCertificate(t *testing.T) { - // This is a minimal, self-signed certificate that should parse correctly. - var cert Certificate - if _, err := Unmarshal(derEncodedSelfSignedCertBytes, &cert); err != nil { - t.Errorf("Unmarshal failed: %v", err) - } - if !reflect.DeepEqual(cert, derEncodedSelfSignedCert) { - t.Errorf("Bad result:\ngot: %+v\nwant: %+v", cert, derEncodedSelfSignedCert) - } -} - -func TestCertificateWithNUL(t *testing.T) { - // This is the paypal NUL-hack certificate. It should fail to parse because - // NUL isn't a permitted character in a PrintableString. - - var cert Certificate - if _, err := Unmarshal(derEncodedPaypalNULCertBytes, &cert); err == nil { - t.Error("Unmarshal succeeded, should not have") - } -} - -type rawStructTest struct { - Raw RawContent - A int -} - -func TestRawStructs(t *testing.T) { - var s rawStructTest - input := []byte{0x30, 0x03, 0x02, 0x01, 0x50} - - rest, err := Unmarshal(input, &s) - if len(rest) != 0 { - t.Errorf("incomplete parse: %x", rest) - return - } - if err != nil { - t.Error(err) - return - } - if s.A != 0x50 { - t.Errorf("bad value for A: got %d want %d", s.A, 0x50) - } - if !bytes.Equal([]byte(s.Raw), input) { - t.Errorf("bad value for Raw: got %x want %x", s.Raw, input) - } -} - -type oiEqualTest struct { - first ObjectIdentifier - second ObjectIdentifier - same bool -} - -var oiEqualTests = []oiEqualTest{ - { - ObjectIdentifier{1, 2, 3}, - ObjectIdentifier{1, 2, 3}, - true, - }, - { - ObjectIdentifier{1}, - ObjectIdentifier{1, 2, 3}, - false, - }, - { - ObjectIdentifier{1, 2, 3}, - ObjectIdentifier{10, 11, 12}, - false, - }, -} - -func TestObjectIdentifierEqual(t *testing.T) { - for _, o := range oiEqualTests { - if s := o.first.Equal(o.second); s != o.same { - t.Errorf("ObjectIdentifier.Equal: got: %t want: %t", s, o.same) - } - } -} - -var derEncodedSelfSignedCert = Certificate{ - TBSCertificate: TBSCertificate{ - Version: 0, - SerialNumber: RawValue{Class: 0, Tag: 2, IsCompound: false, Bytes: []uint8{0x0, 0x8c, 0xc3, 0x37, 0x92, 0x10, 0xec, 0x2c, 0x98}, FullBytes: []byte{2, 9, 0x0, 0x8c, 0xc3, 0x37, 0x92, 0x10, 0xec, 0x2c, 0x98}}, - SignatureAlgorithm: AlgorithmIdentifier{Algorithm: ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}}, - Issuer: RDNSequence{ - RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{2, 5, 4, 6}, Value: "XX"}}, - RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{2, 5, 4, 8}, Value: "Some-State"}}, - RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{2, 5, 4, 7}, Value: "City"}}, - RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{2, 5, 4, 10}, Value: "Internet Widgits Pty Ltd"}}, - RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{2, 5, 4, 3}, Value: "false.example.com"}}, - RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{1, 2, 840, 113549, 1, 9, 1}, Value: "false@example.com"}}, - }, - Validity: Validity{ - NotBefore: time.Date(2009, 10, 8, 00, 25, 53, 0, time.UTC), - NotAfter: time.Date(2010, 10, 8, 00, 25, 53, 0, time.UTC), - }, - Subject: RDNSequence{ - RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{2, 5, 4, 6}, Value: "XX"}}, - RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{2, 5, 4, 8}, Value: "Some-State"}}, - RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{2, 5, 4, 7}, Value: "City"}}, - RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{2, 5, 4, 10}, Value: "Internet Widgits Pty Ltd"}}, - RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{2, 5, 4, 3}, Value: "false.example.com"}}, - RelativeDistinguishedNameSET{AttributeTypeAndValue{Type: ObjectIdentifier{1, 2, 840, 113549, 1, 9, 1}, Value: "false@example.com"}}, - }, - PublicKey: PublicKeyInfo{ - Algorithm: AlgorithmIdentifier{Algorithm: ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}}, - PublicKey: BitString{ - Bytes: []uint8{ - 0x30, 0x48, 0x2, 0x41, 0x0, 0xcd, 0xb7, - 0x63, 0x9c, 0x32, 0x78, 0xf0, 0x6, 0xaa, 0x27, 0x7f, 0x6e, 0xaf, 0x42, - 0x90, 0x2b, 0x59, 0x2d, 0x8c, 0xbc, 0xbe, 0x38, 0xa1, 0xc9, 0x2b, 0xa4, - 0x69, 0x5a, 0x33, 0x1b, 0x1d, 0xea, 0xde, 0xad, 0xd8, 0xe9, 0xa5, 0xc2, - 0x7e, 0x8c, 0x4c, 0x2f, 0xd0, 0xa8, 0x88, 0x96, 0x57, 0x72, 0x2a, 0x4f, - 0x2a, 0xf7, 0x58, 0x9c, 0xf2, 0xc7, 0x70, 0x45, 0xdc, 0x8f, 0xde, 0xec, - 0x35, 0x7d, 0x2, 0x3, 0x1, 0x0, 0x1, - }, - BitLength: 592, - }, - }, - }, - SignatureAlgorithm: AlgorithmIdentifier{Algorithm: ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}}, - SignatureValue: BitString{ - Bytes: []uint8{ - 0xa6, 0x7b, 0x6, 0xec, 0x5e, 0xce, - 0x92, 0x77, 0x2c, 0xa4, 0x13, 0xcb, 0xa3, 0xca, 0x12, 0x56, 0x8f, 0xdc, 0x6c, - 0x7b, 0x45, 0x11, 0xcd, 0x40, 0xa7, 0xf6, 0x59, 0x98, 0x4, 0x2, 0xdf, 0x2b, - 0x99, 0x8b, 0xb9, 0xa4, 0xa8, 0xcb, 0xeb, 0x34, 0xc0, 0xf0, 0xa7, 0x8c, 0xf8, - 0xd9, 0x1e, 0xde, 0x14, 0xa5, 0xed, 0x76, 0xbf, 0x11, 0x6f, 0xe3, 0x60, 0xaa, - 0xfa, 0x88, 0x21, 0x49, 0x4, 0x35, - }, - BitLength: 512, - }, -} - -var derEncodedSelfSignedCertBytes = []byte{ - 0x30, 0x82, 0x02, 0x18, 0x30, - 0x82, 0x01, 0xc2, 0x02, 0x09, 0x00, 0x8c, 0xc3, 0x37, 0x92, 0x10, 0xec, 0x2c, - 0x98, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, - 0x05, 0x05, 0x00, 0x30, 0x81, 0x92, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, - 0x04, 0x06, 0x13, 0x02, 0x58, 0x58, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, - 0x04, 0x08, 0x13, 0x0a, 0x53, 0x6f, 0x6d, 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, - 0x65, 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x04, 0x43, - 0x69, 0x74, 0x79, 0x31, 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, - 0x18, 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x20, 0x57, 0x69, 0x64, - 0x67, 0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c, 0x74, 0x64, 0x31, - 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x66, 0x61, 0x6c, - 0x73, 0x65, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, - 0x6d, 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, - 0x01, 0x09, 0x01, 0x16, 0x11, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x40, 0x65, 0x78, - 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x30, 0x1e, 0x17, 0x0d, - 0x30, 0x39, 0x31, 0x30, 0x30, 0x38, 0x30, 0x30, 0x32, 0x35, 0x35, 0x33, 0x5a, - 0x17, 0x0d, 0x31, 0x30, 0x31, 0x30, 0x30, 0x38, 0x30, 0x30, 0x32, 0x35, 0x35, - 0x33, 0x5a, 0x30, 0x81, 0x92, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, - 0x06, 0x13, 0x02, 0x58, 0x58, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, - 0x08, 0x13, 0x0a, 0x53, 0x6f, 0x6d, 0x65, 0x2d, 0x53, 0x74, 0x61, 0x74, 0x65, - 0x31, 0x0d, 0x30, 0x0b, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x04, 0x43, 0x69, - 0x74, 0x79, 0x31, 0x21, 0x30, 0x1f, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x18, - 0x49, 0x6e, 0x74, 0x65, 0x72, 0x6e, 0x65, 0x74, 0x20, 0x57, 0x69, 0x64, 0x67, - 0x69, 0x74, 0x73, 0x20, 0x50, 0x74, 0x79, 0x20, 0x4c, 0x74, 0x64, 0x31, 0x1a, - 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x11, 0x66, 0x61, 0x6c, 0x73, - 0x65, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d, - 0x31, 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, - 0x09, 0x01, 0x16, 0x11, 0x66, 0x61, 0x6c, 0x73, 0x65, 0x40, 0x65, 0x78, 0x61, - 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x63, 0x6f, 0x6d, 0x30, 0x5c, 0x30, 0x0d, 0x06, - 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, - 0x4b, 0x00, 0x30, 0x48, 0x02, 0x41, 0x00, 0xcd, 0xb7, 0x63, 0x9c, 0x32, 0x78, - 0xf0, 0x06, 0xaa, 0x27, 0x7f, 0x6e, 0xaf, 0x42, 0x90, 0x2b, 0x59, 0x2d, 0x8c, - 0xbc, 0xbe, 0x38, 0xa1, 0xc9, 0x2b, 0xa4, 0x69, 0x5a, 0x33, 0x1b, 0x1d, 0xea, - 0xde, 0xad, 0xd8, 0xe9, 0xa5, 0xc2, 0x7e, 0x8c, 0x4c, 0x2f, 0xd0, 0xa8, 0x88, - 0x96, 0x57, 0x72, 0x2a, 0x4f, 0x2a, 0xf7, 0x58, 0x9c, 0xf2, 0xc7, 0x70, 0x45, - 0xdc, 0x8f, 0xde, 0xec, 0x35, 0x7d, 0x02, 0x03, 0x01, 0x00, 0x01, 0x30, 0x0d, - 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, - 0x03, 0x41, 0x00, 0xa6, 0x7b, 0x06, 0xec, 0x5e, 0xce, 0x92, 0x77, 0x2c, 0xa4, - 0x13, 0xcb, 0xa3, 0xca, 0x12, 0x56, 0x8f, 0xdc, 0x6c, 0x7b, 0x45, 0x11, 0xcd, - 0x40, 0xa7, 0xf6, 0x59, 0x98, 0x04, 0x02, 0xdf, 0x2b, 0x99, 0x8b, 0xb9, 0xa4, - 0xa8, 0xcb, 0xeb, 0x34, 0xc0, 0xf0, 0xa7, 0x8c, 0xf8, 0xd9, 0x1e, 0xde, 0x14, - 0xa5, 0xed, 0x76, 0xbf, 0x11, 0x6f, 0xe3, 0x60, 0xaa, 0xfa, 0x88, 0x21, 0x49, - 0x04, 0x35, -} - -var derEncodedPaypalNULCertBytes = []byte{ - 0x30, 0x82, 0x06, 0x44, 0x30, - 0x82, 0x05, 0xad, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x03, 0x00, 0xf0, 0x9b, - 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, - 0x05, 0x00, 0x30, 0x82, 0x01, 0x12, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, - 0x04, 0x06, 0x13, 0x02, 0x45, 0x53, 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, - 0x04, 0x08, 0x13, 0x09, 0x42, 0x61, 0x72, 0x63, 0x65, 0x6c, 0x6f, 0x6e, 0x61, - 0x31, 0x12, 0x30, 0x10, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x09, 0x42, 0x61, - 0x72, 0x63, 0x65, 0x6c, 0x6f, 0x6e, 0x61, 0x31, 0x29, 0x30, 0x27, 0x06, 0x03, - 0x55, 0x04, 0x0a, 0x13, 0x20, 0x49, 0x50, 0x53, 0x20, 0x43, 0x65, 0x72, 0x74, - 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x41, 0x75, 0x74, - 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x20, 0x73, 0x2e, 0x6c, 0x2e, 0x31, 0x2e, - 0x30, 0x2c, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x14, 0x25, 0x67, 0x65, 0x6e, 0x65, - 0x72, 0x61, 0x6c, 0x40, 0x69, 0x70, 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, - 0x20, 0x43, 0x2e, 0x49, 0x2e, 0x46, 0x2e, 0x20, 0x20, 0x42, 0x2d, 0x42, 0x36, - 0x32, 0x32, 0x31, 0x30, 0x36, 0x39, 0x35, 0x31, 0x2e, 0x30, 0x2c, 0x06, 0x03, - 0x55, 0x04, 0x0b, 0x13, 0x25, 0x69, 0x70, 0x73, 0x43, 0x41, 0x20, 0x43, 0x4c, - 0x41, 0x53, 0x45, 0x41, 0x31, 0x20, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, - 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, - 0x69, 0x74, 0x79, 0x31, 0x2e, 0x30, 0x2c, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, - 0x25, 0x69, 0x70, 0x73, 0x43, 0x41, 0x20, 0x43, 0x4c, 0x41, 0x53, 0x45, 0x41, - 0x31, 0x20, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x20, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x69, 0x74, 0x79, 0x31, - 0x20, 0x30, 0x1e, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, - 0x01, 0x16, 0x11, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x6c, 0x40, 0x69, 0x70, - 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x30, 0x1e, 0x17, 0x0d, 0x30, 0x39, - 0x30, 0x32, 0x32, 0x34, 0x32, 0x33, 0x30, 0x34, 0x31, 0x37, 0x5a, 0x17, 0x0d, - 0x31, 0x31, 0x30, 0x32, 0x32, 0x34, 0x32, 0x33, 0x30, 0x34, 0x31, 0x37, 0x5a, - 0x30, 0x81, 0x94, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, - 0x02, 0x55, 0x53, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, - 0x0a, 0x43, 0x61, 0x6c, 0x69, 0x66, 0x6f, 0x72, 0x6e, 0x69, 0x61, 0x31, 0x16, - 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x0d, 0x53, 0x61, 0x6e, 0x20, - 0x46, 0x72, 0x61, 0x6e, 0x63, 0x69, 0x73, 0x63, 0x6f, 0x31, 0x11, 0x30, 0x0f, - 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x08, 0x53, 0x65, 0x63, 0x75, 0x72, 0x69, - 0x74, 0x79, 0x31, 0x14, 0x30, 0x12, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x13, 0x0b, - 0x53, 0x65, 0x63, 0x75, 0x72, 0x65, 0x20, 0x55, 0x6e, 0x69, 0x74, 0x31, 0x2f, - 0x30, 0x2d, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x26, 0x77, 0x77, 0x77, 0x2e, - 0x70, 0x61, 0x79, 0x70, 0x61, 0x6c, 0x2e, 0x63, 0x6f, 0x6d, 0x00, 0x73, 0x73, - 0x6c, 0x2e, 0x73, 0x65, 0x63, 0x75, 0x72, 0x65, 0x63, 0x6f, 0x6e, 0x6e, 0x65, - 0x63, 0x74, 0x69, 0x6f, 0x6e, 0x2e, 0x63, 0x63, 0x30, 0x81, 0x9f, 0x30, 0x0d, - 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, - 0x03, 0x81, 0x8d, 0x00, 0x30, 0x81, 0x89, 0x02, 0x81, 0x81, 0x00, 0xd2, 0x69, - 0xfa, 0x6f, 0x3a, 0x00, 0xb4, 0x21, 0x1b, 0xc8, 0xb1, 0x02, 0xd7, 0x3f, 0x19, - 0xb2, 0xc4, 0x6d, 0xb4, 0x54, 0xf8, 0x8b, 0x8a, 0xcc, 0xdb, 0x72, 0xc2, 0x9e, - 0x3c, 0x60, 0xb9, 0xc6, 0x91, 0x3d, 0x82, 0xb7, 0x7d, 0x99, 0xff, 0xd1, 0x29, - 0x84, 0xc1, 0x73, 0x53, 0x9c, 0x82, 0xdd, 0xfc, 0x24, 0x8c, 0x77, 0xd5, 0x41, - 0xf3, 0xe8, 0x1e, 0x42, 0xa1, 0xad, 0x2d, 0x9e, 0xff, 0x5b, 0x10, 0x26, 0xce, - 0x9d, 0x57, 0x17, 0x73, 0x16, 0x23, 0x38, 0xc8, 0xd6, 0xf1, 0xba, 0xa3, 0x96, - 0x5b, 0x16, 0x67, 0x4a, 0x4f, 0x73, 0x97, 0x3a, 0x4d, 0x14, 0xa4, 0xf4, 0xe2, - 0x3f, 0x8b, 0x05, 0x83, 0x42, 0xd1, 0xd0, 0xdc, 0x2f, 0x7a, 0xe5, 0xb6, 0x10, - 0xb2, 0x11, 0xc0, 0xdc, 0x21, 0x2a, 0x90, 0xff, 0xae, 0x97, 0x71, 0x5a, 0x49, - 0x81, 0xac, 0x40, 0xf3, 0x3b, 0xb8, 0x59, 0xb2, 0x4f, 0x02, 0x03, 0x01, 0x00, - 0x01, 0xa3, 0x82, 0x03, 0x21, 0x30, 0x82, 0x03, 0x1d, 0x30, 0x09, 0x06, 0x03, - 0x55, 0x1d, 0x13, 0x04, 0x02, 0x30, 0x00, 0x30, 0x11, 0x06, 0x09, 0x60, 0x86, - 0x48, 0x01, 0x86, 0xf8, 0x42, 0x01, 0x01, 0x04, 0x04, 0x03, 0x02, 0x06, 0x40, - 0x30, 0x0b, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x04, 0x04, 0x03, 0x02, 0x03, 0xf8, - 0x30, 0x13, 0x06, 0x03, 0x55, 0x1d, 0x25, 0x04, 0x0c, 0x30, 0x0a, 0x06, 0x08, - 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x03, 0x01, 0x30, 0x1d, 0x06, 0x03, 0x55, - 0x1d, 0x0e, 0x04, 0x16, 0x04, 0x14, 0x61, 0x8f, 0x61, 0x34, 0x43, 0x55, 0x14, - 0x7f, 0x27, 0x09, 0xce, 0x4c, 0x8b, 0xea, 0x9b, 0x7b, 0x19, 0x25, 0xbc, 0x6e, - 0x30, 0x1f, 0x06, 0x03, 0x55, 0x1d, 0x23, 0x04, 0x18, 0x30, 0x16, 0x80, 0x14, - 0x0e, 0x07, 0x60, 0xd4, 0x39, 0xc9, 0x1b, 0x5b, 0x5d, 0x90, 0x7b, 0x23, 0xc8, - 0xd2, 0x34, 0x9d, 0x4a, 0x9a, 0x46, 0x39, 0x30, 0x09, 0x06, 0x03, 0x55, 0x1d, - 0x11, 0x04, 0x02, 0x30, 0x00, 0x30, 0x1c, 0x06, 0x03, 0x55, 0x1d, 0x12, 0x04, - 0x15, 0x30, 0x13, 0x81, 0x11, 0x67, 0x65, 0x6e, 0x65, 0x72, 0x61, 0x6c, 0x40, - 0x69, 0x70, 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x30, 0x72, 0x06, 0x09, - 0x60, 0x86, 0x48, 0x01, 0x86, 0xf8, 0x42, 0x01, 0x0d, 0x04, 0x65, 0x16, 0x63, - 0x4f, 0x72, 0x67, 0x61, 0x6e, 0x69, 0x7a, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, - 0x49, 0x6e, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x4e, - 0x4f, 0x54, 0x20, 0x56, 0x41, 0x4c, 0x49, 0x44, 0x41, 0x54, 0x45, 0x44, 0x2e, - 0x20, 0x43, 0x4c, 0x41, 0x53, 0x45, 0x41, 0x31, 0x20, 0x53, 0x65, 0x72, 0x76, - 0x65, 0x72, 0x20, 0x43, 0x65, 0x72, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, - 0x65, 0x20, 0x69, 0x73, 0x73, 0x75, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x68, - 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x70, - 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x30, 0x2f, 0x06, 0x09, 0x60, - 0x86, 0x48, 0x01, 0x86, 0xf8, 0x42, 0x01, 0x02, 0x04, 0x22, 0x16, 0x20, 0x68, - 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x70, - 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x69, 0x70, 0x73, 0x63, 0x61, - 0x32, 0x30, 0x30, 0x32, 0x2f, 0x30, 0x43, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, - 0x86, 0xf8, 0x42, 0x01, 0x04, 0x04, 0x36, 0x16, 0x34, 0x68, 0x74, 0x74, 0x70, - 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x70, 0x73, 0x63, 0x61, - 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x69, 0x70, 0x73, 0x63, 0x61, 0x32, 0x30, 0x30, - 0x32, 0x2f, 0x69, 0x70, 0x73, 0x63, 0x61, 0x32, 0x30, 0x30, 0x32, 0x43, 0x4c, - 0x41, 0x53, 0x45, 0x41, 0x31, 0x2e, 0x63, 0x72, 0x6c, 0x30, 0x46, 0x06, 0x09, - 0x60, 0x86, 0x48, 0x01, 0x86, 0xf8, 0x42, 0x01, 0x03, 0x04, 0x39, 0x16, 0x37, - 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, - 0x70, 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x69, 0x70, 0x73, 0x63, - 0x61, 0x32, 0x30, 0x30, 0x32, 0x2f, 0x72, 0x65, 0x76, 0x6f, 0x63, 0x61, 0x74, - 0x69, 0x6f, 0x6e, 0x43, 0x4c, 0x41, 0x53, 0x45, 0x41, 0x31, 0x2e, 0x68, 0x74, - 0x6d, 0x6c, 0x3f, 0x30, 0x43, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x86, 0xf8, - 0x42, 0x01, 0x07, 0x04, 0x36, 0x16, 0x34, 0x68, 0x74, 0x74, 0x70, 0x73, 0x3a, - 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x70, 0x73, 0x63, 0x61, 0x2e, 0x63, - 0x6f, 0x6d, 0x2f, 0x69, 0x70, 0x73, 0x63, 0x61, 0x32, 0x30, 0x30, 0x32, 0x2f, - 0x72, 0x65, 0x6e, 0x65, 0x77, 0x61, 0x6c, 0x43, 0x4c, 0x41, 0x53, 0x45, 0x41, - 0x31, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x3f, 0x30, 0x41, 0x06, 0x09, 0x60, 0x86, - 0x48, 0x01, 0x86, 0xf8, 0x42, 0x01, 0x08, 0x04, 0x34, 0x16, 0x32, 0x68, 0x74, - 0x74, 0x70, 0x73, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e, 0x69, 0x70, 0x73, - 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x69, 0x70, 0x73, 0x63, 0x61, 0x32, - 0x30, 0x30, 0x32, 0x2f, 0x70, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x43, 0x4c, 0x41, - 0x53, 0x45, 0x41, 0x31, 0x2e, 0x68, 0x74, 0x6d, 0x6c, 0x30, 0x81, 0x83, 0x06, - 0x03, 0x55, 0x1d, 0x1f, 0x04, 0x7c, 0x30, 0x7a, 0x30, 0x39, 0xa0, 0x37, 0xa0, - 0x35, 0x86, 0x33, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, - 0x2e, 0x69, 0x70, 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x69, 0x70, - 0x73, 0x63, 0x61, 0x32, 0x30, 0x30, 0x32, 0x2f, 0x69, 0x70, 0x73, 0x63, 0x61, - 0x32, 0x30, 0x30, 0x32, 0x43, 0x4c, 0x41, 0x53, 0x45, 0x41, 0x31, 0x2e, 0x63, - 0x72, 0x6c, 0x30, 0x3d, 0xa0, 0x3b, 0xa0, 0x39, 0x86, 0x37, 0x68, 0x74, 0x74, - 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x62, 0x61, 0x63, 0x6b, 0x2e, 0x69, - 0x70, 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x69, 0x70, 0x73, 0x63, - 0x61, 0x32, 0x30, 0x30, 0x32, 0x2f, 0x69, 0x70, 0x73, 0x63, 0x61, 0x32, 0x30, - 0x30, 0x32, 0x43, 0x4c, 0x41, 0x53, 0x45, 0x41, 0x31, 0x2e, 0x63, 0x72, 0x6c, - 0x30, 0x32, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, 0x01, 0x01, 0x04, - 0x26, 0x30, 0x24, 0x30, 0x22, 0x06, 0x08, 0x2b, 0x06, 0x01, 0x05, 0x05, 0x07, - 0x30, 0x01, 0x86, 0x16, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x6f, 0x63, - 0x73, 0x70, 0x2e, 0x69, 0x70, 0x73, 0x63, 0x61, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, - 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, - 0x05, 0x00, 0x03, 0x81, 0x81, 0x00, 0x68, 0xee, 0x79, 0x97, 0x97, 0xdd, 0x3b, - 0xef, 0x16, 0x6a, 0x06, 0xf2, 0x14, 0x9a, 0x6e, 0xcd, 0x9e, 0x12, 0xf7, 0xaa, - 0x83, 0x10, 0xbd, 0xd1, 0x7c, 0x98, 0xfa, 0xc7, 0xae, 0xd4, 0x0e, 0x2c, 0x9e, - 0x38, 0x05, 0x9d, 0x52, 0x60, 0xa9, 0x99, 0x0a, 0x81, 0xb4, 0x98, 0x90, 0x1d, - 0xae, 0xbb, 0x4a, 0xd7, 0xb9, 0xdc, 0x88, 0x9e, 0x37, 0x78, 0x41, 0x5b, 0xf7, - 0x82, 0xa5, 0xf2, 0xba, 0x41, 0x25, 0x5a, 0x90, 0x1a, 0x1e, 0x45, 0x38, 0xa1, - 0x52, 0x58, 0x75, 0x94, 0x26, 0x44, 0xfb, 0x20, 0x07, 0xba, 0x44, 0xcc, 0xe5, - 0x4a, 0x2d, 0x72, 0x3f, 0x98, 0x47, 0xf6, 0x26, 0xdc, 0x05, 0x46, 0x05, 0x07, - 0x63, 0x21, 0xab, 0x46, 0x9b, 0x9c, 0x78, 0xd5, 0x54, 0x5b, 0x3d, 0x0c, 0x1e, - 0xc8, 0x64, 0x8c, 0xb5, 0x50, 0x23, 0x82, 0x6f, 0xdb, 0xb8, 0x22, 0x1c, 0x43, - 0x96, 0x07, 0xa8, 0xbb, -} - -var stringSliceTestData = [][]string{ - {"foo", "bar"}, - {"foo", "\\bar"}, - {"foo", "\"bar\""}, - {"foo", "åäö"}, -} - -func TestStringSlice(t *testing.T) { - for _, test := range stringSliceTestData { - bs, err := Marshal(test) - if err != nil { - t.Error(err) - } - - var res []string - _, err = Unmarshal(bs, &res) - if err != nil { - t.Error(err) - } - - if fmt.Sprintf("%v", res) != fmt.Sprintf("%v", test) { - t.Errorf("incorrect marshal/unmarshal; %v != %v", res, test) - } - } -} diff --git a/src/pkg/encoding/asn1/common.go b/src/pkg/encoding/asn1/common.go deleted file mode 100644 index 33a117ece..000000000 --- a/src/pkg/encoding/asn1/common.go +++ /dev/null @@ -1,163 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package asn1 - -import ( - "reflect" - "strconv" - "strings" -) - -// ASN.1 objects have metadata preceding them: -// the tag: the type of the object -// a flag denoting if this object is compound or not -// the class type: the namespace of the tag -// the length of the object, in bytes - -// Here are some standard tags and classes - -const ( - tagBoolean = 1 - tagInteger = 2 - tagBitString = 3 - tagOctetString = 4 - tagOID = 6 - tagEnum = 10 - tagUTF8String = 12 - tagSequence = 16 - tagSet = 17 - tagPrintableString = 19 - tagT61String = 20 - tagIA5String = 22 - tagUTCTime = 23 - tagGeneralizedTime = 24 - tagGeneralString = 27 -) - -const ( - classUniversal = 0 - classApplication = 1 - classContextSpecific = 2 - classPrivate = 3 -) - -type tagAndLength struct { - class, tag, length int - isCompound bool -} - -// ASN.1 has IMPLICIT and EXPLICIT tags, which can be translated as "instead -// of" and "in addition to". When not specified, every primitive type has a -// default tag in the UNIVERSAL class. -// -// For example: a BIT STRING is tagged [UNIVERSAL 3] by default (although ASN.1 -// doesn't actually have a UNIVERSAL keyword). However, by saying [IMPLICIT -// CONTEXT-SPECIFIC 42], that means that the tag is replaced by another. -// -// On the other hand, if it said [EXPLICIT CONTEXT-SPECIFIC 10], then an -// /additional/ tag would wrap the default tag. This explicit tag will have the -// compound flag set. -// -// (This is used in order to remove ambiguity with optional elements.) -// -// You can layer EXPLICIT and IMPLICIT tags to an arbitrary depth, however we -// don't support that here. We support a single layer of EXPLICIT or IMPLICIT -// tagging with tag strings on the fields of a structure. - -// fieldParameters is the parsed representation of tag string from a structure field. -type fieldParameters struct { - optional bool // true iff the field is OPTIONAL - explicit bool // true iff an EXPLICIT tag is in use. - application bool // true iff an APPLICATION tag is in use. - defaultValue *int64 // a default value for INTEGER typed fields (maybe nil). - tag *int // the EXPLICIT or IMPLICIT tag (maybe nil). - stringType int // the string tag to use when marshaling. - set bool // true iff this should be encoded as a SET - omitEmpty bool // true iff this should be omitted if empty when marshaling. - - // Invariants: - // if explicit is set, tag is non-nil. -} - -// Given a tag string with the format specified in the package comment, -// parseFieldParameters will parse it into a fieldParameters structure, -// ignoring unknown parts of the string. -func parseFieldParameters(str string) (ret fieldParameters) { - for _, part := range strings.Split(str, ",") { - switch { - case part == "optional": - ret.optional = true - case part == "explicit": - ret.explicit = true - if ret.tag == nil { - ret.tag = new(int) - } - case part == "ia5": - ret.stringType = tagIA5String - case part == "printable": - ret.stringType = tagPrintableString - case part == "utf8": - ret.stringType = tagUTF8String - case strings.HasPrefix(part, "default:"): - i, err := strconv.ParseInt(part[8:], 10, 64) - if err == nil { - ret.defaultValue = new(int64) - *ret.defaultValue = i - } - case strings.HasPrefix(part, "tag:"): - i, err := strconv.Atoi(part[4:]) - if err == nil { - ret.tag = new(int) - *ret.tag = i - } - case part == "set": - ret.set = true - case part == "application": - ret.application = true - if ret.tag == nil { - ret.tag = new(int) - } - case part == "omitempty": - ret.omitEmpty = true - } - } - return -} - -// Given a reflected Go type, getUniversalType returns the default tag number -// and expected compound flag. -func getUniversalType(t reflect.Type) (tagNumber int, isCompound, ok bool) { - switch t { - case objectIdentifierType: - return tagOID, false, true - case bitStringType: - return tagBitString, false, true - case timeType: - return tagUTCTime, false, true - case enumeratedType: - return tagEnum, false, true - case bigIntType: - return tagInteger, false, true - } - switch t.Kind() { - case reflect.Bool: - return tagBoolean, false, true - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return tagInteger, false, true - case reflect.Struct: - return tagSequence, true, true - case reflect.Slice: - if t.Elem().Kind() == reflect.Uint8 { - return tagOctetString, false, true - } - if strings.HasSuffix(t.Name(), "SET") { - return tagSet, true, true - } - return tagSequence, true, true - case reflect.String: - return tagPrintableString, false, true - } - return 0, false, false -} diff --git a/src/pkg/encoding/asn1/marshal.go b/src/pkg/encoding/asn1/marshal.go deleted file mode 100644 index b2f104b4c..000000000 --- a/src/pkg/encoding/asn1/marshal.go +++ /dev/null @@ -1,646 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package asn1 - -import ( - "bytes" - "errors" - "fmt" - "io" - "math/big" - "reflect" - "time" - "unicode/utf8" -) - -// A forkableWriter is an in-memory buffer that can be -// 'forked' to create new forkableWriters that bracket the -// original. After -// pre, post := w.fork(); -// the overall sequence of bytes represented is logically w+pre+post. -type forkableWriter struct { - *bytes.Buffer - pre, post *forkableWriter -} - -func newForkableWriter() *forkableWriter { - return &forkableWriter{new(bytes.Buffer), nil, nil} -} - -func (f *forkableWriter) fork() (pre, post *forkableWriter) { - if f.pre != nil || f.post != nil { - panic("have already forked") - } - f.pre = newForkableWriter() - f.post = newForkableWriter() - return f.pre, f.post -} - -func (f *forkableWriter) Len() (l int) { - l += f.Buffer.Len() - if f.pre != nil { - l += f.pre.Len() - } - if f.post != nil { - l += f.post.Len() - } - return -} - -func (f *forkableWriter) writeTo(out io.Writer) (n int, err error) { - n, err = out.Write(f.Bytes()) - if err != nil { - return - } - - var nn int - - if f.pre != nil { - nn, err = f.pre.writeTo(out) - n += nn - if err != nil { - return - } - } - - if f.post != nil { - nn, err = f.post.writeTo(out) - n += nn - } - return -} - -func marshalBase128Int(out *forkableWriter, n int64) (err error) { - if n == 0 { - err = out.WriteByte(0) - return - } - - l := 0 - for i := n; i > 0; i >>= 7 { - l++ - } - - for i := l - 1; i >= 0; i-- { - o := byte(n >> uint(i*7)) - o &= 0x7f - if i != 0 { - o |= 0x80 - } - err = out.WriteByte(o) - if err != nil { - return - } - } - - return nil -} - -func marshalInt64(out *forkableWriter, i int64) (err error) { - n := int64Length(i) - - for ; n > 0; n-- { - err = out.WriteByte(byte(i >> uint((n-1)*8))) - if err != nil { - return - } - } - - return nil -} - -func int64Length(i int64) (numBytes int) { - numBytes = 1 - - for i > 127 { - numBytes++ - i >>= 8 - } - - for i < -128 { - numBytes++ - i >>= 8 - } - - return -} - -func marshalBigInt(out *forkableWriter, n *big.Int) (err error) { - if n.Sign() < 0 { - // A negative number has to be converted to two's-complement - // form. So we'll subtract 1 and invert. If the - // most-significant-bit isn't set then we'll need to pad the - // beginning with 0xff in order to keep the number negative. - nMinus1 := new(big.Int).Neg(n) - nMinus1.Sub(nMinus1, bigOne) - bytes := nMinus1.Bytes() - for i := range bytes { - bytes[i] ^= 0xff - } - if len(bytes) == 0 || bytes[0]&0x80 == 0 { - err = out.WriteByte(0xff) - if err != nil { - return - } - } - _, err = out.Write(bytes) - } else if n.Sign() == 0 { - // Zero is written as a single 0 zero rather than no bytes. - err = out.WriteByte(0x00) - } else { - bytes := n.Bytes() - if len(bytes) > 0 && bytes[0]&0x80 != 0 { - // We'll have to pad this with 0x00 in order to stop it - // looking like a negative number. - err = out.WriteByte(0) - if err != nil { - return - } - } - _, err = out.Write(bytes) - } - return -} - -func marshalLength(out *forkableWriter, i int) (err error) { - n := lengthLength(i) - - for ; n > 0; n-- { - err = out.WriteByte(byte(i >> uint((n-1)*8))) - if err != nil { - return - } - } - - return nil -} - -func lengthLength(i int) (numBytes int) { - numBytes = 1 - for i > 255 { - numBytes++ - i >>= 8 - } - return -} - -func marshalTagAndLength(out *forkableWriter, t tagAndLength) (err error) { - b := uint8(t.class) << 6 - if t.isCompound { - b |= 0x20 - } - if t.tag >= 31 { - b |= 0x1f - err = out.WriteByte(b) - if err != nil { - return - } - err = marshalBase128Int(out, int64(t.tag)) - if err != nil { - return - } - } else { - b |= uint8(t.tag) - err = out.WriteByte(b) - if err != nil { - return - } - } - - if t.length >= 128 { - l := lengthLength(t.length) - err = out.WriteByte(0x80 | byte(l)) - if err != nil { - return - } - err = marshalLength(out, t.length) - if err != nil { - return - } - } else { - err = out.WriteByte(byte(t.length)) - if err != nil { - return - } - } - - return nil -} - -func marshalBitString(out *forkableWriter, b BitString) (err error) { - paddingBits := byte((8 - b.BitLength%8) % 8) - err = out.WriteByte(paddingBits) - if err != nil { - return - } - _, err = out.Write(b.Bytes) - return -} - -func marshalObjectIdentifier(out *forkableWriter, oid []int) (err error) { - if len(oid) < 2 || oid[0] > 2 || (oid[0] < 2 && oid[1] >= 40) { - return StructuralError{"invalid object identifier"} - } - - err = marshalBase128Int(out, int64(oid[0]*40+oid[1])) - if err != nil { - return - } - for i := 2; i < len(oid); i++ { - err = marshalBase128Int(out, int64(oid[i])) - if err != nil { - return - } - } - - return -} - -func marshalPrintableString(out *forkableWriter, s string) (err error) { - b := []byte(s) - for _, c := range b { - if !isPrintable(c) { - return StructuralError{"PrintableString contains invalid character"} - } - } - - _, err = out.Write(b) - return -} - -func marshalIA5String(out *forkableWriter, s string) (err error) { - b := []byte(s) - for _, c := range b { - if c > 127 { - return StructuralError{"IA5String contains invalid character"} - } - } - - _, err = out.Write(b) - return -} - -func marshalUTF8String(out *forkableWriter, s string) (err error) { - _, err = out.Write([]byte(s)) - return -} - -func marshalTwoDigits(out *forkableWriter, v int) (err error) { - err = out.WriteByte(byte('0' + (v/10)%10)) - if err != nil { - return - } - return out.WriteByte(byte('0' + v%10)) -} - -func marshalFourDigits(out *forkableWriter, v int) (err error) { - var bytes [4]byte - for i := range bytes { - bytes[3-i] = '0' + byte(v%10) - v /= 10 - } - _, err = out.Write(bytes[:]) - return -} - -func outsideUTCRange(t time.Time) bool { - year := t.Year() - return year < 1950 || year >= 2050 -} - -func marshalUTCTime(out *forkableWriter, t time.Time) (err error) { - year := t.Year() - - switch { - case 1950 <= year && year < 2000: - err = marshalTwoDigits(out, int(year-1900)) - case 2000 <= year && year < 2050: - err = marshalTwoDigits(out, int(year-2000)) - default: - return StructuralError{"cannot represent time as UTCTime"} - } - if err != nil { - return - } - - return marshalTimeCommon(out, t) -} - -func marshalGeneralizedTime(out *forkableWriter, t time.Time) (err error) { - year := t.Year() - if year < 0 || year > 9999 { - return StructuralError{"cannot represent time as GeneralizedTime"} - } - if err = marshalFourDigits(out, year); err != nil { - return - } - - return marshalTimeCommon(out, t) -} - -func marshalTimeCommon(out *forkableWriter, t time.Time) (err error) { - _, month, day := t.Date() - - err = marshalTwoDigits(out, int(month)) - if err != nil { - return - } - - err = marshalTwoDigits(out, day) - if err != nil { - return - } - - hour, min, sec := t.Clock() - - err = marshalTwoDigits(out, hour) - if err != nil { - return - } - - err = marshalTwoDigits(out, min) - if err != nil { - return - } - - err = marshalTwoDigits(out, sec) - if err != nil { - return - } - - _, offset := t.Zone() - - switch { - case offset/60 == 0: - err = out.WriteByte('Z') - return - case offset > 0: - err = out.WriteByte('+') - case offset < 0: - err = out.WriteByte('-') - } - - if err != nil { - return - } - - offsetMinutes := offset / 60 - if offsetMinutes < 0 { - offsetMinutes = -offsetMinutes - } - - err = marshalTwoDigits(out, offsetMinutes/60) - if err != nil { - return - } - - err = marshalTwoDigits(out, offsetMinutes%60) - return -} - -func stripTagAndLength(in []byte) []byte { - _, offset, err := parseTagAndLength(in, 0) - if err != nil { - return in - } - return in[offset:] -} - -func marshalBody(out *forkableWriter, value reflect.Value, params fieldParameters) (err error) { - switch value.Type() { - case timeType: - t := value.Interface().(time.Time) - if outsideUTCRange(t) { - return marshalGeneralizedTime(out, t) - } else { - return marshalUTCTime(out, t) - } - case bitStringType: - return marshalBitString(out, value.Interface().(BitString)) - case objectIdentifierType: - return marshalObjectIdentifier(out, value.Interface().(ObjectIdentifier)) - case bigIntType: - return marshalBigInt(out, value.Interface().(*big.Int)) - } - - switch v := value; v.Kind() { - case reflect.Bool: - if v.Bool() { - return out.WriteByte(255) - } else { - return out.WriteByte(0) - } - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return marshalInt64(out, int64(v.Int())) - case reflect.Struct: - t := v.Type() - - startingField := 0 - - // If the first element of the structure is a non-empty - // RawContents, then we don't bother serializing the rest. - if t.NumField() > 0 && t.Field(0).Type == rawContentsType { - s := v.Field(0) - if s.Len() > 0 { - bytes := make([]byte, s.Len()) - for i := 0; i < s.Len(); i++ { - bytes[i] = uint8(s.Index(i).Uint()) - } - /* The RawContents will contain the tag and - * length fields but we'll also be writing - * those ourselves, so we strip them out of - * bytes */ - _, err = out.Write(stripTagAndLength(bytes)) - return - } else { - startingField = 1 - } - } - - for i := startingField; i < t.NumField(); i++ { - var pre *forkableWriter - pre, out = out.fork() - err = marshalField(pre, v.Field(i), parseFieldParameters(t.Field(i).Tag.Get("asn1"))) - if err != nil { - return - } - } - return - case reflect.Slice: - sliceType := v.Type() - if sliceType.Elem().Kind() == reflect.Uint8 { - bytes := make([]byte, v.Len()) - for i := 0; i < v.Len(); i++ { - bytes[i] = uint8(v.Index(i).Uint()) - } - _, err = out.Write(bytes) - return - } - - var fp fieldParameters - for i := 0; i < v.Len(); i++ { - var pre *forkableWriter - pre, out = out.fork() - err = marshalField(pre, v.Index(i), fp) - if err != nil { - return - } - } - return - case reflect.String: - switch params.stringType { - case tagIA5String: - return marshalIA5String(out, v.String()) - case tagPrintableString: - return marshalPrintableString(out, v.String()) - default: - return marshalUTF8String(out, v.String()) - } - } - - return StructuralError{"unknown Go type"} -} - -func marshalField(out *forkableWriter, v reflect.Value, params fieldParameters) (err error) { - // If the field is an interface{} then recurse into it. - if v.Kind() == reflect.Interface && v.Type().NumMethod() == 0 { - return marshalField(out, v.Elem(), params) - } - - if v.Kind() == reflect.Slice && v.Len() == 0 && params.omitEmpty { - return - } - - if params.optional && params.defaultValue != nil && canHaveDefaultValue(v.Kind()) { - defaultValue := reflect.New(v.Type()).Elem() - defaultValue.SetInt(*params.defaultValue) - - if reflect.DeepEqual(v.Interface(), defaultValue.Interface()) { - return - } - } - - // If no default value is given then the zero value for the type is - // assumed to be the default value. This isn't obviously the correct - // behaviour, but it's what Go has traditionally done. - if params.optional && params.defaultValue == nil { - if reflect.DeepEqual(v.Interface(), reflect.Zero(v.Type()).Interface()) { - return - } - } - - if v.Type() == rawValueType { - rv := v.Interface().(RawValue) - if len(rv.FullBytes) != 0 { - _, err = out.Write(rv.FullBytes) - } else { - err = marshalTagAndLength(out, tagAndLength{rv.Class, rv.Tag, len(rv.Bytes), rv.IsCompound}) - if err != nil { - return - } - _, err = out.Write(rv.Bytes) - } - return - } - - tag, isCompound, ok := getUniversalType(v.Type()) - if !ok { - err = StructuralError{fmt.Sprintf("unknown Go type: %v", v.Type())} - return - } - class := classUniversal - - if params.stringType != 0 && tag != tagPrintableString { - return StructuralError{"explicit string type given to non-string member"} - } - - switch tag { - case tagPrintableString: - if params.stringType == 0 { - // This is a string without an explicit string type. We'll use - // a PrintableString if the character set in the string is - // sufficiently limited, otherwise we'll use a UTF8String. - for _, r := range v.String() { - if r >= utf8.RuneSelf || !isPrintable(byte(r)) { - if !utf8.ValidString(v.String()) { - return errors.New("asn1: string not valid UTF-8") - } - tag = tagUTF8String - break - } - } - } else { - tag = params.stringType - } - case tagUTCTime: - if outsideUTCRange(v.Interface().(time.Time)) { - tag = tagGeneralizedTime - } - } - - if params.set { - if tag != tagSequence { - return StructuralError{"non sequence tagged as set"} - } - tag = tagSet - } - - tags, body := out.fork() - - err = marshalBody(body, v, params) - if err != nil { - return - } - - bodyLen := body.Len() - - var explicitTag *forkableWriter - if params.explicit { - explicitTag, tags = tags.fork() - } - - if !params.explicit && params.tag != nil { - // implicit tag. - tag = *params.tag - class = classContextSpecific - } - - err = marshalTagAndLength(tags, tagAndLength{class, tag, bodyLen, isCompound}) - if err != nil { - return - } - - if params.explicit { - err = marshalTagAndLength(explicitTag, tagAndLength{ - class: classContextSpecific, - tag: *params.tag, - length: bodyLen + tags.Len(), - isCompound: true, - }) - } - - return nil -} - -// Marshal returns the ASN.1 encoding of val. -// -// In addition to the struct tags recognised by Unmarshal, the following can be -// used: -// -// ia5: causes strings to be marshaled as ASN.1, IA5 strings -// omitempty: causes empty slices to be skipped -// printable: causes strings to be marshaled as ASN.1, PrintableString strings. -// utf8: causes strings to be marshaled as ASN.1, UTF8 strings -func Marshal(val interface{}) ([]byte, error) { - var out bytes.Buffer - v := reflect.ValueOf(val) - f := newForkableWriter() - err := marshalField(f, v, fieldParameters{}) - if err != nil { - return nil, err - } - _, err = f.writeTo(&out) - return out.Bytes(), nil -} diff --git a/src/pkg/encoding/asn1/marshal_test.go b/src/pkg/encoding/asn1/marshal_test.go deleted file mode 100644 index 5b0115f28..000000000 --- a/src/pkg/encoding/asn1/marshal_test.go +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package asn1 - -import ( - "bytes" - "encoding/hex" - "math/big" - "testing" - "time" -) - -type intStruct struct { - A int -} - -type twoIntStruct struct { - A int - B int -} - -type bigIntStruct struct { - A *big.Int -} - -type nestedStruct struct { - A intStruct -} - -type rawContentsStruct struct { - Raw RawContent - A int -} - -type implicitTagTest struct { - A int `asn1:"implicit,tag:5"` -} - -type explicitTagTest struct { - A int `asn1:"explicit,tag:5"` -} - -type ia5StringTest struct { - A string `asn1:"ia5"` -} - -type printableStringTest struct { - A string `asn1:"printable"` -} - -type optionalRawValueTest struct { - A RawValue `asn1:"optional"` -} - -type omitEmptyTest struct { - A []string `asn1:"omitempty"` -} - -type defaultTest struct { - A int `asn1:"optional,default:1"` -} - -type testSET []int - -var PST = time.FixedZone("PST", -8*60*60) - -type marshalTest struct { - in interface{} - out string // hex encoded -} - -func farFuture() time.Time { - t, err := time.Parse(time.RFC3339, "2100-04-05T12:01:01Z") - if err != nil { - panic(err) - } - return t -} - -var marshalTests = []marshalTest{ - {10, "02010a"}, - {127, "02017f"}, - {128, "02020080"}, - {-128, "020180"}, - {-129, "0202ff7f"}, - {intStruct{64}, "3003020140"}, - {bigIntStruct{big.NewInt(0x123456)}, "30050203123456"}, - {twoIntStruct{64, 65}, "3006020140020141"}, - {nestedStruct{intStruct{127}}, "3005300302017f"}, - {[]byte{1, 2, 3}, "0403010203"}, - {implicitTagTest{64}, "3003850140"}, - {explicitTagTest{64}, "3005a503020140"}, - {time.Unix(0, 0).UTC(), "170d3730303130313030303030305a"}, - {time.Unix(1258325776, 0).UTC(), "170d3039313131353232353631365a"}, - {time.Unix(1258325776, 0).In(PST), "17113039313131353134353631362d30383030"}, - {farFuture(), "180f32313030303430353132303130315a"}, - {BitString{[]byte{0x80}, 1}, "03020780"}, - {BitString{[]byte{0x81, 0xf0}, 12}, "03030481f0"}, - {ObjectIdentifier([]int{1, 2, 3, 4}), "06032a0304"}, - {ObjectIdentifier([]int{1, 2, 840, 133549, 1, 1, 5}), "06092a864888932d010105"}, - {ObjectIdentifier([]int{2, 100, 3}), "0603813403"}, - {"test", "130474657374"}, - { - "" + - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", // This is 127 times 'x' - "137f" + - "7878787878787878787878787878787878787878787878787878787878787878" + - "7878787878787878787878787878787878787878787878787878787878787878" + - "7878787878787878787878787878787878787878787878787878787878787878" + - "78787878787878787878787878787878787878787878787878787878787878", - }, - { - "" + - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" + - "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", // This is 128 times 'x' - "138180" + - "7878787878787878787878787878787878787878787878787878787878787878" + - "7878787878787878787878787878787878787878787878787878787878787878" + - "7878787878787878787878787878787878787878787878787878787878787878" + - "7878787878787878787878787878787878787878787878787878787878787878", - }, - {ia5StringTest{"test"}, "3006160474657374"}, - {optionalRawValueTest{}, "3000"}, - {printableStringTest{"test"}, "3006130474657374"}, - {printableStringTest{"test*"}, "30071305746573742a"}, - {rawContentsStruct{nil, 64}, "3003020140"}, - {rawContentsStruct{[]byte{0x30, 3, 1, 2, 3}, 64}, "3003010203"}, - {RawValue{Tag: 1, Class: 2, IsCompound: false, Bytes: []byte{1, 2, 3}}, "8103010203"}, - {testSET([]int{10}), "310302010a"}, - {omitEmptyTest{[]string{}}, "3000"}, - {omitEmptyTest{[]string{"1"}}, "30053003130131"}, - {"Σ", "0c02cea3"}, - {defaultTest{0}, "3003020100"}, - {defaultTest{1}, "3000"}, - {defaultTest{2}, "3003020102"}, -} - -func TestMarshal(t *testing.T) { - for i, test := range marshalTests { - data, err := Marshal(test.in) - if err != nil { - t.Errorf("#%d failed: %s", i, err) - } - out, _ := hex.DecodeString(test.out) - if !bytes.Equal(out, data) { - t.Errorf("#%d got: %x want %x\n\t%q\n\t%q", i, data, out, data, out) - - } - } -} - -func TestInvalidUTF8(t *testing.T) { - _, err := Marshal(string([]byte{0xff, 0xff})) - if err == nil { - t.Errorf("invalid UTF8 string was accepted") - } -} diff --git a/src/pkg/encoding/base32/base32.go b/src/pkg/encoding/base32/base32.go deleted file mode 100644 index 5a9e86919..000000000 --- a/src/pkg/encoding/base32/base32.go +++ /dev/null @@ -1,426 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package base32 implements base32 encoding as specified by RFC 4648. -package base32 - -import ( - "bytes" - "io" - "strconv" - "strings" -) - -/* - * Encodings - */ - -// An Encoding is a radix 32 encoding/decoding scheme, defined by a -// 32-character alphabet. The most common is the "base32" encoding -// introduced for SASL GSSAPI and standardized in RFC 4648. -// The alternate "base32hex" encoding is used in DNSSEC. -type Encoding struct { - encode string - decodeMap [256]byte -} - -const encodeStd = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" -const encodeHex = "0123456789ABCDEFGHIJKLMNOPQRSTUV" - -// NewEncoding returns a new Encoding defined by the given alphabet, -// which must be a 32-byte string. -func NewEncoding(encoder string) *Encoding { - e := new(Encoding) - e.encode = encoder - for i := 0; i < len(e.decodeMap); i++ { - e.decodeMap[i] = 0xFF - } - for i := 0; i < len(encoder); i++ { - e.decodeMap[encoder[i]] = byte(i) - } - return e -} - -// StdEncoding is the standard base32 encoding, as defined in -// RFC 4648. -var StdEncoding = NewEncoding(encodeStd) - -// HexEncoding is the ``Extended Hex Alphabet'' defined in RFC 4648. -// It is typically used in DNS. -var HexEncoding = NewEncoding(encodeHex) - -var removeNewlinesMapper = func(r rune) rune { - if r == '\r' || r == '\n' { - return -1 - } - return r -} - -/* - * Encoder - */ - -// Encode encodes src using the encoding enc, writing -// EncodedLen(len(src)) bytes to dst. -// -// The encoding pads the output to a multiple of 8 bytes, -// so Encode is not appropriate for use on individual blocks -// of a large data stream. Use NewEncoder() instead. -func (enc *Encoding) Encode(dst, src []byte) { - if len(src) == 0 { - return - } - - for len(src) > 0 { - var b0, b1, b2, b3, b4, b5, b6, b7 byte - - // Unpack 8x 5-bit source blocks into a 5 byte - // destination quantum - switch len(src) { - default: - b7 = src[4] & 0x1F - b6 = src[4] >> 5 - fallthrough - case 4: - b6 |= (src[3] << 3) & 0x1F - b5 = (src[3] >> 2) & 0x1F - b4 = src[3] >> 7 - fallthrough - case 3: - b4 |= (src[2] << 1) & 0x1F - b3 = (src[2] >> 4) & 0x1F - fallthrough - case 2: - b3 |= (src[1] << 4) & 0x1F - b2 = (src[1] >> 1) & 0x1F - b1 = (src[1] >> 6) & 0x1F - fallthrough - case 1: - b1 |= (src[0] << 2) & 0x1F - b0 = src[0] >> 3 - } - - // Encode 5-bit blocks using the base32 alphabet - dst[0] = enc.encode[b0] - dst[1] = enc.encode[b1] - dst[2] = enc.encode[b2] - dst[3] = enc.encode[b3] - dst[4] = enc.encode[b4] - dst[5] = enc.encode[b5] - dst[6] = enc.encode[b6] - dst[7] = enc.encode[b7] - - // Pad the final quantum - if len(src) < 5 { - dst[7] = '=' - if len(src) < 4 { - dst[6] = '=' - dst[5] = '=' - if len(src) < 3 { - dst[4] = '=' - if len(src) < 2 { - dst[3] = '=' - dst[2] = '=' - } - } - } - break - } - src = src[5:] - dst = dst[8:] - } -} - -// EncodeToString returns the base32 encoding of src. -func (enc *Encoding) EncodeToString(src []byte) string { - buf := make([]byte, enc.EncodedLen(len(src))) - enc.Encode(buf, src) - return string(buf) -} - -type encoder struct { - err error - enc *Encoding - w io.Writer - buf [5]byte // buffered data waiting to be encoded - nbuf int // number of bytes in buf - out [1024]byte // output buffer -} - -func (e *encoder) Write(p []byte) (n int, err error) { - if e.err != nil { - return 0, e.err - } - - // Leading fringe. - if e.nbuf > 0 { - var i int - for i = 0; i < len(p) && e.nbuf < 5; i++ { - e.buf[e.nbuf] = p[i] - e.nbuf++ - } - n += i - p = p[i:] - if e.nbuf < 5 { - return - } - e.enc.Encode(e.out[0:], e.buf[0:]) - if _, e.err = e.w.Write(e.out[0:8]); e.err != nil { - return n, e.err - } - e.nbuf = 0 - } - - // Large interior chunks. - for len(p) >= 5 { - nn := len(e.out) / 8 * 5 - if nn > len(p) { - nn = len(p) - nn -= nn % 5 - } - e.enc.Encode(e.out[0:], p[0:nn]) - if _, e.err = e.w.Write(e.out[0 : nn/5*8]); e.err != nil { - return n, e.err - } - n += nn - p = p[nn:] - } - - // Trailing fringe. - for i := 0; i < len(p); i++ { - e.buf[i] = p[i] - } - e.nbuf = len(p) - n += len(p) - return -} - -// Close flushes any pending output from the encoder. -// It is an error to call Write after calling Close. -func (e *encoder) Close() error { - // If there's anything left in the buffer, flush it out - if e.err == nil && e.nbuf > 0 { - e.enc.Encode(e.out[0:], e.buf[0:e.nbuf]) - e.nbuf = 0 - _, e.err = e.w.Write(e.out[0:8]) - } - return e.err -} - -// NewEncoder returns a new base32 stream encoder. Data written to -// the returned writer will be encoded using enc and then written to w. -// Base32 encodings operate in 5-byte blocks; when finished -// writing, the caller must Close the returned encoder to flush any -// partially written blocks. -func NewEncoder(enc *Encoding, w io.Writer) io.WriteCloser { - return &encoder{enc: enc, w: w} -} - -// EncodedLen returns the length in bytes of the base32 encoding -// of an input buffer of length n. -func (enc *Encoding) EncodedLen(n int) int { return (n + 4) / 5 * 8 } - -/* - * Decoder - */ - -type CorruptInputError int64 - -func (e CorruptInputError) Error() string { - return "illegal base32 data at input byte " + strconv.FormatInt(int64(e), 10) -} - -// decode is like Decode but returns an additional 'end' value, which -// indicates if end-of-message padding was encountered and thus any -// additional data is an error. This method assumes that src has been -// stripped of all supported whitespace ('\r' and '\n'). -func (enc *Encoding) decode(dst, src []byte) (n int, end bool, err error) { - olen := len(src) - for len(src) > 0 && !end { - // Decode quantum using the base32 alphabet - var dbuf [8]byte - dlen := 8 - - for j := 0; j < 8; { - if len(src) == 0 { - return n, false, CorruptInputError(olen - len(src) - j) - } - in := src[0] - src = src[1:] - if in == '=' && j >= 2 && len(src) < 8 { - // We've reached the end and there's padding - if len(src)+j < 8-1 { - // not enough padding - return n, false, CorruptInputError(olen) - } - for k := 0; k < 8-1-j; k++ { - if len(src) > k && src[k] != '=' { - // incorrect padding - return n, false, CorruptInputError(olen - len(src) + k - 1) - } - } - dlen, end = j, true - // 7, 5 and 2 are not valid padding lengths, and so 1, 3 and 6 are not - // valid dlen values. See RFC 4648 Section 6 "Base 32 Encoding" listing - // the five valid padding lengths, and Section 9 "Illustrations and - // Examples" for an illustration for how the 1st, 3rd and 6th base32 - // src bytes do not yield enough information to decode a dst byte. - if dlen == 1 || dlen == 3 || dlen == 6 { - return n, false, CorruptInputError(olen - len(src) - 1) - } - break - } - dbuf[j] = enc.decodeMap[in] - if dbuf[j] == 0xFF { - return n, false, CorruptInputError(olen - len(src) - 1) - } - j++ - } - - // Pack 8x 5-bit source blocks into 5 byte destination - // quantum - switch dlen { - case 8: - dst[4] = dbuf[6]<<5 | dbuf[7] - fallthrough - case 7: - dst[3] = dbuf[4]<<7 | dbuf[5]<<2 | dbuf[6]>>3 - fallthrough - case 5: - dst[2] = dbuf[3]<<4 | dbuf[4]>>1 - fallthrough - case 4: - dst[1] = dbuf[1]<<6 | dbuf[2]<<1 | dbuf[3]>>4 - fallthrough - case 2: - dst[0] = dbuf[0]<<3 | dbuf[1]>>2 - } - dst = dst[5:] - switch dlen { - case 2: - n += 1 - case 4: - n += 2 - case 5: - n += 3 - case 7: - n += 4 - case 8: - n += 5 - } - } - return n, end, nil -} - -// Decode decodes src using the encoding enc. It writes at most -// DecodedLen(len(src)) bytes to dst and returns the number of bytes -// written. If src contains invalid base32 data, it will return the -// number of bytes successfully written and CorruptInputError. -// New line characters (\r and \n) are ignored. -func (enc *Encoding) Decode(dst, src []byte) (n int, err error) { - src = bytes.Map(removeNewlinesMapper, src) - n, _, err = enc.decode(dst, src) - return -} - -// DecodeString returns the bytes represented by the base32 string s. -func (enc *Encoding) DecodeString(s string) ([]byte, error) { - s = strings.Map(removeNewlinesMapper, s) - dbuf := make([]byte, enc.DecodedLen(len(s))) - n, _, err := enc.decode(dbuf, []byte(s)) - return dbuf[:n], err -} - -type decoder struct { - err error - enc *Encoding - r io.Reader - end bool // saw end of message - buf [1024]byte // leftover input - nbuf int - out []byte // leftover decoded output - outbuf [1024 / 8 * 5]byte -} - -func (d *decoder) Read(p []byte) (n int, err error) { - if d.err != nil { - return 0, d.err - } - - // Use leftover decoded output from last read. - if len(d.out) > 0 { - n = copy(p, d.out) - d.out = d.out[n:] - return n, nil - } - - // Read a chunk. - nn := len(p) / 5 * 8 - if nn < 8 { - nn = 8 - } - if nn > len(d.buf) { - nn = len(d.buf) - } - nn, d.err = io.ReadAtLeast(d.r, d.buf[d.nbuf:nn], 8-d.nbuf) - d.nbuf += nn - if d.nbuf < 8 { - return 0, d.err - } - - // Decode chunk into p, or d.out and then p if p is too small. - nr := d.nbuf / 8 * 8 - nw := d.nbuf / 8 * 5 - if nw > len(p) { - nw, d.end, d.err = d.enc.decode(d.outbuf[0:], d.buf[0:nr]) - d.out = d.outbuf[0:nw] - n = copy(p, d.out) - d.out = d.out[n:] - } else { - n, d.end, d.err = d.enc.decode(p, d.buf[0:nr]) - } - d.nbuf -= nr - for i := 0; i < d.nbuf; i++ { - d.buf[i] = d.buf[i+nr] - } - - if d.err == nil { - d.err = err - } - return n, d.err -} - -type newlineFilteringReader struct { - wrapped io.Reader -} - -func (r *newlineFilteringReader) Read(p []byte) (int, error) { - n, err := r.wrapped.Read(p) - for n > 0 { - offset := 0 - for i, b := range p[0:n] { - if b != '\r' && b != '\n' { - if i != offset { - p[offset] = b - } - offset++ - } - } - if offset > 0 { - return offset, err - } - // Previous buffer entirely whitespace, read again - n, err = r.wrapped.Read(p) - } - return n, err -} - -// NewDecoder constructs a new base32 stream decoder. -func NewDecoder(enc *Encoding, r io.Reader) io.Reader { - return &decoder{enc: enc, r: &newlineFilteringReader{r}} -} - -// DecodedLen returns the maximum length in bytes of the decoded data -// corresponding to n bytes of base32-encoded data. -func (enc *Encoding) DecodedLen(n int) int { return n / 8 * 5 } diff --git a/src/pkg/encoding/base32/base32_test.go b/src/pkg/encoding/base32/base32_test.go deleted file mode 100644 index 5a68f06e1..000000000 --- a/src/pkg/encoding/base32/base32_test.go +++ /dev/null @@ -1,302 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package base32 - -import ( - "bytes" - "io" - "io/ioutil" - "strings" - "testing" -) - -type testpair struct { - decoded, encoded string -} - -var pairs = []testpair{ - // RFC 4648 examples - {"", ""}, - {"f", "MY======"}, - {"fo", "MZXQ===="}, - {"foo", "MZXW6==="}, - {"foob", "MZXW6YQ="}, - {"fooba", "MZXW6YTB"}, - {"foobar", "MZXW6YTBOI======"}, - - // Wikipedia examples, converted to base32 - {"sure.", "ON2XEZJO"}, - {"sure", "ON2XEZI="}, - {"sur", "ON2XE==="}, - {"su", "ON2Q===="}, - {"leasure.", "NRSWC43VOJSS4==="}, - {"easure.", "MVQXG5LSMUXA===="}, - {"asure.", "MFZXK4TFFY======"}, - {"sure.", "ON2XEZJO"}, -} - -var bigtest = testpair{ - "Twas brillig, and the slithy toves", - "KR3WC4ZAMJZGS3DMNFTSYIDBNZSCA5DIMUQHG3DJORUHSIDUN53GK4Y=", -} - -func testEqual(t *testing.T, msg string, args ...interface{}) bool { - if args[len(args)-2] != args[len(args)-1] { - t.Errorf(msg, args...) - return false - } - return true -} - -func TestEncode(t *testing.T) { - for _, p := range pairs { - got := StdEncoding.EncodeToString([]byte(p.decoded)) - testEqual(t, "Encode(%q) = %q, want %q", p.decoded, got, p.encoded) - } -} - -func TestEncoder(t *testing.T) { - for _, p := range pairs { - bb := &bytes.Buffer{} - encoder := NewEncoder(StdEncoding, bb) - encoder.Write([]byte(p.decoded)) - encoder.Close() - testEqual(t, "Encode(%q) = %q, want %q", p.decoded, bb.String(), p.encoded) - } -} - -func TestEncoderBuffering(t *testing.T) { - input := []byte(bigtest.decoded) - for bs := 1; bs <= 12; bs++ { - bb := &bytes.Buffer{} - encoder := NewEncoder(StdEncoding, bb) - for pos := 0; pos < len(input); pos += bs { - end := pos + bs - if end > len(input) { - end = len(input) - } - n, err := encoder.Write(input[pos:end]) - testEqual(t, "Write(%q) gave error %v, want %v", input[pos:end], err, error(nil)) - testEqual(t, "Write(%q) gave length %v, want %v", input[pos:end], n, end-pos) - } - err := encoder.Close() - testEqual(t, "Close gave error %v, want %v", err, error(nil)) - testEqual(t, "Encoding/%d of %q = %q, want %q", bs, bigtest.decoded, bb.String(), bigtest.encoded) - } -} - -func TestDecode(t *testing.T) { - for _, p := range pairs { - dbuf := make([]byte, StdEncoding.DecodedLen(len(p.encoded))) - count, end, err := StdEncoding.decode(dbuf, []byte(p.encoded)) - testEqual(t, "Decode(%q) = error %v, want %v", p.encoded, err, error(nil)) - testEqual(t, "Decode(%q) = length %v, want %v", p.encoded, count, len(p.decoded)) - if len(p.encoded) > 0 { - testEqual(t, "Decode(%q) = end %v, want %v", p.encoded, end, (p.encoded[len(p.encoded)-1] == '=')) - } - testEqual(t, "Decode(%q) = %q, want %q", p.encoded, - string(dbuf[0:count]), - p.decoded) - - dbuf, err = StdEncoding.DecodeString(p.encoded) - testEqual(t, "DecodeString(%q) = error %v, want %v", p.encoded, err, error(nil)) - testEqual(t, "DecodeString(%q) = %q, want %q", p.encoded, string(dbuf), p.decoded) - } -} - -func TestDecoder(t *testing.T) { - for _, p := range pairs { - decoder := NewDecoder(StdEncoding, strings.NewReader(p.encoded)) - dbuf := make([]byte, StdEncoding.DecodedLen(len(p.encoded))) - count, err := decoder.Read(dbuf) - if err != nil && err != io.EOF { - t.Fatal("Read failed", err) - } - testEqual(t, "Read from %q = length %v, want %v", p.encoded, count, len(p.decoded)) - testEqual(t, "Decoding of %q = %q, want %q", p.encoded, string(dbuf[0:count]), p.decoded) - if err != io.EOF { - count, err = decoder.Read(dbuf) - } - testEqual(t, "Read from %q = %v, want %v", p.encoded, err, io.EOF) - } -} - -func TestDecoderBuffering(t *testing.T) { - for bs := 1; bs <= 12; bs++ { - decoder := NewDecoder(StdEncoding, strings.NewReader(bigtest.encoded)) - buf := make([]byte, len(bigtest.decoded)+12) - var total int - for total = 0; total < len(bigtest.decoded); { - n, err := decoder.Read(buf[total : total+bs]) - testEqual(t, "Read from %q at pos %d = %d, %v, want _, %v", bigtest.encoded, total, n, err, error(nil)) - total += n - } - testEqual(t, "Decoding/%d of %q = %q, want %q", bs, bigtest.encoded, string(buf[0:total]), bigtest.decoded) - } -} - -func TestDecodeCorrupt(t *testing.T) { - testCases := []struct { - input string - offset int // -1 means no corruption. - }{ - {"", -1}, - {"!!!!", 0}, - {"x===", 0}, - {"AA=A====", 2}, - {"AAA=AAAA", 3}, - {"MMMMMMMMM", 8}, - {"MMMMMM", 0}, - {"A=", 1}, - {"AA=", 3}, - {"AA==", 4}, - {"AA===", 5}, - {"AAAA=", 5}, - {"AAAA==", 6}, - {"AAAAA=", 6}, - {"AAAAA==", 7}, - {"A=======", 1}, - {"AA======", -1}, - {"AAA=====", 3}, - {"AAAA====", -1}, - {"AAAAA===", -1}, - {"AAAAAA==", 6}, - {"AAAAAAA=", -1}, - {"AAAAAAAA", -1}, - } - for _, tc := range testCases { - dbuf := make([]byte, StdEncoding.DecodedLen(len(tc.input))) - _, err := StdEncoding.Decode(dbuf, []byte(tc.input)) - if tc.offset == -1 { - if err != nil { - t.Error("Decoder wrongly detected coruption in", tc.input) - } - continue - } - switch err := err.(type) { - case CorruptInputError: - testEqual(t, "Corruption in %q at offset %v, want %v", tc.input, int(err), tc.offset) - default: - t.Error("Decoder failed to detect corruption in", tc) - } - } -} - -func TestBig(t *testing.T) { - n := 3*1000 + 1 - raw := make([]byte, n) - const alpha = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" - for i := 0; i < n; i++ { - raw[i] = alpha[i%len(alpha)] - } - encoded := new(bytes.Buffer) - w := NewEncoder(StdEncoding, encoded) - nn, err := w.Write(raw) - if nn != n || err != nil { - t.Fatalf("Encoder.Write(raw) = %d, %v want %d, nil", nn, err, n) - } - err = w.Close() - if err != nil { - t.Fatalf("Encoder.Close() = %v want nil", err) - } - decoded, err := ioutil.ReadAll(NewDecoder(StdEncoding, encoded)) - if err != nil { - t.Fatalf("ioutil.ReadAll(NewDecoder(...)): %v", err) - } - - if !bytes.Equal(raw, decoded) { - var i int - for i = 0; i < len(decoded) && i < len(raw); i++ { - if decoded[i] != raw[i] { - break - } - } - t.Errorf("Decode(Encode(%d-byte string)) failed at offset %d", n, i) - } -} - -func testStringEncoding(t *testing.T, expected string, examples []string) { - for _, e := range examples { - buf, err := StdEncoding.DecodeString(e) - if err != nil { - t.Errorf("Decode(%q) failed: %v", e, err) - continue - } - if s := string(buf); s != expected { - t.Errorf("Decode(%q) = %q, want %q", e, s, expected) - } - } -} - -func TestNewLineCharacters(t *testing.T) { - // Each of these should decode to the string "sure", without errors. - examples := []string{ - "ON2XEZI=", - "ON2XEZI=\r", - "ON2XEZI=\n", - "ON2XEZI=\r\n", - "ON2XEZ\r\nI=", - "ON2X\rEZ\nI=", - "ON2X\nEZ\rI=", - "ON2XEZ\nI=", - "ON2XEZI\n=", - } - testStringEncoding(t, "sure", examples) - - // Each of these should decode to the string "foobar", without errors. - examples = []string{ - "MZXW6YTBOI======", - "MZXW6YTBOI=\r\n=====", - } - testStringEncoding(t, "foobar", examples) -} - -func TestDecoderIssue4779(t *testing.T) { - encoded := `JRXXEZLNEBUXA43VNUQGI33MN5ZCA43JOQQGC3LFOQWCAY3PNZZWKY3UMV2HK4 -RAMFSGS4DJONUWG2LOM4QGK3DJOQWCA43FMQQGI3YKMVUXK43NN5SCA5DFNVYG64RANFXGG2LENFSH -K3TUEB2XIIDMMFRG64TFEBSXIIDEN5WG64TFEBWWCZ3OMEQGC3DJOF2WCLRAKV2CAZLONFWQUYLEEB -WWS3TJNUQHMZLONFQW2LBAOF2WS4ZANZXXG5DSOVSCAZLYMVZGG2LUMF2GS33OEB2WY3DBNVRW6IDM -MFRG64TJOMQG42LTNEQHK5AKMFWGS4LVNFYCAZLYEBSWCIDDN5WW233EN4QGG33OONSXC5LBOQXCAR -DVNFZSAYLVORSSA2LSOVZGKIDEN5WG64RANFXAU4TFOBZGK2DFNZSGK4TJOQQGS3RAOZXWY5LQORQX -IZJAOZSWY2LUEBSXG43FEBRWS3DMOVWSAZDPNRXXEZJAMV2SAZTVM5UWC5BANZ2WY3DBBJYGC4TJMF -2HK4ROEBCXQY3FOB2GK5LSEBZWS3TUEBXWGY3BMVRWC5BAMN2XA2LEMF2GC5BANZXW4IDQOJXWSZDF -NZ2CYIDTOVXHIIDJNYFGG5LMOBQSA4LVNEQG6ZTGNFRWSYJAMRSXGZLSOVXHIIDNN5WGY2LUEBQW42 -LNEBUWIIDFON2CA3DBMJXXE5LNFY== -====` - encodedShort := strings.Replace(encoded, "\n", "", -1) - - dec := NewDecoder(StdEncoding, strings.NewReader(encoded)) - res1, err := ioutil.ReadAll(dec) - if err != nil { - t.Errorf("ReadAll failed: %v", err) - } - - dec = NewDecoder(StdEncoding, strings.NewReader(encodedShort)) - var res2 []byte - res2, err = ioutil.ReadAll(dec) - if err != nil { - t.Errorf("ReadAll failed: %v", err) - } - - if !bytes.Equal(res1, res2) { - t.Error("Decoded results not equal") - } -} - -func BenchmarkEncodeToString(b *testing.B) { - data := make([]byte, 8192) - b.SetBytes(int64(len(data))) - for i := 0; i < b.N; i++ { - StdEncoding.EncodeToString(data) - } -} - -func BenchmarkDecodeString(b *testing.B) { - data := StdEncoding.EncodeToString(make([]byte, 8192)) - b.SetBytes(int64(len(data))) - for i := 0; i < b.N; i++ { - StdEncoding.DecodeString(data) - } -} diff --git a/src/pkg/encoding/base32/example_test.go b/src/pkg/encoding/base32/example_test.go deleted file mode 100644 index f6128d900..000000000 --- a/src/pkg/encoding/base32/example_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Keep in sync with ../base64/example_test.go. - -package base32_test - -import ( - "encoding/base32" - "fmt" - "os" -) - -func ExampleEncoding_EncodeToString() { - data := []byte("any + old & data") - str := base32.StdEncoding.EncodeToString(data) - fmt.Println(str) - // Output: - // MFXHSIBLEBXWYZBAEYQGIYLUME====== -} - -func ExampleEncoding_DecodeString() { - str := "ONXW2ZJAMRQXIYJAO5UXI2BAAAQGC3TEEDX3XPY=" - data, err := base32.StdEncoding.DecodeString(str) - if err != nil { - fmt.Println("error:", err) - return - } - fmt.Printf("%q\n", data) - // Output: - // "some data with \x00 and \ufeff" -} - -func ExampleNewEncoder() { - input := []byte("foo\x00bar") - encoder := base32.NewEncoder(base32.StdEncoding, os.Stdout) - encoder.Write(input) - // Must close the encoder when finished to flush any partial blocks. - // If you comment out the following line, the last partial block "r" - // won't be encoded. - encoder.Close() - // Output: - // MZXW6ADCMFZA==== -} diff --git a/src/pkg/encoding/base64/base64.go b/src/pkg/encoding/base64/base64.go deleted file mode 100644 index ad3abe662..000000000 --- a/src/pkg/encoding/base64/base64.go +++ /dev/null @@ -1,391 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package base64 implements base64 encoding as specified by RFC 4648. -package base64 - -import ( - "bytes" - "io" - "strconv" - "strings" -) - -/* - * Encodings - */ - -// An Encoding is a radix 64 encoding/decoding scheme, defined by a -// 64-character alphabet. The most common encoding is the "base64" -// encoding defined in RFC 4648 and used in MIME (RFC 2045) and PEM -// (RFC 1421). RFC 4648 also defines an alternate encoding, which is -// the standard encoding with - and _ substituted for + and /. -type Encoding struct { - encode string - decodeMap [256]byte -} - -const encodeStd = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" -const encodeURL = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_" - -// NewEncoding returns a new Encoding defined by the given alphabet, -// which must be a 64-byte string. -func NewEncoding(encoder string) *Encoding { - e := new(Encoding) - e.encode = encoder - for i := 0; i < len(e.decodeMap); i++ { - e.decodeMap[i] = 0xFF - } - for i := 0; i < len(encoder); i++ { - e.decodeMap[encoder[i]] = byte(i) - } - return e -} - -// StdEncoding is the standard base64 encoding, as defined in -// RFC 4648. -var StdEncoding = NewEncoding(encodeStd) - -// URLEncoding is the alternate base64 encoding defined in RFC 4648. -// It is typically used in URLs and file names. -var URLEncoding = NewEncoding(encodeURL) - -var removeNewlinesMapper = func(r rune) rune { - if r == '\r' || r == '\n' { - return -1 - } - return r -} - -/* - * Encoder - */ - -// Encode encodes src using the encoding enc, writing -// EncodedLen(len(src)) bytes to dst. -// -// The encoding pads the output to a multiple of 4 bytes, -// so Encode is not appropriate for use on individual blocks -// of a large data stream. Use NewEncoder() instead. -func (enc *Encoding) Encode(dst, src []byte) { - if len(src) == 0 { - return - } - - for len(src) > 0 { - var b0, b1, b2, b3 byte - - // Unpack 4x 6-bit source blocks into a 4 byte - // destination quantum - switch len(src) { - default: - b3 = src[2] & 0x3F - b2 = src[2] >> 6 - fallthrough - case 2: - b2 |= (src[1] << 2) & 0x3F - b1 = src[1] >> 4 - fallthrough - case 1: - b1 |= (src[0] << 4) & 0x3F - b0 = src[0] >> 2 - } - - // Encode 6-bit blocks using the base64 alphabet - dst[0] = enc.encode[b0] - dst[1] = enc.encode[b1] - dst[2] = enc.encode[b2] - dst[3] = enc.encode[b3] - - // Pad the final quantum - if len(src) < 3 { - dst[3] = '=' - if len(src) < 2 { - dst[2] = '=' - } - break - } - - src = src[3:] - dst = dst[4:] - } -} - -// EncodeToString returns the base64 encoding of src. -func (enc *Encoding) EncodeToString(src []byte) string { - buf := make([]byte, enc.EncodedLen(len(src))) - enc.Encode(buf, src) - return string(buf) -} - -type encoder struct { - err error - enc *Encoding - w io.Writer - buf [3]byte // buffered data waiting to be encoded - nbuf int // number of bytes in buf - out [1024]byte // output buffer -} - -func (e *encoder) Write(p []byte) (n int, err error) { - if e.err != nil { - return 0, e.err - } - - // Leading fringe. - if e.nbuf > 0 { - var i int - for i = 0; i < len(p) && e.nbuf < 3; i++ { - e.buf[e.nbuf] = p[i] - e.nbuf++ - } - n += i - p = p[i:] - if e.nbuf < 3 { - return - } - e.enc.Encode(e.out[0:], e.buf[0:]) - if _, e.err = e.w.Write(e.out[0:4]); e.err != nil { - return n, e.err - } - e.nbuf = 0 - } - - // Large interior chunks. - for len(p) >= 3 { - nn := len(e.out) / 4 * 3 - if nn > len(p) { - nn = len(p) - nn -= nn % 3 - } - e.enc.Encode(e.out[0:], p[0:nn]) - if _, e.err = e.w.Write(e.out[0 : nn/3*4]); e.err != nil { - return n, e.err - } - n += nn - p = p[nn:] - } - - // Trailing fringe. - for i := 0; i < len(p); i++ { - e.buf[i] = p[i] - } - e.nbuf = len(p) - n += len(p) - return -} - -// Close flushes any pending output from the encoder. -// It is an error to call Write after calling Close. -func (e *encoder) Close() error { - // If there's anything left in the buffer, flush it out - if e.err == nil && e.nbuf > 0 { - e.enc.Encode(e.out[0:], e.buf[0:e.nbuf]) - e.nbuf = 0 - _, e.err = e.w.Write(e.out[0:4]) - } - return e.err -} - -// NewEncoder returns a new base64 stream encoder. Data written to -// the returned writer will be encoded using enc and then written to w. -// Base64 encodings operate in 4-byte blocks; when finished -// writing, the caller must Close the returned encoder to flush any -// partially written blocks. -func NewEncoder(enc *Encoding, w io.Writer) io.WriteCloser { - return &encoder{enc: enc, w: w} -} - -// EncodedLen returns the length in bytes of the base64 encoding -// of an input buffer of length n. -func (enc *Encoding) EncodedLen(n int) int { return (n + 2) / 3 * 4 } - -/* - * Decoder - */ - -type CorruptInputError int64 - -func (e CorruptInputError) Error() string { - return "illegal base64 data at input byte " + strconv.FormatInt(int64(e), 10) -} - -// decode is like Decode but returns an additional 'end' value, which -// indicates if end-of-message padding was encountered and thus any -// additional data is an error. This method assumes that src has been -// stripped of all supported whitespace ('\r' and '\n'). -func (enc *Encoding) decode(dst, src []byte) (n int, end bool, err error) { - olen := len(src) - for len(src) > 0 && !end { - // Decode quantum using the base64 alphabet - var dbuf [4]byte - dlen := 4 - - for j := range dbuf { - if len(src) == 0 { - return n, false, CorruptInputError(olen - len(src) - j) - } - in := src[0] - src = src[1:] - if in == '=' { - // We've reached the end and there's padding - switch j { - case 0, 1: - // incorrect padding - return n, false, CorruptInputError(olen - len(src) - 1) - case 2: - // "==" is expected, the first "=" is already consumed. - if len(src) == 0 { - // not enough padding - return n, false, CorruptInputError(olen) - } - if src[0] != '=' { - // incorrect padding - return n, false, CorruptInputError(olen - len(src) - 1) - } - src = src[1:] - } - if len(src) > 0 { - // trailing garbage - err = CorruptInputError(olen - len(src)) - } - dlen, end = j, true - break - } - dbuf[j] = enc.decodeMap[in] - if dbuf[j] == 0xFF { - return n, false, CorruptInputError(olen - len(src) - 1) - } - } - - // Pack 4x 6-bit source blocks into 3 byte destination - // quantum - switch dlen { - case 4: - dst[2] = dbuf[2]<<6 | dbuf[3] - fallthrough - case 3: - dst[1] = dbuf[1]<<4 | dbuf[2]>>2 - fallthrough - case 2: - dst[0] = dbuf[0]<<2 | dbuf[1]>>4 - } - dst = dst[3:] - n += dlen - 1 - } - - return n, end, err -} - -// Decode decodes src using the encoding enc. It writes at most -// DecodedLen(len(src)) bytes to dst and returns the number of bytes -// written. If src contains invalid base64 data, it will return the -// number of bytes successfully written and CorruptInputError. -// New line characters (\r and \n) are ignored. -func (enc *Encoding) Decode(dst, src []byte) (n int, err error) { - src = bytes.Map(removeNewlinesMapper, src) - n, _, err = enc.decode(dst, src) - return -} - -// DecodeString returns the bytes represented by the base64 string s. -func (enc *Encoding) DecodeString(s string) ([]byte, error) { - s = strings.Map(removeNewlinesMapper, s) - dbuf := make([]byte, enc.DecodedLen(len(s))) - n, _, err := enc.decode(dbuf, []byte(s)) - return dbuf[:n], err -} - -type decoder struct { - err error - enc *Encoding - r io.Reader - end bool // saw end of message - buf [1024]byte // leftover input - nbuf int - out []byte // leftover decoded output - outbuf [1024 / 4 * 3]byte -} - -func (d *decoder) Read(p []byte) (n int, err error) { - if d.err != nil { - return 0, d.err - } - - // Use leftover decoded output from last read. - if len(d.out) > 0 { - n = copy(p, d.out) - d.out = d.out[n:] - return n, nil - } - - // Read a chunk. - nn := len(p) / 3 * 4 - if nn < 4 { - nn = 4 - } - if nn > len(d.buf) { - nn = len(d.buf) - } - nn, d.err = io.ReadAtLeast(d.r, d.buf[d.nbuf:nn], 4-d.nbuf) - d.nbuf += nn - if d.err != nil || d.nbuf < 4 { - return 0, d.err - } - - // Decode chunk into p, or d.out and then p if p is too small. - nr := d.nbuf / 4 * 4 - nw := d.nbuf / 4 * 3 - if nw > len(p) { - nw, d.end, d.err = d.enc.decode(d.outbuf[0:], d.buf[0:nr]) - d.out = d.outbuf[0:nw] - n = copy(p, d.out) - d.out = d.out[n:] - } else { - n, d.end, d.err = d.enc.decode(p, d.buf[0:nr]) - } - d.nbuf -= nr - for i := 0; i < d.nbuf; i++ { - d.buf[i] = d.buf[i+nr] - } - - if d.err == nil { - d.err = err - } - return n, d.err -} - -type newlineFilteringReader struct { - wrapped io.Reader -} - -func (r *newlineFilteringReader) Read(p []byte) (int, error) { - n, err := r.wrapped.Read(p) - for n > 0 { - offset := 0 - for i, b := range p[0:n] { - if b != '\r' && b != '\n' { - if i != offset { - p[offset] = b - } - offset++ - } - } - if offset > 0 { - return offset, err - } - // Previous buffer entirely whitespace, read again - n, err = r.wrapped.Read(p) - } - return n, err -} - -// NewDecoder constructs a new base64 stream decoder. -func NewDecoder(enc *Encoding, r io.Reader) io.Reader { - return &decoder{enc: enc, r: &newlineFilteringReader{r}} -} - -// DecodedLen returns the maximum length in bytes of the decoded data -// corresponding to n bytes of base64-encoded data. -func (enc *Encoding) DecodedLen(n int) int { return n / 4 * 3 } diff --git a/src/pkg/encoding/base64/base64_test.go b/src/pkg/encoding/base64/base64_test.go deleted file mode 100644 index 7d199bfa0..000000000 --- a/src/pkg/encoding/base64/base64_test.go +++ /dev/null @@ -1,360 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package base64 - -import ( - "bytes" - "errors" - "io" - "io/ioutil" - "reflect" - "strings" - "testing" - "time" -) - -type testpair struct { - decoded, encoded string -} - -var pairs = []testpair{ - // RFC 3548 examples - {"\x14\xfb\x9c\x03\xd9\x7e", "FPucA9l+"}, - {"\x14\xfb\x9c\x03\xd9", "FPucA9k="}, - {"\x14\xfb\x9c\x03", "FPucAw=="}, - - // RFC 4648 examples - {"", ""}, - {"f", "Zg=="}, - {"fo", "Zm8="}, - {"foo", "Zm9v"}, - {"foob", "Zm9vYg=="}, - {"fooba", "Zm9vYmE="}, - {"foobar", "Zm9vYmFy"}, - - // Wikipedia examples - {"sure.", "c3VyZS4="}, - {"sure", "c3VyZQ=="}, - {"sur", "c3Vy"}, - {"su", "c3U="}, - {"leasure.", "bGVhc3VyZS4="}, - {"easure.", "ZWFzdXJlLg=="}, - {"asure.", "YXN1cmUu"}, - {"sure.", "c3VyZS4="}, -} - -var bigtest = testpair{ - "Twas brillig, and the slithy toves", - "VHdhcyBicmlsbGlnLCBhbmQgdGhlIHNsaXRoeSB0b3Zlcw==", -} - -func testEqual(t *testing.T, msg string, args ...interface{}) bool { - if args[len(args)-2] != args[len(args)-1] { - t.Errorf(msg, args...) - return false - } - return true -} - -func TestEncode(t *testing.T) { - for _, p := range pairs { - got := StdEncoding.EncodeToString([]byte(p.decoded)) - testEqual(t, "Encode(%q) = %q, want %q", p.decoded, got, p.encoded) - } -} - -func TestEncoder(t *testing.T) { - for _, p := range pairs { - bb := &bytes.Buffer{} - encoder := NewEncoder(StdEncoding, bb) - encoder.Write([]byte(p.decoded)) - encoder.Close() - testEqual(t, "Encode(%q) = %q, want %q", p.decoded, bb.String(), p.encoded) - } -} - -func TestEncoderBuffering(t *testing.T) { - input := []byte(bigtest.decoded) - for bs := 1; bs <= 12; bs++ { - bb := &bytes.Buffer{} - encoder := NewEncoder(StdEncoding, bb) - for pos := 0; pos < len(input); pos += bs { - end := pos + bs - if end > len(input) { - end = len(input) - } - n, err := encoder.Write(input[pos:end]) - testEqual(t, "Write(%q) gave error %v, want %v", input[pos:end], err, error(nil)) - testEqual(t, "Write(%q) gave length %v, want %v", input[pos:end], n, end-pos) - } - err := encoder.Close() - testEqual(t, "Close gave error %v, want %v", err, error(nil)) - testEqual(t, "Encoding/%d of %q = %q, want %q", bs, bigtest.decoded, bb.String(), bigtest.encoded) - } -} - -func TestDecode(t *testing.T) { - for _, p := range pairs { - dbuf := make([]byte, StdEncoding.DecodedLen(len(p.encoded))) - count, end, err := StdEncoding.decode(dbuf, []byte(p.encoded)) - testEqual(t, "Decode(%q) = error %v, want %v", p.encoded, err, error(nil)) - testEqual(t, "Decode(%q) = length %v, want %v", p.encoded, count, len(p.decoded)) - if len(p.encoded) > 0 { - testEqual(t, "Decode(%q) = end %v, want %v", p.encoded, end, (p.encoded[len(p.encoded)-1] == '=')) - } - testEqual(t, "Decode(%q) = %q, want %q", p.encoded, string(dbuf[0:count]), p.decoded) - - dbuf, err = StdEncoding.DecodeString(p.encoded) - testEqual(t, "DecodeString(%q) = error %v, want %v", p.encoded, err, error(nil)) - testEqual(t, "DecodeString(%q) = %q, want %q", string(dbuf), p.decoded) - } -} - -func TestDecoder(t *testing.T) { - for _, p := range pairs { - decoder := NewDecoder(StdEncoding, strings.NewReader(p.encoded)) - dbuf := make([]byte, StdEncoding.DecodedLen(len(p.encoded))) - count, err := decoder.Read(dbuf) - if err != nil && err != io.EOF { - t.Fatal("Read failed", err) - } - testEqual(t, "Read from %q = length %v, want %v", p.encoded, count, len(p.decoded)) - testEqual(t, "Decoding of %q = %q, want %q", p.encoded, string(dbuf[0:count]), p.decoded) - if err != io.EOF { - count, err = decoder.Read(dbuf) - } - testEqual(t, "Read from %q = %v, want %v", p.encoded, err, io.EOF) - } -} - -func TestDecoderBuffering(t *testing.T) { - for bs := 1; bs <= 12; bs++ { - decoder := NewDecoder(StdEncoding, strings.NewReader(bigtest.encoded)) - buf := make([]byte, len(bigtest.decoded)+12) - var total int - for total = 0; total < len(bigtest.decoded); { - n, err := decoder.Read(buf[total : total+bs]) - testEqual(t, "Read from %q at pos %d = %d, %v, want _, %v", bigtest.encoded, total, n, err, error(nil)) - total += n - } - testEqual(t, "Decoding/%d of %q = %q, want %q", bs, bigtest.encoded, string(buf[0:total]), bigtest.decoded) - } -} - -func TestDecodeCorrupt(t *testing.T) { - testCases := []struct { - input string - offset int // -1 means no corruption. - }{ - {"", -1}, - {"!!!!", 0}, - {"====", 0}, - {"x===", 1}, - {"=AAA", 0}, - {"A=AA", 1}, - {"AA=A", 2}, - {"AA==A", 4}, - {"AAA=AAAA", 4}, - {"AAAAA", 4}, - {"AAAAAA", 4}, - {"A=", 1}, - {"A==", 1}, - {"AA=", 3}, - {"AA==", -1}, - {"AAA=", -1}, - {"AAAA", -1}, - {"AAAAAA=", 7}, - {"YWJjZA=====", 8}, - } - for _, tc := range testCases { - dbuf := make([]byte, StdEncoding.DecodedLen(len(tc.input))) - _, err := StdEncoding.Decode(dbuf, []byte(tc.input)) - if tc.offset == -1 { - if err != nil { - t.Error("Decoder wrongly detected coruption in", tc.input) - } - continue - } - switch err := err.(type) { - case CorruptInputError: - testEqual(t, "Corruption in %q at offset %v, want %v", tc.input, int(err), tc.offset) - default: - t.Error("Decoder failed to detect corruption in", tc) - } - } -} - -func TestBig(t *testing.T) { - n := 3*1000 + 1 - raw := make([]byte, n) - const alpha = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" - for i := 0; i < n; i++ { - raw[i] = alpha[i%len(alpha)] - } - encoded := new(bytes.Buffer) - w := NewEncoder(StdEncoding, encoded) - nn, err := w.Write(raw) - if nn != n || err != nil { - t.Fatalf("Encoder.Write(raw) = %d, %v want %d, nil", nn, err, n) - } - err = w.Close() - if err != nil { - t.Fatalf("Encoder.Close() = %v want nil", err) - } - decoded, err := ioutil.ReadAll(NewDecoder(StdEncoding, encoded)) - if err != nil { - t.Fatalf("ioutil.ReadAll(NewDecoder(...)): %v", err) - } - - if !bytes.Equal(raw, decoded) { - var i int - for i = 0; i < len(decoded) && i < len(raw); i++ { - if decoded[i] != raw[i] { - break - } - } - t.Errorf("Decode(Encode(%d-byte string)) failed at offset %d", n, i) - } -} - -func TestNewLineCharacters(t *testing.T) { - // Each of these should decode to the string "sure", without errors. - const expected = "sure" - examples := []string{ - "c3VyZQ==", - "c3VyZQ==\r", - "c3VyZQ==\n", - "c3VyZQ==\r\n", - "c3VyZ\r\nQ==", - "c3V\ryZ\nQ==", - "c3V\nyZ\rQ==", - "c3VyZ\nQ==", - "c3VyZQ\n==", - "c3VyZQ=\n=", - "c3VyZQ=\r\n\r\n=", - } - for _, e := range examples { - buf, err := StdEncoding.DecodeString(e) - if err != nil { - t.Errorf("Decode(%q) failed: %v", e, err) - continue - } - if s := string(buf); s != expected { - t.Errorf("Decode(%q) = %q, want %q", e, s, expected) - } - } -} - -type nextRead struct { - n int // bytes to return - err error // error to return -} - -// faultInjectReader returns data from source, rate-limited -// and with the errors as written to nextc. -type faultInjectReader struct { - source string - nextc <-chan nextRead -} - -func (r *faultInjectReader) Read(p []byte) (int, error) { - nr := <-r.nextc - if len(p) > nr.n { - p = p[:nr.n] - } - n := copy(p, r.source) - r.source = r.source[n:] - return n, nr.err -} - -// tests that we don't ignore errors from our underlying reader -func TestDecoderIssue3577(t *testing.T) { - next := make(chan nextRead, 10) - wantErr := errors.New("my error") - next <- nextRead{5, nil} - next <- nextRead{10, wantErr} - next <- nextRead{0, wantErr} - d := NewDecoder(StdEncoding, &faultInjectReader{ - source: "VHdhcyBicmlsbGlnLCBhbmQgdGhlIHNsaXRoeSB0b3Zlcw==", // twas brillig... - nextc: next, - }) - errc := make(chan error) - go func() { - _, err := ioutil.ReadAll(d) - errc <- err - }() - select { - case err := <-errc: - if err != wantErr { - t.Errorf("got error %v; want %v", err, wantErr) - } - case <-time.After(5 * time.Second): - t.Errorf("timeout; Decoder blocked without returning an error") - } -} - -func TestDecoderIssue4779(t *testing.T) { - encoded := `CP/EAT8AAAEF -AQEBAQEBAAAAAAAAAAMAAQIEBQYHCAkKCwEAAQUBAQEBAQEAAAAAAAAAAQACAwQFBgcICQoLEAAB -BAEDAgQCBQcGCAUDDDMBAAIRAwQhEjEFQVFhEyJxgTIGFJGhsUIjJBVSwWIzNHKC0UMHJZJT8OHx -Y3M1FqKygyZEk1RkRcKjdDYX0lXiZfKzhMPTdePzRieUpIW0lcTU5PSltcXV5fVWZnaGlqa2xtbm -9jdHV2d3h5ent8fX5/cRAAICAQIEBAMEBQYHBwYFNQEAAhEDITESBEFRYXEiEwUygZEUobFCI8FS -0fAzJGLhcoKSQ1MVY3M08SUGFqKygwcmNcLSRJNUoxdkRVU2dGXi8rOEw9N14/NGlKSFtJXE1OT0 -pbXF1eX1VmZ2hpamtsbW5vYnN0dXZ3eHl6e3x//aAAwDAQACEQMRAD8A9VSSSSUpJJJJSkkkJ+Tj -1kiy1jCJJDnAcCTykpKkuQ6p/jN6FgmxlNduXawwAzaGH+V6jn/R/wCt71zdn+N/qL3kVYFNYB4N -ji6PDVjWpKp9TSXnvTf8bFNjg3qOEa2n6VlLpj/rT/pf567DpX1i6L1hs9Py67X8mqdtg/rUWbbf -+gkp0kkkklKSSSSUpJJJJT//0PVUkkklKVLq3WMDpGI7KzrNjADtYNXvI/Mqr/Pd/q9W3vaxjnvM -NaCXE9gNSvGPrf8AWS3qmba5jjsJhoB0DAf0NDf6sevf+/lf8Hj0JJATfWT6/dV6oXU1uOLQeKKn -EQP+Hubtfe/+R7Mf/g7f5xcocp++Z11JMCJPgFBxOg7/AOuqDx8I/ikpkXkmSdU8mJIJA/O8EMAy -j+mSARB/17pKVXYWHXjsj7yIex0PadzXMO1zT5KHoNA3HT8ietoGhgjsfA+CSnvvqh/jJtqsrwOv -2b6NGNzXfTYexzJ+nU7/ALkf4P8Awv6P9KvTQQ4AgyDqCF85Pho3CTB7eHwXoH+LT65uZbX9X+o2 -bqbPb06551Y4 -` - encodedShort := strings.Replace(encoded, "\n", "", -1) - - dec := NewDecoder(StdEncoding, strings.NewReader(encoded)) - res1, err := ioutil.ReadAll(dec) - if err != nil { - t.Errorf("ReadAll failed: %v", err) - } - - dec = NewDecoder(StdEncoding, strings.NewReader(encodedShort)) - var res2 []byte - res2, err = ioutil.ReadAll(dec) - if err != nil { - t.Errorf("ReadAll failed: %v", err) - } - - if !bytes.Equal(res1, res2) { - t.Error("Decoded results not equal") - } -} - -func TestDecoderIssue7733(t *testing.T) { - s, err := StdEncoding.DecodeString("YWJjZA=====") - want := CorruptInputError(8) - if !reflect.DeepEqual(want, err) { - t.Errorf("Error = %v; want CorruptInputError(8)", err) - } - if string(s) != "abcd" { - t.Errorf("DecodeString = %q; want abcd", s) - } -} - -func BenchmarkEncodeToString(b *testing.B) { - data := make([]byte, 8192) - b.SetBytes(int64(len(data))) - for i := 0; i < b.N; i++ { - StdEncoding.EncodeToString(data) - } -} - -func BenchmarkDecodeString(b *testing.B) { - data := StdEncoding.EncodeToString(make([]byte, 8192)) - b.SetBytes(int64(len(data))) - for i := 0; i < b.N; i++ { - StdEncoding.DecodeString(data) - } -} diff --git a/src/pkg/encoding/base64/example_test.go b/src/pkg/encoding/base64/example_test.go deleted file mode 100644 index d18b856a0..000000000 --- a/src/pkg/encoding/base64/example_test.go +++ /dev/null @@ -1,45 +0,0 @@ -// Copyright 2012 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Keep in sync with ../base32/example_test.go. - -package base64_test - -import ( - "encoding/base64" - "fmt" - "os" -) - -func ExampleEncoding_EncodeToString() { - data := []byte("any + old & data") - str := base64.StdEncoding.EncodeToString(data) - fmt.Println(str) - // Output: - // YW55ICsgb2xkICYgZGF0YQ== -} - -func ExampleEncoding_DecodeString() { - str := "c29tZSBkYXRhIHdpdGggACBhbmQg77u/" - data, err := base64.StdEncoding.DecodeString(str) - if err != nil { - fmt.Println("error:", err) - return - } - fmt.Printf("%q\n", data) - // Output: - // "some data with \x00 and \ufeff" -} - -func ExampleNewEncoder() { - input := []byte("foo\x00bar") - encoder := base64.NewEncoder(base64.StdEncoding, os.Stdout) - encoder.Write(input) - // Must close the encoder when finished to flush any partial blocks. - // If you comment out the following line, the last partial block "r" - // won't be encoded. - encoder.Close() - // Output: - // Zm9vAGJhcg== -} diff --git a/src/pkg/encoding/binary/binary.go b/src/pkg/encoding/binary/binary.go deleted file mode 100644 index a5694876a..000000000 --- a/src/pkg/encoding/binary/binary.go +++ /dev/null @@ -1,639 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package binary implements simple translation between numbers and byte -// sequences and encoding and decoding of varints. -// -// Numbers are translated by reading and writing fixed-size values. -// A fixed-size value is either a fixed-size arithmetic -// type (int8, uint8, int16, float32, complex64, ...) -// or an array or struct containing only fixed-size values. -// -// Varints are a method of encoding integers using one or more bytes; -// numbers with smaller absolute value take a smaller number of bytes. -// For a specification, see http://code.google.com/apis/protocolbuffers/docs/encoding.html. -// -// This package favors simplicity over efficiency. Clients that require -// high-performance serialization, especially for large data structures, -// should look at more advanced solutions such as the encoding/gob -// package or protocol buffers. -package binary - -import ( - "errors" - "io" - "math" - "reflect" -) - -// A ByteOrder specifies how to convert byte sequences into -// 16-, 32-, or 64-bit unsigned integers. -type ByteOrder interface { - Uint16([]byte) uint16 - Uint32([]byte) uint32 - Uint64([]byte) uint64 - PutUint16([]byte, uint16) - PutUint32([]byte, uint32) - PutUint64([]byte, uint64) - String() string -} - -// LittleEndian is the little-endian implementation of ByteOrder. -var LittleEndian littleEndian - -// BigEndian is the big-endian implementation of ByteOrder. -var BigEndian bigEndian - -type littleEndian struct{} - -func (littleEndian) Uint16(b []byte) uint16 { return uint16(b[0]) | uint16(b[1])<<8 } - -func (littleEndian) PutUint16(b []byte, v uint16) { - b[0] = byte(v) - b[1] = byte(v >> 8) -} - -func (littleEndian) Uint32(b []byte) uint32 { - return uint32(b[0]) | uint32(b[1])<<8 | uint32(b[2])<<16 | uint32(b[3])<<24 -} - -func (littleEndian) PutUint32(b []byte, v uint32) { - b[0] = byte(v) - b[1] = byte(v >> 8) - b[2] = byte(v >> 16) - b[3] = byte(v >> 24) -} - -func (littleEndian) Uint64(b []byte) uint64 { - return uint64(b[0]) | uint64(b[1])<<8 | uint64(b[2])<<16 | uint64(b[3])<<24 | - uint64(b[4])<<32 | uint64(b[5])<<40 | uint64(b[6])<<48 | uint64(b[7])<<56 -} - -func (littleEndian) PutUint64(b []byte, v uint64) { - b[0] = byte(v) - b[1] = byte(v >> 8) - b[2] = byte(v >> 16) - b[3] = byte(v >> 24) - b[4] = byte(v >> 32) - b[5] = byte(v >> 40) - b[6] = byte(v >> 48) - b[7] = byte(v >> 56) -} - -func (littleEndian) String() string { return "LittleEndian" } - -func (littleEndian) GoString() string { return "binary.LittleEndian" } - -type bigEndian struct{} - -func (bigEndian) Uint16(b []byte) uint16 { return uint16(b[1]) | uint16(b[0])<<8 } - -func (bigEndian) PutUint16(b []byte, v uint16) { - b[0] = byte(v >> 8) - b[1] = byte(v) -} - -func (bigEndian) Uint32(b []byte) uint32 { - return uint32(b[3]) | uint32(b[2])<<8 | uint32(b[1])<<16 | uint32(b[0])<<24 -} - -func (bigEndian) PutUint32(b []byte, v uint32) { - b[0] = byte(v >> 24) - b[1] = byte(v >> 16) - b[2] = byte(v >> 8) - b[3] = byte(v) -} - -func (bigEndian) Uint64(b []byte) uint64 { - return uint64(b[7]) | uint64(b[6])<<8 | uint64(b[5])<<16 | uint64(b[4])<<24 | - uint64(b[3])<<32 | uint64(b[2])<<40 | uint64(b[1])<<48 | uint64(b[0])<<56 -} - -func (bigEndian) PutUint64(b []byte, v uint64) { - b[0] = byte(v >> 56) - b[1] = byte(v >> 48) - b[2] = byte(v >> 40) - b[3] = byte(v >> 32) - b[4] = byte(v >> 24) - b[5] = byte(v >> 16) - b[6] = byte(v >> 8) - b[7] = byte(v) -} - -func (bigEndian) String() string { return "BigEndian" } - -func (bigEndian) GoString() string { return "binary.BigEndian" } - -// Read reads structured binary data from r into data. -// Data must be a pointer to a fixed-size value or a slice -// of fixed-size values. -// Bytes read from r are decoded using the specified byte order -// and written to successive fields of the data. -// When reading into structs, the field data for fields with -// blank (_) field names is skipped; i.e., blank field names -// may be used for padding. -// When reading into a struct, all non-blank fields must be exported. -func Read(r io.Reader, order ByteOrder, data interface{}) error { - // Fast path for basic types and slices. - if n := intDataSize(data); n != 0 { - var b [8]byte - var bs []byte - if n > len(b) { - bs = make([]byte, n) - } else { - bs = b[:n] - } - if _, err := io.ReadFull(r, bs); err != nil { - return err - } - switch data := data.(type) { - case *int8: - *data = int8(b[0]) - case *uint8: - *data = b[0] - case *int16: - *data = int16(order.Uint16(bs)) - case *uint16: - *data = order.Uint16(bs) - case *int32: - *data = int32(order.Uint32(bs)) - case *uint32: - *data = order.Uint32(bs) - case *int64: - *data = int64(order.Uint64(bs)) - case *uint64: - *data = order.Uint64(bs) - case []int8: - for i, x := range bs { // Easier to loop over the input for 8-bit values. - data[i] = int8(x) - } - case []uint8: - copy(data, bs) - case []int16: - for i := range data { - data[i] = int16(order.Uint16(bs[2*i:])) - } - case []uint16: - for i := range data { - data[i] = order.Uint16(bs[2*i:]) - } - case []int32: - for i := range data { - data[i] = int32(order.Uint32(bs[4*i:])) - } - case []uint32: - for i := range data { - data[i] = order.Uint32(bs[4*i:]) - } - case []int64: - for i := range data { - data[i] = int64(order.Uint64(bs[8*i:])) - } - case []uint64: - for i := range data { - data[i] = order.Uint64(bs[8*i:]) - } - } - return nil - } - - // Fallback to reflect-based decoding. - var v reflect.Value - switch d := reflect.ValueOf(data); d.Kind() { - case reflect.Ptr: - v = d.Elem() - case reflect.Slice: - v = d - default: - return errors.New("binary.Read: invalid type " + d.Type().String()) - } - size, err := dataSize(v) - if err != nil { - return errors.New("binary.Read: " + err.Error()) - } - d := &decoder{order: order, buf: make([]byte, size)} - if _, err := io.ReadFull(r, d.buf); err != nil { - return err - } - d.value(v) - return nil -} - -// Write writes the binary representation of data into w. -// Data must be a fixed-size value or a slice of fixed-size -// values, or a pointer to such data. -// Bytes written to w are encoded using the specified byte order -// and read from successive fields of the data. -// When writing structs, zero values are written for fields -// with blank (_) field names. -func Write(w io.Writer, order ByteOrder, data interface{}) error { - // Fast path for basic types and slices. - if n := intDataSize(data); n != 0 { - var b [8]byte - var bs []byte - if n > len(b) { - bs = make([]byte, n) - } else { - bs = b[:n] - } - switch v := data.(type) { - case *int8: - bs = b[:1] - b[0] = byte(*v) - case int8: - bs = b[:1] - b[0] = byte(v) - case []int8: - for i, x := range v { - bs[i] = byte(x) - } - case *uint8: - bs = b[:1] - b[0] = *v - case uint8: - bs = b[:1] - b[0] = byte(v) - case []uint8: - bs = v - case *int16: - bs = b[:2] - order.PutUint16(bs, uint16(*v)) - case int16: - bs = b[:2] - order.PutUint16(bs, uint16(v)) - case []int16: - for i, x := range v { - order.PutUint16(bs[2*i:], uint16(x)) - } - case *uint16: - bs = b[:2] - order.PutUint16(bs, *v) - case uint16: - bs = b[:2] - order.PutUint16(bs, v) - case []uint16: - for i, x := range v { - order.PutUint16(bs[2*i:], x) - } - case *int32: - bs = b[:4] - order.PutUint32(bs, uint32(*v)) - case int32: - bs = b[:4] - order.PutUint32(bs, uint32(v)) - case []int32: - for i, x := range v { - order.PutUint32(bs[4*i:], uint32(x)) - } - case *uint32: - bs = b[:4] - order.PutUint32(bs, *v) - case uint32: - bs = b[:4] - order.PutUint32(bs, v) - case []uint32: - for i, x := range v { - order.PutUint32(bs[4*i:], x) - } - case *int64: - bs = b[:8] - order.PutUint64(bs, uint64(*v)) - case int64: - bs = b[:8] - order.PutUint64(bs, uint64(v)) - case []int64: - for i, x := range v { - order.PutUint64(bs[8*i:], uint64(x)) - } - case *uint64: - bs = b[:8] - order.PutUint64(bs, *v) - case uint64: - bs = b[:8] - order.PutUint64(bs, v) - case []uint64: - for i, x := range v { - order.PutUint64(bs[8*i:], x) - } - } - _, err := w.Write(bs) - return err - } - - // Fallback to reflect-based encoding. - v := reflect.Indirect(reflect.ValueOf(data)) - size, err := dataSize(v) - if err != nil { - return errors.New("binary.Write: " + err.Error()) - } - buf := make([]byte, size) - e := &encoder{order: order, buf: buf} - e.value(v) - _, err = w.Write(buf) - return err -} - -// Size returns how many bytes Write would generate to encode the value v, which -// must be a fixed-size value or a slice of fixed-size values, or a pointer to such data. -func Size(v interface{}) int { - n, err := dataSize(reflect.Indirect(reflect.ValueOf(v))) - if err != nil { - return -1 - } - return n -} - -// dataSize returns the number of bytes the actual data represented by v occupies in memory. -// For compound structures, it sums the sizes of the elements. Thus, for instance, for a slice -// it returns the length of the slice times the element size and does not count the memory -// occupied by the header. -func dataSize(v reflect.Value) (int, error) { - if v.Kind() == reflect.Slice { - elem, err := sizeof(v.Type().Elem()) - if err != nil { - return 0, err - } - return v.Len() * elem, nil - } - return sizeof(v.Type()) -} - -func sizeof(t reflect.Type) (int, error) { - switch t.Kind() { - case reflect.Array: - n, err := sizeof(t.Elem()) - if err != nil { - return 0, err - } - return t.Len() * n, nil - - case reflect.Struct: - sum := 0 - for i, n := 0, t.NumField(); i < n; i++ { - s, err := sizeof(t.Field(i).Type) - if err != nil { - return 0, err - } - sum += s - } - return sum, nil - - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, - reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, - reflect.Float32, reflect.Float64, reflect.Complex64, reflect.Complex128: - return int(t.Size()), nil - } - return 0, errors.New("invalid type " + t.String()) -} - -type coder struct { - order ByteOrder - buf []byte -} - -type decoder coder -type encoder coder - -func (d *decoder) uint8() uint8 { - x := d.buf[0] - d.buf = d.buf[1:] - return x -} - -func (e *encoder) uint8(x uint8) { - e.buf[0] = x - e.buf = e.buf[1:] -} - -func (d *decoder) uint16() uint16 { - x := d.order.Uint16(d.buf[0:2]) - d.buf = d.buf[2:] - return x -} - -func (e *encoder) uint16(x uint16) { - e.order.PutUint16(e.buf[0:2], x) - e.buf = e.buf[2:] -} - -func (d *decoder) uint32() uint32 { - x := d.order.Uint32(d.buf[0:4]) - d.buf = d.buf[4:] - return x -} - -func (e *encoder) uint32(x uint32) { - e.order.PutUint32(e.buf[0:4], x) - e.buf = e.buf[4:] -} - -func (d *decoder) uint64() uint64 { - x := d.order.Uint64(d.buf[0:8]) - d.buf = d.buf[8:] - return x -} - -func (e *encoder) uint64(x uint64) { - e.order.PutUint64(e.buf[0:8], x) - e.buf = e.buf[8:] -} - -func (d *decoder) int8() int8 { return int8(d.uint8()) } - -func (e *encoder) int8(x int8) { e.uint8(uint8(x)) } - -func (d *decoder) int16() int16 { return int16(d.uint16()) } - -func (e *encoder) int16(x int16) { e.uint16(uint16(x)) } - -func (d *decoder) int32() int32 { return int32(d.uint32()) } - -func (e *encoder) int32(x int32) { e.uint32(uint32(x)) } - -func (d *decoder) int64() int64 { return int64(d.uint64()) } - -func (e *encoder) int64(x int64) { e.uint64(uint64(x)) } - -func (d *decoder) value(v reflect.Value) { - switch v.Kind() { - case reflect.Array: - l := v.Len() - for i := 0; i < l; i++ { - d.value(v.Index(i)) - } - - case reflect.Struct: - t := v.Type() - l := v.NumField() - for i := 0; i < l; i++ { - // Note: Calling v.CanSet() below is an optimization. - // It would be sufficient to check the field name, - // but creating the StructField info for each field is - // costly (run "go test -bench=ReadStruct" and compare - // results when making changes to this code). - if v := v.Field(i); v.CanSet() || t.Field(i).Name != "_" { - d.value(v) - } else { - d.skip(v) - } - } - - case reflect.Slice: - l := v.Len() - for i := 0; i < l; i++ { - d.value(v.Index(i)) - } - - case reflect.Int8: - v.SetInt(int64(d.int8())) - case reflect.Int16: - v.SetInt(int64(d.int16())) - case reflect.Int32: - v.SetInt(int64(d.int32())) - case reflect.Int64: - v.SetInt(d.int64()) - - case reflect.Uint8: - v.SetUint(uint64(d.uint8())) - case reflect.Uint16: - v.SetUint(uint64(d.uint16())) - case reflect.Uint32: - v.SetUint(uint64(d.uint32())) - case reflect.Uint64: - v.SetUint(d.uint64()) - - case reflect.Float32: - v.SetFloat(float64(math.Float32frombits(d.uint32()))) - case reflect.Float64: - v.SetFloat(math.Float64frombits(d.uint64())) - - case reflect.Complex64: - v.SetComplex(complex( - float64(math.Float32frombits(d.uint32())), - float64(math.Float32frombits(d.uint32())), - )) - case reflect.Complex128: - v.SetComplex(complex( - math.Float64frombits(d.uint64()), - math.Float64frombits(d.uint64()), - )) - } -} - -func (e *encoder) value(v reflect.Value) { - switch v.Kind() { - case reflect.Array: - l := v.Len() - for i := 0; i < l; i++ { - e.value(v.Index(i)) - } - - case reflect.Struct: - t := v.Type() - l := v.NumField() - for i := 0; i < l; i++ { - // see comment for corresponding code in decoder.value() - if v := v.Field(i); v.CanSet() || t.Field(i).Name != "_" { - e.value(v) - } else { - e.skip(v) - } - } - - case reflect.Slice: - l := v.Len() - for i := 0; i < l; i++ { - e.value(v.Index(i)) - } - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - switch v.Type().Kind() { - case reflect.Int8: - e.int8(int8(v.Int())) - case reflect.Int16: - e.int16(int16(v.Int())) - case reflect.Int32: - e.int32(int32(v.Int())) - case reflect.Int64: - e.int64(v.Int()) - } - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - switch v.Type().Kind() { - case reflect.Uint8: - e.uint8(uint8(v.Uint())) - case reflect.Uint16: - e.uint16(uint16(v.Uint())) - case reflect.Uint32: - e.uint32(uint32(v.Uint())) - case reflect.Uint64: - e.uint64(v.Uint()) - } - - case reflect.Float32, reflect.Float64: - switch v.Type().Kind() { - case reflect.Float32: - e.uint32(math.Float32bits(float32(v.Float()))) - case reflect.Float64: - e.uint64(math.Float64bits(v.Float())) - } - - case reflect.Complex64, reflect.Complex128: - switch v.Type().Kind() { - case reflect.Complex64: - x := v.Complex() - e.uint32(math.Float32bits(float32(real(x)))) - e.uint32(math.Float32bits(float32(imag(x)))) - case reflect.Complex128: - x := v.Complex() - e.uint64(math.Float64bits(real(x))) - e.uint64(math.Float64bits(imag(x))) - } - } -} - -func (d *decoder) skip(v reflect.Value) { - n, _ := dataSize(v) - d.buf = d.buf[n:] -} - -func (e *encoder) skip(v reflect.Value) { - n, _ := dataSize(v) - for i := range e.buf[0:n] { - e.buf[i] = 0 - } - e.buf = e.buf[n:] -} - -// intDataSize returns the size of the data required to represent the data when encoded. -// It returns zero if the type cannot be implemented by the fast path in Read or Write. -func intDataSize(data interface{}) int { - switch data := data.(type) { - case int8, *int8, *uint8: - return 1 - case []int8: - return len(data) - case []uint8: - return len(data) - case int16, *int16, *uint16: - return 2 - case []int16: - return 2 * len(data) - case []uint16: - return 2 * len(data) - case int32, *int32, *uint32: - return 4 - case []int32: - return 4 * len(data) - case []uint32: - return 4 * len(data) - case int64, *int64, *uint64: - return 8 - case []int64: - return 8 * len(data) - case []uint64: - return 8 * len(data) - } - return 0 -} diff --git a/src/pkg/encoding/binary/binary_test.go b/src/pkg/encoding/binary/binary_test.go deleted file mode 100644 index c80c90383..000000000 --- a/src/pkg/encoding/binary/binary_test.go +++ /dev/null @@ -1,397 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package binary - -import ( - "bytes" - "io" - "math" - "reflect" - "strings" - "testing" -) - -type Struct struct { - Int8 int8 - Int16 int16 - Int32 int32 - Int64 int64 - Uint8 uint8 - Uint16 uint16 - Uint32 uint32 - Uint64 uint64 - Float32 float32 - Float64 float64 - Complex64 complex64 - Complex128 complex128 - Array [4]uint8 -} - -type T struct { - Int int - Uint uint - Uintptr uintptr - Array [4]int -} - -var s = Struct{ - 0x01, - 0x0203, - 0x04050607, - 0x08090a0b0c0d0e0f, - 0x10, - 0x1112, - 0x13141516, - 0x1718191a1b1c1d1e, - - math.Float32frombits(0x1f202122), - math.Float64frombits(0x232425262728292a), - complex( - math.Float32frombits(0x2b2c2d2e), - math.Float32frombits(0x2f303132), - ), - complex( - math.Float64frombits(0x333435363738393a), - math.Float64frombits(0x3b3c3d3e3f404142), - ), - - [4]uint8{0x43, 0x44, 0x45, 0x46}, -} - -var big = []byte{ - 1, - 2, 3, - 4, 5, 6, 7, - 8, 9, 10, 11, 12, 13, 14, 15, - 16, - 17, 18, - 19, 20, 21, 22, - 23, 24, 25, 26, 27, 28, 29, 30, - - 31, 32, 33, 34, - 35, 36, 37, 38, 39, 40, 41, 42, - 43, 44, 45, 46, 47, 48, 49, 50, - 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, - - 67, 68, 69, 70, -} - -var little = []byte{ - 1, - 3, 2, - 7, 6, 5, 4, - 15, 14, 13, 12, 11, 10, 9, 8, - 16, - 18, 17, - 22, 21, 20, 19, - 30, 29, 28, 27, 26, 25, 24, 23, - - 34, 33, 32, 31, - 42, 41, 40, 39, 38, 37, 36, 35, - 46, 45, 44, 43, 50, 49, 48, 47, - 58, 57, 56, 55, 54, 53, 52, 51, 66, 65, 64, 63, 62, 61, 60, 59, - - 67, 68, 69, 70, -} - -var src = []byte{1, 2, 3, 4, 5, 6, 7, 8} -var res = []int32{0x01020304, 0x05060708} - -func checkResult(t *testing.T, dir string, order ByteOrder, err error, have, want interface{}) { - if err != nil { - t.Errorf("%v %v: %v", dir, order, err) - return - } - if !reflect.DeepEqual(have, want) { - t.Errorf("%v %v:\n\thave %+v\n\twant %+v", dir, order, have, want) - } -} - -func testRead(t *testing.T, order ByteOrder, b []byte, s1 interface{}) { - var s2 Struct - err := Read(bytes.NewReader(b), order, &s2) - checkResult(t, "Read", order, err, s2, s1) -} - -func testWrite(t *testing.T, order ByteOrder, b []byte, s1 interface{}) { - buf := new(bytes.Buffer) - err := Write(buf, order, s1) - checkResult(t, "Write", order, err, buf.Bytes(), b) -} - -func TestLittleEndianRead(t *testing.T) { testRead(t, LittleEndian, little, s) } -func TestLittleEndianWrite(t *testing.T) { testWrite(t, LittleEndian, little, s) } -func TestLittleEndianPtrWrite(t *testing.T) { testWrite(t, LittleEndian, little, &s) } - -func TestBigEndianRead(t *testing.T) { testRead(t, BigEndian, big, s) } -func TestBigEndianWrite(t *testing.T) { testWrite(t, BigEndian, big, s) } -func TestBigEndianPtrWrite(t *testing.T) { testWrite(t, BigEndian, big, &s) } - -func TestReadSlice(t *testing.T) { - slice := make([]int32, 2) - err := Read(bytes.NewReader(src), BigEndian, slice) - checkResult(t, "ReadSlice", BigEndian, err, slice, res) -} - -func TestWriteSlice(t *testing.T) { - buf := new(bytes.Buffer) - err := Write(buf, BigEndian, res) - checkResult(t, "WriteSlice", BigEndian, err, buf.Bytes(), src) -} - -// Addresses of arrays are easier to manipulate with reflection than are slices. -var intArrays = []interface{}{ - &[100]int8{}, - &[100]int16{}, - &[100]int32{}, - &[100]int64{}, - &[100]uint8{}, - &[100]uint16{}, - &[100]uint32{}, - &[100]uint64{}, -} - -func TestSliceRoundTrip(t *testing.T) { - buf := new(bytes.Buffer) - for _, array := range intArrays { - src := reflect.ValueOf(array).Elem() - unsigned := false - switch src.Index(0).Kind() { - case reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64: - unsigned = true - } - for i := 0; i < src.Len(); i++ { - if unsigned { - src.Index(i).SetUint(uint64(i * 0x07654321)) - } else { - src.Index(i).SetInt(int64(i * 0x07654321)) - } - } - buf.Reset() - srcSlice := src.Slice(0, src.Len()) - err := Write(buf, BigEndian, srcSlice.Interface()) - if err != nil { - t.Fatal(err) - } - dst := reflect.New(src.Type()).Elem() - dstSlice := dst.Slice(0, dst.Len()) - err = Read(buf, BigEndian, dstSlice.Interface()) - if err != nil { - t.Fatal(err) - } - if !reflect.DeepEqual(src.Interface(), dst.Interface()) { - t.Fatal(src) - } - } -} - -func TestWriteT(t *testing.T) { - buf := new(bytes.Buffer) - ts := T{} - if err := Write(buf, BigEndian, ts); err == nil { - t.Errorf("WriteT: have err == nil, want non-nil") - } - - tv := reflect.Indirect(reflect.ValueOf(ts)) - for i, n := 0, tv.NumField(); i < n; i++ { - typ := tv.Field(i).Type().String() - if typ == "[4]int" { - typ = "int" // the problem is int, not the [4] - } - if err := Write(buf, BigEndian, tv.Field(i).Interface()); err == nil { - t.Errorf("WriteT.%v: have err == nil, want non-nil", tv.Field(i).Type()) - } else if !strings.Contains(err.Error(), typ) { - t.Errorf("WriteT: have err == %q, want it to mention %s", err, typ) - } - } -} - -type BlankFields struct { - A uint32 - _ int32 - B float64 - _ [4]int16 - C byte - _ [7]byte - _ struct { - f [8]float32 - } -} - -type BlankFieldsProbe struct { - A uint32 - P0 int32 - B float64 - P1 [4]int16 - C byte - P2 [7]byte - P3 struct { - F [8]float32 - } -} - -func TestBlankFields(t *testing.T) { - buf := new(bytes.Buffer) - b1 := BlankFields{A: 1234567890, B: 2.718281828, C: 42} - if err := Write(buf, LittleEndian, &b1); err != nil { - t.Error(err) - } - - // zero values must have been written for blank fields - var p BlankFieldsProbe - if err := Read(buf, LittleEndian, &p); err != nil { - t.Error(err) - } - - // quick test: only check first value of slices - if p.P0 != 0 || p.P1[0] != 0 || p.P2[0] != 0 || p.P3.F[0] != 0 { - t.Errorf("non-zero values for originally blank fields: %#v", p) - } - - // write p and see if we can probe only some fields - if err := Write(buf, LittleEndian, &p); err != nil { - t.Error(err) - } - - // read should ignore blank fields in b2 - var b2 BlankFields - if err := Read(buf, LittleEndian, &b2); err != nil { - t.Error(err) - } - if b1.A != b2.A || b1.B != b2.B || b1.C != b2.C { - t.Errorf("%#v != %#v", b1, b2) - } -} - -// An attempt to read into a struct with an unexported field will -// panic. This is probably not the best choice, but at this point -// anything else would be an API change. - -type Unexported struct { - a int32 -} - -func TestUnexportedRead(t *testing.T) { - var buf bytes.Buffer - u1 := Unexported{a: 1} - if err := Write(&buf, LittleEndian, &u1); err != nil { - t.Fatal(err) - } - - defer func() { - if recover() == nil { - t.Fatal("did not panic") - } - }() - var u2 Unexported - Read(&buf, LittleEndian, &u2) -} - -type byteSliceReader struct { - remain []byte -} - -func (br *byteSliceReader) Read(p []byte) (int, error) { - n := copy(p, br.remain) - br.remain = br.remain[n:] - return n, nil -} - -func BenchmarkReadSlice1000Int32s(b *testing.B) { - bsr := &byteSliceReader{} - slice := make([]int32, 1000) - buf := make([]byte, len(slice)*4) - b.SetBytes(int64(len(buf))) - b.ResetTimer() - for i := 0; i < b.N; i++ { - bsr.remain = buf - Read(bsr, BigEndian, slice) - } -} - -func BenchmarkReadStruct(b *testing.B) { - bsr := &byteSliceReader{} - var buf bytes.Buffer - Write(&buf, BigEndian, &s) - n, _ := dataSize(reflect.ValueOf(s)) - b.SetBytes(int64(n)) - t := s - b.ResetTimer() - for i := 0; i < b.N; i++ { - bsr.remain = buf.Bytes() - Read(bsr, BigEndian, &t) - } - b.StopTimer() - if !reflect.DeepEqual(s, t) { - b.Fatal("no match") - } -} - -func BenchmarkReadInts(b *testing.B) { - var ls Struct - bsr := &byteSliceReader{} - var r io.Reader = bsr - b.SetBytes(2 * (1 + 2 + 4 + 8)) - b.ResetTimer() - for i := 0; i < b.N; i++ { - bsr.remain = big - Read(r, BigEndian, &ls.Int8) - Read(r, BigEndian, &ls.Int16) - Read(r, BigEndian, &ls.Int32) - Read(r, BigEndian, &ls.Int64) - Read(r, BigEndian, &ls.Uint8) - Read(r, BigEndian, &ls.Uint16) - Read(r, BigEndian, &ls.Uint32) - Read(r, BigEndian, &ls.Uint64) - } - - want := s - want.Float32 = 0 - want.Float64 = 0 - want.Complex64 = 0 - want.Complex128 = 0 - for i := range want.Array { - want.Array[i] = 0 - } - b.StopTimer() - if !reflect.DeepEqual(ls, want) { - panic("no match") - } -} - -func BenchmarkWriteInts(b *testing.B) { - buf := new(bytes.Buffer) - var w io.Writer = buf - b.SetBytes(2 * (1 + 2 + 4 + 8)) - b.ResetTimer() - for i := 0; i < b.N; i++ { - buf.Reset() - Write(w, BigEndian, s.Int8) - Write(w, BigEndian, s.Int16) - Write(w, BigEndian, s.Int32) - Write(w, BigEndian, s.Int64) - Write(w, BigEndian, s.Uint8) - Write(w, BigEndian, s.Uint16) - Write(w, BigEndian, s.Uint32) - Write(w, BigEndian, s.Uint64) - } - b.StopTimer() - if !bytes.Equal(buf.Bytes(), big[:30]) { - b.Fatalf("first half doesn't match: %x %x", buf.Bytes(), big[:30]) - } -} - -func BenchmarkWriteSlice1000Int32s(b *testing.B) { - slice := make([]int32, 1000) - buf := new(bytes.Buffer) - var w io.Writer = buf - b.SetBytes(4 * 1000) - b.ResetTimer() - for i := 0; i < b.N; i++ { - buf.Reset() - Write(w, BigEndian, slice) - } - b.StopTimer() -} diff --git a/src/pkg/encoding/binary/example_test.go b/src/pkg/encoding/binary/example_test.go deleted file mode 100644 index 067cf553b..000000000 --- a/src/pkg/encoding/binary/example_test.go +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package binary_test - -import ( - "bytes" - "encoding/binary" - "fmt" - "math" -) - -func ExampleWrite() { - buf := new(bytes.Buffer) - var pi float64 = math.Pi - err := binary.Write(buf, binary.LittleEndian, pi) - if err != nil { - fmt.Println("binary.Write failed:", err) - } - fmt.Printf("% x", buf.Bytes()) - // Output: 18 2d 44 54 fb 21 09 40 -} - -func ExampleWrite_multi() { - buf := new(bytes.Buffer) - var data = []interface{}{ - uint16(61374), - int8(-54), - uint8(254), - } - for _, v := range data { - err := binary.Write(buf, binary.LittleEndian, v) - if err != nil { - fmt.Println("binary.Write failed:", err) - } - } - fmt.Printf("%x", buf.Bytes()) - // Output: beefcafe -} - -func ExampleRead() { - var pi float64 - b := []byte{0x18, 0x2d, 0x44, 0x54, 0xfb, 0x21, 0x09, 0x40} - buf := bytes.NewReader(b) - err := binary.Read(buf, binary.LittleEndian, &pi) - if err != nil { - fmt.Println("binary.Read failed:", err) - } - fmt.Print(pi) - // Output: 3.141592653589793 -} diff --git a/src/pkg/encoding/binary/varint.go b/src/pkg/encoding/binary/varint.go deleted file mode 100644 index 3a2dfa3c7..000000000 --- a/src/pkg/encoding/binary/varint.go +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package binary - -// This file implements "varint" encoding of 64-bit integers. -// The encoding is: -// - unsigned integers are serialized 7 bits at a time, starting with the -// least significant bits -// - the most significant bit (msb) in each output byte indicates if there -// is a continuation byte (msb = 1) -// - signed integers are mapped to unsigned integers using "zig-zag" -// encoding: Positive values x are written as 2*x + 0, negative values -// are written as 2*(^x) + 1; that is, negative numbers are complemented -// and whether to complement is encoded in bit 0. -// -// Design note: -// At most 10 bytes are needed for 64-bit values. The encoding could -// be more dense: a full 64-bit value needs an extra byte just to hold bit 63. -// Instead, the msb of the previous byte could be used to hold bit 63 since we -// know there can't be more than 64 bits. This is a trivial improvement and -// would reduce the maximum encoding length to 9 bytes. However, it breaks the -// invariant that the msb is always the "continuation bit" and thus makes the -// format incompatible with a varint encoding for larger numbers (say 128-bit). - -import ( - "errors" - "io" -) - -// MaxVarintLenN is the maximum length of a varint-encoded N-bit integer. -const ( - MaxVarintLen16 = 3 - MaxVarintLen32 = 5 - MaxVarintLen64 = 10 -) - -// PutUvarint encodes a uint64 into buf and returns the number of bytes written. -// If the buffer is too small, PutUvarint will panic. -func PutUvarint(buf []byte, x uint64) int { - i := 0 - for x >= 0x80 { - buf[i] = byte(x) | 0x80 - x >>= 7 - i++ - } - buf[i] = byte(x) - return i + 1 -} - -// Uvarint decodes a uint64 from buf and returns that value and the -// number of bytes read (> 0). If an error occurred, the value is 0 -// and the number of bytes n is <= 0 meaning: -// -// n == 0: buf too small -// n < 0: value larger than 64 bits (overflow) -// and -n is the number of bytes read -// -func Uvarint(buf []byte) (uint64, int) { - var x uint64 - var s uint - for i, b := range buf { - if b < 0x80 { - if i > 9 || i == 9 && b > 1 { - return 0, -(i + 1) // overflow - } - return x | uint64(b)< 0). If an error occurred, the value is 0 -// and the number of bytes n is <= 0 with the following meaning: -// -// n == 0: buf too small -// n < 0: value larger than 64 bits (overflow) -// and -n is the number of bytes read -// -func Varint(buf []byte) (int64, int) { - ux, n := Uvarint(buf) // ok to continue in presence of error - x := int64(ux >> 1) - if ux&1 != 0 { - x = ^x - } - return x, n -} - -var overflow = errors.New("binary: varint overflows a 64-bit integer") - -// ReadUvarint reads an encoded unsigned integer from r and returns it as a uint64. -func ReadUvarint(r io.ByteReader) (uint64, error) { - var x uint64 - var s uint - for i := 0; ; i++ { - b, err := r.ReadByte() - if err != nil { - return x, err - } - if b < 0x80 { - if i > 9 || i == 9 && b > 1 { - return x, overflow - } - return x | uint64(b)<> 1) - if ux&1 != 0 { - x = ^x - } - return x, err -} diff --git a/src/pkg/encoding/binary/varint_test.go b/src/pkg/encoding/binary/varint_test.go deleted file mode 100644 index ca411ecbd..000000000 --- a/src/pkg/encoding/binary/varint_test.go +++ /dev/null @@ -1,168 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package binary - -import ( - "bytes" - "io" - "testing" -) - -func testConstant(t *testing.T, w uint, max int) { - buf := make([]byte, MaxVarintLen64) - n := PutUvarint(buf, 1< 0 { - if len(record) != r.FieldsPerRecord { - r.column = 0 // report at start of record - return record, r.error(ErrFieldCount) - } - } else if r.FieldsPerRecord == 0 { - r.FieldsPerRecord = len(record) - } - return record, nil -} - -// ReadAll reads all the remaining records from r. -// Each record is a slice of fields. -// A successful call returns err == nil, not err == EOF. Because ReadAll is -// defined to read until EOF, it does not treat end of file as an error to be -// reported. -func (r *Reader) ReadAll() (records [][]string, err error) { - for { - record, err := r.Read() - if err == io.EOF { - return records, nil - } - if err != nil { - return nil, err - } - records = append(records, record) - } -} - -// readRune reads one rune from r, folding \r\n to \n and keeping track -// of how far into the line we have read. r.column will point to the start -// of this rune, not the end of this rune. -func (r *Reader) readRune() (rune, error) { - r1, _, err := r.r.ReadRune() - - // Handle \r\n here. We make the simplifying assumption that - // anytime \r is followed by \n that it can be folded to \n. - // We will not detect files which contain both \r\n and bare \n. - if r1 == '\r' { - r1, _, err = r.r.ReadRune() - if err == nil { - if r1 != '\n' { - r.r.UnreadRune() - r1 = '\r' - } - } - } - r.column++ - return r1, err -} - -// skip reads runes up to and including the rune delim or until error. -func (r *Reader) skip(delim rune) error { - for { - r1, err := r.readRune() - if err != nil { - return err - } - if r1 == delim { - return nil - } - } -} - -// parseRecord reads and parses a single csv record from r. -func (r *Reader) parseRecord() (fields []string, err error) { - // Each record starts on a new line. We increment our line - // number (lines start at 1, not 0) and set column to -1 - // so as we increment in readRune it points to the character we read. - r.line++ - r.column = -1 - - // Peek at the first rune. If it is an error we are done. - // If we are support comments and it is the comment character - // then skip to the end of line. - - r1, _, err := r.r.ReadRune() - if err != nil { - return nil, err - } - - if r.Comment != 0 && r1 == r.Comment { - return nil, r.skip('\n') - } - r.r.UnreadRune() - - // At this point we have at least one field. - for { - haveField, delim, err := r.parseField() - if haveField { - fields = append(fields, r.field.String()) - } - if delim == '\n' || err == io.EOF { - return fields, err - } else if err != nil { - return nil, err - } - } -} - -// parseField parses the next field in the record. The read field is -// located in r.field. Delim is the first character not part of the field -// (r.Comma or '\n'). -func (r *Reader) parseField() (haveField bool, delim rune, err error) { - r.field.Reset() - - r1, err := r.readRune() - for err == nil && r.TrimLeadingSpace && r1 != '\n' && unicode.IsSpace(r1) { - r1, err = r.readRune() - } - - if err == io.EOF && r.column != 0 { - return true, 0, err - } - if err != nil { - return false, 0, err - } - - switch r1 { - case r.Comma: - // will check below - - case '\n': - // We are a trailing empty field or a blank line - if r.column == 0 { - return false, r1, nil - } - return true, r1, nil - - case '"': - // quoted field - Quoted: - for { - r1, err = r.readRune() - if err != nil { - if err == io.EOF { - if r.LazyQuotes { - return true, 0, err - } - return false, 0, r.error(ErrQuote) - } - return false, 0, err - } - switch r1 { - case '"': - r1, err = r.readRune() - if err != nil || r1 == r.Comma { - break Quoted - } - if r1 == '\n' { - return true, r1, nil - } - if r1 != '"' { - if !r.LazyQuotes { - r.column-- - return false, 0, r.error(ErrQuote) - } - // accept the bare quote - r.field.WriteRune('"') - } - case '\n': - r.line++ - r.column = -1 - } - r.field.WriteRune(r1) - } - - default: - // unquoted field - for { - r.field.WriteRune(r1) - r1, err = r.readRune() - if err != nil || r1 == r.Comma { - break - } - if r1 == '\n' { - return true, r1, nil - } - if !r.LazyQuotes && r1 == '"' { - return false, 0, r.error(ErrBareQuote) - } - } - } - - if err != nil { - if err == io.EOF { - return true, 0, err - } - return false, 0, err - } - - return true, r1, nil -} diff --git a/src/pkg/encoding/csv/reader_test.go b/src/pkg/encoding/csv/reader_test.go deleted file mode 100644 index 123df06bc..000000000 --- a/src/pkg/encoding/csv/reader_test.go +++ /dev/null @@ -1,284 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package csv - -import ( - "reflect" - "strings" - "testing" -) - -var readTests = []struct { - Name string - Input string - Output [][]string - UseFieldsPerRecord bool // false (default) means FieldsPerRecord is -1 - - // These fields are copied into the Reader - Comma rune - Comment rune - FieldsPerRecord int - LazyQuotes bool - TrailingComma bool - TrimLeadingSpace bool - - Error string - Line int // Expected error line if != 0 - Column int // Expected error column if line != 0 -}{ - { - Name: "Simple", - Input: "a,b,c\n", - Output: [][]string{{"a", "b", "c"}}, - }, - { - Name: "CRLF", - Input: "a,b\r\nc,d\r\n", - Output: [][]string{{"a", "b"}, {"c", "d"}}, - }, - { - Name: "BareCR", - Input: "a,b\rc,d\r\n", - Output: [][]string{{"a", "b\rc", "d"}}, - }, - { - Name: "RFC4180test", - UseFieldsPerRecord: true, - Input: `#field1,field2,field3 -"aaa","bb -b","ccc" -"a,a","b""bb","ccc" -zzz,yyy,xxx -`, - Output: [][]string{ - {"#field1", "field2", "field3"}, - {"aaa", "bb\nb", "ccc"}, - {"a,a", `b"bb`, "ccc"}, - {"zzz", "yyy", "xxx"}, - }, - }, - { - Name: "NoEOLTest", - Input: "a,b,c", - Output: [][]string{{"a", "b", "c"}}, - }, - { - Name: "Semicolon", - Comma: ';', - Input: "a;b;c\n", - Output: [][]string{{"a", "b", "c"}}, - }, - { - Name: "MultiLine", - Input: `"two -line","one line","three -line -field"`, - Output: [][]string{{"two\nline", "one line", "three\nline\nfield"}}, - }, - { - Name: "BlankLine", - Input: "a,b,c\n\nd,e,f\n\n", - Output: [][]string{ - {"a", "b", "c"}, - {"d", "e", "f"}, - }, - }, - { - Name: "TrimSpace", - Input: " a, b, c\n", - TrimLeadingSpace: true, - Output: [][]string{{"a", "b", "c"}}, - }, - { - Name: "LeadingSpace", - Input: " a, b, c\n", - Output: [][]string{{" a", " b", " c"}}, - }, - { - Name: "Comment", - Comment: '#', - Input: "#1,2,3\na,b,c\n#comment", - Output: [][]string{{"a", "b", "c"}}, - }, - { - Name: "NoComment", - Input: "#1,2,3\na,b,c", - Output: [][]string{{"#1", "2", "3"}, {"a", "b", "c"}}, - }, - { - Name: "LazyQuotes", - LazyQuotes: true, - Input: `a "word","1"2",a","b`, - Output: [][]string{{`a "word"`, `1"2`, `a"`, `b`}}, - }, - { - Name: "BareQuotes", - LazyQuotes: true, - Input: `a "word","1"2",a"`, - Output: [][]string{{`a "word"`, `1"2`, `a"`}}, - }, - { - Name: "BareDoubleQuotes", - LazyQuotes: true, - Input: `a""b,c`, - Output: [][]string{{`a""b`, `c`}}, - }, - { - Name: "BadDoubleQuotes", - Input: `a""b,c`, - Error: `bare " in non-quoted-field`, Line: 1, Column: 1, - }, - { - Name: "TrimQuote", - Input: ` "a"," b",c`, - TrimLeadingSpace: true, - Output: [][]string{{"a", " b", "c"}}, - }, - { - Name: "BadBareQuote", - Input: `a "word","b"`, - Error: `bare " in non-quoted-field`, Line: 1, Column: 2, - }, - { - Name: "BadTrailingQuote", - Input: `"a word",b"`, - Error: `bare " in non-quoted-field`, Line: 1, Column: 10, - }, - { - Name: "ExtraneousQuote", - Input: `"a "word","b"`, - Error: `extraneous " in field`, Line: 1, Column: 3, - }, - { - Name: "BadFieldCount", - UseFieldsPerRecord: true, - Input: "a,b,c\nd,e", - Error: "wrong number of fields", Line: 2, - }, - { - Name: "BadFieldCount1", - UseFieldsPerRecord: true, - FieldsPerRecord: 2, - Input: `a,b,c`, - Error: "wrong number of fields", Line: 1, - }, - { - Name: "FieldCount", - Input: "a,b,c\nd,e", - Output: [][]string{{"a", "b", "c"}, {"d", "e"}}, - }, - { - Name: "TrailingCommaEOF", - Input: "a,b,c,", - Output: [][]string{{"a", "b", "c", ""}}, - }, - { - Name: "TrailingCommaEOL", - Input: "a,b,c,\n", - Output: [][]string{{"a", "b", "c", ""}}, - }, - { - Name: "TrailingCommaSpaceEOF", - TrimLeadingSpace: true, - Input: "a,b,c, ", - Output: [][]string{{"a", "b", "c", ""}}, - }, - { - Name: "TrailingCommaSpaceEOL", - TrimLeadingSpace: true, - Input: "a,b,c, \n", - Output: [][]string{{"a", "b", "c", ""}}, - }, - { - Name: "TrailingCommaLine3", - TrimLeadingSpace: true, - Input: "a,b,c\nd,e,f\ng,hi,", - Output: [][]string{{"a", "b", "c"}, {"d", "e", "f"}, {"g", "hi", ""}}, - }, - { - Name: "NotTrailingComma3", - Input: "a,b,c, \n", - Output: [][]string{{"a", "b", "c", " "}}, - }, - { - Name: "CommaFieldTest", - TrailingComma: true, - Input: `x,y,z,w -x,y,z, -x,y,, -x,,, -,,, -"x","y","z","w" -"x","y","z","" -"x","y","","" -"x","","","" -"","","","" -`, - Output: [][]string{ - {"x", "y", "z", "w"}, - {"x", "y", "z", ""}, - {"x", "y", "", ""}, - {"x", "", "", ""}, - {"", "", "", ""}, - {"x", "y", "z", "w"}, - {"x", "y", "z", ""}, - {"x", "y", "", ""}, - {"x", "", "", ""}, - {"", "", "", ""}, - }, - }, - { - Name: "TrailingCommaIneffective1", - TrailingComma: true, - TrimLeadingSpace: true, - Input: "a,b,\nc,d,e", - Output: [][]string{ - {"a", "b", ""}, - {"c", "d", "e"}, - }, - }, - { - Name: "TrailingCommaIneffective2", - TrailingComma: false, - TrimLeadingSpace: true, - Input: "a,b,\nc,d,e", - Output: [][]string{ - {"a", "b", ""}, - {"c", "d", "e"}, - }, - }, -} - -func TestRead(t *testing.T) { - for _, tt := range readTests { - r := NewReader(strings.NewReader(tt.Input)) - r.Comment = tt.Comment - if tt.UseFieldsPerRecord { - r.FieldsPerRecord = tt.FieldsPerRecord - } else { - r.FieldsPerRecord = -1 - } - r.LazyQuotes = tt.LazyQuotes - r.TrailingComma = tt.TrailingComma - r.TrimLeadingSpace = tt.TrimLeadingSpace - if tt.Comma != 0 { - r.Comma = tt.Comma - } - out, err := r.ReadAll() - perr, _ := err.(*ParseError) - if tt.Error != "" { - if err == nil || !strings.Contains(err.Error(), tt.Error) { - t.Errorf("%s: error %v, want error %q", tt.Name, err, tt.Error) - } else if tt.Line != 0 && (tt.Line != perr.Line || tt.Column != perr.Column) { - t.Errorf("%s: error at %d:%d expected %d:%d", tt.Name, perr.Line, perr.Column, tt.Line, tt.Column) - } - } else if err != nil { - t.Errorf("%s: unexpected error %v", tt.Name, err) - } else if !reflect.DeepEqual(out, tt.Output) { - t.Errorf("%s: out=%q want %q", tt.Name, out, tt.Output) - } - } -} diff --git a/src/pkg/encoding/csv/writer.go b/src/pkg/encoding/csv/writer.go deleted file mode 100644 index 1faecb664..000000000 --- a/src/pkg/encoding/csv/writer.go +++ /dev/null @@ -1,127 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package csv - -import ( - "bufio" - "io" - "strings" - "unicode" - "unicode/utf8" -) - -// A Writer writes records to a CSV encoded file. -// -// As returned by NewWriter, a Writer writes records terminated by a -// newline and uses ',' as the field delimiter. The exported fields can be -// changed to customize the details before the first call to Write or WriteAll. -// -// Comma is the field delimiter. -// -// If UseCRLF is true, the Writer ends each record with \r\n instead of \n. -type Writer struct { - Comma rune // Field delimiter (set to ',' by NewWriter) - UseCRLF bool // True to use \r\n as the line terminator - w *bufio.Writer -} - -// NewWriter returns a new Writer that writes to w. -func NewWriter(w io.Writer) *Writer { - return &Writer{ - Comma: ',', - w: bufio.NewWriter(w), - } -} - -// Writer writes a single CSV record to w along with any necessary quoting. -// A record is a slice of strings with each string being one field. -func (w *Writer) Write(record []string) (err error) { - for n, field := range record { - if n > 0 { - if _, err = w.w.WriteRune(w.Comma); err != nil { - return - } - } - - // If we don't have to have a quoted field then just - // write out the field and continue to the next field. - if !w.fieldNeedsQuotes(field) { - if _, err = w.w.WriteString(field); err != nil { - return - } - continue - } - if err = w.w.WriteByte('"'); err != nil { - return - } - - for _, r1 := range field { - switch r1 { - case '"': - _, err = w.w.WriteString(`""`) - case '\r': - if !w.UseCRLF { - err = w.w.WriteByte('\r') - } - case '\n': - if w.UseCRLF { - _, err = w.w.WriteString("\r\n") - } else { - err = w.w.WriteByte('\n') - } - default: - _, err = w.w.WriteRune(r1) - } - if err != nil { - return - } - } - - if err = w.w.WriteByte('"'); err != nil { - return - } - } - if w.UseCRLF { - _, err = w.w.WriteString("\r\n") - } else { - err = w.w.WriteByte('\n') - } - return -} - -// Flush writes any buffered data to the underlying io.Writer. -// To check if an error occurred during the Flush, call Error. -func (w *Writer) Flush() { - w.w.Flush() -} - -// Error reports any error that has occurred during a previous Write or Flush. -func (w *Writer) Error() error { - _, err := w.w.Write(nil) - return err -} - -// WriteAll writes multiple CSV records to w using Write and then calls Flush. -func (w *Writer) WriteAll(records [][]string) (err error) { - for _, record := range records { - err = w.Write(record) - if err != nil { - return err - } - } - return w.w.Flush() -} - -// fieldNeedsQuotes returns true if our field must be enclosed in quotes. -// Empty fields, files with a Comma, fields with a quote or newline, and -// fields which start with a space must be enclosed in quotes. -func (w *Writer) fieldNeedsQuotes(field string) bool { - if len(field) == 0 || strings.IndexRune(field, w.Comma) >= 0 || strings.IndexAny(field, "\"\r\n") >= 0 { - return true - } - - r1, _ := utf8.DecodeRuneInString(field) - return unicode.IsSpace(r1) -} diff --git a/src/pkg/encoding/csv/writer_test.go b/src/pkg/encoding/csv/writer_test.go deleted file mode 100644 index 22b740c07..000000000 --- a/src/pkg/encoding/csv/writer_test.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package csv - -import ( - "bytes" - "errors" - "testing" -) - -var writeTests = []struct { - Input [][]string - Output string - UseCRLF bool -}{ - {Input: [][]string{{"abc"}}, Output: "abc\n"}, - {Input: [][]string{{"abc"}}, Output: "abc\r\n", UseCRLF: true}, - {Input: [][]string{{`"abc"`}}, Output: `"""abc"""` + "\n"}, - {Input: [][]string{{`a"b`}}, Output: `"a""b"` + "\n"}, - {Input: [][]string{{`"a"b"`}}, Output: `"""a""b"""` + "\n"}, - {Input: [][]string{{" abc"}}, Output: `" abc"` + "\n"}, - {Input: [][]string{{"abc,def"}}, Output: `"abc,def"` + "\n"}, - {Input: [][]string{{"abc", "def"}}, Output: "abc,def\n"}, - {Input: [][]string{{"abc"}, {"def"}}, Output: "abc\ndef\n"}, - {Input: [][]string{{"abc\ndef"}}, Output: "\"abc\ndef\"\n"}, - {Input: [][]string{{"abc\ndef"}}, Output: "\"abc\r\ndef\"\r\n", UseCRLF: true}, - {Input: [][]string{{"abc\rdef"}}, Output: "\"abcdef\"\r\n", UseCRLF: true}, - {Input: [][]string{{"abc\rdef"}}, Output: "\"abc\rdef\"\n", UseCRLF: false}, -} - -func TestWrite(t *testing.T) { - for n, tt := range writeTests { - b := &bytes.Buffer{} - f := NewWriter(b) - f.UseCRLF = tt.UseCRLF - err := f.WriteAll(tt.Input) - if err != nil { - t.Errorf("Unexpected error: %s\n", err) - } - out := b.String() - if out != tt.Output { - t.Errorf("#%d: out=%q want %q", n, out, tt.Output) - } - } -} - -type errorWriter struct{} - -func (e errorWriter) Write(b []byte) (int, error) { - return 0, errors.New("Test") -} - -func TestError(t *testing.T) { - b := &bytes.Buffer{} - f := NewWriter(b) - f.Write([]string{"abc"}) - f.Flush() - err := f.Error() - - if err != nil { - t.Errorf("Unexpected error: %s\n", err) - } - - f = NewWriter(errorWriter{}) - f.Write([]string{"abc"}) - f.Flush() - err = f.Error() - - if err == nil { - t.Error("Error should not be nil") - } -} diff --git a/src/pkg/encoding/encoding.go b/src/pkg/encoding/encoding.go deleted file mode 100644 index 6d218071b..000000000 --- a/src/pkg/encoding/encoding.go +++ /dev/null @@ -1,48 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package encoding defines interfaces shared by other packages that -// convert data to and from byte-level and textual representations. -// Packages that check for these interfaces include encoding/gob, -// encoding/json, and encoding/xml. As a result, implementing an -// interface once can make a type useful in multiple encodings. -// Standard types that implement these interfaces include time.Time and net.IP. -// The interfaces come in pairs that produce and consume encoded data. -package encoding - -// BinaryMarshaler is the interface implemented by an object that can -// marshal itself into a binary form. -// -// MarshalBinary encodes the receiver into a binary form and returns the result. -type BinaryMarshaler interface { - MarshalBinary() (data []byte, err error) -} - -// BinaryUnmarshaler is the interface implemented by an object that can -// unmarshal a binary representation of itself. -// -// UnmarshalBinary must be able to decode the form generated by MarshalBinary. -// UnmarshalBinary must copy the data if it wishes to retain the data -// after returning. -type BinaryUnmarshaler interface { - UnmarshalBinary(data []byte) error -} - -// TextMarshaler is the interface implemented by an object that can -// marshal itself into a textual form. -// -// MarshalText encodes the receiver into UTF-8-encoded text and returns the result. -type TextMarshaler interface { - MarshalText() (text []byte, err error) -} - -// TextUnmarshaler is the interface implemented by an object that can -// unmarshal a textual representation of itself. -// -// UnmarshalText must be able to decode the form generated by MarshalText. -// UnmarshalText must copy the text if it wishes to retain the text -// after returning. -type TextUnmarshaler interface { - UnmarshalText(text []byte) error -} diff --git a/src/pkg/encoding/gob/codec_test.go b/src/pkg/encoding/gob/codec_test.go deleted file mode 100644 index 4f17a2893..000000000 --- a/src/pkg/encoding/gob/codec_test.go +++ /dev/null @@ -1,1469 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gob - -import ( - "bytes" - "errors" - "flag" - "math" - "math/rand" - "reflect" - "strings" - "testing" - "time" -) - -var doFuzzTests = flag.Bool("gob.fuzz", false, "run the fuzz tests, which are large and very slow") - -// Guarantee encoding format by comparing some encodings to hand-written values -type EncodeT struct { - x uint64 - b []byte -} - -var encodeT = []EncodeT{ - {0x00, []byte{0x00}}, - {0x0F, []byte{0x0F}}, - {0xFF, []byte{0xFF, 0xFF}}, - {0xFFFF, []byte{0xFE, 0xFF, 0xFF}}, - {0xFFFFFF, []byte{0xFD, 0xFF, 0xFF, 0xFF}}, - {0xFFFFFFFF, []byte{0xFC, 0xFF, 0xFF, 0xFF, 0xFF}}, - {0xFFFFFFFFFF, []byte{0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}, - {0xFFFFFFFFFFFF, []byte{0xFA, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}, - {0xFFFFFFFFFFFFFF, []byte{0xF9, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}, - {0xFFFFFFFFFFFFFFFF, []byte{0xF8, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}, - {0x1111, []byte{0xFE, 0x11, 0x11}}, - {0x1111111111111111, []byte{0xF8, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}}, - {0x8888888888888888, []byte{0xF8, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x88}}, - {1 << 63, []byte{0xF8, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}}, -} - -// testError is meant to be used as a deferred function to turn a panic(gobError) into a -// plain test.Error call. -func testError(t *testing.T) { - if e := recover(); e != nil { - t.Error(e.(gobError).err) // Will re-panic if not one of our errors, such as a runtime error. - } - return -} - -// Test basic encode/decode routines for unsigned integers -func TestUintCodec(t *testing.T) { - defer testError(t) - b := new(bytes.Buffer) - encState := newEncoderState(b) - for _, tt := range encodeT { - b.Reset() - encState.encodeUint(tt.x) - if !bytes.Equal(tt.b, b.Bytes()) { - t.Errorf("encodeUint: %#x encode: expected % x got % x", tt.x, tt.b, b.Bytes()) - } - } - decState := newDecodeState(b) - for u := uint64(0); ; u = (u + 1) * 7 { - b.Reset() - encState.encodeUint(u) - v := decState.decodeUint() - if u != v { - t.Errorf("Encode/Decode: sent %#x received %#x", u, v) - } - if u&(1<<63) != 0 { - break - } - } -} - -func verifyInt(i int64, t *testing.T) { - defer testError(t) - var b = new(bytes.Buffer) - encState := newEncoderState(b) - encState.encodeInt(i) - decState := newDecodeState(b) - decState.buf = make([]byte, 8) - j := decState.decodeInt() - if i != j { - t.Errorf("Encode/Decode: sent %#x received %#x", uint64(i), uint64(j)) - } -} - -// Test basic encode/decode routines for signed integers -func TestIntCodec(t *testing.T) { - for u := uint64(0); ; u = (u + 1) * 7 { - // Do positive and negative values - i := int64(u) - verifyInt(i, t) - verifyInt(-i, t) - verifyInt(^i, t) - if u&(1<<63) != 0 { - break - } - } - verifyInt(-1<<63, t) // a tricky case -} - -// The result of encoding a true boolean with field number 7 -var boolResult = []byte{0x07, 0x01} - -// The result of encoding a number 17 with field number 7 -var signedResult = []byte{0x07, 2 * 17} -var unsignedResult = []byte{0x07, 17} -var floatResult = []byte{0x07, 0xFE, 0x31, 0x40} - -// The result of encoding a number 17+19i with field number 7 -var complexResult = []byte{0x07, 0xFE, 0x31, 0x40, 0xFE, 0x33, 0x40} - -// The result of encoding "hello" with field number 7 -var bytesResult = []byte{0x07, 0x05, 'h', 'e', 'l', 'l', 'o'} - -func newDecodeState(buf *bytes.Buffer) *decoderState { - d := new(decoderState) - d.b = buf - d.buf = make([]byte, uint64Size) - return d -} - -func newEncoderState(b *bytes.Buffer) *encoderState { - b.Reset() - state := &encoderState{enc: nil, b: b} - state.fieldnum = -1 - return state -} - -// Test instruction execution for encoding. -// Do not run the machine yet; instead do individual instructions crafted by hand. -func TestScalarEncInstructions(t *testing.T) { - var b = new(bytes.Buffer) - - // bool - { - var data bool = true - instr := &encInstr{encBool, 6, nil, 0} - state := newEncoderState(b) - instr.op(instr, state, reflect.ValueOf(data)) - if !bytes.Equal(boolResult, b.Bytes()) { - t.Errorf("bool enc instructions: expected % x got % x", boolResult, b.Bytes()) - } - } - - // int - { - b.Reset() - var data int = 17 - instr := &encInstr{encInt, 6, nil, 0} - state := newEncoderState(b) - instr.op(instr, state, reflect.ValueOf(data)) - if !bytes.Equal(signedResult, b.Bytes()) { - t.Errorf("int enc instructions: expected % x got % x", signedResult, b.Bytes()) - } - } - - // uint - { - b.Reset() - var data uint = 17 - instr := &encInstr{encUint, 6, nil, 0} - state := newEncoderState(b) - instr.op(instr, state, reflect.ValueOf(data)) - if !bytes.Equal(unsignedResult, b.Bytes()) { - t.Errorf("uint enc instructions: expected % x got % x", unsignedResult, b.Bytes()) - } - } - - // int8 - { - b.Reset() - var data int8 = 17 - instr := &encInstr{encInt, 6, nil, 0} - state := newEncoderState(b) - instr.op(instr, state, reflect.ValueOf(data)) - if !bytes.Equal(signedResult, b.Bytes()) { - t.Errorf("int8 enc instructions: expected % x got % x", signedResult, b.Bytes()) - } - } - - // uint8 - { - b.Reset() - var data uint8 = 17 - instr := &encInstr{encUint, 6, nil, 0} - state := newEncoderState(b) - instr.op(instr, state, reflect.ValueOf(data)) - if !bytes.Equal(unsignedResult, b.Bytes()) { - t.Errorf("uint8 enc instructions: expected % x got % x", unsignedResult, b.Bytes()) - } - } - - // int16 - { - b.Reset() - var data int16 = 17 - instr := &encInstr{encInt, 6, nil, 0} - state := newEncoderState(b) - instr.op(instr, state, reflect.ValueOf(data)) - if !bytes.Equal(signedResult, b.Bytes()) { - t.Errorf("int16 enc instructions: expected % x got % x", signedResult, b.Bytes()) - } - } - - // uint16 - { - b.Reset() - var data uint16 = 17 - instr := &encInstr{encUint, 6, nil, 0} - state := newEncoderState(b) - instr.op(instr, state, reflect.ValueOf(data)) - if !bytes.Equal(unsignedResult, b.Bytes()) { - t.Errorf("uint16 enc instructions: expected % x got % x", unsignedResult, b.Bytes()) - } - } - - // int32 - { - b.Reset() - var data int32 = 17 - instr := &encInstr{encInt, 6, nil, 0} - state := newEncoderState(b) - instr.op(instr, state, reflect.ValueOf(data)) - if !bytes.Equal(signedResult, b.Bytes()) { - t.Errorf("int32 enc instructions: expected % x got % x", signedResult, b.Bytes()) - } - } - - // uint32 - { - b.Reset() - var data uint32 = 17 - instr := &encInstr{encUint, 6, nil, 0} - state := newEncoderState(b) - instr.op(instr, state, reflect.ValueOf(data)) - if !bytes.Equal(unsignedResult, b.Bytes()) { - t.Errorf("uint32 enc instructions: expected % x got % x", unsignedResult, b.Bytes()) - } - } - - // int64 - { - b.Reset() - var data int64 = 17 - instr := &encInstr{encInt, 6, nil, 0} - state := newEncoderState(b) - instr.op(instr, state, reflect.ValueOf(data)) - if !bytes.Equal(signedResult, b.Bytes()) { - t.Errorf("int64 enc instructions: expected % x got % x", signedResult, b.Bytes()) - } - } - - // uint64 - { - b.Reset() - var data uint64 = 17 - instr := &encInstr{encUint, 6, nil, 0} - state := newEncoderState(b) - instr.op(instr, state, reflect.ValueOf(data)) - if !bytes.Equal(unsignedResult, b.Bytes()) { - t.Errorf("uint64 enc instructions: expected % x got % x", unsignedResult, b.Bytes()) - } - } - - // float32 - { - b.Reset() - var data float32 = 17 - instr := &encInstr{encFloat, 6, nil, 0} - state := newEncoderState(b) - instr.op(instr, state, reflect.ValueOf(data)) - if !bytes.Equal(floatResult, b.Bytes()) { - t.Errorf("float32 enc instructions: expected % x got % x", floatResult, b.Bytes()) - } - } - - // float64 - { - b.Reset() - var data float64 = 17 - instr := &encInstr{encFloat, 6, nil, 0} - state := newEncoderState(b) - instr.op(instr, state, reflect.ValueOf(data)) - if !bytes.Equal(floatResult, b.Bytes()) { - t.Errorf("float64 enc instructions: expected % x got % x", floatResult, b.Bytes()) - } - } - - // bytes == []uint8 - { - b.Reset() - data := []byte("hello") - instr := &encInstr{encUint8Array, 6, nil, 0} - state := newEncoderState(b) - instr.op(instr, state, reflect.ValueOf(data)) - if !bytes.Equal(bytesResult, b.Bytes()) { - t.Errorf("bytes enc instructions: expected % x got % x", bytesResult, b.Bytes()) - } - } - - // string - { - b.Reset() - var data string = "hello" - instr := &encInstr{encString, 6, nil, 0} - state := newEncoderState(b) - instr.op(instr, state, reflect.ValueOf(data)) - if !bytes.Equal(bytesResult, b.Bytes()) { - t.Errorf("string enc instructions: expected % x got % x", bytesResult, b.Bytes()) - } - } -} - -func execDec(typ string, instr *decInstr, state *decoderState, t *testing.T, value reflect.Value) { - defer testError(t) - v := int(state.decodeUint()) - if v+state.fieldnum != 6 { - t.Fatalf("decoding field number %d, got %d", 6, v+state.fieldnum) - } - instr.op(instr, state, value.Elem()) - state.fieldnum = 6 -} - -func newDecodeStateFromData(data []byte) *decoderState { - b := bytes.NewBuffer(data) - state := newDecodeState(b) - state.fieldnum = -1 - return state -} - -// Test instruction execution for decoding. -// Do not run the machine yet; instead do individual instructions crafted by hand. -func TestScalarDecInstructions(t *testing.T) { - ovfl := errors.New("overflow") - - // bool - { - var data bool - instr := &decInstr{decBool, 6, nil, ovfl} - state := newDecodeStateFromData(boolResult) - execDec("bool", instr, state, t, reflect.ValueOf(&data)) - if data != true { - t.Errorf("bool a = %v not true", data) - } - } - // int - { - var data int - instr := &decInstr{decOpTable[reflect.Int], 6, nil, ovfl} - state := newDecodeStateFromData(signedResult) - execDec("int", instr, state, t, reflect.ValueOf(&data)) - if data != 17 { - t.Errorf("int a = %v not 17", data) - } - } - - // uint - { - var data uint - instr := &decInstr{decOpTable[reflect.Uint], 6, nil, ovfl} - state := newDecodeStateFromData(unsignedResult) - execDec("uint", instr, state, t, reflect.ValueOf(&data)) - if data != 17 { - t.Errorf("uint a = %v not 17", data) - } - } - - // int8 - { - var data int8 - instr := &decInstr{decInt8, 6, nil, ovfl} - state := newDecodeStateFromData(signedResult) - execDec("int8", instr, state, t, reflect.ValueOf(&data)) - if data != 17 { - t.Errorf("int8 a = %v not 17", data) - } - } - - // uint8 - { - var data uint8 - instr := &decInstr{decUint8, 6, nil, ovfl} - state := newDecodeStateFromData(unsignedResult) - execDec("uint8", instr, state, t, reflect.ValueOf(&data)) - if data != 17 { - t.Errorf("uint8 a = %v not 17", data) - } - } - - // int16 - { - var data int16 - instr := &decInstr{decInt16, 6, nil, ovfl} - state := newDecodeStateFromData(signedResult) - execDec("int16", instr, state, t, reflect.ValueOf(&data)) - if data != 17 { - t.Errorf("int16 a = %v not 17", data) - } - } - - // uint16 - { - var data uint16 - instr := &decInstr{decUint16, 6, nil, ovfl} - state := newDecodeStateFromData(unsignedResult) - execDec("uint16", instr, state, t, reflect.ValueOf(&data)) - if data != 17 { - t.Errorf("uint16 a = %v not 17", data) - } - } - - // int32 - { - var data int32 - instr := &decInstr{decInt32, 6, nil, ovfl} - state := newDecodeStateFromData(signedResult) - execDec("int32", instr, state, t, reflect.ValueOf(&data)) - if data != 17 { - t.Errorf("int32 a = %v not 17", data) - } - } - - // uint32 - { - var data uint32 - instr := &decInstr{decUint32, 6, nil, ovfl} - state := newDecodeStateFromData(unsignedResult) - execDec("uint32", instr, state, t, reflect.ValueOf(&data)) - if data != 17 { - t.Errorf("uint32 a = %v not 17", data) - } - } - - // uintptr - { - var data uintptr - instr := &decInstr{decOpTable[reflect.Uintptr], 6, nil, ovfl} - state := newDecodeStateFromData(unsignedResult) - execDec("uintptr", instr, state, t, reflect.ValueOf(&data)) - if data != 17 { - t.Errorf("uintptr a = %v not 17", data) - } - } - - // int64 - { - var data int64 - instr := &decInstr{decInt64, 6, nil, ovfl} - state := newDecodeStateFromData(signedResult) - execDec("int64", instr, state, t, reflect.ValueOf(&data)) - if data != 17 { - t.Errorf("int64 a = %v not 17", data) - } - } - - // uint64 - { - var data uint64 - instr := &decInstr{decUint64, 6, nil, ovfl} - state := newDecodeStateFromData(unsignedResult) - execDec("uint64", instr, state, t, reflect.ValueOf(&data)) - if data != 17 { - t.Errorf("uint64 a = %v not 17", data) - } - } - - // float32 - { - var data float32 - instr := &decInstr{decFloat32, 6, nil, ovfl} - state := newDecodeStateFromData(floatResult) - execDec("float32", instr, state, t, reflect.ValueOf(&data)) - if data != 17 { - t.Errorf("float32 a = %v not 17", data) - } - } - - // float64 - { - var data float64 - instr := &decInstr{decFloat64, 6, nil, ovfl} - state := newDecodeStateFromData(floatResult) - execDec("float64", instr, state, t, reflect.ValueOf(&data)) - if data != 17 { - t.Errorf("float64 a = %v not 17", data) - } - } - - // complex64 - { - var data complex64 - instr := &decInstr{decOpTable[reflect.Complex64], 6, nil, ovfl} - state := newDecodeStateFromData(complexResult) - execDec("complex", instr, state, t, reflect.ValueOf(&data)) - if data != 17+19i { - t.Errorf("complex a = %v not 17+19i", data) - } - } - - // complex128 - { - var data complex128 - instr := &decInstr{decOpTable[reflect.Complex128], 6, nil, ovfl} - state := newDecodeStateFromData(complexResult) - execDec("complex", instr, state, t, reflect.ValueOf(&data)) - if data != 17+19i { - t.Errorf("complex a = %v not 17+19i", data) - } - } - - // bytes == []uint8 - { - var data []byte - instr := &decInstr{decUint8Slice, 6, nil, ovfl} - state := newDecodeStateFromData(bytesResult) - execDec("bytes", instr, state, t, reflect.ValueOf(&data)) - if string(data) != "hello" { - t.Errorf(`bytes a = %q not "hello"`, string(data)) - } - } - - // string - { - var data string - instr := &decInstr{decString, 6, nil, ovfl} - state := newDecodeStateFromData(bytesResult) - execDec("bytes", instr, state, t, reflect.ValueOf(&data)) - if data != "hello" { - t.Errorf(`bytes a = %q not "hello"`, data) - } - } -} - -func TestEndToEnd(t *testing.T) { - type T2 struct { - T string - } - s1 := "string1" - s2 := "string2" - type T1 struct { - A, B, C int - M map[string]*float64 - EmptyMap map[string]int // to check that we receive a non-nil map. - N *[3]float64 - Strs *[2]string - Int64s *[]int64 - RI complex64 - S string - Y []byte - T *T2 - } - pi := 3.14159 - e := 2.71828 - t1 := &T1{ - A: 17, - B: 18, - C: -5, - M: map[string]*float64{"pi": &pi, "e": &e}, - EmptyMap: make(map[string]int), - N: &[3]float64{1.5, 2.5, 3.5}, - Strs: &[2]string{s1, s2}, - Int64s: &[]int64{77, 89, 123412342134}, - RI: 17 - 23i, - S: "Now is the time", - Y: []byte("hello, sailor"), - T: &T2{"this is T2"}, - } - b := new(bytes.Buffer) - err := NewEncoder(b).Encode(t1) - if err != nil { - t.Error("encode:", err) - } - var _t1 T1 - err = NewDecoder(b).Decode(&_t1) - if err != nil { - t.Fatal("decode:", err) - } - if !reflect.DeepEqual(t1, &_t1) { - t.Errorf("encode expected %v got %v", *t1, _t1) - } - // Be absolutely sure the received map is non-nil. - if t1.EmptyMap == nil { - t.Errorf("nil map sent") - } - if _t1.EmptyMap == nil { - t.Errorf("nil map received") - } -} - -func TestOverflow(t *testing.T) { - type inputT struct { - Maxi int64 - Mini int64 - Maxu uint64 - Maxf float64 - Minf float64 - Maxc complex128 - Minc complex128 - } - var it inputT - var err error - b := new(bytes.Buffer) - enc := NewEncoder(b) - dec := NewDecoder(b) - - // int8 - b.Reset() - it = inputT{ - Maxi: math.MaxInt8 + 1, - } - type outi8 struct { - Maxi int8 - Mini int8 - } - var o1 outi8 - enc.Encode(it) - err = dec.Decode(&o1) - if err == nil || err.Error() != `value for "Maxi" out of range` { - t.Error("wrong overflow error for int8:", err) - } - it = inputT{ - Mini: math.MinInt8 - 1, - } - b.Reset() - enc.Encode(it) - err = dec.Decode(&o1) - if err == nil || err.Error() != `value for "Mini" out of range` { - t.Error("wrong underflow error for int8:", err) - } - - // int16 - b.Reset() - it = inputT{ - Maxi: math.MaxInt16 + 1, - } - type outi16 struct { - Maxi int16 - Mini int16 - } - var o2 outi16 - enc.Encode(it) - err = dec.Decode(&o2) - if err == nil || err.Error() != `value for "Maxi" out of range` { - t.Error("wrong overflow error for int16:", err) - } - it = inputT{ - Mini: math.MinInt16 - 1, - } - b.Reset() - enc.Encode(it) - err = dec.Decode(&o2) - if err == nil || err.Error() != `value for "Mini" out of range` { - t.Error("wrong underflow error for int16:", err) - } - - // int32 - b.Reset() - it = inputT{ - Maxi: math.MaxInt32 + 1, - } - type outi32 struct { - Maxi int32 - Mini int32 - } - var o3 outi32 - enc.Encode(it) - err = dec.Decode(&o3) - if err == nil || err.Error() != `value for "Maxi" out of range` { - t.Error("wrong overflow error for int32:", err) - } - it = inputT{ - Mini: math.MinInt32 - 1, - } - b.Reset() - enc.Encode(it) - err = dec.Decode(&o3) - if err == nil || err.Error() != `value for "Mini" out of range` { - t.Error("wrong underflow error for int32:", err) - } - - // uint8 - b.Reset() - it = inputT{ - Maxu: math.MaxUint8 + 1, - } - type outu8 struct { - Maxu uint8 - } - var o4 outu8 - enc.Encode(it) - err = dec.Decode(&o4) - if err == nil || err.Error() != `value for "Maxu" out of range` { - t.Error("wrong overflow error for uint8:", err) - } - - // uint16 - b.Reset() - it = inputT{ - Maxu: math.MaxUint16 + 1, - } - type outu16 struct { - Maxu uint16 - } - var o5 outu16 - enc.Encode(it) - err = dec.Decode(&o5) - if err == nil || err.Error() != `value for "Maxu" out of range` { - t.Error("wrong overflow error for uint16:", err) - } - - // uint32 - b.Reset() - it = inputT{ - Maxu: math.MaxUint32 + 1, - } - type outu32 struct { - Maxu uint32 - } - var o6 outu32 - enc.Encode(it) - err = dec.Decode(&o6) - if err == nil || err.Error() != `value for "Maxu" out of range` { - t.Error("wrong overflow error for uint32:", err) - } - - // float32 - b.Reset() - it = inputT{ - Maxf: math.MaxFloat32 * 2, - } - type outf32 struct { - Maxf float32 - Minf float32 - } - var o7 outf32 - enc.Encode(it) - err = dec.Decode(&o7) - if err == nil || err.Error() != `value for "Maxf" out of range` { - t.Error("wrong overflow error for float32:", err) - } - - // complex64 - b.Reset() - it = inputT{ - Maxc: complex(math.MaxFloat32*2, math.MaxFloat32*2), - } - type outc64 struct { - Maxc complex64 - Minc complex64 - } - var o8 outc64 - enc.Encode(it) - err = dec.Decode(&o8) - if err == nil || err.Error() != `value for "Maxc" out of range` { - t.Error("wrong overflow error for complex64:", err) - } -} - -func TestNesting(t *testing.T) { - type RT struct { - A string - Next *RT - } - rt := new(RT) - rt.A = "level1" - rt.Next = new(RT) - rt.Next.A = "level2" - b := new(bytes.Buffer) - NewEncoder(b).Encode(rt) - var drt RT - dec := NewDecoder(b) - err := dec.Decode(&drt) - if err != nil { - t.Fatal("decoder error:", err) - } - if drt.A != rt.A { - t.Errorf("nesting: encode expected %v got %v", *rt, drt) - } - if drt.Next == nil { - t.Errorf("nesting: recursion failed") - } - if drt.Next.A != rt.Next.A { - t.Errorf("nesting: encode expected %v got %v", *rt.Next, *drt.Next) - } -} - -// These three structures have the same data with different indirections -type T0 struct { - A int - B int - C int - D int -} -type T1 struct { - A int - B *int - C **int - D ***int -} -type T2 struct { - A ***int - B **int - C *int - D int -} - -func TestAutoIndirection(t *testing.T) { - // First transfer t1 into t0 - var t1 T1 - t1.A = 17 - t1.B = new(int) - *t1.B = 177 - t1.C = new(*int) - *t1.C = new(int) - **t1.C = 1777 - t1.D = new(**int) - *t1.D = new(*int) - **t1.D = new(int) - ***t1.D = 17777 - b := new(bytes.Buffer) - enc := NewEncoder(b) - enc.Encode(t1) - dec := NewDecoder(b) - var t0 T0 - dec.Decode(&t0) - if t0.A != 17 || t0.B != 177 || t0.C != 1777 || t0.D != 17777 { - t.Errorf("t1->t0: expected {17 177 1777 17777}; got %v", t0) - } - - // Now transfer t2 into t0 - var t2 T2 - t2.D = 17777 - t2.C = new(int) - *t2.C = 1777 - t2.B = new(*int) - *t2.B = new(int) - **t2.B = 177 - t2.A = new(**int) - *t2.A = new(*int) - **t2.A = new(int) - ***t2.A = 17 - b.Reset() - enc.Encode(t2) - t0 = T0{} - dec.Decode(&t0) - if t0.A != 17 || t0.B != 177 || t0.C != 1777 || t0.D != 17777 { - t.Errorf("t2->t0 expected {17 177 1777 17777}; got %v", t0) - } - - // Now transfer t0 into t1 - t0 = T0{17, 177, 1777, 17777} - b.Reset() - enc.Encode(t0) - t1 = T1{} - dec.Decode(&t1) - if t1.A != 17 || *t1.B != 177 || **t1.C != 1777 || ***t1.D != 17777 { - t.Errorf("t0->t1 expected {17 177 1777 17777}; got {%d %d %d %d}", t1.A, *t1.B, **t1.C, ***t1.D) - } - - // Now transfer t0 into t2 - b.Reset() - enc.Encode(t0) - t2 = T2{} - dec.Decode(&t2) - if ***t2.A != 17 || **t2.B != 177 || *t2.C != 1777 || t2.D != 17777 { - t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.A, **t2.B, *t2.C, t2.D) - } - - // Now do t2 again but without pre-allocated pointers. - b.Reset() - enc.Encode(t0) - ***t2.A = 0 - **t2.B = 0 - *t2.C = 0 - t2.D = 0 - dec.Decode(&t2) - if ***t2.A != 17 || **t2.B != 177 || *t2.C != 1777 || t2.D != 17777 { - t.Errorf("t0->t2 expected {17 177 1777 17777}; got {%d %d %d %d}", ***t2.A, **t2.B, *t2.C, t2.D) - } -} - -type RT0 struct { - A int - B string - C float64 -} -type RT1 struct { - C float64 - B string - A int - NotSet string -} - -func TestReorderedFields(t *testing.T) { - var rt0 RT0 - rt0.A = 17 - rt0.B = "hello" - rt0.C = 3.14159 - b := new(bytes.Buffer) - NewEncoder(b).Encode(rt0) - dec := NewDecoder(b) - var rt1 RT1 - // Wire type is RT0, local type is RT1. - err := dec.Decode(&rt1) - if err != nil { - t.Fatal("decode error:", err) - } - if rt0.A != rt1.A || rt0.B != rt1.B || rt0.C != rt1.C { - t.Errorf("rt1->rt0: expected %v; got %v", rt0, rt1) - } -} - -// Like an RT0 but with fields we'll ignore on the decode side. -type IT0 struct { - A int64 - B string - Ignore_d []int - Ignore_e [3]float64 - Ignore_f bool - Ignore_g string - Ignore_h []byte - Ignore_i *RT1 - Ignore_m map[string]int - C float64 -} - -func TestIgnoredFields(t *testing.T) { - var it0 IT0 - it0.A = 17 - it0.B = "hello" - it0.C = 3.14159 - it0.Ignore_d = []int{1, 2, 3} - it0.Ignore_e[0] = 1.0 - it0.Ignore_e[1] = 2.0 - it0.Ignore_e[2] = 3.0 - it0.Ignore_f = true - it0.Ignore_g = "pay no attention" - it0.Ignore_h = []byte("to the curtain") - it0.Ignore_i = &RT1{3.1, "hi", 7, "hello"} - it0.Ignore_m = map[string]int{"one": 1, "two": 2} - - b := new(bytes.Buffer) - NewEncoder(b).Encode(it0) - dec := NewDecoder(b) - var rt1 RT1 - // Wire type is IT0, local type is RT1. - err := dec.Decode(&rt1) - if err != nil { - t.Error("error: ", err) - } - if int(it0.A) != rt1.A || it0.B != rt1.B || it0.C != rt1.C { - t.Errorf("rt0->rt1: expected %v; got %v", it0, rt1) - } -} - -func TestBadRecursiveType(t *testing.T) { - type Rec ***Rec - var rec Rec - b := new(bytes.Buffer) - err := NewEncoder(b).Encode(&rec) - if err == nil { - t.Error("expected error; got none") - } else if strings.Index(err.Error(), "recursive") < 0 { - t.Error("expected recursive type error; got", err) - } - // Can't test decode easily because we can't encode one, so we can't pass one to a Decoder. -} - -type Indirect struct { - A ***[3]int - S ***[]int - M ****map[string]int -} - -type Direct struct { - A [3]int - S []int - M map[string]int -} - -func TestIndirectSliceMapArray(t *testing.T) { - // Marshal indirect, unmarshal to direct. - i := new(Indirect) - i.A = new(**[3]int) - *i.A = new(*[3]int) - **i.A = new([3]int) - ***i.A = [3]int{1, 2, 3} - i.S = new(**[]int) - *i.S = new(*[]int) - **i.S = new([]int) - ***i.S = []int{4, 5, 6} - i.M = new(***map[string]int) - *i.M = new(**map[string]int) - **i.M = new(*map[string]int) - ***i.M = new(map[string]int) - ****i.M = map[string]int{"one": 1, "two": 2, "three": 3} - b := new(bytes.Buffer) - NewEncoder(b).Encode(i) - dec := NewDecoder(b) - var d Direct - err := dec.Decode(&d) - if err != nil { - t.Error("error: ", err) - } - if len(d.A) != 3 || d.A[0] != 1 || d.A[1] != 2 || d.A[2] != 3 { - t.Errorf("indirect to direct: d.A is %v not %v", d.A, ***i.A) - } - if len(d.S) != 3 || d.S[0] != 4 || d.S[1] != 5 || d.S[2] != 6 { - t.Errorf("indirect to direct: d.S is %v not %v", d.S, ***i.S) - } - if len(d.M) != 3 || d.M["one"] != 1 || d.M["two"] != 2 || d.M["three"] != 3 { - t.Errorf("indirect to direct: d.M is %v not %v", d.M, ***i.M) - } - // Marshal direct, unmarshal to indirect. - d.A = [3]int{11, 22, 33} - d.S = []int{44, 55, 66} - d.M = map[string]int{"four": 4, "five": 5, "six": 6} - i = new(Indirect) - b.Reset() - NewEncoder(b).Encode(d) - dec = NewDecoder(b) - err = dec.Decode(&i) - if err != nil { - t.Fatal("error: ", err) - } - if len(***i.A) != 3 || (***i.A)[0] != 11 || (***i.A)[1] != 22 || (***i.A)[2] != 33 { - t.Errorf("direct to indirect: ***i.A is %v not %v", ***i.A, d.A) - } - if len(***i.S) != 3 || (***i.S)[0] != 44 || (***i.S)[1] != 55 || (***i.S)[2] != 66 { - t.Errorf("direct to indirect: ***i.S is %v not %v", ***i.S, ***i.S) - } - if len(****i.M) != 3 || (****i.M)["four"] != 4 || (****i.M)["five"] != 5 || (****i.M)["six"] != 6 { - t.Errorf("direct to indirect: ****i.M is %v not %v", ****i.M, d.M) - } -} - -// An interface with several implementations -type Squarer interface { - Square() int -} - -type Int int - -func (i Int) Square() int { - return int(i * i) -} - -type Float float64 - -func (f Float) Square() int { - return int(f * f) -} - -type Vector []int - -func (v Vector) Square() int { - sum := 0 - for _, x := range v { - sum += x * x - } - return sum -} - -type Point struct { - X, Y int -} - -func (p Point) Square() int { - return p.X*p.X + p.Y*p.Y -} - -// A struct with interfaces in it. -type InterfaceItem struct { - I int - Sq1, Sq2, Sq3 Squarer - F float64 - Sq []Squarer -} - -// The same struct without interfaces -type NoInterfaceItem struct { - I int - F float64 -} - -func TestInterface(t *testing.T) { - iVal := Int(3) - fVal := Float(5) - // Sending a Vector will require that the receiver define a type in the middle of - // receiving the value for item2. - vVal := Vector{1, 2, 3} - b := new(bytes.Buffer) - item1 := &InterfaceItem{1, iVal, fVal, vVal, 11.5, []Squarer{iVal, fVal, nil, vVal}} - // Register the types. - Register(Int(0)) - Register(Float(0)) - Register(Vector{}) - err := NewEncoder(b).Encode(item1) - if err != nil { - t.Error("expected no encode error; got", err) - } - - item2 := InterfaceItem{} - err = NewDecoder(b).Decode(&item2) - if err != nil { - t.Fatal("decode:", err) - } - if item2.I != item1.I { - t.Error("normal int did not decode correctly") - } - if item2.Sq1 == nil || item2.Sq1.Square() != iVal.Square() { - t.Error("Int did not decode correctly") - } - if item2.Sq2 == nil || item2.Sq2.Square() != fVal.Square() { - t.Error("Float did not decode correctly") - } - if item2.Sq3 == nil || item2.Sq3.Square() != vVal.Square() { - t.Error("Vector did not decode correctly") - } - if item2.F != item1.F { - t.Error("normal float did not decode correctly") - } - // Now check that we received a slice of Squarers correctly, including a nil element - if len(item1.Sq) != len(item2.Sq) { - t.Fatalf("[]Squarer length wrong: got %d; expected %d", len(item2.Sq), len(item1.Sq)) - } - for i, v1 := range item1.Sq { - v2 := item2.Sq[i] - if v1 == nil || v2 == nil { - if v1 != nil || v2 != nil { - t.Errorf("item %d inconsistent nils", i) - } - } else if v1.Square() != v2.Square() { - t.Errorf("item %d inconsistent values: %v %v", i, v1, v2) - } - } -} - -// A struct with all basic types, stored in interfaces. -type BasicInterfaceItem struct { - Int, Int8, Int16, Int32, Int64 interface{} - Uint, Uint8, Uint16, Uint32, Uint64 interface{} - Float32, Float64 interface{} - Complex64, Complex128 interface{} - Bool interface{} - String interface{} - Bytes interface{} -} - -func TestInterfaceBasic(t *testing.T) { - b := new(bytes.Buffer) - item1 := &BasicInterfaceItem{ - int(1), int8(1), int16(1), int32(1), int64(1), - uint(1), uint8(1), uint16(1), uint32(1), uint64(1), - float32(1), 1.0, - complex64(1i), complex128(1i), - true, - "hello", - []byte("sailor"), - } - err := NewEncoder(b).Encode(item1) - if err != nil { - t.Error("expected no encode error; got", err) - } - - item2 := &BasicInterfaceItem{} - err = NewDecoder(b).Decode(&item2) - if err != nil { - t.Fatal("decode:", err) - } - if !reflect.DeepEqual(item1, item2) { - t.Errorf("encode expected %v got %v", item1, item2) - } - // Hand check a couple for correct types. - if v, ok := item2.Bool.(bool); !ok || !v { - t.Error("boolean should be true") - } - if v, ok := item2.String.(string); !ok || v != item1.String.(string) { - t.Errorf("string should be %v is %v", item1.String, v) - } -} - -type String string - -type PtrInterfaceItem struct { - Str1 interface{} // basic - Str2 interface{} // derived -} - -// We'll send pointers; should receive values. -// Also check that we can register T but send *T. -func TestInterfacePointer(t *testing.T) { - b := new(bytes.Buffer) - str1 := "howdy" - str2 := String("kiddo") - item1 := &PtrInterfaceItem{ - &str1, - &str2, - } - // Register the type. - Register(str2) - err := NewEncoder(b).Encode(item1) - if err != nil { - t.Error("expected no encode error; got", err) - } - - item2 := &PtrInterfaceItem{} - err = NewDecoder(b).Decode(&item2) - if err != nil { - t.Fatal("decode:", err) - } - // Hand test for correct types and values. - if v, ok := item2.Str1.(string); !ok || v != str1 { - t.Errorf("basic string failed: %q should be %q", v, str1) - } - if v, ok := item2.Str2.(String); !ok || v != str2 { - t.Errorf("derived type String failed: %q should be %q", v, str2) - } -} - -func TestIgnoreInterface(t *testing.T) { - iVal := Int(3) - fVal := Float(5) - // Sending a Point will require that the receiver define a type in the middle of - // receiving the value for item2. - pVal := Point{2, 3} - b := new(bytes.Buffer) - item1 := &InterfaceItem{1, iVal, fVal, pVal, 11.5, nil} - // Register the types. - Register(Int(0)) - Register(Float(0)) - Register(Point{}) - err := NewEncoder(b).Encode(item1) - if err != nil { - t.Error("expected no encode error; got", err) - } - - item2 := NoInterfaceItem{} - err = NewDecoder(b).Decode(&item2) - if err != nil { - t.Fatal("decode:", err) - } - if item2.I != item1.I { - t.Error("normal int did not decode correctly") - } - if item2.F != item2.F { - t.Error("normal float did not decode correctly") - } -} - -type U struct { - A int - B string - c float64 - D uint -} - -func TestUnexportedFields(t *testing.T) { - var u0 U - u0.A = 17 - u0.B = "hello" - u0.c = 3.14159 - u0.D = 23 - b := new(bytes.Buffer) - NewEncoder(b).Encode(u0) - dec := NewDecoder(b) - var u1 U - u1.c = 1234. - err := dec.Decode(&u1) - if err != nil { - t.Fatal("decode error:", err) - } - if u0.A != u0.A || u0.B != u1.B || u0.D != u1.D { - t.Errorf("u1->u0: expected %v; got %v", u0, u1) - } - if u1.c != 1234. { - t.Error("u1.c modified") - } -} - -var singletons = []interface{}{ - true, - 7, - 3.2, - "hello", - [3]int{11, 22, 33}, - []float32{0.5, 0.25, 0.125}, - map[string]int{"one": 1, "two": 2}, -} - -func TestDebugSingleton(t *testing.T) { - if debugFunc == nil { - return - } - b := new(bytes.Buffer) - // Accumulate a number of values and print them out all at once. - for _, x := range singletons { - err := NewEncoder(b).Encode(x) - if err != nil { - t.Fatal("encode:", err) - } - } - debugFunc(b) -} - -// A type that won't be defined in the gob until we send it in an interface value. -type OnTheFly struct { - A int -} - -type DT struct { - // X OnTheFly - A int - B string - C float64 - I interface{} - J interface{} - I_nil interface{} - M map[string]int - T [3]int - S []string -} - -func newDT() DT { - var dt DT - dt.A = 17 - dt.B = "hello" - dt.C = 3.14159 - dt.I = 271828 - dt.J = OnTheFly{3} - dt.I_nil = nil - dt.M = map[string]int{"one": 1, "two": 2} - dt.T = [3]int{11, 22, 33} - dt.S = []string{"hi", "joe"} - return dt -} - -func TestDebugStruct(t *testing.T) { - if debugFunc == nil { - return - } - Register(OnTheFly{}) - dt := newDT() - b := new(bytes.Buffer) - err := NewEncoder(b).Encode(dt) - if err != nil { - t.Fatal("encode:", err) - } - debugBuffer := bytes.NewBuffer(b.Bytes()) - dt2 := &DT{} - err = NewDecoder(b).Decode(&dt2) - if err != nil { - t.Error("decode:", err) - } - debugFunc(debugBuffer) -} - -func encFuzzDec(rng *rand.Rand, in interface{}) error { - buf := new(bytes.Buffer) - enc := NewEncoder(buf) - if err := enc.Encode(&in); err != nil { - return err - } - - b := buf.Bytes() - for i, bi := range b { - if rng.Intn(10) < 3 { - b[i] = bi + uint8(rng.Intn(256)) - } - } - - dec := NewDecoder(buf) - var e interface{} - if err := dec.Decode(&e); err != nil { - return err - } - return nil -} - -// This does some "fuzz testing" by attempting to decode a sequence of random bytes. -func TestFuzz(t *testing.T) { - if !*doFuzzTests { - t.Logf("disabled; run with -gob.fuzz to enable") - return - } - - // all possible inputs - input := []interface{}{ - new(int), - new(float32), - new(float64), - new(complex128), - &ByteStruct{255}, - &ArrayStruct{}, - &StringStruct{"hello"}, - &GobTest1{0, &StringStruct{"hello"}}, - } - testFuzz(t, time.Now().UnixNano(), 100, input...) -} - -func TestFuzzRegressions(t *testing.T) { - if !*doFuzzTests { - t.Logf("disabled; run with -gob.fuzz to enable") - return - } - - // An instance triggering a type name of length ~102 GB. - testFuzz(t, 1328492090837718000, 100, new(float32)) - // An instance triggering a type name of 1.6 GB. - // Note: can take several minutes to run. - testFuzz(t, 1330522872628565000, 100, new(int)) -} - -func testFuzz(t *testing.T, seed int64, n int, input ...interface{}) { - for _, e := range input { - t.Logf("seed=%d n=%d e=%T", seed, n, e) - rng := rand.New(rand.NewSource(seed)) - for i := 0; i < n; i++ { - encFuzzDec(rng, e) - } - } -} - -// TestFuzzOneByte tries to decode corrupted input sequences -// and checks that no panic occurs. -func TestFuzzOneByte(t *testing.T) { - buf := new(bytes.Buffer) - Register(OnTheFly{}) - dt := newDT() - if err := NewEncoder(buf).Encode(dt); err != nil { - t.Fatal(err) - } - s := buf.String() - - indices := make([]int, 0, len(s)) - for i := 0; i < len(s); i++ { - switch i { - case 14, 167, 231, 265: // a slice length, corruptions are not handled yet. - continue - } - indices = append(indices, i) - } - if testing.Short() { - indices = []int{1, 111, 178} // known fixed panics - } - for _, i := range indices { - for j := 0; j < 256; j += 3 { - b := []byte(s) - b[i] ^= byte(j) - var e DT - func() { - defer func() { - if p := recover(); p != nil { - t.Errorf("crash for b[%d] ^= 0x%x", i, j) - panic(p) - } - }() - err := NewDecoder(bytes.NewReader(b)).Decode(&e) - _ = err - }() - } - } -} diff --git a/src/pkg/encoding/gob/debug.go b/src/pkg/encoding/gob/debug.go deleted file mode 100644 index 536bbdb5a..000000000 --- a/src/pkg/encoding/gob/debug.go +++ /dev/null @@ -1,705 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Delete the next line to include in the gob package. -// +build ignore - -package gob - -// This file is not normally included in the gob package. Used only for debugging the package itself. -// Except for reading uints, it is an implementation of a reader that is independent of -// the one implemented by Decoder. -// To enable the Debug function, delete the +build ignore line above and do -// go install - -import ( - "bytes" - "fmt" - "io" - "os" - "strings" - "sync" -) - -var dumpBytes = false // If true, print the remaining bytes in the input buffer at each item. - -// Init installs the debugging facility. If this file is not compiled in the -// package, the tests in codec_test.go are no-ops. -func init() { - debugFunc = Debug -} - -var ( - blanks = bytes.Repeat([]byte{' '}, 3*10) - empty = []byte(": \n") - tabs = strings.Repeat("\t", 100) -) - -// tab indents itself when printed. -type tab int - -func (t tab) String() string { - n := int(t) - if n > len(tabs) { - n = len(tabs) - } - return tabs[0:n] -} - -func (t tab) print() { - fmt.Fprint(os.Stderr, t) -} - -// A peekReader wraps an io.Reader, allowing one to peek ahead to see -// what's coming without stealing the data from the client of the Reader. -type peekReader struct { - r io.Reader - data []byte // read-ahead data -} - -// newPeekReader returns a peekReader that wraps r. -func newPeekReader(r io.Reader) *peekReader { - return &peekReader{r: r} -} - -// Read is the usual method. It will first take data that has been read ahead. -func (p *peekReader) Read(b []byte) (n int, err error) { - if len(p.data) == 0 { - return p.r.Read(b) - } - // Satisfy what's possible from the read-ahead data. - n = copy(b, p.data) - // Move data down to beginning of slice, to avoid endless growth - copy(p.data, p.data[n:]) - p.data = p.data[:len(p.data)-n] - return -} - -// peek returns as many bytes as possible from the unread -// portion of the stream, up to the length of b. -func (p *peekReader) peek(b []byte) (n int, err error) { - if len(p.data) > 0 { - n = copy(b, p.data) - if n == len(b) { - return - } - b = b[n:] - } - if len(b) == 0 { - return - } - m, e := io.ReadFull(p.r, b) - if m > 0 { - p.data = append(p.data, b[:m]...) - } - n += m - if e == io.ErrUnexpectedEOF { - // That means m > 0 but we reached EOF. If we got data - // we won't complain about not being able to peek enough. - if n > 0 { - e = nil - } else { - e = io.EOF - } - } - return n, e -} - -type debugger struct { - mutex sync.Mutex - remain int // the number of bytes known to remain in the input - remainingKnown bool // the value of 'remain' is valid - r *peekReader - wireType map[typeId]*wireType - tmp []byte // scratch space for decoding uints. -} - -// dump prints the next nBytes of the input. -// It arranges to print the output aligned from call to -// call, to make it easy to see what has been consumed. -func (deb *debugger) dump(format string, args ...interface{}) { - if !dumpBytes { - return - } - fmt.Fprintf(os.Stderr, format+" ", args...) - if !deb.remainingKnown { - return - } - if deb.remain < 0 { - fmt.Fprintf(os.Stderr, "remaining byte count is negative! %d\n", deb.remain) - return - } - data := make([]byte, deb.remain) - n, _ := deb.r.peek(data) - if n == 0 { - os.Stderr.Write(empty) - return - } - b := new(bytes.Buffer) - fmt.Fprintf(b, "[%d]{\n", deb.remain) - // Blanks until first byte - lineLength := 0 - if n := len(data); n%10 != 0 { - lineLength = 10 - n%10 - fmt.Fprintf(b, "\t%s", blanks[:lineLength*3]) - } - // 10 bytes per line - for len(data) > 0 { - if lineLength == 0 { - fmt.Fprint(b, "\t") - } - m := 10 - lineLength - lineLength = 0 - if m > len(data) { - m = len(data) - } - fmt.Fprintf(b, "% x\n", data[:m]) - data = data[m:] - } - fmt.Fprint(b, "}\n") - os.Stderr.Write(b.Bytes()) -} - -// Debug prints a human-readable representation of the gob data read from r. -// It is a no-op unless debugging was enabled when the package was built. -func Debug(r io.Reader) { - err := debug(r) - if err != nil { - fmt.Fprintf(os.Stderr, "gob debug: %s\n", err) - } -} - -// debug implements Debug, but catches panics and returns -// them as errors to be printed by Debug. -func debug(r io.Reader) (err error) { - defer catchError(&err) - fmt.Fprintln(os.Stderr, "Start of debugging") - deb := &debugger{ - r: newPeekReader(r), - wireType: make(map[typeId]*wireType), - tmp: make([]byte, 16), - } - if b, ok := r.(*bytes.Buffer); ok { - deb.remain = b.Len() - deb.remainingKnown = true - } - deb.gobStream() - return -} - -// note that we've consumed some bytes -func (deb *debugger) consumed(n int) { - if deb.remainingKnown { - deb.remain -= n - } -} - -// int64 decodes and returns the next integer, which must be present. -// Don't call this if you could be at EOF. -func (deb *debugger) int64() int64 { - return toInt(deb.uint64()) -} - -// uint64 returns and decodes the next unsigned integer, which must be present. -// Don't call this if you could be at EOF. -// TODO: handle errors better. -func (deb *debugger) uint64() uint64 { - n, w, err := decodeUintReader(deb.r, deb.tmp) - if err != nil { - errorf("debug: read error: %s", err) - } - deb.consumed(w) - return n -} - -// GobStream: -// DelimitedMessage* (until EOF) -func (deb *debugger) gobStream() { - // Make sure we're single-threaded through here. - deb.mutex.Lock() - defer deb.mutex.Unlock() - - for deb.delimitedMessage(0) { - } -} - -// DelimitedMessage: -// uint(lengthOfMessage) Message -func (deb *debugger) delimitedMessage(indent tab) bool { - for { - n := deb.loadBlock(true) - if n < 0 { - return false - } - deb.dump("Delimited message of length %d", n) - deb.message(indent) - } - return true -} - -// loadBlock preps us to read a message -// of the length specified next in the input. It returns -// the length of the block. The argument tells whether -// an EOF is acceptable now. If it is and one is found, -// the return value is negative. -func (deb *debugger) loadBlock(eofOK bool) int { - n64, w, err := decodeUintReader(deb.r, deb.tmp) // deb.uint64 will error at EOF - if err != nil { - if eofOK && err == io.EOF { - return -1 - } - errorf("debug: unexpected error: %s", err) - } - deb.consumed(w) - n := int(n64) - if n < 0 { - errorf("huge value for message length: %d", n64) - } - return int(n) -} - -// Message: -// TypeSequence TypedValue -// TypeSequence -// (TypeDefinition DelimitedTypeDefinition*)? -// DelimitedTypeDefinition: -// uint(lengthOfTypeDefinition) TypeDefinition -// TypedValue: -// int(typeId) Value -func (deb *debugger) message(indent tab) bool { - for { - // Convert the uint64 to a signed integer typeId - uid := deb.int64() - id := typeId(uid) - deb.dump("type id=%d", id) - if id < 0 { - deb.typeDefinition(indent, -id) - n := deb.loadBlock(false) - deb.dump("Message of length %d", n) - continue - } else { - deb.value(indent, id) - break - } - } - return true -} - -// Helper methods to make it easy to scan a type descriptor. - -// common returns the CommonType at the input point. -func (deb *debugger) common() CommonType { - fieldNum := -1 - name := "" - id := typeId(0) - for { - delta := deb.delta(-1) - if delta == 0 { - break - } - fieldNum += delta - switch fieldNum { - case 0: - name = deb.string() - case 1: - // Id typeId - id = deb.typeId() - default: - errorf("corrupted CommonType, delta is %d fieldNum is %d", delta, fieldNum) - } - } - return CommonType{name, id} -} - -// uint returns the unsigned int at the input point, as a uint (not uint64). -func (deb *debugger) uint() uint { - return uint(deb.uint64()) -} - -// int returns the signed int at the input point, as an int (not int64). -func (deb *debugger) int() int { - return int(deb.int64()) -} - -// typeId returns the type id at the input point. -func (deb *debugger) typeId() typeId { - return typeId(deb.int64()) -} - -// string returns the string at the input point. -func (deb *debugger) string() string { - x := int(deb.uint64()) - b := make([]byte, x) - nb, _ := deb.r.Read(b) - if nb != x { - errorf("corrupted type") - } - deb.consumed(nb) - return string(b) -} - -// delta returns the field delta at the input point. The expect argument, -// if non-negative, identifies what the value should be. -func (deb *debugger) delta(expect int) int { - delta := int(deb.uint64()) - if delta < 0 || (expect >= 0 && delta != expect) { - errorf("decode: corrupted type: delta %d expected %d", delta, expect) - } - return delta -} - -// TypeDefinition: -// [int(-typeId) (already read)] encodingOfWireType -func (deb *debugger) typeDefinition(indent tab, id typeId) { - deb.dump("type definition for id %d", id) - // Encoding is of a wireType. Decode the structure as usual - fieldNum := -1 - wire := new(wireType) - // A wireType defines a single field. - delta := deb.delta(-1) - fieldNum += delta - switch fieldNum { - case 0: // array type, one field of {{Common}, elem, length} - // Field number 0 is CommonType - deb.delta(1) - com := deb.common() - // Field number 1 is type Id of elem - deb.delta(1) - id := deb.typeId() - // Field number 3 is length - deb.delta(1) - length := deb.int() - wire.ArrayT = &arrayType{com, id, length} - - case 1: // slice type, one field of {{Common}, elem} - // Field number 0 is CommonType - deb.delta(1) - com := deb.common() - // Field number 1 is type Id of elem - deb.delta(1) - id := deb.typeId() - wire.SliceT = &sliceType{com, id} - - case 2: // struct type, one field of {{Common}, []fieldType} - // Field number 0 is CommonType - deb.delta(1) - com := deb.common() - // Field number 1 is slice of FieldType - deb.delta(1) - numField := int(deb.uint()) - field := make([]*fieldType, numField) - for i := 0; i < numField; i++ { - field[i] = new(fieldType) - deb.delta(1) // field 0 of fieldType: name - field[i].Name = deb.string() - deb.delta(1) // field 1 of fieldType: id - field[i].Id = deb.typeId() - deb.delta(0) // end of fieldType - } - wire.StructT = &structType{com, field} - - case 3: // map type, one field of {{Common}, key, elem} - // Field number 0 is CommonType - deb.delta(1) - com := deb.common() - // Field number 1 is type Id of key - deb.delta(1) - keyId := deb.typeId() - // Field number 2 is type Id of elem - deb.delta(1) - elemId := deb.typeId() - wire.MapT = &mapType{com, keyId, elemId} - case 4: // GobEncoder type, one field of {{Common}} - // Field number 0 is CommonType - deb.delta(1) - com := deb.common() - wire.GobEncoderT = &gobEncoderType{com} - case 5: // BinaryMarshaler type, one field of {{Common}} - // Field number 0 is CommonType - deb.delta(1) - com := deb.common() - wire.BinaryMarshalerT = &gobEncoderType{com} - case 6: // TextMarshaler type, one field of {{Common}} - // Field number 0 is CommonType - deb.delta(1) - com := deb.common() - wire.TextMarshalerT = &gobEncoderType{com} - default: - errorf("bad field in type %d", fieldNum) - } - deb.printWireType(indent, wire) - deb.delta(0) // end inner type (arrayType, etc.) - deb.delta(0) // end wireType - // Remember we've seen this type. - deb.wireType[id] = wire -} - -// Value: -// SingletonValue | StructValue -func (deb *debugger) value(indent tab, id typeId) { - wire, ok := deb.wireType[id] - if ok && wire.StructT != nil { - deb.structValue(indent, id) - } else { - deb.singletonValue(indent, id) - } -} - -// SingletonValue: -// uint(0) FieldValue -func (deb *debugger) singletonValue(indent tab, id typeId) { - deb.dump("Singleton value") - // is it a builtin type? - wire := deb.wireType[id] - _, ok := builtinIdToType[id] - if !ok && wire == nil { - errorf("type id %d not defined", id) - } - m := deb.uint64() - if m != 0 { - errorf("expected zero; got %d", m) - } - deb.fieldValue(indent, id) -} - -// InterfaceValue: -// NilInterfaceValue | NonNilInterfaceValue -func (deb *debugger) interfaceValue(indent tab) { - deb.dump("Start of interface value") - if nameLen := deb.uint64(); nameLen == 0 { - deb.nilInterfaceValue(indent) - } else { - deb.nonNilInterfaceValue(indent, int(nameLen)) - } -} - -// NilInterfaceValue: -// uint(0) [already read] -func (deb *debugger) nilInterfaceValue(indent tab) int { - fmt.Fprintf(os.Stderr, "%snil interface\n", indent) - return 0 -} - -// NonNilInterfaceValue: -// ConcreteTypeName TypeSequence InterfaceContents -// ConcreteTypeName: -// uint(lengthOfName) [already read=n] name -// InterfaceContents: -// int(concreteTypeId) DelimitedValue -// DelimitedValue: -// uint(length) Value -func (deb *debugger) nonNilInterfaceValue(indent tab, nameLen int) { - // ConcreteTypeName - b := make([]byte, nameLen) - deb.r.Read(b) // TODO: CHECK THESE READS!! - deb.consumed(nameLen) - name := string(b) - - for { - id := deb.typeId() - if id < 0 { - deb.typeDefinition(indent, -id) - n := deb.loadBlock(false) - deb.dump("Nested message of length %d", n) - } else { - // DelimitedValue - x := deb.uint64() // in case we want to ignore the value; we don't. - fmt.Fprintf(os.Stderr, "%sinterface value, type %q id=%d; valueLength %d\n", indent, name, id, x) - deb.value(indent, id) - break - } - } -} - -// printCommonType prints a common type; used by printWireType. -func (deb *debugger) printCommonType(indent tab, kind string, common *CommonType) { - indent.print() - fmt.Fprintf(os.Stderr, "%s %q id=%d\n", kind, common.Name, common.Id) -} - -// printWireType prints the contents of a wireType. -func (deb *debugger) printWireType(indent tab, wire *wireType) { - fmt.Fprintf(os.Stderr, "%stype definition {\n", indent) - indent++ - switch { - case wire.ArrayT != nil: - deb.printCommonType(indent, "array", &wire.ArrayT.CommonType) - fmt.Fprintf(os.Stderr, "%slen %d\n", indent+1, wire.ArrayT.Len) - fmt.Fprintf(os.Stderr, "%selemid %d\n", indent+1, wire.ArrayT.Elem) - case wire.MapT != nil: - deb.printCommonType(indent, "map", &wire.MapT.CommonType) - fmt.Fprintf(os.Stderr, "%skey id=%d\n", indent+1, wire.MapT.Key) - fmt.Fprintf(os.Stderr, "%selem id=%d\n", indent+1, wire.MapT.Elem) - case wire.SliceT != nil: - deb.printCommonType(indent, "slice", &wire.SliceT.CommonType) - fmt.Fprintf(os.Stderr, "%selem id=%d\n", indent+1, wire.SliceT.Elem) - case wire.StructT != nil: - deb.printCommonType(indent, "struct", &wire.StructT.CommonType) - for i, field := range wire.StructT.Field { - fmt.Fprintf(os.Stderr, "%sfield %d:\t%s\tid=%d\n", indent+1, i, field.Name, field.Id) - } - case wire.GobEncoderT != nil: - deb.printCommonType(indent, "GobEncoder", &wire.GobEncoderT.CommonType) - } - indent-- - fmt.Fprintf(os.Stderr, "%s}\n", indent) -} - -// fieldValue prints a value of any type, such as a struct field. -// FieldValue: -// builtinValue | ArrayValue | MapValue | SliceValue | StructValue | InterfaceValue -func (deb *debugger) fieldValue(indent tab, id typeId) { - _, ok := builtinIdToType[id] - if ok { - if id == tInterface { - deb.interfaceValue(indent) - } else { - deb.printBuiltin(indent, id) - } - return - } - wire, ok := deb.wireType[id] - if !ok { - errorf("type id %d not defined", id) - } - switch { - case wire.ArrayT != nil: - deb.arrayValue(indent, wire) - case wire.MapT != nil: - deb.mapValue(indent, wire) - case wire.SliceT != nil: - deb.sliceValue(indent, wire) - case wire.StructT != nil: - deb.structValue(indent, id) - case wire.GobEncoderT != nil: - deb.gobEncoderValue(indent, id) - default: - panic("bad wire type for field") - } -} - -// printBuiltin prints a value not of a fundamental type, that is, -// one whose type is known to gobs at bootstrap time. -func (deb *debugger) printBuiltin(indent tab, id typeId) { - switch id { - case tBool: - x := deb.int64() - if x == 0 { - fmt.Fprintf(os.Stderr, "%sfalse\n", indent) - } else { - fmt.Fprintf(os.Stderr, "%strue\n", indent) - } - case tInt: - x := deb.int64() - fmt.Fprintf(os.Stderr, "%s%d\n", indent, x) - case tUint: - x := deb.int64() - fmt.Fprintf(os.Stderr, "%s%d\n", indent, x) - case tFloat: - x := deb.uint64() - fmt.Fprintf(os.Stderr, "%s%g\n", indent, float64FromBits(x)) - case tComplex: - r := deb.uint64() - i := deb.uint64() - fmt.Fprintf(os.Stderr, "%s%g+%gi\n", indent, float64FromBits(r), float64FromBits(i)) - case tBytes: - x := int(deb.uint64()) - b := make([]byte, x) - deb.r.Read(b) - deb.consumed(x) - fmt.Fprintf(os.Stderr, "%s{% x}=%q\n", indent, b, b) - case tString: - x := int(deb.uint64()) - b := make([]byte, x) - deb.r.Read(b) - deb.consumed(x) - fmt.Fprintf(os.Stderr, "%s%q\n", indent, b) - default: - panic("unknown builtin") - } -} - -// ArrayValue: -// uint(n) FieldValue*n -func (deb *debugger) arrayValue(indent tab, wire *wireType) { - elemId := wire.ArrayT.Elem - u := deb.uint64() - length := int(u) - for i := 0; i < length; i++ { - deb.fieldValue(indent, elemId) - } - if length != wire.ArrayT.Len { - fmt.Fprintf(os.Stderr, "%s(wrong length for array: %d should be %d)\n", indent, length, wire.ArrayT.Len) - } -} - -// MapValue: -// uint(n) (FieldValue FieldValue)*n [n (key, value) pairs] -func (deb *debugger) mapValue(indent tab, wire *wireType) { - keyId := wire.MapT.Key - elemId := wire.MapT.Elem - u := deb.uint64() - length := int(u) - for i := 0; i < length; i++ { - deb.fieldValue(indent+1, keyId) - deb.fieldValue(indent+1, elemId) - } -} - -// SliceValue: -// uint(n) (n FieldValue) -func (deb *debugger) sliceValue(indent tab, wire *wireType) { - elemId := wire.SliceT.Elem - u := deb.uint64() - length := int(u) - deb.dump("Start of slice of length %d", length) - - for i := 0; i < length; i++ { - deb.fieldValue(indent, elemId) - } -} - -// StructValue: -// (uint(fieldDelta) FieldValue)* -func (deb *debugger) structValue(indent tab, id typeId) { - deb.dump("Start of struct value of %q id=%d\n<<\n", id.name(), id) - fmt.Fprintf(os.Stderr, "%s%s struct {\n", indent, id.name()) - wire, ok := deb.wireType[id] - if !ok { - errorf("type id %d not defined", id) - } - strct := wire.StructT - fieldNum := -1 - indent++ - for { - delta := deb.uint64() - if delta == 0 { // struct terminator is zero delta fieldnum - break - } - fieldNum += int(delta) - if fieldNum < 0 || fieldNum >= len(strct.Field) { - deb.dump("field number out of range: prevField=%d delta=%d", fieldNum-int(delta), delta) - break - } - fmt.Fprintf(os.Stderr, "%sfield %d:\t%s\n", indent, fieldNum, wire.StructT.Field[fieldNum].Name) - deb.fieldValue(indent+1, strct.Field[fieldNum].Id) - } - indent-- - fmt.Fprintf(os.Stderr, "%s} // end %s struct\n", indent, id.name()) - deb.dump(">> End of struct value of type %d %q", id, id.name()) -} - -// GobEncoderValue: -// uint(n) byte*n -func (deb *debugger) gobEncoderValue(indent tab, id typeId) { - len := deb.uint64() - deb.dump("GobEncoder value of %q id=%d, length %d\n", id.name(), id, len) - fmt.Fprintf(os.Stderr, "%s%s (implements GobEncoder)\n", indent, id.name()) - data := make([]byte, len) - _, err := deb.r.Read(data) - if err != nil { - errorf("gobEncoder data read: %s", err) - } - fmt.Fprintf(os.Stderr, "%s[% .2x]\n", indent+1, data) -} diff --git a/src/pkg/encoding/gob/decode.go b/src/pkg/encoding/gob/decode.go deleted file mode 100644 index 2367650c8..000000000 --- a/src/pkg/encoding/gob/decode.go +++ /dev/null @@ -1,1146 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gob - -import ( - "bytes" - "encoding" - "errors" - "io" - "math" - "reflect" -) - -var ( - errBadUint = errors.New("gob: encoded unsigned integer out of range") - errBadType = errors.New("gob: unknown type id or corrupted data") - errRange = errors.New("gob: bad data: field numbers out of bounds") -) - -// decoderState is the execution state of an instance of the decoder. A new state -// is created for nested objects. -type decoderState struct { - dec *Decoder - // The buffer is stored with an extra indirection because it may be replaced - // if we load a type during decode (when reading an interface value). - b *bytes.Buffer - fieldnum int // the last field number read. - buf []byte - next *decoderState // for free list -} - -// We pass the bytes.Buffer separately for easier testing of the infrastructure -// without requiring a full Decoder. -func (dec *Decoder) newDecoderState(buf *bytes.Buffer) *decoderState { - d := dec.freeList - if d == nil { - d = new(decoderState) - d.dec = dec - d.buf = make([]byte, uint64Size) - } else { - dec.freeList = d.next - } - d.b = buf - return d -} - -func (dec *Decoder) freeDecoderState(d *decoderState) { - d.next = dec.freeList - dec.freeList = d -} - -func overflow(name string) error { - return errors.New(`value for "` + name + `" out of range`) -} - -// decodeUintReader reads an encoded unsigned integer from an io.Reader. -// Used only by the Decoder to read the message length. -func decodeUintReader(r io.Reader, buf []byte) (x uint64, width int, err error) { - width = 1 - n, err := io.ReadFull(r, buf[0:width]) - if n == 0 { - return - } - b := buf[0] - if b <= 0x7f { - return uint64(b), width, nil - } - n = -int(int8(b)) - if n > uint64Size { - err = errBadUint - return - } - width, err = io.ReadFull(r, buf[0:n]) - if err != nil { - if err == io.EOF { - err = io.ErrUnexpectedEOF - } - return - } - // Could check that the high byte is zero but it's not worth it. - for _, b := range buf[0:width] { - x = x<<8 | uint64(b) - } - width++ // +1 for length byte - return -} - -// decodeUint reads an encoded unsigned integer from state.r. -// Does not check for overflow. -func (state *decoderState) decodeUint() (x uint64) { - b, err := state.b.ReadByte() - if err != nil { - error_(err) - } - if b <= 0x7f { - return uint64(b) - } - n := -int(int8(b)) - if n > uint64Size { - error_(errBadUint) - } - width, err := state.b.Read(state.buf[0:n]) - if err != nil { - error_(err) - } - // Don't need to check error; it's safe to loop regardless. - // Could check that the high byte is zero but it's not worth it. - for _, b := range state.buf[0:width] { - x = x<<8 | uint64(b) - } - return x -} - -// decodeInt reads an encoded signed integer from state.r. -// Does not check for overflow. -func (state *decoderState) decodeInt() int64 { - x := state.decodeUint() - if x&1 != 0 { - return ^int64(x >> 1) - } - return int64(x >> 1) -} - -// decOp is the signature of a decoding operator for a given type. -type decOp func(i *decInstr, state *decoderState, v reflect.Value) - -// The 'instructions' of the decoding machine -type decInstr struct { - op decOp - field int // field number of the wire type - index []int // field access indices for destination type - ovfl error // error message for overflow/underflow (for arrays, of the elements) -} - -// ignoreUint discards a uint value with no destination. -func ignoreUint(i *decInstr, state *decoderState, v reflect.Value) { - state.decodeUint() -} - -// ignoreTwoUints discards a uint value with no destination. It's used to skip -// complex values. -func ignoreTwoUints(i *decInstr, state *decoderState, v reflect.Value) { - state.decodeUint() - state.decodeUint() -} - -// Since the encoder writes no zeros, if we arrive at a decoder we have -// a value to extract and store. The field number has already been read -// (it's how we knew to call this decoder). -// Each decoder is responsible for handling any indirections associated -// with the data structure. If any pointer so reached is nil, allocation must -// be done. - -// decAlloc takes a value and returns a settable value that can -// be assigned to. If the value is a pointer, decAlloc guarantees it points to storage. -// The callers to the individual decoders are expected to have used decAlloc. -// The individual decoders don't need to it. -func decAlloc(v reflect.Value) reflect.Value { - for v.Kind() == reflect.Ptr { - if v.IsNil() { - v.Set(reflect.New(v.Type().Elem())) - } - v = v.Elem() - } - return v -} - -// decBool decodes a uint and stores it as a boolean in value. -func decBool(i *decInstr, state *decoderState, value reflect.Value) { - value.SetBool(state.decodeUint() != 0) -} - -// decInt8 decodes an integer and stores it as an int8 in value. -func decInt8(i *decInstr, state *decoderState, value reflect.Value) { - v := state.decodeInt() - if v < math.MinInt8 || math.MaxInt8 < v { - error_(i.ovfl) - } - value.SetInt(v) -} - -// decUint8 decodes an unsigned integer and stores it as a uint8 in value. -func decUint8(i *decInstr, state *decoderState, value reflect.Value) { - v := state.decodeUint() - if math.MaxUint8 < v { - error_(i.ovfl) - } - value.SetUint(v) -} - -// decInt16 decodes an integer and stores it as an int16 in value. -func decInt16(i *decInstr, state *decoderState, value reflect.Value) { - v := state.decodeInt() - if v < math.MinInt16 || math.MaxInt16 < v { - error_(i.ovfl) - } - value.SetInt(v) -} - -// decUint16 decodes an unsigned integer and stores it as a uint16 in value. -func decUint16(i *decInstr, state *decoderState, value reflect.Value) { - v := state.decodeUint() - if math.MaxUint16 < v { - error_(i.ovfl) - } - value.SetUint(v) -} - -// decInt32 decodes an integer and stores it as an int32 in value. -func decInt32(i *decInstr, state *decoderState, value reflect.Value) { - v := state.decodeInt() - if v < math.MinInt32 || math.MaxInt32 < v { - error_(i.ovfl) - } - value.SetInt(v) -} - -// decUint32 decodes an unsigned integer and stores it as a uint32 in value. -func decUint32(i *decInstr, state *decoderState, value reflect.Value) { - v := state.decodeUint() - if math.MaxUint32 < v { - error_(i.ovfl) - } - value.SetUint(v) -} - -// decInt64 decodes an integer and stores it as an int64 in value. -func decInt64(i *decInstr, state *decoderState, value reflect.Value) { - v := state.decodeInt() - value.SetInt(v) -} - -// decUint64 decodes an unsigned integer and stores it as a uint64 in value. -func decUint64(i *decInstr, state *decoderState, value reflect.Value) { - v := state.decodeUint() - value.SetUint(v) -} - -// Floating-point numbers are transmitted as uint64s holding the bits -// of the underlying representation. They are sent byte-reversed, with -// the exponent end coming out first, so integer floating point numbers -// (for example) transmit more compactly. This routine does the -// unswizzling. -func float64FromBits(u uint64) float64 { - var v uint64 - for i := 0; i < 8; i++ { - v <<= 8 - v |= u & 0xFF - u >>= 8 - } - return math.Float64frombits(v) -} - -// float32FromBits decodes an unsigned integer, treats it as a 32-bit floating-point -// number, and returns it. It's a helper function for float32 and complex64. -// It returns a float64 because that's what reflection needs, but its return -// value is known to be accurately representable in a float32. -func float32FromBits(i *decInstr, u uint64) float64 { - v := float64FromBits(u) - av := v - if av < 0 { - av = -av - } - // +Inf is OK in both 32- and 64-bit floats. Underflow is always OK. - if math.MaxFloat32 < av && av <= math.MaxFloat64 { - error_(i.ovfl) - } - return v -} - -// decFloat32 decodes an unsigned integer, treats it as a 32-bit floating-point -// number, and stores it in value. -func decFloat32(i *decInstr, state *decoderState, value reflect.Value) { - value.SetFloat(float32FromBits(i, state.decodeUint())) -} - -// decFloat64 decodes an unsigned integer, treats it as a 64-bit floating-point -// number, and stores it in value. -func decFloat64(i *decInstr, state *decoderState, value reflect.Value) { - value.SetFloat(float64FromBits(state.decodeUint())) -} - -// decComplex64 decodes a pair of unsigned integers, treats them as a -// pair of floating point numbers, and stores them as a complex64 in value. -// The real part comes first. -func decComplex64(i *decInstr, state *decoderState, value reflect.Value) { - real := float32FromBits(i, state.decodeUint()) - imag := float32FromBits(i, state.decodeUint()) - value.SetComplex(complex(real, imag)) -} - -// decComplex128 decodes a pair of unsigned integers, treats them as a -// pair of floating point numbers, and stores them as a complex128 in value. -// The real part comes first. -func decComplex128(i *decInstr, state *decoderState, value reflect.Value) { - real := float64FromBits(state.decodeUint()) - imag := float64FromBits(state.decodeUint()) - value.SetComplex(complex(real, imag)) -} - -// decUint8Slice decodes a byte slice and stores in value a slice header -// describing the data. -// uint8 slices are encoded as an unsigned count followed by the raw bytes. -func decUint8Slice(i *decInstr, state *decoderState, value reflect.Value) { - u := state.decodeUint() - n := int(u) - if n < 0 || uint64(n) != u { - errorf("length of %s exceeds input size (%d bytes)", value.Type(), u) - } - if n > state.b.Len() { - errorf("%s data too long for buffer: %d", value.Type(), n) - } - if value.Cap() < n { - value.Set(reflect.MakeSlice(value.Type(), n, n)) - } else { - value.Set(value.Slice(0, n)) - } - if _, err := state.b.Read(value.Bytes()); err != nil { - errorf("error decoding []byte: %s", err) - } -} - -// decString decodes byte array and stores in value a string header -// describing the data. -// Strings are encoded as an unsigned count followed by the raw bytes. -func decString(i *decInstr, state *decoderState, value reflect.Value) { - u := state.decodeUint() - n := int(u) - if n < 0 || uint64(n) != u || n > state.b.Len() { - errorf("length of %s exceeds input size (%d bytes)", value.Type(), u) - } - if n > state.b.Len() { - errorf("%s data too long for buffer: %d", value.Type(), n) - } - // Read the data. - data := make([]byte, n) - if _, err := state.b.Read(data); err != nil { - errorf("error decoding string: %s", err) - } - value.SetString(string(data)) -} - -// ignoreUint8Array skips over the data for a byte slice value with no destination. -func ignoreUint8Array(i *decInstr, state *decoderState, value reflect.Value) { - b := make([]byte, state.decodeUint()) - state.b.Read(b) -} - -// Execution engine - -// The encoder engine is an array of instructions indexed by field number of the incoming -// decoder. It is executed with random access according to field number. -type decEngine struct { - instr []decInstr - numInstr int // the number of active instructions -} - -// decodeSingle decodes a top-level value that is not a struct and stores it in value. -// Such values are preceded by a zero, making them have the memory layout of a -// struct field (although with an illegal field number). -func (dec *Decoder) decodeSingle(engine *decEngine, ut *userTypeInfo, value reflect.Value) { - state := dec.newDecoderState(&dec.buf) - defer dec.freeDecoderState(state) - state.fieldnum = singletonField - if state.decodeUint() != 0 { - errorf("decode: corrupted data: non-zero delta for singleton") - } - instr := &engine.instr[singletonField] - instr.op(instr, state, value) -} - -// decodeStruct decodes a top-level struct and stores it in value. -// Indir is for the value, not the type. At the time of the call it may -// differ from ut.indir, which was computed when the engine was built. -// This state cannot arise for decodeSingle, which is called directly -// from the user's value, not from the innards of an engine. -func (dec *Decoder) decodeStruct(engine *decEngine, ut *userTypeInfo, value reflect.Value) { - state := dec.newDecoderState(&dec.buf) - defer dec.freeDecoderState(state) - state.fieldnum = -1 - for state.b.Len() > 0 { - delta := int(state.decodeUint()) - if delta < 0 { - errorf("decode: corrupted data: negative delta") - } - if delta == 0 { // struct terminator is zero delta fieldnum - break - } - fieldnum := state.fieldnum + delta - if fieldnum >= len(engine.instr) { - error_(errRange) - break - } - instr := &engine.instr[fieldnum] - var field reflect.Value - if instr.index != nil { - // Otherwise the field is unknown to us and instr.op is an ignore op. - field = value.FieldByIndex(instr.index) - if field.Kind() == reflect.Ptr { - field = decAlloc(field) - } - } - instr.op(instr, state, field) - state.fieldnum = fieldnum - } -} - -var noValue reflect.Value - -// ignoreStruct discards the data for a struct with no destination. -func (dec *Decoder) ignoreStruct(engine *decEngine) { - state := dec.newDecoderState(&dec.buf) - defer dec.freeDecoderState(state) - state.fieldnum = -1 - for state.b.Len() > 0 { - delta := int(state.decodeUint()) - if delta < 0 { - errorf("ignore decode: corrupted data: negative delta") - } - if delta == 0 { // struct terminator is zero delta fieldnum - break - } - fieldnum := state.fieldnum + delta - if fieldnum >= len(engine.instr) { - error_(errRange) - } - instr := &engine.instr[fieldnum] - instr.op(instr, state, noValue) - state.fieldnum = fieldnum - } -} - -// ignoreSingle discards the data for a top-level non-struct value with no -// destination. It's used when calling Decode with a nil value. -func (dec *Decoder) ignoreSingle(engine *decEngine) { - state := dec.newDecoderState(&dec.buf) - defer dec.freeDecoderState(state) - state.fieldnum = singletonField - delta := int(state.decodeUint()) - if delta != 0 { - errorf("decode: corrupted data: non-zero delta for singleton") - } - instr := &engine.instr[singletonField] - instr.op(instr, state, noValue) -} - -// decodeArrayHelper does the work for decoding arrays and slices. -func (dec *Decoder) decodeArrayHelper(state *decoderState, value reflect.Value, elemOp decOp, length int, ovfl error) { - instr := &decInstr{elemOp, 0, nil, ovfl} - isPtr := value.Type().Elem().Kind() == reflect.Ptr - for i := 0; i < length; i++ { - if state.b.Len() == 0 { - errorf("decoding array or slice: length exceeds input size (%d elements)", length) - } - v := value.Index(i) - if isPtr { - v = decAlloc(v) - } - elemOp(instr, state, v) - } -} - -// decodeArray decodes an array and stores it in value. -// The length is an unsigned integer preceding the elements. Even though the length is redundant -// (it's part of the type), it's a useful check and is included in the encoding. -func (dec *Decoder) decodeArray(atyp reflect.Type, state *decoderState, value reflect.Value, elemOp decOp, length int, ovfl error) { - if n := state.decodeUint(); n != uint64(length) { - errorf("length mismatch in decodeArray") - } - dec.decodeArrayHelper(state, value, elemOp, length, ovfl) -} - -// decodeIntoValue is a helper for map decoding. -func decodeIntoValue(state *decoderState, op decOp, isPtr bool, value reflect.Value, ovfl error) reflect.Value { - instr := &decInstr{op, 0, nil, ovfl} - v := value - if isPtr { - v = decAlloc(value) - } - op(instr, state, v) - return value -} - -// decodeMap decodes a map and stores it in value. -// Maps are encoded as a length followed by key:value pairs. -// Because the internals of maps are not visible to us, we must -// use reflection rather than pointer magic. -func (dec *Decoder) decodeMap(mtyp reflect.Type, state *decoderState, value reflect.Value, keyOp, elemOp decOp, ovfl error) { - if value.IsNil() { - // Allocate map. - value.Set(reflect.MakeMap(mtyp)) - } - n := int(state.decodeUint()) - keyIsPtr := mtyp.Key().Kind() == reflect.Ptr - elemIsPtr := mtyp.Elem().Kind() == reflect.Ptr - for i := 0; i < n; i++ { - key := decodeIntoValue(state, keyOp, keyIsPtr, allocValue(mtyp.Key()), ovfl) - elem := decodeIntoValue(state, elemOp, elemIsPtr, allocValue(mtyp.Elem()), ovfl) - value.SetMapIndex(key, elem) - } -} - -// ignoreArrayHelper does the work for discarding arrays and slices. -func (dec *Decoder) ignoreArrayHelper(state *decoderState, elemOp decOp, length int) { - instr := &decInstr{elemOp, 0, nil, errors.New("no error")} - for i := 0; i < length; i++ { - elemOp(instr, state, noValue) - } -} - -// ignoreArray discards the data for an array value with no destination. -func (dec *Decoder) ignoreArray(state *decoderState, elemOp decOp, length int) { - if n := state.decodeUint(); n != uint64(length) { - errorf("length mismatch in ignoreArray") - } - dec.ignoreArrayHelper(state, elemOp, length) -} - -// ignoreMap discards the data for a map value with no destination. -func (dec *Decoder) ignoreMap(state *decoderState, keyOp, elemOp decOp) { - n := int(state.decodeUint()) - keyInstr := &decInstr{keyOp, 0, nil, errors.New("no error")} - elemInstr := &decInstr{elemOp, 0, nil, errors.New("no error")} - for i := 0; i < n; i++ { - keyOp(keyInstr, state, noValue) - elemOp(elemInstr, state, noValue) - } -} - -// decodeSlice decodes a slice and stores it in value. -// Slices are encoded as an unsigned length followed by the elements. -func (dec *Decoder) decodeSlice(state *decoderState, value reflect.Value, elemOp decOp, ovfl error) { - u := state.decodeUint() - n := int(u) - if n < 0 || uint64(n) != u { - // We don't check n against buffer length here because if it's a slice - // of interfaces, there will be buffer reloads. - errorf("length of %s is negative (%d bytes)", value.Type(), u) - } - if value.Cap() < n { - value.Set(reflect.MakeSlice(value.Type(), n, n)) - } else { - value.Set(value.Slice(0, n)) - } - dec.decodeArrayHelper(state, value, elemOp, n, ovfl) -} - -// ignoreSlice skips over the data for a slice value with no destination. -func (dec *Decoder) ignoreSlice(state *decoderState, elemOp decOp) { - dec.ignoreArrayHelper(state, elemOp, int(state.decodeUint())) -} - -// decodeInterface decodes an interface value and stores it in value. -// Interfaces are encoded as the name of a concrete type followed by a value. -// If the name is empty, the value is nil and no value is sent. -func (dec *Decoder) decodeInterface(ityp reflect.Type, state *decoderState, value reflect.Value) { - // Read the name of the concrete type. - nr := state.decodeUint() - if nr < 0 || nr > 1<<31 { // zero is permissible for anonymous types - errorf("invalid type name length %d", nr) - } - if nr > uint64(state.b.Len()) { - errorf("invalid type name length %d: exceeds input size", nr) - } - b := make([]byte, nr) - state.b.Read(b) - name := string(b) - // Allocate the destination interface value. - if name == "" { - // Copy the nil interface value to the target. - value.Set(reflect.Zero(value.Type())) - return - } - if len(name) > 1024 { - errorf("name too long (%d bytes): %.20q...", len(name), name) - } - // The concrete type must be registered. - registerLock.RLock() - typ, ok := nameToConcreteType[name] - registerLock.RUnlock() - if !ok { - errorf("name not registered for interface: %q", name) - } - // Read the type id of the concrete value. - concreteId := dec.decodeTypeSequence(true) - if concreteId < 0 { - error_(dec.err) - } - // Byte count of value is next; we don't care what it is (it's there - // in case we want to ignore the value by skipping it completely). - state.decodeUint() - // Read the concrete value. - v := allocValue(typ) - dec.decodeValue(concreteId, v) - if dec.err != nil { - error_(dec.err) - } - // Assign the concrete value to the interface. - // Tread carefully; it might not satisfy the interface. - if !typ.AssignableTo(ityp) { - errorf("%s is not assignable to type %s", typ, ityp) - } - // Copy the interface value to the target. - value.Set(v) -} - -// ignoreInterface discards the data for an interface value with no destination. -func (dec *Decoder) ignoreInterface(state *decoderState) { - // Read the name of the concrete type. - b := make([]byte, state.decodeUint()) - _, err := state.b.Read(b) - if err != nil { - error_(err) - } - id := dec.decodeTypeSequence(true) - if id < 0 { - error_(dec.err) - } - // At this point, the decoder buffer contains a delimited value. Just toss it. - state.b.Next(int(state.decodeUint())) -} - -// decodeGobDecoder decodes something implementing the GobDecoder interface. -// The data is encoded as a byte slice. -func (dec *Decoder) decodeGobDecoder(ut *userTypeInfo, state *decoderState, value reflect.Value) { - // Read the bytes for the value. - b := make([]byte, state.decodeUint()) - _, err := state.b.Read(b) - if err != nil { - error_(err) - } - // We know it's one of these. - switch ut.externalDec { - case xGob: - err = value.Interface().(GobDecoder).GobDecode(b) - case xBinary: - err = value.Interface().(encoding.BinaryUnmarshaler).UnmarshalBinary(b) - case xText: - err = value.Interface().(encoding.TextUnmarshaler).UnmarshalText(b) - } - if err != nil { - error_(err) - } -} - -// ignoreGobDecoder discards the data for a GobDecoder value with no destination. -func (dec *Decoder) ignoreGobDecoder(state *decoderState) { - // Read the bytes for the value. - b := make([]byte, state.decodeUint()) - _, err := state.b.Read(b) - if err != nil { - error_(err) - } -} - -// Index by Go types. -var decOpTable = [...]decOp{ - reflect.Bool: decBool, - reflect.Int8: decInt8, - reflect.Int16: decInt16, - reflect.Int32: decInt32, - reflect.Int64: decInt64, - reflect.Uint8: decUint8, - reflect.Uint16: decUint16, - reflect.Uint32: decUint32, - reflect.Uint64: decUint64, - reflect.Float32: decFloat32, - reflect.Float64: decFloat64, - reflect.Complex64: decComplex64, - reflect.Complex128: decComplex128, - reflect.String: decString, -} - -// Indexed by gob types. tComplex will be added during type.init(). -var decIgnoreOpMap = map[typeId]decOp{ - tBool: ignoreUint, - tInt: ignoreUint, - tUint: ignoreUint, - tFloat: ignoreUint, - tBytes: ignoreUint8Array, - tString: ignoreUint8Array, - tComplex: ignoreTwoUints, -} - -// decOpFor returns the decoding op for the base type under rt and -// the indirection count to reach it. -func (dec *Decoder) decOpFor(wireId typeId, rt reflect.Type, name string, inProgress map[reflect.Type]*decOp) *decOp { - ut := userType(rt) - // If the type implements GobEncoder, we handle it without further processing. - if ut.externalDec != 0 { - return dec.gobDecodeOpFor(ut) - } - - // If this type is already in progress, it's a recursive type (e.g. map[string]*T). - // Return the pointer to the op we're already building. - if opPtr := inProgress[rt]; opPtr != nil { - return opPtr - } - typ := ut.base - var op decOp - k := typ.Kind() - if int(k) < len(decOpTable) { - op = decOpTable[k] - } - if op == nil { - inProgress[rt] = &op - // Special cases - switch t := typ; t.Kind() { - case reflect.Array: - name = "element of " + name - elemId := dec.wireType[wireId].ArrayT.Elem - elemOp := dec.decOpFor(elemId, t.Elem(), name, inProgress) - ovfl := overflow(name) - op = func(i *decInstr, state *decoderState, value reflect.Value) { - state.dec.decodeArray(t, state, value, *elemOp, t.Len(), ovfl) - } - - case reflect.Map: - keyId := dec.wireType[wireId].MapT.Key - elemId := dec.wireType[wireId].MapT.Elem - keyOp := dec.decOpFor(keyId, t.Key(), "key of "+name, inProgress) - elemOp := dec.decOpFor(elemId, t.Elem(), "element of "+name, inProgress) - ovfl := overflow(name) - op = func(i *decInstr, state *decoderState, value reflect.Value) { - state.dec.decodeMap(t, state, value, *keyOp, *elemOp, ovfl) - } - - case reflect.Slice: - name = "element of " + name - if t.Elem().Kind() == reflect.Uint8 { - op = decUint8Slice - break - } - var elemId typeId - if tt, ok := builtinIdToType[wireId]; ok { - elemId = tt.(*sliceType).Elem - } else { - elemId = dec.wireType[wireId].SliceT.Elem - } - elemOp := dec.decOpFor(elemId, t.Elem(), name, inProgress) - ovfl := overflow(name) - op = func(i *decInstr, state *decoderState, value reflect.Value) { - state.dec.decodeSlice(state, value, *elemOp, ovfl) - } - - case reflect.Struct: - // Generate a closure that calls out to the engine for the nested type. - ut := userType(typ) - enginePtr, err := dec.getDecEnginePtr(wireId, ut) - if err != nil { - error_(err) - } - op = func(i *decInstr, state *decoderState, value reflect.Value) { - // indirect through enginePtr to delay evaluation for recursive structs. - dec.decodeStruct(*enginePtr, ut, value) - } - case reflect.Interface: - op = func(i *decInstr, state *decoderState, value reflect.Value) { - state.dec.decodeInterface(t, state, value) - } - } - } - if op == nil { - errorf("decode can't handle type %s", rt) - } - return &op -} - -// decIgnoreOpFor returns the decoding op for a field that has no destination. -func (dec *Decoder) decIgnoreOpFor(wireId typeId) decOp { - op, ok := decIgnoreOpMap[wireId] - if !ok { - if wireId == tInterface { - // Special case because it's a method: the ignored item might - // define types and we need to record their state in the decoder. - op = func(i *decInstr, state *decoderState, value reflect.Value) { - state.dec.ignoreInterface(state) - } - return op - } - // Special cases - wire := dec.wireType[wireId] - switch { - case wire == nil: - errorf("bad data: undefined type %s", wireId.string()) - case wire.ArrayT != nil: - elemId := wire.ArrayT.Elem - elemOp := dec.decIgnoreOpFor(elemId) - op = func(i *decInstr, state *decoderState, value reflect.Value) { - state.dec.ignoreArray(state, elemOp, wire.ArrayT.Len) - } - - case wire.MapT != nil: - keyId := dec.wireType[wireId].MapT.Key - elemId := dec.wireType[wireId].MapT.Elem - keyOp := dec.decIgnoreOpFor(keyId) - elemOp := dec.decIgnoreOpFor(elemId) - op = func(i *decInstr, state *decoderState, value reflect.Value) { - state.dec.ignoreMap(state, keyOp, elemOp) - } - - case wire.SliceT != nil: - elemId := wire.SliceT.Elem - elemOp := dec.decIgnoreOpFor(elemId) - op = func(i *decInstr, state *decoderState, value reflect.Value) { - state.dec.ignoreSlice(state, elemOp) - } - - case wire.StructT != nil: - // Generate a closure that calls out to the engine for the nested type. - enginePtr, err := dec.getIgnoreEnginePtr(wireId) - if err != nil { - error_(err) - } - op = func(i *decInstr, state *decoderState, value reflect.Value) { - // indirect through enginePtr to delay evaluation for recursive structs - state.dec.ignoreStruct(*enginePtr) - } - - case wire.GobEncoderT != nil, wire.BinaryMarshalerT != nil, wire.TextMarshalerT != nil: - op = func(i *decInstr, state *decoderState, value reflect.Value) { - state.dec.ignoreGobDecoder(state) - } - } - } - if op == nil { - errorf("bad data: ignore can't handle type %s", wireId.string()) - } - return op -} - -// gobDecodeOpFor returns the op for a type that is known to implement -// GobDecoder. -func (dec *Decoder) gobDecodeOpFor(ut *userTypeInfo) *decOp { - rcvrType := ut.user - if ut.decIndir == -1 { - rcvrType = reflect.PtrTo(rcvrType) - } else if ut.decIndir > 0 { - for i := int8(0); i < ut.decIndir; i++ { - rcvrType = rcvrType.Elem() - } - } - var op decOp - op = func(i *decInstr, state *decoderState, value reflect.Value) { - // We now have the base type. We need its address if the receiver is a pointer. - if value.Kind() != reflect.Ptr && rcvrType.Kind() == reflect.Ptr { - value = value.Addr() - } - state.dec.decodeGobDecoder(ut, state, value) - } - return &op -} - -// compatibleType asks: Are these two gob Types compatible? -// Answers the question for basic types, arrays, maps and slices, plus -// GobEncoder/Decoder pairs. -// Structs are considered ok; fields will be checked later. -func (dec *Decoder) compatibleType(fr reflect.Type, fw typeId, inProgress map[reflect.Type]typeId) bool { - if rhs, ok := inProgress[fr]; ok { - return rhs == fw - } - inProgress[fr] = fw - ut := userType(fr) - wire, ok := dec.wireType[fw] - // If wire was encoded with an encoding method, fr must have that method. - // And if not, it must not. - // At most one of the booleans in ut is set. - // We could possibly relax this constraint in the future in order to - // choose the decoding method using the data in the wireType. - // The parentheses look odd but are correct. - if (ut.externalDec == xGob) != (ok && wire.GobEncoderT != nil) || - (ut.externalDec == xBinary) != (ok && wire.BinaryMarshalerT != nil) || - (ut.externalDec == xText) != (ok && wire.TextMarshalerT != nil) { - return false - } - if ut.externalDec != 0 { // This test trumps all others. - return true - } - switch t := ut.base; t.Kind() { - default: - // chan, etc: cannot handle. - return false - case reflect.Bool: - return fw == tBool - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return fw == tInt - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return fw == tUint - case reflect.Float32, reflect.Float64: - return fw == tFloat - case reflect.Complex64, reflect.Complex128: - return fw == tComplex - case reflect.String: - return fw == tString - case reflect.Interface: - return fw == tInterface - case reflect.Array: - if !ok || wire.ArrayT == nil { - return false - } - array := wire.ArrayT - return t.Len() == array.Len && dec.compatibleType(t.Elem(), array.Elem, inProgress) - case reflect.Map: - if !ok || wire.MapT == nil { - return false - } - MapType := wire.MapT - return dec.compatibleType(t.Key(), MapType.Key, inProgress) && dec.compatibleType(t.Elem(), MapType.Elem, inProgress) - case reflect.Slice: - // Is it an array of bytes? - if t.Elem().Kind() == reflect.Uint8 { - return fw == tBytes - } - // Extract and compare element types. - var sw *sliceType - if tt, ok := builtinIdToType[fw]; ok { - sw, _ = tt.(*sliceType) - } else if wire != nil { - sw = wire.SliceT - } - elem := userType(t.Elem()).base - return sw != nil && dec.compatibleType(elem, sw.Elem, inProgress) - case reflect.Struct: - return true - } -} - -// typeString returns a human-readable description of the type identified by remoteId. -func (dec *Decoder) typeString(remoteId typeId) string { - if t := idToType[remoteId]; t != nil { - // globally known type. - return t.string() - } - return dec.wireType[remoteId].string() -} - -// compileSingle compiles the decoder engine for a non-struct top-level value, including -// GobDecoders. -func (dec *Decoder) compileSingle(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error) { - rt := ut.user - engine = new(decEngine) - engine.instr = make([]decInstr, 1) // one item - name := rt.String() // best we can do - if !dec.compatibleType(rt, remoteId, make(map[reflect.Type]typeId)) { - remoteType := dec.typeString(remoteId) - // Common confusing case: local interface type, remote concrete type. - if ut.base.Kind() == reflect.Interface && remoteId != tInterface { - return nil, errors.New("gob: local interface type " + name + " can only be decoded from remote interface type; received concrete type " + remoteType) - } - return nil, errors.New("gob: decoding into local type " + name + ", received remote type " + remoteType) - } - op := dec.decOpFor(remoteId, rt, name, make(map[reflect.Type]*decOp)) - ovfl := errors.New(`value for "` + name + `" out of range`) - engine.instr[singletonField] = decInstr{*op, singletonField, nil, ovfl} - engine.numInstr = 1 - return -} - -// compileIgnoreSingle compiles the decoder engine for a non-struct top-level value that will be discarded. -func (dec *Decoder) compileIgnoreSingle(remoteId typeId) (engine *decEngine, err error) { - engine = new(decEngine) - engine.instr = make([]decInstr, 1) // one item - op := dec.decIgnoreOpFor(remoteId) - ovfl := overflow(dec.typeString(remoteId)) - engine.instr[0] = decInstr{op, 0, nil, ovfl} - engine.numInstr = 1 - return -} - -// compileDec compiles the decoder engine for a value. If the value is not a struct, -// it calls out to compileSingle. -func (dec *Decoder) compileDec(remoteId typeId, ut *userTypeInfo) (engine *decEngine, err error) { - rt := ut.base - srt := rt - if srt.Kind() != reflect.Struct || ut.externalDec != 0 { - return dec.compileSingle(remoteId, ut) - } - var wireStruct *structType - // Builtin types can come from global pool; the rest must be defined by the decoder. - // Also we know we're decoding a struct now, so the client must have sent one. - if t, ok := builtinIdToType[remoteId]; ok { - wireStruct, _ = t.(*structType) - } else { - wire := dec.wireType[remoteId] - if wire == nil { - error_(errBadType) - } - wireStruct = wire.StructT - } - if wireStruct == nil { - errorf("type mismatch in decoder: want struct type %s; got non-struct", rt) - } - engine = new(decEngine) - engine.instr = make([]decInstr, len(wireStruct.Field)) - seen := make(map[reflect.Type]*decOp) - // Loop over the fields of the wire type. - for fieldnum := 0; fieldnum < len(wireStruct.Field); fieldnum++ { - wireField := wireStruct.Field[fieldnum] - if wireField.Name == "" { - errorf("empty name for remote field of type %s", wireStruct.Name) - } - ovfl := overflow(wireField.Name) - // Find the field of the local type with the same name. - localField, present := srt.FieldByName(wireField.Name) - // TODO(r): anonymous names - if !present || !isExported(wireField.Name) { - op := dec.decIgnoreOpFor(wireField.Id) - engine.instr[fieldnum] = decInstr{op, fieldnum, nil, ovfl} - continue - } - if !dec.compatibleType(localField.Type, wireField.Id, make(map[reflect.Type]typeId)) { - errorf("wrong type (%s) for received field %s.%s", localField.Type, wireStruct.Name, wireField.Name) - } - op := dec.decOpFor(wireField.Id, localField.Type, localField.Name, seen) - engine.instr[fieldnum] = decInstr{*op, fieldnum, localField.Index, ovfl} - engine.numInstr++ - } - return -} - -// getDecEnginePtr returns the engine for the specified type. -func (dec *Decoder) getDecEnginePtr(remoteId typeId, ut *userTypeInfo) (enginePtr **decEngine, err error) { - rt := ut.user - decoderMap, ok := dec.decoderCache[rt] - if !ok { - decoderMap = make(map[typeId]**decEngine) - dec.decoderCache[rt] = decoderMap - } - if enginePtr, ok = decoderMap[remoteId]; !ok { - // To handle recursive types, mark this engine as underway before compiling. - enginePtr = new(*decEngine) - decoderMap[remoteId] = enginePtr - *enginePtr, err = dec.compileDec(remoteId, ut) - if err != nil { - delete(decoderMap, remoteId) - } - } - return -} - -// emptyStruct is the type we compile into when ignoring a struct value. -type emptyStruct struct{} - -var emptyStructType = reflect.TypeOf(emptyStruct{}) - -// getDecEnginePtr returns the engine for the specified type when the value is to be discarded. -func (dec *Decoder) getIgnoreEnginePtr(wireId typeId) (enginePtr **decEngine, err error) { - var ok bool - if enginePtr, ok = dec.ignorerCache[wireId]; !ok { - // To handle recursive types, mark this engine as underway before compiling. - enginePtr = new(*decEngine) - dec.ignorerCache[wireId] = enginePtr - wire := dec.wireType[wireId] - if wire != nil && wire.StructT != nil { - *enginePtr, err = dec.compileDec(wireId, userType(emptyStructType)) - } else { - *enginePtr, err = dec.compileIgnoreSingle(wireId) - } - if err != nil { - delete(dec.ignorerCache, wireId) - } - } - return -} - -// decodeValue decodes the data stream representing a value and stores it in value. -func (dec *Decoder) decodeValue(wireId typeId, value reflect.Value) { - defer catchError(&dec.err) - // If the value is nil, it means we should just ignore this item. - if !value.IsValid() { - dec.decodeIgnoredValue(wireId) - return - } - // Dereference down to the underlying type. - ut := userType(value.Type()) - base := ut.base - var enginePtr **decEngine - enginePtr, dec.err = dec.getDecEnginePtr(wireId, ut) - if dec.err != nil { - return - } - value = decAlloc(value) - engine := *enginePtr - if st := base; st.Kind() == reflect.Struct && ut.externalDec == 0 { - if engine.numInstr == 0 && st.NumField() > 0 && - dec.wireType[wireId] != nil && len(dec.wireType[wireId].StructT.Field) > 0 { - name := base.Name() - errorf("type mismatch: no fields matched compiling decoder for %s", name) - } - dec.decodeStruct(engine, ut, value) - } else { - dec.decodeSingle(engine, ut, value) - } -} - -// decodeIgnoredValue decodes the data stream representing a value of the specified type and discards it. -func (dec *Decoder) decodeIgnoredValue(wireId typeId) { - var enginePtr **decEngine - enginePtr, dec.err = dec.getIgnoreEnginePtr(wireId) - if dec.err != nil { - return - } - wire := dec.wireType[wireId] - if wire != nil && wire.StructT != nil { - dec.ignoreStruct(*enginePtr) - } else { - dec.ignoreSingle(*enginePtr) - } -} - -func init() { - var iop, uop decOp - switch reflect.TypeOf(int(0)).Bits() { - case 32: - iop = decInt32 - uop = decUint32 - case 64: - iop = decInt64 - uop = decUint64 - default: - panic("gob: unknown size of int/uint") - } - decOpTable[reflect.Int] = iop - decOpTable[reflect.Uint] = uop - - // Finally uintptr - switch reflect.TypeOf(uintptr(0)).Bits() { - case 32: - uop = decUint32 - case 64: - uop = decUint64 - default: - panic("gob: unknown size of uintptr") - } - decOpTable[reflect.Uintptr] = uop -} - -// Gob depends on being able to take the address -// of zeroed Values it creates, so use this wrapper instead -// of the standard reflect.Zero. -// Each call allocates once. -func allocValue(t reflect.Type) reflect.Value { - return reflect.New(t).Elem() -} diff --git a/src/pkg/encoding/gob/decoder.go b/src/pkg/encoding/gob/decoder.go deleted file mode 100644 index 3a769ec12..000000000 --- a/src/pkg/encoding/gob/decoder.go +++ /dev/null @@ -1,237 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gob - -import ( - "bufio" - "bytes" - "errors" - "io" - "reflect" - "sync" -) - -// A Decoder manages the receipt of type and data information read from the -// remote side of a connection. -type Decoder struct { - mutex sync.Mutex // each item must be received atomically - r io.Reader // source of the data - buf bytes.Buffer // buffer for more efficient i/o from r - wireType map[typeId]*wireType // map from remote ID to local description - decoderCache map[reflect.Type]map[typeId]**decEngine // cache of compiled engines - ignorerCache map[typeId]**decEngine // ditto for ignored objects - freeList *decoderState // list of free decoderStates; avoids reallocation - countBuf []byte // used for decoding integers while parsing messages - tmp []byte // temporary storage for i/o; saves reallocating - err error -} - -// NewDecoder returns a new decoder that reads from the io.Reader. -// If r does not also implement io.ByteReader, it will be wrapped in a -// bufio.Reader. -func NewDecoder(r io.Reader) *Decoder { - dec := new(Decoder) - // We use the ability to read bytes as a plausible surrogate for buffering. - if _, ok := r.(io.ByteReader); !ok { - r = bufio.NewReader(r) - } - dec.r = r - dec.wireType = make(map[typeId]*wireType) - dec.decoderCache = make(map[reflect.Type]map[typeId]**decEngine) - dec.ignorerCache = make(map[typeId]**decEngine) - dec.countBuf = make([]byte, 9) // counts may be uint64s (unlikely!), require 9 bytes - - return dec -} - -// recvType loads the definition of a type. -func (dec *Decoder) recvType(id typeId) { - // Have we already seen this type? That's an error - if id < firstUserId || dec.wireType[id] != nil { - dec.err = errors.New("gob: duplicate type received") - return - } - - // Type: - wire := new(wireType) - dec.decodeValue(tWireType, reflect.ValueOf(wire)) - if dec.err != nil { - return - } - // Remember we've seen this type. - dec.wireType[id] = wire -} - -var errBadCount = errors.New("invalid message length") - -// recvMessage reads the next count-delimited item from the input. It is the converse -// of Encoder.writeMessage. It returns false on EOF or other error reading the message. -func (dec *Decoder) recvMessage() bool { - // Read a count. - nbytes, _, err := decodeUintReader(dec.r, dec.countBuf) - if err != nil { - dec.err = err - return false - } - // Upper limit of 1GB, allowing room to grow a little without overflow. - // TODO: We might want more control over this limit. - if nbytes >= 1<<30 { - dec.err = errBadCount - return false - } - dec.readMessage(int(nbytes)) - return dec.err == nil -} - -// readMessage reads the next nbytes bytes from the input. -func (dec *Decoder) readMessage(nbytes int) { - // Allocate the dec.tmp buffer, up to 10KB. - const maxBuf = 10 * 1024 - nTmp := nbytes - if nTmp > maxBuf { - nTmp = maxBuf - } - if cap(dec.tmp) < nTmp { - nAlloc := nTmp + 100 // A little extra for growth. - if nAlloc > maxBuf { - nAlloc = maxBuf - } - dec.tmp = make([]byte, nAlloc) - } - dec.tmp = dec.tmp[:nTmp] - - // Read the data - dec.buf.Grow(nbytes) - for nbytes > 0 { - if nbytes < nTmp { - dec.tmp = dec.tmp[:nbytes] - } - var nRead int - nRead, dec.err = io.ReadFull(dec.r, dec.tmp) - if dec.err != nil { - if dec.err == io.EOF { - dec.err = io.ErrUnexpectedEOF - } - return - } - dec.buf.Write(dec.tmp) - nbytes -= nRead - } -} - -// toInt turns an encoded uint64 into an int, according to the marshaling rules. -func toInt(x uint64) int64 { - i := int64(x >> 1) - if x&1 != 0 { - i = ^i - } - return i -} - -func (dec *Decoder) nextInt() int64 { - n, _, err := decodeUintReader(&dec.buf, dec.countBuf) - if err != nil { - dec.err = err - } - return toInt(n) -} - -func (dec *Decoder) nextUint() uint64 { - n, _, err := decodeUintReader(&dec.buf, dec.countBuf) - if err != nil { - dec.err = err - } - return n -} - -// decodeTypeSequence parses: -// TypeSequence -// (TypeDefinition DelimitedTypeDefinition*)? -// and returns the type id of the next value. It returns -1 at -// EOF. Upon return, the remainder of dec.buf is the value to be -// decoded. If this is an interface value, it can be ignored by -// resetting that buffer. -func (dec *Decoder) decodeTypeSequence(isInterface bool) typeId { - for dec.err == nil { - if dec.buf.Len() == 0 { - if !dec.recvMessage() { - break - } - } - // Receive a type id. - id := typeId(dec.nextInt()) - if id >= 0 { - // Value follows. - return id - } - // Type definition for (-id) follows. - dec.recvType(-id) - // When decoding an interface, after a type there may be a - // DelimitedValue still in the buffer. Skip its count. - // (Alternatively, the buffer is empty and the byte count - // will be absorbed by recvMessage.) - if dec.buf.Len() > 0 { - if !isInterface { - dec.err = errors.New("extra data in buffer") - break - } - dec.nextUint() - } - } - return -1 -} - -// Decode reads the next value from the input stream and stores -// it in the data represented by the empty interface value. -// If e is nil, the value will be discarded. Otherwise, -// the value underlying e must be a pointer to the -// correct type for the next data item received. -// If the input is at EOF, Decode returns io.EOF and -// does not modify e. -func (dec *Decoder) Decode(e interface{}) error { - if e == nil { - return dec.DecodeValue(reflect.Value{}) - } - value := reflect.ValueOf(e) - // If e represents a value as opposed to a pointer, the answer won't - // get back to the caller. Make sure it's a pointer. - if value.Type().Kind() != reflect.Ptr { - dec.err = errors.New("gob: attempt to decode into a non-pointer") - return dec.err - } - return dec.DecodeValue(value) -} - -// DecodeValue reads the next value from the input stream. -// If v is the zero reflect.Value (v.Kind() == Invalid), DecodeValue discards the value. -// Otherwise, it stores the value into v. In that case, v must represent -// a non-nil pointer to data or be an assignable reflect.Value (v.CanSet()) -// If the input is at EOF, DecodeValue returns io.EOF and -// does not modify e. -func (dec *Decoder) DecodeValue(v reflect.Value) error { - if v.IsValid() { - if v.Kind() == reflect.Ptr && !v.IsNil() { - // That's okay, we'll store through the pointer. - } else if !v.CanSet() { - return errors.New("gob: DecodeValue of unassignable value") - } - } - // Make sure we're single-threaded through here. - dec.mutex.Lock() - defer dec.mutex.Unlock() - - dec.buf.Reset() // In case data lingers from previous invocation. - dec.err = nil - id := dec.decodeTypeSequence(false) - if dec.err == nil { - dec.decodeValue(id, v) - } - return dec.err -} - -// If debug.go is compiled into the program , debugFunc prints a human-readable -// representation of the gob data read from r by calling that file's Debug function. -// Otherwise it is nil. -var debugFunc func(io.Reader) diff --git a/src/pkg/encoding/gob/doc.go b/src/pkg/encoding/gob/doc.go deleted file mode 100644 index d0acaba1a..000000000 --- a/src/pkg/encoding/gob/doc.go +++ /dev/null @@ -1,386 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -/* -Package gob manages streams of gobs - binary values exchanged between an -Encoder (transmitter) and a Decoder (receiver). A typical use is transporting -arguments and results of remote procedure calls (RPCs) such as those provided by -package "rpc". - -The implementation compiles a custom codec for each data type in the stream and -is most efficient when a single Encoder is used to transmit a stream of values, -amortizing the cost of compilation. - -Basics - -A stream of gobs is self-describing. Each data item in the stream is preceded by -a specification of its type, expressed in terms of a small set of predefined -types. Pointers are not transmitted, but the things they point to are -transmitted; that is, the values are flattened. Recursive types work fine, but -recursive values (data with cycles) are problematic. This may change. - -To use gobs, create an Encoder and present it with a series of data items as -values or addresses that can be dereferenced to values. The Encoder makes sure -all type information is sent before it is needed. At the receive side, a -Decoder retrieves values from the encoded stream and unpacks them into local -variables. - -Types and Values - -The source and destination values/types need not correspond exactly. For structs, -fields (identified by name) that are in the source but absent from the receiving -variable will be ignored. Fields that are in the receiving variable but missing -from the transmitted type or value will be ignored in the destination. If a field -with the same name is present in both, their types must be compatible. Both the -receiver and transmitter will do all necessary indirection and dereferencing to -convert between gobs and actual Go values. For instance, a gob type that is -schematically, - - struct { A, B int } - -can be sent from or received into any of these Go types: - - struct { A, B int } // the same - *struct { A, B int } // extra indirection of the struct - struct { *A, **B int } // extra indirection of the fields - struct { A, B int64 } // different concrete value type; see below - -It may also be received into any of these: - - struct { A, B int } // the same - struct { B, A int } // ordering doesn't matter; matching is by name - struct { A, B, C int } // extra field (C) ignored - struct { B int } // missing field (A) ignored; data will be dropped - struct { B, C int } // missing field (A) ignored; extra field (C) ignored. - -Attempting to receive into these types will draw a decode error: - - struct { A int; B uint } // change of signedness for B - struct { A int; B float } // change of type for B - struct { } // no field names in common - struct { C, D int } // no field names in common - -Integers are transmitted two ways: arbitrary precision signed integers or -arbitrary precision unsigned integers. There is no int8, int16 etc. -discrimination in the gob format; there are only signed and unsigned integers. As -described below, the transmitter sends the value in a variable-length encoding; -the receiver accepts the value and stores it in the destination variable. -Floating-point numbers are always sent using IEEE-754 64-bit precision (see -below). - -Signed integers may be received into any signed integer variable: int, int16, etc.; -unsigned integers may be received into any unsigned integer variable; and floating -point values may be received into any floating point variable. However, -the destination variable must be able to represent the value or the decode -operation will fail. - -Structs, arrays and slices are also supported. Structs encode and decode only -exported fields. Strings and arrays of bytes are supported with a special, -efficient representation (see below). When a slice is decoded, if the existing -slice has capacity the slice will be extended in place; if not, a new array is -allocated. Regardless, the length of the resulting slice reports the number of -elements decoded. - -Functions and channels will not be sent in a gob. Attempting to encode such a value -at top the level will fail. A struct field of chan or func type is treated exactly -like an unexported field and is ignored. - -Gob can encode a value of any type implementing the GobEncoder or -encoding.BinaryMarshaler interfaces by calling the corresponding method, -in that order of preference. - -Gob can decode a value of any type implementing the GobDecoder or -encoding.BinaryUnmarshaler interfaces by calling the corresponding method, -again in that order of preference. - -Encoding Details - -This section documents the encoding, details that are not important for most -users. Details are presented bottom-up. - -An unsigned integer is sent one of two ways. If it is less than 128, it is sent -as a byte with that value. Otherwise it is sent as a minimal-length big-endian -(high byte first) byte stream holding the value, preceded by one byte holding the -byte count, negated. Thus 0 is transmitted as (00), 7 is transmitted as (07) and -256 is transmitted as (FE 01 00). - -A boolean is encoded within an unsigned integer: 0 for false, 1 for true. - -A signed integer, i, is encoded within an unsigned integer, u. Within u, bits 1 -upward contain the value; bit 0 says whether they should be complemented upon -receipt. The encode algorithm looks like this: - - uint u; - if i < 0 { - u = (^i << 1) | 1 // complement i, bit 0 is 1 - } else { - u = (i << 1) // do not complement i, bit 0 is 0 - } - encodeUnsigned(u) - -The low bit is therefore analogous to a sign bit, but making it the complement bit -instead guarantees that the largest negative integer is not a special case. For -example, -129=^128=(^256>>1) encodes as (FE 01 01). - -Floating-point numbers are always sent as a representation of a float64 value. -That value is converted to a uint64 using math.Float64bits. The uint64 is then -byte-reversed and sent as a regular unsigned integer. The byte-reversal means the -exponent and high-precision part of the mantissa go first. Since the low bits are -often zero, this can save encoding bytes. For instance, 17.0 is encoded in only -three bytes (FE 31 40). - -Strings and slices of bytes are sent as an unsigned count followed by that many -uninterpreted bytes of the value. - -All other slices and arrays are sent as an unsigned count followed by that many -elements using the standard gob encoding for their type, recursively. - -Maps are sent as an unsigned count followed by that many key, element -pairs. Empty but non-nil maps are sent, so if the sender has allocated -a map, the receiver will allocate a map even if no elements are -transmitted. - -Structs are sent as a sequence of (field number, field value) pairs. The field -value is sent using the standard gob encoding for its type, recursively. If a -field has the zero value for its type, it is omitted from the transmission. The -field number is defined by the type of the encoded struct: the first field of the -encoded type is field 0, the second is field 1, etc. When encoding a value, the -field numbers are delta encoded for efficiency and the fields are always sent in -order of increasing field number; the deltas are therefore unsigned. The -initialization for the delta encoding sets the field number to -1, so an unsigned -integer field 0 with value 7 is transmitted as unsigned delta = 1, unsigned value -= 7 or (01 07). Finally, after all the fields have been sent a terminating mark -denotes the end of the struct. That mark is a delta=0 value, which has -representation (00). - -Interface types are not checked for compatibility; all interface types are -treated, for transmission, as members of a single "interface" type, analogous to -int or []byte - in effect they're all treated as interface{}. Interface values -are transmitted as a string identifying the concrete type being sent (a name -that must be pre-defined by calling Register), followed by a byte count of the -length of the following data (so the value can be skipped if it cannot be -stored), followed by the usual encoding of concrete (dynamic) value stored in -the interface value. (A nil interface value is identified by the empty string -and transmits no value.) Upon receipt, the decoder verifies that the unpacked -concrete item satisfies the interface of the receiving variable. - -The representation of types is described below. When a type is defined on a given -connection between an Encoder and Decoder, it is assigned a signed integer type -id. When Encoder.Encode(v) is called, it makes sure there is an id assigned for -the type of v and all its elements and then it sends the pair (typeid, encoded-v) -where typeid is the type id of the encoded type of v and encoded-v is the gob -encoding of the value v. - -To define a type, the encoder chooses an unused, positive type id and sends the -pair (-type id, encoded-type) where encoded-type is the gob encoding of a wireType -description, constructed from these types: - - type wireType struct { - ArrayT *ArrayType - SliceT *SliceType - StructT *StructType - MapT *MapType - } - type arrayType struct { - CommonType - Elem typeId - Len int - } - type CommonType struct { - Name string // the name of the struct type - Id int // the id of the type, repeated so it's inside the type - } - type sliceType struct { - CommonType - Elem typeId - } - type structType struct { - CommonType - Field []*fieldType // the fields of the struct. - } - type fieldType struct { - Name string // the name of the field. - Id int // the type id of the field, which must be already defined - } - type mapType struct { - CommonType - Key typeId - Elem typeId - } - -If there are nested type ids, the types for all inner type ids must be defined -before the top-level type id is used to describe an encoded-v. - -For simplicity in setup, the connection is defined to understand these types a -priori, as well as the basic gob types int, uint, etc. Their ids are: - - bool 1 - int 2 - uint 3 - float 4 - []byte 5 - string 6 - complex 7 - interface 8 - // gap for reserved ids. - WireType 16 - ArrayType 17 - CommonType 18 - SliceType 19 - StructType 20 - FieldType 21 - // 22 is slice of fieldType. - MapType 23 - -Finally, each message created by a call to Encode is preceded by an encoded -unsigned integer count of the number of bytes remaining in the message. After -the initial type name, interface values are wrapped the same way; in effect, the -interface value acts like a recursive invocation of Encode. - -In summary, a gob stream looks like - - (byteCount (-type id, encoding of a wireType)* (type id, encoding of a value))* - -where * signifies zero or more repetitions and the type id of a value must -be predefined or be defined before the value in the stream. - -See "Gobs of data" for a design discussion of the gob wire format: -http://golang.org/doc/articles/gobs_of_data.html -*/ -package gob - -/* -Grammar: - -Tokens starting with a lower case letter are terminals; int(n) -and uint(n) represent the signed/unsigned encodings of the value n. - -GobStream: - DelimitedMessage* -DelimitedMessage: - uint(lengthOfMessage) Message -Message: - TypeSequence TypedValue -TypeSequence - (TypeDefinition DelimitedTypeDefinition*)? -DelimitedTypeDefinition: - uint(lengthOfTypeDefinition) TypeDefinition -TypedValue: - int(typeId) Value -TypeDefinition: - int(-typeId) encodingOfWireType -Value: - SingletonValue | StructValue -SingletonValue: - uint(0) FieldValue -FieldValue: - builtinValue | ArrayValue | MapValue | SliceValue | StructValue | InterfaceValue -InterfaceValue: - NilInterfaceValue | NonNilInterfaceValue -NilInterfaceValue: - uint(0) -NonNilInterfaceValue: - ConcreteTypeName TypeSequence InterfaceContents -ConcreteTypeName: - uint(lengthOfName) [already read=n] name -InterfaceContents: - int(concreteTypeId) DelimitedValue -DelimitedValue: - uint(length) Value -ArrayValue: - uint(n) FieldValue*n [n elements] -MapValue: - uint(n) (FieldValue FieldValue)*n [n (key, value) pairs] -SliceValue: - uint(n) FieldValue*n [n elements] -StructValue: - (uint(fieldDelta) FieldValue)* -*/ - -/* -For implementers and the curious, here is an encoded example. Given - type Point struct {X, Y int} -and the value - p := Point{22, 33} -the bytes transmitted that encode p will be: - 1f ff 81 03 01 01 05 50 6f 69 6e 74 01 ff 82 00 - 01 02 01 01 58 01 04 00 01 01 59 01 04 00 00 00 - 07 ff 82 01 2c 01 42 00 -They are determined as follows. - -Since this is the first transmission of type Point, the type descriptor -for Point itself must be sent before the value. This is the first type -we've sent on this Encoder, so it has type id 65 (0 through 64 are -reserved). - - 1f // This item (a type descriptor) is 31 bytes long. - ff 81 // The negative of the id for the type we're defining, -65. - // This is one byte (indicated by FF = -1) followed by - // ^-65<<1 | 1. The low 1 bit signals to complement the - // rest upon receipt. - - // Now we send a type descriptor, which is itself a struct (wireType). - // The type of wireType itself is known (it's built in, as is the type of - // all its components), so we just need to send a *value* of type wireType - // that represents type "Point". - // Here starts the encoding of that value. - // Set the field number implicitly to -1; this is done at the beginning - // of every struct, including nested structs. - 03 // Add 3 to field number; now 2 (wireType.structType; this is a struct). - // structType starts with an embedded CommonType, which appears - // as a regular structure here too. - 01 // add 1 to field number (now 0); start of embedded CommonType. - 01 // add 1 to field number (now 0, the name of the type) - 05 // string is (unsigned) 5 bytes long - 50 6f 69 6e 74 // wireType.structType.CommonType.name = "Point" - 01 // add 1 to field number (now 1, the id of the type) - ff 82 // wireType.structType.CommonType._id = 65 - 00 // end of embedded wiretype.structType.CommonType struct - 01 // add 1 to field number (now 1, the field array in wireType.structType) - 02 // There are two fields in the type (len(structType.field)) - 01 // Start of first field structure; add 1 to get field number 0: field[0].name - 01 // 1 byte - 58 // structType.field[0].name = "X" - 01 // Add 1 to get field number 1: field[0].id - 04 // structType.field[0].typeId is 2 (signed int). - 00 // End of structType.field[0]; start structType.field[1]; set field number to -1. - 01 // Add 1 to get field number 0: field[1].name - 01 // 1 byte - 59 // structType.field[1].name = "Y" - 01 // Add 1 to get field number 1: field[1].id - 04 // struct.Type.field[1].typeId is 2 (signed int). - 00 // End of structType.field[1]; end of structType.field. - 00 // end of wireType.structType structure - 00 // end of wireType structure - -Now we can send the Point value. Again the field number resets to -1: - - 07 // this value is 7 bytes long - ff 82 // the type number, 65 (1 byte (-FF) followed by 65<<1) - 01 // add one to field number, yielding field 0 - 2c // encoding of signed "22" (0x22 = 44 = 22<<1); Point.x = 22 - 01 // add one to field number, yielding field 1 - 42 // encoding of signed "33" (0x42 = 66 = 33<<1); Point.y = 33 - 00 // end of structure - -The type encoding is long and fairly intricate but we send it only once. -If p is transmitted a second time, the type is already known so the -output will be just: - - 07 ff 82 01 2c 01 42 00 - -A single non-struct value at top level is transmitted like a field with -delta tag 0. For instance, a signed integer with value 3 presented as -the argument to Encode will emit: - - 03 04 00 06 - -Which represents: - - 03 // this value is 3 bytes long - 04 // the type number, 2, represents an integer - 00 // tag delta 0 - 06 // value 3 - -*/ diff --git a/src/pkg/encoding/gob/dump.go b/src/pkg/encoding/gob/dump.go deleted file mode 100644 index 17238c98d..000000000 --- a/src/pkg/encoding/gob/dump.go +++ /dev/null @@ -1,29 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// +build ignore - -package main - -// Need to compile package gob with debug.go to build this program. -// See comments in debug.go for how to do this. - -import ( - "encoding/gob" - "fmt" - "os" -) - -func main() { - var err error - file := os.Stdin - if len(os.Args) > 1 { - file, err = os.Open(os.Args[1]) - if err != nil { - fmt.Fprintf(os.Stderr, "dump: %s\n", err) - os.Exit(1) - } - } - gob.Debug(file) -} diff --git a/src/pkg/encoding/gob/encode.go b/src/pkg/encoding/gob/encode.go deleted file mode 100644 index 5d35db20e..000000000 --- a/src/pkg/encoding/gob/encode.go +++ /dev/null @@ -1,661 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gob - -import ( - "bytes" - "encoding" - "math" - "reflect" -) - -const uint64Size = 8 - -// encoderState is the global execution state of an instance of the encoder. -// Field numbers are delta encoded and always increase. The field -// number is initialized to -1 so 0 comes out as delta(1). A delta of -// 0 terminates the structure. -type encoderState struct { - enc *Encoder - b *bytes.Buffer - sendZero bool // encoding an array element or map key/value pair; send zero values - fieldnum int // the last field number written. - buf [1 + uint64Size]byte // buffer used by the encoder; here to avoid allocation. - next *encoderState // for free list -} - -func (enc *Encoder) newEncoderState(b *bytes.Buffer) *encoderState { - e := enc.freeList - if e == nil { - e = new(encoderState) - e.enc = enc - } else { - enc.freeList = e.next - } - e.sendZero = false - e.fieldnum = 0 - e.b = b - return e -} - -func (enc *Encoder) freeEncoderState(e *encoderState) { - e.next = enc.freeList - enc.freeList = e -} - -// Unsigned integers have a two-state encoding. If the number is less -// than 128 (0 through 0x7F), its value is written directly. -// Otherwise the value is written in big-endian byte order preceded -// by the byte length, negated. - -// encodeUint writes an encoded unsigned integer to state.b. -func (state *encoderState) encodeUint(x uint64) { - if x <= 0x7F { - err := state.b.WriteByte(uint8(x)) - if err != nil { - error_(err) - } - return - } - i := uint64Size - for x > 0 { - state.buf[i] = uint8(x) - x >>= 8 - i-- - } - state.buf[i] = uint8(i - uint64Size) // = loop count, negated - _, err := state.b.Write(state.buf[i : uint64Size+1]) - if err != nil { - error_(err) - } -} - -// encodeInt writes an encoded signed integer to state.w. -// The low bit of the encoding says whether to bit complement the (other bits of the) -// uint to recover the int. -func (state *encoderState) encodeInt(i int64) { - var x uint64 - if i < 0 { - x = uint64(^i<<1) | 1 - } else { - x = uint64(i << 1) - } - state.encodeUint(uint64(x)) -} - -// encOp is the signature of an encoding operator for a given type. -type encOp func(i *encInstr, state *encoderState, v reflect.Value) - -// The 'instructions' of the encoding machine -type encInstr struct { - op encOp - field int // field number in input - index []int // struct index - indir int // how many pointer indirections to reach the value in the struct -} - -// update emits a field number and updates the state to record its value for delta encoding. -// If the instruction pointer is nil, it does nothing -func (state *encoderState) update(instr *encInstr) { - if instr != nil { - state.encodeUint(uint64(instr.field - state.fieldnum)) - state.fieldnum = instr.field - } -} - -// Each encoder for a composite is responsible for handling any -// indirections associated with the elements of the data structure. -// If any pointer so reached is nil, no bytes are written. If the -// data item is zero, no bytes are written. Single values - ints, -// strings etc. - are indirected before calling their encoders. -// Otherwise, the output (for a scalar) is the field number, as an -// encoded integer, followed by the field data in its appropriate -// format. - -// encIndirect dereferences pv indir times and returns the result. -func encIndirect(pv reflect.Value, indir int) reflect.Value { - for ; indir > 0; indir-- { - if pv.IsNil() { - break - } - pv = pv.Elem() - } - return pv -} - -// encBool encodes the bool referenced by v as an unsigned 0 or 1. -func encBool(i *encInstr, state *encoderState, v reflect.Value) { - b := v.Bool() - if b || state.sendZero { - state.update(i) - if b { - state.encodeUint(1) - } else { - state.encodeUint(0) - } - } -} - -// encInt encodes the signed integer (int int8 int16 int32 int64) referenced by v. -func encInt(i *encInstr, state *encoderState, v reflect.Value) { - value := v.Int() - if value != 0 || state.sendZero { - state.update(i) - state.encodeInt(value) - } -} - -// encUint encodes the unsigned integer (uint uint8 uint16 uint32 uint64 uintptr) referenced by v. -func encUint(i *encInstr, state *encoderState, v reflect.Value) { - value := v.Uint() - if value != 0 || state.sendZero { - state.update(i) - state.encodeUint(value) - } -} - -// floatBits returns a uint64 holding the bits of a floating-point number. -// Floating-point numbers are transmitted as uint64s holding the bits -// of the underlying representation. They are sent byte-reversed, with -// the exponent end coming out first, so integer floating point numbers -// (for example) transmit more compactly. This routine does the -// swizzling. -func floatBits(f float64) uint64 { - u := math.Float64bits(f) - var v uint64 - for i := 0; i < 8; i++ { - v <<= 8 - v |= u & 0xFF - u >>= 8 - } - return v -} - -// encFloat encodes the floating point value (float32 float64) referenced by v. -func encFloat(i *encInstr, state *encoderState, v reflect.Value) { - f := v.Float() - if f != 0 || state.sendZero { - bits := floatBits(f) - state.update(i) - state.encodeUint(bits) - } -} - -// encComplex encodes the complex value (complex64 complex128) referenced by v. -// Complex numbers are just a pair of floating-point numbers, real part first. -func encComplex(i *encInstr, state *encoderState, v reflect.Value) { - c := v.Complex() - if c != 0+0i || state.sendZero { - rpart := floatBits(real(c)) - ipart := floatBits(imag(c)) - state.update(i) - state.encodeUint(rpart) - state.encodeUint(ipart) - } -} - -// encUint8Array encodes the byte array referenced by v. -// Byte arrays are encoded as an unsigned count followed by the raw bytes. -func encUint8Array(i *encInstr, state *encoderState, v reflect.Value) { - b := v.Bytes() - if len(b) > 0 || state.sendZero { - state.update(i) - state.encodeUint(uint64(len(b))) - state.b.Write(b) - } -} - -// encString encodes the string referenced by v. -// Strings are encoded as an unsigned count followed by the raw bytes. -func encString(i *encInstr, state *encoderState, v reflect.Value) { - s := v.String() - if len(s) > 0 || state.sendZero { - state.update(i) - state.encodeUint(uint64(len(s))) - state.b.WriteString(s) - } -} - -// encStructTerminator encodes the end of an encoded struct -// as delta field number of 0. -func encStructTerminator(i *encInstr, state *encoderState, v reflect.Value) { - state.encodeUint(0) -} - -// Execution engine - -// encEngine an array of instructions indexed by field number of the encoding -// data, typically a struct. It is executed top to bottom, walking the struct. -type encEngine struct { - instr []encInstr -} - -const singletonField = 0 - -// valid reports whether the value is valid and a non-nil pointer. -// (Slices, maps, and chans take care of themselves.) -func valid(v reflect.Value) bool { - switch v.Kind() { - case reflect.Invalid: - return false - case reflect.Ptr: - return !v.IsNil() - } - return true -} - -// encodeSingle encodes a single top-level non-struct value. -func (enc *Encoder) encodeSingle(b *bytes.Buffer, engine *encEngine, value reflect.Value) { - state := enc.newEncoderState(b) - defer enc.freeEncoderState(state) - state.fieldnum = singletonField - // There is no surrounding struct to frame the transmission, so we must - // generate data even if the item is zero. To do this, set sendZero. - state.sendZero = true - instr := &engine.instr[singletonField] - if instr.indir > 0 { - value = encIndirect(value, instr.indir) - } - if valid(value) { - instr.op(instr, state, value) - } -} - -// encodeStruct encodes a single struct value. -func (enc *Encoder) encodeStruct(b *bytes.Buffer, engine *encEngine, value reflect.Value) { - if !valid(value) { - return - } - state := enc.newEncoderState(b) - defer enc.freeEncoderState(state) - state.fieldnum = -1 - for i := 0; i < len(engine.instr); i++ { - instr := &engine.instr[i] - if i >= value.NumField() { - // encStructTerminator - instr.op(instr, state, reflect.Value{}) - break - } - field := value.FieldByIndex(instr.index) - if instr.indir > 0 { - field = encIndirect(field, instr.indir) - } - if !valid(field) { - continue - } - instr.op(instr, state, field) - } -} - -// encodeArray encodes the array whose 0th element is at p. -func (enc *Encoder) encodeArray(b *bytes.Buffer, value reflect.Value, op encOp, elemIndir int, length int) { - state := enc.newEncoderState(b) - defer enc.freeEncoderState(state) - state.fieldnum = -1 - state.sendZero = true - state.encodeUint(uint64(length)) - for i := 0; i < length; i++ { - elem := value.Index(i) - if elemIndir > 0 { - elem = encIndirect(elem, elemIndir) - if !valid(elem) { - errorf("encodeArray: nil element") - } - } - op(nil, state, elem) - } -} - -// encodeReflectValue is a helper for maps. It encodes the value v. -func encodeReflectValue(state *encoderState, v reflect.Value, op encOp, indir int) { - for i := 0; i < indir && v.IsValid(); i++ { - v = reflect.Indirect(v) - } - if !v.IsValid() { - errorf("encodeReflectValue: nil element") - } - op(nil, state, v) -} - -// encodeMap encodes a map as unsigned count followed by key:value pairs. -func (enc *Encoder) encodeMap(b *bytes.Buffer, mv reflect.Value, keyOp, elemOp encOp, keyIndir, elemIndir int) { - state := enc.newEncoderState(b) - state.fieldnum = -1 - state.sendZero = true - keys := mv.MapKeys() - state.encodeUint(uint64(len(keys))) - for _, key := range keys { - encodeReflectValue(state, key, keyOp, keyIndir) - encodeReflectValue(state, mv.MapIndex(key), elemOp, elemIndir) - } - enc.freeEncoderState(state) -} - -// encodeInterface encodes the interface value iv. -// To send an interface, we send a string identifying the concrete type, followed -// by the type identifier (which might require defining that type right now), followed -// by the concrete value. A nil value gets sent as the empty string for the name, -// followed by no value. -func (enc *Encoder) encodeInterface(b *bytes.Buffer, iv reflect.Value) { - // Gobs can encode nil interface values but not typed interface - // values holding nil pointers, since nil pointers point to no value. - elem := iv.Elem() - if elem.Kind() == reflect.Ptr && elem.IsNil() { - errorf("gob: cannot encode nil pointer of type %s inside interface", iv.Elem().Type()) - } - state := enc.newEncoderState(b) - state.fieldnum = -1 - state.sendZero = true - if iv.IsNil() { - state.encodeUint(0) - return - } - - ut := userType(iv.Elem().Type()) - registerLock.RLock() - name, ok := concreteTypeToName[ut.base] - registerLock.RUnlock() - if !ok { - errorf("type not registered for interface: %s", ut.base) - } - // Send the name. - state.encodeUint(uint64(len(name))) - _, err := state.b.WriteString(name) - if err != nil { - error_(err) - } - // Define the type id if necessary. - enc.sendTypeDescriptor(enc.writer(), state, ut) - // Send the type id. - enc.sendTypeId(state, ut) - // Encode the value into a new buffer. Any nested type definitions - // should be written to b, before the encoded value. - enc.pushWriter(b) - data := new(bytes.Buffer) - data.Write(spaceForLength) - enc.encode(data, elem, ut) - if enc.err != nil { - error_(enc.err) - } - enc.popWriter() - enc.writeMessage(b, data) - if enc.err != nil { - error_(err) - } - enc.freeEncoderState(state) -} - -// isZero reports whether the value is the zero of its type. -func isZero(val reflect.Value) bool { - switch val.Kind() { - case reflect.Array: - for i := 0; i < val.Len(); i++ { - if !isZero(val.Index(i)) { - return false - } - } - return true - case reflect.Map, reflect.Slice, reflect.String: - return val.Len() == 0 - case reflect.Bool: - return !val.Bool() - case reflect.Complex64, reflect.Complex128: - return val.Complex() == 0 - case reflect.Chan, reflect.Func, reflect.Interface, reflect.Ptr: - return val.IsNil() - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return val.Int() == 0 - case reflect.Float32, reflect.Float64: - return val.Float() == 0 - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return val.Uint() == 0 - case reflect.Struct: - for i := 0; i < val.NumField(); i++ { - if !isZero(val.Field(i)) { - return false - } - } - return true - } - panic("unknown type in isZero " + val.Type().String()) -} - -// encGobEncoder encodes a value that implements the GobEncoder interface. -// The data is sent as a byte array. -func (enc *Encoder) encodeGobEncoder(b *bytes.Buffer, ut *userTypeInfo, v reflect.Value) { - // TODO: should we catch panics from the called method? - - var data []byte - var err error - // We know it's one of these. - switch ut.externalEnc { - case xGob: - data, err = v.Interface().(GobEncoder).GobEncode() - case xBinary: - data, err = v.Interface().(encoding.BinaryMarshaler).MarshalBinary() - case xText: - data, err = v.Interface().(encoding.TextMarshaler).MarshalText() - } - if err != nil { - error_(err) - } - state := enc.newEncoderState(b) - state.fieldnum = -1 - state.encodeUint(uint64(len(data))) - state.b.Write(data) - enc.freeEncoderState(state) -} - -var encOpTable = [...]encOp{ - reflect.Bool: encBool, - reflect.Int: encInt, - reflect.Int8: encInt, - reflect.Int16: encInt, - reflect.Int32: encInt, - reflect.Int64: encInt, - reflect.Uint: encUint, - reflect.Uint8: encUint, - reflect.Uint16: encUint, - reflect.Uint32: encUint, - reflect.Uint64: encUint, - reflect.Uintptr: encUint, - reflect.Float32: encFloat, - reflect.Float64: encFloat, - reflect.Complex64: encComplex, - reflect.Complex128: encComplex, - reflect.String: encString, -} - -// encOpFor returns (a pointer to) the encoding op for the base type under rt and -// the indirection count to reach it. -func encOpFor(rt reflect.Type, inProgress map[reflect.Type]*encOp) (*encOp, int) { - ut := userType(rt) - // If the type implements GobEncoder, we handle it without further processing. - if ut.externalEnc != 0 { - return gobEncodeOpFor(ut) - } - // If this type is already in progress, it's a recursive type (e.g. map[string]*T). - // Return the pointer to the op we're already building. - if opPtr := inProgress[rt]; opPtr != nil { - return opPtr, ut.indir - } - typ := ut.base - indir := ut.indir - k := typ.Kind() - var op encOp - if int(k) < len(encOpTable) { - op = encOpTable[k] - } - if op == nil { - inProgress[rt] = &op - // Special cases - switch t := typ; t.Kind() { - case reflect.Slice: - if t.Elem().Kind() == reflect.Uint8 { - op = encUint8Array - break - } - // Slices have a header; we decode it to find the underlying array. - elemOp, elemIndir := encOpFor(t.Elem(), inProgress) - op = func(i *encInstr, state *encoderState, slice reflect.Value) { - if !state.sendZero && slice.Len() == 0 { - return - } - state.update(i) - state.enc.encodeArray(state.b, slice, *elemOp, elemIndir, slice.Len()) - } - case reflect.Array: - // True arrays have size in the type. - elemOp, elemIndir := encOpFor(t.Elem(), inProgress) - op = func(i *encInstr, state *encoderState, array reflect.Value) { - state.update(i) - state.enc.encodeArray(state.b, array, *elemOp, elemIndir, array.Len()) - } - case reflect.Map: - keyOp, keyIndir := encOpFor(t.Key(), inProgress) - elemOp, elemIndir := encOpFor(t.Elem(), inProgress) - op = func(i *encInstr, state *encoderState, mv reflect.Value) { - // We send zero-length (but non-nil) maps because the - // receiver might want to use the map. (Maps don't use append.) - if !state.sendZero && mv.IsNil() { - return - } - state.update(i) - state.enc.encodeMap(state.b, mv, *keyOp, *elemOp, keyIndir, elemIndir) - } - case reflect.Struct: - // Generate a closure that calls out to the engine for the nested type. - getEncEngine(userType(typ)) - info := mustGetTypeInfo(typ) - op = func(i *encInstr, state *encoderState, sv reflect.Value) { - state.update(i) - // indirect through info to delay evaluation for recursive structs - state.enc.encodeStruct(state.b, info.encoder, sv) - } - case reflect.Interface: - op = func(i *encInstr, state *encoderState, iv reflect.Value) { - if !state.sendZero && (!iv.IsValid() || iv.IsNil()) { - return - } - state.update(i) - state.enc.encodeInterface(state.b, iv) - } - } - } - if op == nil { - errorf("can't happen: encode type %s", rt) - } - return &op, indir -} - -// gobEncodeOpFor returns the op for a type that is known to implement GobEncoder. -func gobEncodeOpFor(ut *userTypeInfo) (*encOp, int) { - rt := ut.user - if ut.encIndir == -1 { - rt = reflect.PtrTo(rt) - } else if ut.encIndir > 0 { - for i := int8(0); i < ut.encIndir; i++ { - rt = rt.Elem() - } - } - var op encOp - op = func(i *encInstr, state *encoderState, v reflect.Value) { - if ut.encIndir == -1 { - // Need to climb up one level to turn value into pointer. - if !v.CanAddr() { - errorf("unaddressable value of type %s", rt) - } - v = v.Addr() - } - if !state.sendZero && isZero(v) { - return - } - state.update(i) - state.enc.encodeGobEncoder(state.b, ut, v) - } - return &op, int(ut.encIndir) // encIndir: op will get called with p == address of receiver. -} - -// compileEnc returns the engine to compile the type. -func compileEnc(ut *userTypeInfo) *encEngine { - srt := ut.base - engine := new(encEngine) - seen := make(map[reflect.Type]*encOp) - rt := ut.base - if ut.externalEnc != 0 { - rt = ut.user - } - if ut.externalEnc == 0 && srt.Kind() == reflect.Struct { - for fieldNum, wireFieldNum := 0, 0; fieldNum < srt.NumField(); fieldNum++ { - f := srt.Field(fieldNum) - if !isSent(&f) { - continue - } - op, indir := encOpFor(f.Type, seen) - engine.instr = append(engine.instr, encInstr{*op, wireFieldNum, f.Index, indir}) - wireFieldNum++ - } - if srt.NumField() > 0 && len(engine.instr) == 0 { - errorf("type %s has no exported fields", rt) - } - engine.instr = append(engine.instr, encInstr{encStructTerminator, 0, nil, 0}) - } else { - engine.instr = make([]encInstr, 1) - op, indir := encOpFor(rt, seen) - engine.instr[0] = encInstr{*op, singletonField, nil, indir} - } - return engine -} - -// getEncEngine returns the engine to compile the type. -// typeLock must be held (or we're in initialization and guaranteed single-threaded). -func getEncEngine(ut *userTypeInfo) *encEngine { - info, err1 := getTypeInfo(ut) - if err1 != nil { - error_(err1) - } - if info.encoder == nil { - // Assign the encEngine now, so recursive types work correctly. But... - info.encoder = new(encEngine) - // ... if we fail to complete building the engine, don't cache the half-built machine. - // Doing this here means we won't cache a type that is itself OK but - // that contains a nested type that won't compile. The result is consistent - // error behavior when Encode is called multiple times on the top-level type. - ok := false - defer func() { - if !ok { - info.encoder = nil - } - }() - info.encoder = compileEnc(ut) - ok = true - } - return info.encoder -} - -// lockAndGetEncEngine is a function that locks and compiles. -// This lets us hold the lock only while compiling, not when encoding. -func lockAndGetEncEngine(ut *userTypeInfo) *encEngine { - typeLock.Lock() - defer typeLock.Unlock() - return getEncEngine(ut) -} - -func (enc *Encoder) encode(b *bytes.Buffer, value reflect.Value, ut *userTypeInfo) { - defer catchError(&enc.err) - engine := lockAndGetEncEngine(ut) - indir := ut.indir - if ut.externalEnc != 0 { - indir = int(ut.encIndir) - } - for i := 0; i < indir; i++ { - value = reflect.Indirect(value) - } - if ut.externalEnc == 0 && value.Type().Kind() == reflect.Struct { - enc.encodeStruct(b, engine, value) - } else { - enc.encodeSingle(b, engine, value) - } -} diff --git a/src/pkg/encoding/gob/encoder.go b/src/pkg/encoding/gob/encoder.go deleted file mode 100644 index a3301c3bd..000000000 --- a/src/pkg/encoding/gob/encoder.go +++ /dev/null @@ -1,253 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gob - -import ( - "bytes" - "io" - "reflect" - "sync" -) - -// An Encoder manages the transmission of type and data information to the -// other side of a connection. -type Encoder struct { - mutex sync.Mutex // each item must be sent atomically - w []io.Writer // where to send the data - sent map[reflect.Type]typeId // which types we've already sent - countState *encoderState // stage for writing counts - freeList *encoderState // list of free encoderStates; avoids reallocation - byteBuf bytes.Buffer // buffer for top-level encoderState - err error -} - -// Before we encode a message, we reserve space at the head of the -// buffer in which to encode its length. This means we can use the -// buffer to assemble the message without another allocation. -const maxLength = 9 // Maximum size of an encoded length. -var spaceForLength = make([]byte, maxLength) - -// NewEncoder returns a new encoder that will transmit on the io.Writer. -func NewEncoder(w io.Writer) *Encoder { - enc := new(Encoder) - enc.w = []io.Writer{w} - enc.sent = make(map[reflect.Type]typeId) - enc.countState = enc.newEncoderState(new(bytes.Buffer)) - return enc -} - -// writer() returns the innermost writer the encoder is using -func (enc *Encoder) writer() io.Writer { - return enc.w[len(enc.w)-1] -} - -// pushWriter adds a writer to the encoder. -func (enc *Encoder) pushWriter(w io.Writer) { - enc.w = append(enc.w, w) -} - -// popWriter pops the innermost writer. -func (enc *Encoder) popWriter() { - enc.w = enc.w[0 : len(enc.w)-1] -} - -func (enc *Encoder) setError(err error) { - if enc.err == nil { // remember the first. - enc.err = err - } -} - -// writeMessage sends the data item preceded by a unsigned count of its length. -func (enc *Encoder) writeMessage(w io.Writer, b *bytes.Buffer) { - // Space has been reserved for the length at the head of the message. - // This is a little dirty: we grab the slice from the bytes.Buffer and massage - // it by hand. - message := b.Bytes() - messageLen := len(message) - maxLength - // Encode the length. - enc.countState.b.Reset() - enc.countState.encodeUint(uint64(messageLen)) - // Copy the length to be a prefix of the message. - offset := maxLength - enc.countState.b.Len() - copy(message[offset:], enc.countState.b.Bytes()) - // Write the data. - _, err := w.Write(message[offset:]) - // Drain the buffer and restore the space at the front for the count of the next message. - b.Reset() - b.Write(spaceForLength) - if err != nil { - enc.setError(err) - } -} - -// sendActualType sends the requested type, without further investigation, unless -// it's been sent before. -func (enc *Encoder) sendActualType(w io.Writer, state *encoderState, ut *userTypeInfo, actual reflect.Type) (sent bool) { - if _, alreadySent := enc.sent[actual]; alreadySent { - return false - } - typeLock.Lock() - info, err := getTypeInfo(ut) - typeLock.Unlock() - if err != nil { - enc.setError(err) - return - } - // Send the pair (-id, type) - // Id: - state.encodeInt(-int64(info.id)) - // Type: - enc.encode(state.b, reflect.ValueOf(info.wire), wireTypeUserInfo) - enc.writeMessage(w, state.b) - if enc.err != nil { - return - } - - // Remember we've sent this type, both what the user gave us and the base type. - enc.sent[ut.base] = info.id - if ut.user != ut.base { - enc.sent[ut.user] = info.id - } - // Now send the inner types - switch st := actual; st.Kind() { - case reflect.Struct: - for i := 0; i < st.NumField(); i++ { - if isExported(st.Field(i).Name) { - enc.sendType(w, state, st.Field(i).Type) - } - } - case reflect.Array, reflect.Slice: - enc.sendType(w, state, st.Elem()) - case reflect.Map: - enc.sendType(w, state, st.Key()) - enc.sendType(w, state, st.Elem()) - } - return true -} - -// sendType sends the type info to the other side, if necessary. -func (enc *Encoder) sendType(w io.Writer, state *encoderState, origt reflect.Type) (sent bool) { - ut := userType(origt) - if ut.externalEnc != 0 { - // The rules are different: regardless of the underlying type's representation, - // we need to tell the other side that the base type is a GobEncoder. - return enc.sendActualType(w, state, ut, ut.base) - } - - // It's a concrete value, so drill down to the base type. - switch rt := ut.base; rt.Kind() { - default: - // Basic types and interfaces do not need to be described. - return - case reflect.Slice: - // If it's []uint8, don't send; it's considered basic. - if rt.Elem().Kind() == reflect.Uint8 { - return - } - // Otherwise we do send. - break - case reflect.Array: - // arrays must be sent so we know their lengths and element types. - break - case reflect.Map: - // maps must be sent so we know their lengths and key/value types. - break - case reflect.Struct: - // structs must be sent so we know their fields. - break - case reflect.Chan, reflect.Func: - // If we get here, it's a field of a struct; ignore it. - return - } - - return enc.sendActualType(w, state, ut, ut.base) -} - -// Encode transmits the data item represented by the empty interface value, -// guaranteeing that all necessary type information has been transmitted first. -func (enc *Encoder) Encode(e interface{}) error { - return enc.EncodeValue(reflect.ValueOf(e)) -} - -// sendTypeDescriptor makes sure the remote side knows about this type. -// It will send a descriptor if this is the first time the type has been -// sent. -func (enc *Encoder) sendTypeDescriptor(w io.Writer, state *encoderState, ut *userTypeInfo) { - // Make sure the type is known to the other side. - // First, have we already sent this type? - rt := ut.base - if ut.externalEnc != 0 { - rt = ut.user - } - if _, alreadySent := enc.sent[rt]; !alreadySent { - // No, so send it. - sent := enc.sendType(w, state, rt) - if enc.err != nil { - return - } - // If the type info has still not been transmitted, it means we have - // a singleton basic type (int, []byte etc.) at top level. We don't - // need to send the type info but we do need to update enc.sent. - if !sent { - typeLock.Lock() - info, err := getTypeInfo(ut) - typeLock.Unlock() - if err != nil { - enc.setError(err) - return - } - enc.sent[rt] = info.id - } - } -} - -// sendTypeId sends the id, which must have already been defined. -func (enc *Encoder) sendTypeId(state *encoderState, ut *userTypeInfo) { - // Identify the type of this top-level value. - state.encodeInt(int64(enc.sent[ut.base])) -} - -// EncodeValue transmits the data item represented by the reflection value, -// guaranteeing that all necessary type information has been transmitted first. -func (enc *Encoder) EncodeValue(value reflect.Value) error { - // Gobs contain values. They cannot represent nil pointers, which - // have no value to encode. - if value.Kind() == reflect.Ptr && value.IsNil() { - panic("gob: cannot encode nil pointer of type " + value.Type().String()) - } - - // Make sure we're single-threaded through here, so multiple - // goroutines can share an encoder. - enc.mutex.Lock() - defer enc.mutex.Unlock() - - // Remove any nested writers remaining due to previous errors. - enc.w = enc.w[0:1] - - ut, err := validUserType(value.Type()) - if err != nil { - return err - } - - enc.err = nil - enc.byteBuf.Reset() - enc.byteBuf.Write(spaceForLength) - state := enc.newEncoderState(&enc.byteBuf) - - enc.sendTypeDescriptor(enc.writer(), state, ut) - enc.sendTypeId(state, ut) - if enc.err != nil { - return enc.err - } - - // Encode the object. - enc.encode(state.b, value, ut) - if enc.err == nil { - enc.writeMessage(enc.writer(), state.b) - } - - enc.freeEncoderState(state) - return enc.err -} diff --git a/src/pkg/encoding/gob/encoder_test.go b/src/pkg/encoding/gob/encoder_test.go deleted file mode 100644 index 376df82f1..000000000 --- a/src/pkg/encoding/gob/encoder_test.go +++ /dev/null @@ -1,934 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gob - -import ( - "bytes" - "fmt" - "io" - "reflect" - "strings" - "testing" -) - -// Test basic operations in a safe manner. -func TestBasicEncoderDecoder(t *testing.T) { - var values = []interface{}{ - true, - int(123), - int8(123), - int16(-12345), - int32(123456), - int64(-1234567), - uint(123), - uint8(123), - uint16(12345), - uint32(123456), - uint64(1234567), - uintptr(12345678), - float32(1.2345), - float64(1.2345678), - complex64(1.2345 + 2.3456i), - complex128(1.2345678 + 2.3456789i), - []byte("hello"), - string("hello"), - } - for _, value := range values { - b := new(bytes.Buffer) - enc := NewEncoder(b) - err := enc.Encode(value) - if err != nil { - t.Error("encoder fail:", err) - } - dec := NewDecoder(b) - result := reflect.New(reflect.TypeOf(value)) - err = dec.Decode(result.Interface()) - if err != nil { - t.Fatalf("error decoding %T: %v:", reflect.TypeOf(value), err) - } - if !reflect.DeepEqual(value, result.Elem().Interface()) { - t.Fatalf("%T: expected %v got %v", value, value, result.Elem().Interface()) - } - } -} - -type ET0 struct { - A int - B string -} - -type ET2 struct { - X string -} - -type ET1 struct { - A int - Et2 *ET2 - Next *ET1 -} - -// Like ET1 but with a different name for a field -type ET3 struct { - A int - Et2 *ET2 - DifferentNext *ET1 -} - -// Like ET1 but with a different type for a field -type ET4 struct { - A int - Et2 float64 - Next int -} - -func TestEncoderDecoder(t *testing.T) { - b := new(bytes.Buffer) - enc := NewEncoder(b) - et0 := new(ET0) - et0.A = 7 - et0.B = "gobs of fun" - err := enc.Encode(et0) - if err != nil { - t.Error("encoder fail:", err) - } - //fmt.Printf("% x %q\n", b, b) - //Debug(b) - dec := NewDecoder(b) - newEt0 := new(ET0) - err = dec.Decode(newEt0) - if err != nil { - t.Fatal("error decoding ET0:", err) - } - - if !reflect.DeepEqual(et0, newEt0) { - t.Fatalf("invalid data for et0: expected %+v; got %+v", *et0, *newEt0) - } - if b.Len() != 0 { - t.Error("not at eof;", b.Len(), "bytes left") - } - // t.FailNow() - - b = new(bytes.Buffer) - enc = NewEncoder(b) - et1 := new(ET1) - et1.A = 7 - et1.Et2 = new(ET2) - err = enc.Encode(et1) - if err != nil { - t.Error("encoder fail:", err) - } - dec = NewDecoder(b) - newEt1 := new(ET1) - err = dec.Decode(newEt1) - if err != nil { - t.Fatal("error decoding ET1:", err) - } - - if !reflect.DeepEqual(et1, newEt1) { - t.Fatalf("invalid data for et1: expected %+v; got %+v", *et1, *newEt1) - } - if b.Len() != 0 { - t.Error("not at eof;", b.Len(), "bytes left") - } - - enc.Encode(et1) - newEt1 = new(ET1) - err = dec.Decode(newEt1) - if err != nil { - t.Fatal("round 2: error decoding ET1:", err) - } - if !reflect.DeepEqual(et1, newEt1) { - t.Fatalf("round 2: invalid data for et1: expected %+v; got %+v", *et1, *newEt1) - } - if b.Len() != 0 { - t.Error("round 2: not at eof;", b.Len(), "bytes left") - } - - // Now test with a running encoder/decoder pair that we recognize a type mismatch. - err = enc.Encode(et1) - if err != nil { - t.Error("round 3: encoder fail:", err) - } - newEt2 := new(ET2) - err = dec.Decode(newEt2) - if err == nil { - t.Fatal("round 3: expected `bad type' error decoding ET2") - } -} - -// Run one value through the encoder/decoder, but use the wrong type. -// Input is always an ET1; we compare it to whatever is under 'e'. -func badTypeCheck(e interface{}, shouldFail bool, msg string, t *testing.T) { - b := new(bytes.Buffer) - enc := NewEncoder(b) - et1 := new(ET1) - et1.A = 7 - et1.Et2 = new(ET2) - err := enc.Encode(et1) - if err != nil { - t.Error("encoder fail:", err) - } - dec := NewDecoder(b) - err = dec.Decode(e) - if shouldFail && err == nil { - t.Error("expected error for", msg) - } - if !shouldFail && err != nil { - t.Error("unexpected error for", msg, err) - } -} - -// Test that we recognize a bad type the first time. -func TestWrongTypeDecoder(t *testing.T) { - badTypeCheck(new(ET2), true, "no fields in common", t) - badTypeCheck(new(ET3), false, "different name of field", t) - badTypeCheck(new(ET4), true, "different type of field", t) -} - -func corruptDataCheck(s string, err error, t *testing.T) { - b := bytes.NewBufferString(s) - dec := NewDecoder(b) - err1 := dec.Decode(new(ET2)) - if err1 != err { - t.Errorf("from %q expected error %s; got %s", s, err, err1) - } -} - -// Check that we survive bad data. -func TestBadData(t *testing.T) { - corruptDataCheck("", io.EOF, t) - corruptDataCheck("\x7Fhi", io.ErrUnexpectedEOF, t) - corruptDataCheck("\x03now is the time for all good men", errBadType, t) - // issue 6323. - corruptDataCheck("\x04\x24foo", errRange, t) -} - -// Types not supported at top level by the Encoder. -var unsupportedValues = []interface{}{ - make(chan int), - func(a int) bool { return true }, -} - -func TestUnsupported(t *testing.T) { - var b bytes.Buffer - enc := NewEncoder(&b) - for _, v := range unsupportedValues { - err := enc.Encode(v) - if err == nil { - t.Errorf("expected error for %T; got none", v) - } - } -} - -func encAndDec(in, out interface{}) error { - b := new(bytes.Buffer) - enc := NewEncoder(b) - err := enc.Encode(in) - if err != nil { - return err - } - dec := NewDecoder(b) - err = dec.Decode(out) - if err != nil { - return err - } - return nil -} - -func TestTypeToPtrType(t *testing.T) { - // Encode a T, decode a *T - type Type0 struct { - A int - } - t0 := Type0{7} - t0p := new(Type0) - if err := encAndDec(t0, t0p); err != nil { - t.Error(err) - } -} - -func TestPtrTypeToType(t *testing.T) { - // Encode a *T, decode a T - type Type1 struct { - A uint - } - t1p := &Type1{17} - var t1 Type1 - if err := encAndDec(t1, t1p); err != nil { - t.Error(err) - } -} - -func TestTypeToPtrPtrPtrPtrType(t *testing.T) { - type Type2 struct { - A ****float64 - } - t2 := Type2{} - t2.A = new(***float64) - *t2.A = new(**float64) - **t2.A = new(*float64) - ***t2.A = new(float64) - ****t2.A = 27.4 - t2pppp := new(***Type2) - if err := encAndDec(t2, t2pppp); err != nil { - t.Fatal(err) - } - if ****(****t2pppp).A != ****t2.A { - t.Errorf("wrong value after decode: %g not %g", ****(****t2pppp).A, ****t2.A) - } -} - -func TestSlice(t *testing.T) { - type Type3 struct { - A []string - } - t3p := &Type3{[]string{"hello", "world"}} - var t3 Type3 - if err := encAndDec(t3, t3p); err != nil { - t.Error(err) - } -} - -func TestValueError(t *testing.T) { - // Encode a *T, decode a T - type Type4 struct { - A int - } - t4p := &Type4{3} - var t4 Type4 // note: not a pointer. - if err := encAndDec(t4p, t4); err == nil || strings.Index(err.Error(), "pointer") < 0 { - t.Error("expected error about pointer; got", err) - } -} - -func TestArray(t *testing.T) { - type Type5 struct { - A [3]string - B [3]byte - } - type Type6 struct { - A [2]string // can't hold t5.a - } - t5 := Type5{[3]string{"hello", ",", "world"}, [3]byte{1, 2, 3}} - var t5p Type5 - if err := encAndDec(t5, &t5p); err != nil { - t.Error(err) - } - var t6 Type6 - if err := encAndDec(t5, &t6); err == nil { - t.Error("should fail with mismatched array sizes") - } -} - -func TestRecursiveMapType(t *testing.T) { - type recursiveMap map[string]recursiveMap - r1 := recursiveMap{"A": recursiveMap{"B": nil, "C": nil}, "D": nil} - r2 := make(recursiveMap) - if err := encAndDec(r1, &r2); err != nil { - t.Error(err) - } -} - -func TestRecursiveSliceType(t *testing.T) { - type recursiveSlice []recursiveSlice - r1 := recursiveSlice{0: recursiveSlice{0: nil}, 1: nil} - r2 := make(recursiveSlice, 0) - if err := encAndDec(r1, &r2); err != nil { - t.Error(err) - } -} - -// Regression test for bug: must send zero values inside arrays -func TestDefaultsInArray(t *testing.T) { - type Type7 struct { - B []bool - I []int - S []string - F []float64 - } - t7 := Type7{ - []bool{false, false, true}, - []int{0, 0, 1}, - []string{"hi", "", "there"}, - []float64{0, 0, 1}, - } - var t7p Type7 - if err := encAndDec(t7, &t7p); err != nil { - t.Error(err) - } -} - -var testInt int -var testFloat32 float32 -var testString string -var testSlice []string -var testMap map[string]int -var testArray [7]int - -type SingleTest struct { - in interface{} - out interface{} - err string -} - -var singleTests = []SingleTest{ - {17, &testInt, ""}, - {float32(17.5), &testFloat32, ""}, - {"bike shed", &testString, ""}, - {[]string{"bike", "shed", "paint", "color"}, &testSlice, ""}, - {map[string]int{"seven": 7, "twelve": 12}, &testMap, ""}, - {[7]int{4, 55, 0, 0, 0, 0, 0}, &testArray, ""}, // case that once triggered a bug - {[7]int{4, 55, 1, 44, 22, 66, 1234}, &testArray, ""}, - - // Decode errors - {172, &testFloat32, "type"}, -} - -func TestSingletons(t *testing.T) { - b := new(bytes.Buffer) - enc := NewEncoder(b) - dec := NewDecoder(b) - for _, test := range singleTests { - b.Reset() - err := enc.Encode(test.in) - if err != nil { - t.Errorf("error encoding %v: %s", test.in, err) - continue - } - err = dec.Decode(test.out) - switch { - case err != nil && test.err == "": - t.Errorf("error decoding %v: %s", test.in, err) - continue - case err == nil && test.err != "": - t.Errorf("expected error decoding %v: %s", test.in, test.err) - continue - case err != nil && test.err != "": - if strings.Index(err.Error(), test.err) < 0 { - t.Errorf("wrong error decoding %v: wanted %s, got %v", test.in, test.err, err) - } - continue - } - // Get rid of the pointer in the rhs - val := reflect.ValueOf(test.out).Elem().Interface() - if !reflect.DeepEqual(test.in, val) { - t.Errorf("decoding singleton: expected %v got %v", test.in, val) - } - } -} - -func TestStructNonStruct(t *testing.T) { - type Struct struct { - A string - } - type NonStruct string - s := Struct{"hello"} - var sp Struct - if err := encAndDec(s, &sp); err != nil { - t.Error(err) - } - var ns NonStruct - if err := encAndDec(s, &ns); err == nil { - t.Error("should get error for struct/non-struct") - } else if strings.Index(err.Error(), "type") < 0 { - t.Error("for struct/non-struct expected type error; got", err) - } - // Now try the other way - var nsp NonStruct - if err := encAndDec(ns, &nsp); err != nil { - t.Error(err) - } - if err := encAndDec(ns, &s); err == nil { - t.Error("should get error for non-struct/struct") - } else if strings.Index(err.Error(), "type") < 0 { - t.Error("for non-struct/struct expected type error; got", err) - } -} - -type interfaceIndirectTestI interface { - F() bool -} - -type interfaceIndirectTestT struct{} - -func (this *interfaceIndirectTestT) F() bool { - return true -} - -// A version of a bug reported on golang-nuts. Also tests top-level -// slice of interfaces. The issue was registering *T caused T to be -// stored as the concrete type. -func TestInterfaceIndirect(t *testing.T) { - Register(&interfaceIndirectTestT{}) - b := new(bytes.Buffer) - w := []interfaceIndirectTestI{&interfaceIndirectTestT{}} - err := NewEncoder(b).Encode(w) - if err != nil { - t.Fatal("encode error:", err) - } - - var r []interfaceIndirectTestI - err = NewDecoder(b).Decode(&r) - if err != nil { - t.Fatal("decode error:", err) - } -} - -// Now follow various tests that decode into things that can't represent the -// encoded value, all of which should be legal. - -// Also, when the ignored object contains an interface value, it may define -// types. Make sure that skipping the value still defines the types by using -// the encoder/decoder pair to send a value afterwards. If an interface -// is sent, its type in the test is always NewType0, so this checks that the -// encoder and decoder don't skew with respect to type definitions. - -type Struct0 struct { - I interface{} -} - -type NewType0 struct { - S string -} - -type ignoreTest struct { - in, out interface{} -} - -var ignoreTests = []ignoreTest{ - // Decode normal struct into an empty struct - {&struct{ A int }{23}, &struct{}{}}, - // Decode normal struct into a nil. - {&struct{ A int }{23}, nil}, - // Decode singleton string into a nil. - {"hello, world", nil}, - // Decode singleton slice into a nil. - {[]int{1, 2, 3, 4}, nil}, - // Decode struct containing an interface into a nil. - {&Struct0{&NewType0{"value0"}}, nil}, - // Decode singleton slice of interfaces into a nil. - {[]interface{}{"hi", &NewType0{"value1"}, 23}, nil}, -} - -func TestDecodeIntoNothing(t *testing.T) { - Register(new(NewType0)) - for i, test := range ignoreTests { - b := new(bytes.Buffer) - enc := NewEncoder(b) - err := enc.Encode(test.in) - if err != nil { - t.Errorf("%d: encode error %s:", i, err) - continue - } - dec := NewDecoder(b) - err = dec.Decode(test.out) - if err != nil { - t.Errorf("%d: decode error: %s", i, err) - continue - } - // Now see if the encoder and decoder are in a consistent state. - str := fmt.Sprintf("Value %d", i) - err = enc.Encode(&NewType0{str}) - if err != nil { - t.Fatalf("%d: NewType0 encode error: %s", i, err) - } - ns := new(NewType0) - err = dec.Decode(ns) - if err != nil { - t.Fatalf("%d: NewType0 decode error: %s", i, err) - } - if ns.S != str { - t.Fatalf("%d: expected %q got %q", i, str, ns.S) - } - } -} - -// Another bug from golang-nuts, involving nested interfaces. -type Bug0Outer struct { - Bug0Field interface{} -} - -type Bug0Inner struct { - A int -} - -func TestNestedInterfaces(t *testing.T) { - var buf bytes.Buffer - e := NewEncoder(&buf) - d := NewDecoder(&buf) - Register(new(Bug0Outer)) - Register(new(Bug0Inner)) - f := &Bug0Outer{&Bug0Outer{&Bug0Inner{7}}} - var v interface{} = f - err := e.Encode(&v) - if err != nil { - t.Fatal("Encode:", err) - } - err = d.Decode(&v) - if err != nil { - t.Fatal("Decode:", err) - } - // Make sure it decoded correctly. - outer1, ok := v.(*Bug0Outer) - if !ok { - t.Fatalf("v not Bug0Outer: %T", v) - } - outer2, ok := outer1.Bug0Field.(*Bug0Outer) - if !ok { - t.Fatalf("v.Bug0Field not Bug0Outer: %T", outer1.Bug0Field) - } - inner, ok := outer2.Bug0Field.(*Bug0Inner) - if !ok { - t.Fatalf("v.Bug0Field.Bug0Field not Bug0Inner: %T", outer2.Bug0Field) - } - if inner.A != 7 { - t.Fatalf("final value %d; expected %d", inner.A, 7) - } -} - -// The bugs keep coming. We forgot to send map subtypes before the map. - -type Bug1Elem struct { - Name string - Id int -} - -type Bug1StructMap map[string]Bug1Elem - -func bug1EncDec(in Bug1StructMap, out *Bug1StructMap) error { - return nil -} - -func TestMapBug1(t *testing.T) { - in := make(Bug1StructMap) - in["val1"] = Bug1Elem{"elem1", 1} - in["val2"] = Bug1Elem{"elem2", 2} - - b := new(bytes.Buffer) - enc := NewEncoder(b) - err := enc.Encode(in) - if err != nil { - t.Fatal("encode:", err) - } - dec := NewDecoder(b) - out := make(Bug1StructMap) - err = dec.Decode(&out) - if err != nil { - t.Fatal("decode:", err) - } - if !reflect.DeepEqual(in, out) { - t.Errorf("mismatch: %v %v", in, out) - } -} - -func TestGobMapInterfaceEncode(t *testing.T) { - m := map[string]interface{}{ - "up": uintptr(0), - "i0": []int{-1}, - "i1": []int8{-1}, - "i2": []int16{-1}, - "i3": []int32{-1}, - "i4": []int64{-1}, - "u0": []uint{1}, - "u1": []uint8{1}, - "u2": []uint16{1}, - "u3": []uint32{1}, - "u4": []uint64{1}, - "f0": []float32{1}, - "f1": []float64{1}, - "c0": []complex64{complex(2, -2)}, - "c1": []complex128{complex(2, float64(-2))}, - "us": []uintptr{0}, - "bo": []bool{false}, - "st": []string{"s"}, - } - enc := NewEncoder(new(bytes.Buffer)) - err := enc.Encode(m) - if err != nil { - t.Errorf("encode map: %s", err) - } -} - -func TestSliceReusesMemory(t *testing.T) { - buf := new(bytes.Buffer) - // Bytes - { - x := []byte("abcd") - enc := NewEncoder(buf) - err := enc.Encode(x) - if err != nil { - t.Errorf("bytes: encode: %s", err) - } - // Decode into y, which is big enough. - y := []byte("ABCDE") - addr := &y[0] - dec := NewDecoder(buf) - err = dec.Decode(&y) - if err != nil { - t.Fatal("bytes: decode:", err) - } - if !bytes.Equal(x, y) { - t.Errorf("bytes: expected %q got %q\n", x, y) - } - if addr != &y[0] { - t.Errorf("bytes: unnecessary reallocation") - } - } - // general slice - { - x := []rune("abcd") - enc := NewEncoder(buf) - err := enc.Encode(x) - if err != nil { - t.Errorf("ints: encode: %s", err) - } - // Decode into y, which is big enough. - y := []rune("ABCDE") - addr := &y[0] - dec := NewDecoder(buf) - err = dec.Decode(&y) - if err != nil { - t.Fatal("ints: decode:", err) - } - if !reflect.DeepEqual(x, y) { - t.Errorf("ints: expected %q got %q\n", x, y) - } - if addr != &y[0] { - t.Errorf("ints: unnecessary reallocation") - } - } -} - -// Used to crash: negative count in recvMessage. -func TestBadCount(t *testing.T) { - b := []byte{0xfb, 0xa5, 0x82, 0x2f, 0xca, 0x1} - if err := NewDecoder(bytes.NewReader(b)).Decode(nil); err == nil { - t.Error("expected error from bad count") - } else if err.Error() != errBadCount.Error() { - t.Error("expected bad count error; got", err) - } -} - -// Verify that sequential Decoders built on a single input will -// succeed if the input implements ReadByte and there is no -// type information in the stream. -func TestSequentialDecoder(t *testing.T) { - b := new(bytes.Buffer) - enc := NewEncoder(b) - const count = 10 - for i := 0; i < count; i++ { - s := fmt.Sprintf("%d", i) - if err := enc.Encode(s); err != nil { - t.Error("encoder fail:", err) - } - } - for i := 0; i < count; i++ { - dec := NewDecoder(b) - var s string - if err := dec.Decode(&s); err != nil { - t.Fatal("decoder fail:", err) - } - if s != fmt.Sprintf("%d", i) { - t.Fatalf("decode expected %d got %s", i, s) - } - } -} - -// Should be able to have unrepresentable fields (chan, func, *chan etc.); we just ignore them. -type Bug2 struct { - A int - C chan int - CP *chan int - F func() - FPP **func() -} - -func TestChanFuncIgnored(t *testing.T) { - c := make(chan int) - f := func() {} - fp := &f - b0 := Bug2{23, c, &c, f, &fp} - var buf bytes.Buffer - enc := NewEncoder(&buf) - if err := enc.Encode(b0); err != nil { - t.Fatal("error encoding:", err) - } - var b1 Bug2 - err := NewDecoder(&buf).Decode(&b1) - if err != nil { - t.Fatal("decode:", err) - } - if b1.A != b0.A { - t.Fatalf("got %d want %d", b1.A, b0.A) - } - if b1.C != nil || b1.CP != nil || b1.F != nil || b1.FPP != nil { - t.Fatal("unexpected value for chan or func") - } -} - -func TestSliceIncompatibility(t *testing.T) { - var in = []byte{1, 2, 3} - var out []int - if err := encAndDec(in, &out); err == nil { - t.Error("expected compatibility error") - } -} - -// Mutually recursive slices of structs caused problems. -type Bug3 struct { - Num int - Children []*Bug3 -} - -func TestGobPtrSlices(t *testing.T) { - in := []*Bug3{ - {1, nil}, - {2, nil}, - } - b := new(bytes.Buffer) - err := NewEncoder(b).Encode(&in) - if err != nil { - t.Fatal("encode:", err) - } - - var out []*Bug3 - err = NewDecoder(b).Decode(&out) - if err != nil { - t.Fatal("decode:", err) - } - if !reflect.DeepEqual(in, out) { - t.Fatalf("got %v; wanted %v", out, in) - } -} - -// getDecEnginePtr cached engine for ut.base instead of ut.user so we passed -// a *map and then tried to reuse its engine to decode the inner map. -func TestPtrToMapOfMap(t *testing.T) { - Register(make(map[string]interface{})) - subdata := make(map[string]interface{}) - subdata["bar"] = "baz" - data := make(map[string]interface{}) - data["foo"] = subdata - - b := new(bytes.Buffer) - err := NewEncoder(b).Encode(data) - if err != nil { - t.Fatal("encode:", err) - } - var newData map[string]interface{} - err = NewDecoder(b).Decode(&newData) - if err != nil { - t.Fatal("decode:", err) - } - if !reflect.DeepEqual(data, newData) { - t.Fatalf("expected %v got %v", data, newData) - } -} - -// A top-level nil pointer generates a panic with a helpful string-valued message. -func TestTopLevelNilPointer(t *testing.T) { - errMsg := topLevelNilPanic(t) - if errMsg == "" { - t.Fatal("top-level nil pointer did not panic") - } - if !strings.Contains(errMsg, "nil pointer") { - t.Fatal("expected nil pointer error, got:", errMsg) - } -} - -func topLevelNilPanic(t *testing.T) (panicErr string) { - defer func() { - e := recover() - if err, ok := e.(string); ok { - panicErr = err - } - }() - var ip *int - buf := new(bytes.Buffer) - if err := NewEncoder(buf).Encode(ip); err != nil { - t.Fatal("error in encode:", err) - } - return -} - -func TestNilPointerInsideInterface(t *testing.T) { - var ip *int - si := struct { - I interface{} - }{ - I: ip, - } - buf := new(bytes.Buffer) - err := NewEncoder(buf).Encode(si) - if err == nil { - t.Fatal("expected error, got none") - } - errMsg := err.Error() - if !strings.Contains(errMsg, "nil pointer") || !strings.Contains(errMsg, "interface") { - t.Fatal("expected error about nil pointer and interface, got:", errMsg) - } -} - -type Bug4Public struct { - Name string - Secret Bug4Secret -} - -type Bug4Secret struct { - a int // error: no exported fields. -} - -// Test that a failed compilation doesn't leave around an executable encoder. -// Issue 3273. -func TestMutipleEncodingsOfBadType(t *testing.T) { - x := Bug4Public{ - Name: "name", - Secret: Bug4Secret{1}, - } - buf := new(bytes.Buffer) - enc := NewEncoder(buf) - err := enc.Encode(x) - if err == nil { - t.Fatal("first encoding: expected error") - } - buf.Reset() - enc = NewEncoder(buf) - err = enc.Encode(x) - if err == nil { - t.Fatal("second encoding: expected error") - } - if !strings.Contains(err.Error(), "no exported fields") { - t.Errorf("expected error about no exported fields; got %v", err) - } -} - -// There was an error check comparing the length of the input with the -// length of the slice being decoded. It was wrong because the next -// thing in the input might be a type definition, which would lead to -// an incorrect length check. This test reproduces the corner case. - -type Z struct { -} - -func Test29ElementSlice(t *testing.T) { - Register(Z{}) - src := make([]interface{}, 100) // Size needs to be bigger than size of type definition. - for i := range src { - src[i] = Z{} - } - buf := new(bytes.Buffer) - err := NewEncoder(buf).Encode(src) - if err != nil { - t.Fatalf("encode: %v", err) - return - } - - var dst []interface{} - err = NewDecoder(buf).Decode(&dst) - if err != nil { - t.Errorf("decode: %v", err) - return - } -} diff --git a/src/pkg/encoding/gob/error.go b/src/pkg/encoding/gob/error.go deleted file mode 100644 index 92cc0c615..000000000 --- a/src/pkg/encoding/gob/error.go +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gob - -import "fmt" - -// Errors in decoding and encoding are handled using panic and recover. -// Panics caused by user error (that is, everything except run-time panics -// such as "index out of bounds" errors) do not leave the file that caused -// them, but are instead turned into plain error returns. Encoding and -// decoding functions and methods that do not return an error either use -// panic to report an error or are guaranteed error-free. - -// A gobError is used to distinguish errors (panics) generated in this package. -type gobError struct { - err error -} - -// errorf is like error_ but takes Printf-style arguments to construct an error. -// It always prefixes the message with "gob: ". -func errorf(format string, args ...interface{}) { - error_(fmt.Errorf("gob: "+format, args...)) -} - -// error wraps the argument error and uses it as the argument to panic. -func error_(err error) { - panic(gobError{err}) -} - -// catchError is meant to be used as a deferred function to turn a panic(gobError) into a -// plain error. It overwrites the error return of the function that deferred its call. -func catchError(err *error) { - if e := recover(); e != nil { - ge, ok := e.(gobError) - if !ok { - panic(e) - } - *err = ge.err - } - return -} diff --git a/src/pkg/encoding/gob/example_encdec_test.go b/src/pkg/encoding/gob/example_encdec_test.go deleted file mode 100644 index e45ad4ccf..000000000 --- a/src/pkg/encoding/gob/example_encdec_test.go +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gob_test - -import ( - "bytes" - "encoding/gob" - "fmt" - "log" -) - -// The Vector type has unexported fields, which the package cannot access. -// We therefore write a BinaryMarshal/BinaryUnmarshal method pair to allow us -// to send and receive the type with the gob package. These interfaces are -// defined in the "encoding" package. -// We could equivalently use the locally defined GobEncode/GobDecoder -// interfaces. -type Vector struct { - x, y, z int -} - -func (v Vector) MarshalBinary() ([]byte, error) { - // A simple encoding: plain text. - var b bytes.Buffer - fmt.Fprintln(&b, v.x, v.y, v.z) - return b.Bytes(), nil -} - -// UnmarshalBinary modifies the receiver so it must take a pointer receiver. -func (v *Vector) UnmarshalBinary(data []byte) error { - // A simple encoding: plain text. - b := bytes.NewBuffer(data) - _, err := fmt.Fscanln(b, &v.x, &v.y, &v.z) - return err -} - -// This example transmits a value that implements the custom encoding and decoding methods. -func Example_encodeDecode() { - var network bytes.Buffer // Stand-in for the network. - - // Create an encoder and send a value. - enc := gob.NewEncoder(&network) - err := enc.Encode(Vector{3, 4, 5}) - if err != nil { - log.Fatal("encode:", err) - } - - // Create a decoder and receive a value. - dec := gob.NewDecoder(&network) - var v Vector - err = dec.Decode(&v) - if err != nil { - log.Fatal("decode:", err) - } - fmt.Println(v) - - // Output: - // {3 4 5} -} diff --git a/src/pkg/encoding/gob/example_interface_test.go b/src/pkg/encoding/gob/example_interface_test.go deleted file mode 100644 index 4681e6307..000000000 --- a/src/pkg/encoding/gob/example_interface_test.go +++ /dev/null @@ -1,81 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gob_test - -import ( - "bytes" - "encoding/gob" - "fmt" - "log" - "math" -) - -type Point struct { - X, Y int -} - -func (p Point) Hypotenuse() float64 { - return math.Hypot(float64(p.X), float64(p.Y)) -} - -type Pythagoras interface { - Hypotenuse() float64 -} - -// This example shows how to encode an interface value. The key -// distinction from regular types is to register the concrete type that -// implements the interface. -func Example_interface() { - var network bytes.Buffer // Stand-in for the network. - - // We must register the concrete type for the encoder and decoder (which would - // normally be on a separate machine from the encoder). On each end, this tells the - // engine which concrete type is being sent that implements the interface. - gob.Register(Point{}) - - // Create an encoder and send some values. - enc := gob.NewEncoder(&network) - for i := 1; i <= 3; i++ { - interfaceEncode(enc, Point{3 * i, 4 * i}) - } - - // Create a decoder and receive some values. - dec := gob.NewDecoder(&network) - for i := 1; i <= 3; i++ { - result := interfaceDecode(dec) - fmt.Println(result.Hypotenuse()) - } - - // Output: - // 5 - // 10 - // 15 -} - -// interfaceEncode encodes the interface value into the encoder. -func interfaceEncode(enc *gob.Encoder, p Pythagoras) { - // The encode will fail unless the concrete type has been - // registered. We registered it in the calling function. - - // Pass pointer to interface so Encode sees (and hence sends) a value of - // interface type. If we passed p directly it would see the concrete type instead. - // See the blog post, "The Laws of Reflection" for background. - err := enc.Encode(&p) - if err != nil { - log.Fatal("encode:", err) - } -} - -// interfaceDecode decodes the next interface value from the stream and returns it. -func interfaceDecode(dec *gob.Decoder) Pythagoras { - // The decode will fail unless the concrete type on the wire has been - // registered. We registered it in the calling function. - var p Pythagoras - err := dec.Decode(&p) - if err != nil { - log.Fatal("decode:", err) - } - return p -} diff --git a/src/pkg/encoding/gob/example_test.go b/src/pkg/encoding/gob/example_test.go deleted file mode 100644 index 020352cee..000000000 --- a/src/pkg/encoding/gob/example_test.go +++ /dev/null @@ -1,60 +0,0 @@ -// Copyright 2013 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gob_test - -import ( - "bytes" - "encoding/gob" - "fmt" - "log" -) - -type P struct { - X, Y, Z int - Name string -} - -type Q struct { - X, Y *int32 - Name string -} - -// This example shows the basic usage of the package: Create an encoder, -// transmit some values, receive them with a decoder. -func Example_basic() { - // Initialize the encoder and decoder. Normally enc and dec would be - // bound to network connections and the encoder and decoder would - // run in different processes. - var network bytes.Buffer // Stand-in for a network connection - enc := gob.NewEncoder(&network) // Will write to network. - dec := gob.NewDecoder(&network) // Will read from network. - - // Encode (send) some values. - err := enc.Encode(P{3, 4, 5, "Pythagoras"}) - if err != nil { - log.Fatal("encode error:", err) - } - err = enc.Encode(P{1782, 1841, 1922, "Treehouse"}) - if err != nil { - log.Fatal("encode error:", err) - } - - // Decode (receive) and print the values. - var q Q - err = dec.Decode(&q) - if err != nil { - log.Fatal("decode error 1:", err) - } - fmt.Printf("%q: {%d, %d}\n", q.Name, *q.X, *q.Y) - err = dec.Decode(&q) - if err != nil { - log.Fatal("decode error 2:", err) - } - fmt.Printf("%q: {%d, %d}\n", q.Name, *q.X, *q.Y) - - // Output: - // "Pythagoras": {3, 4} - // "Treehouse": {1782, 1841} -} diff --git a/src/pkg/encoding/gob/gobencdec_test.go b/src/pkg/encoding/gob/gobencdec_test.go deleted file mode 100644 index eb76b481d..000000000 --- a/src/pkg/encoding/gob/gobencdec_test.go +++ /dev/null @@ -1,798 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// This file contains tests of the GobEncoder/GobDecoder support. - -package gob - -import ( - "bytes" - "errors" - "fmt" - "io" - "net" - "strings" - "testing" - "time" -) - -// Types that implement the GobEncoder/Decoder interfaces. - -type ByteStruct struct { - a byte // not an exported field -} - -type StringStruct struct { - s string // not an exported field -} - -type ArrayStruct struct { - a [8192]byte // not an exported field -} - -type Gobber int - -type ValueGobber string // encodes with a value, decodes with a pointer. - -type BinaryGobber int - -type BinaryValueGobber string - -type TextGobber int - -type TextValueGobber string - -// The relevant methods - -func (g *ByteStruct) GobEncode() ([]byte, error) { - b := make([]byte, 3) - b[0] = g.a - b[1] = g.a + 1 - b[2] = g.a + 2 - return b, nil -} - -func (g *ByteStruct) GobDecode(data []byte) error { - if g == nil { - return errors.New("NIL RECEIVER") - } - // Expect N sequential-valued bytes. - if len(data) == 0 { - return io.EOF - } - g.a = data[0] - for i, c := range data { - if c != g.a+byte(i) { - return errors.New("invalid data sequence") - } - } - return nil -} - -func (g *StringStruct) GobEncode() ([]byte, error) { - return []byte(g.s), nil -} - -func (g *StringStruct) GobDecode(data []byte) error { - // Expect N sequential-valued bytes. - if len(data) == 0 { - return io.EOF - } - a := data[0] - for i, c := range data { - if c != a+byte(i) { - return errors.New("invalid data sequence") - } - } - g.s = string(data) - return nil -} - -func (a *ArrayStruct) GobEncode() ([]byte, error) { - return a.a[:], nil -} - -func (a *ArrayStruct) GobDecode(data []byte) error { - if len(data) != len(a.a) { - return errors.New("wrong length in array decode") - } - copy(a.a[:], data) - return nil -} - -func (g *Gobber) GobEncode() ([]byte, error) { - return []byte(fmt.Sprintf("VALUE=%d", *g)), nil -} - -func (g *Gobber) GobDecode(data []byte) error { - _, err := fmt.Sscanf(string(data), "VALUE=%d", (*int)(g)) - return err -} - -func (g *BinaryGobber) MarshalBinary() ([]byte, error) { - return []byte(fmt.Sprintf("VALUE=%d", *g)), nil -} - -func (g *BinaryGobber) UnmarshalBinary(data []byte) error { - _, err := fmt.Sscanf(string(data), "VALUE=%d", (*int)(g)) - return err -} - -func (g *TextGobber) MarshalText() ([]byte, error) { - return []byte(fmt.Sprintf("VALUE=%d", *g)), nil -} - -func (g *TextGobber) UnmarshalText(data []byte) error { - _, err := fmt.Sscanf(string(data), "VALUE=%d", (*int)(g)) - return err -} - -func (v ValueGobber) GobEncode() ([]byte, error) { - return []byte(fmt.Sprintf("VALUE=%s", v)), nil -} - -func (v *ValueGobber) GobDecode(data []byte) error { - _, err := fmt.Sscanf(string(data), "VALUE=%s", (*string)(v)) - return err -} - -func (v BinaryValueGobber) MarshalBinary() ([]byte, error) { - return []byte(fmt.Sprintf("VALUE=%s", v)), nil -} - -func (v *BinaryValueGobber) UnmarshalBinary(data []byte) error { - _, err := fmt.Sscanf(string(data), "VALUE=%s", (*string)(v)) - return err -} - -func (v TextValueGobber) MarshalText() ([]byte, error) { - return []byte(fmt.Sprintf("VALUE=%s", v)), nil -} - -func (v *TextValueGobber) UnmarshalText(data []byte) error { - _, err := fmt.Sscanf(string(data), "VALUE=%s", (*string)(v)) - return err -} - -// Structs that include GobEncodable fields. - -type GobTest0 struct { - X int // guarantee we have something in common with GobTest* - G *ByteStruct -} - -type GobTest1 struct { - X int // guarantee we have something in common with GobTest* - G *StringStruct -} - -type GobTest2 struct { - X int // guarantee we have something in common with GobTest* - G string // not a GobEncoder - should give us errors -} - -type GobTest3 struct { - X int // guarantee we have something in common with GobTest* - G *Gobber - B *BinaryGobber - T *TextGobber -} - -type GobTest4 struct { - X int // guarantee we have something in common with GobTest* - V ValueGobber - BV BinaryValueGobber - TV TextValueGobber -} - -type GobTest5 struct { - X int // guarantee we have something in common with GobTest* - V *ValueGobber - BV *BinaryValueGobber - TV *TextValueGobber -} - -type GobTest6 struct { - X int // guarantee we have something in common with GobTest* - V ValueGobber - W *ValueGobber - BV BinaryValueGobber - BW *BinaryValueGobber - TV TextValueGobber - TW *TextValueGobber -} - -type GobTest7 struct { - X int // guarantee we have something in common with GobTest* - V *ValueGobber - W ValueGobber - BV *BinaryValueGobber - BW BinaryValueGobber - TV *TextValueGobber - TW TextValueGobber -} - -type GobTestIgnoreEncoder struct { - X int // guarantee we have something in common with GobTest* -} - -type GobTestValueEncDec struct { - X int // guarantee we have something in common with GobTest* - G StringStruct // not a pointer. -} - -type GobTestIndirectEncDec struct { - X int // guarantee we have something in common with GobTest* - G ***StringStruct // indirections to the receiver. -} - -type GobTestArrayEncDec struct { - X int // guarantee we have something in common with GobTest* - A ArrayStruct // not a pointer. -} - -type GobTestIndirectArrayEncDec struct { - X int // guarantee we have something in common with GobTest* - A ***ArrayStruct // indirections to a large receiver. -} - -func TestGobEncoderField(t *testing.T) { - b := new(bytes.Buffer) - // First a field that's a structure. - enc := NewEncoder(b) - err := enc.Encode(GobTest0{17, &ByteStruct{'A'}}) - if err != nil { - t.Fatal("encode error:", err) - } - dec := NewDecoder(b) - x := new(GobTest0) - err = dec.Decode(x) - if err != nil { - t.Fatal("decode error:", err) - } - if x.G.a != 'A' { - t.Errorf("expected 'A' got %c", x.G.a) - } - // Now a field that's not a structure. - b.Reset() - gobber := Gobber(23) - bgobber := BinaryGobber(24) - tgobber := TextGobber(25) - err = enc.Encode(GobTest3{17, &gobber, &bgobber, &tgobber}) - if err != nil { - t.Fatal("encode error:", err) - } - y := new(GobTest3) - err = dec.Decode(y) - if err != nil { - t.Fatal("decode error:", err) - } - if *y.G != 23 || *y.B != 24 || *y.T != 25 { - t.Errorf("expected '23 got %d", *y.G) - } -} - -// Even though the field is a value, we can still take its address -// and should be able to call the methods. -func TestGobEncoderValueField(t *testing.T) { - b := new(bytes.Buffer) - // First a field that's a structure. - enc := NewEncoder(b) - err := enc.Encode(&GobTestValueEncDec{17, StringStruct{"HIJKL"}}) - if err != nil { - t.Fatal("encode error:", err) - } - dec := NewDecoder(b) - x := new(GobTestValueEncDec) - err = dec.Decode(x) - if err != nil { - t.Fatal("decode error:", err) - } - if x.G.s != "HIJKL" { - t.Errorf("expected `HIJKL` got %s", x.G.s) - } -} - -// GobEncode/Decode should work even if the value is -// more indirect than the receiver. -func TestGobEncoderIndirectField(t *testing.T) { - b := new(bytes.Buffer) - // First a field that's a structure. - enc := NewEncoder(b) - s := &StringStruct{"HIJKL"} - sp := &s - err := enc.Encode(GobTestIndirectEncDec{17, &sp}) - if err != nil { - t.Fatal("encode error:", err) - } - dec := NewDecoder(b) - x := new(GobTestIndirectEncDec) - err = dec.Decode(x) - if err != nil { - t.Fatal("decode error:", err) - } - if (***x.G).s != "HIJKL" { - t.Errorf("expected `HIJKL` got %s", (***x.G).s) - } -} - -// Test with a large field with methods. -func TestGobEncoderArrayField(t *testing.T) { - b := new(bytes.Buffer) - enc := NewEncoder(b) - var a GobTestArrayEncDec - a.X = 17 - for i := range a.A.a { - a.A.a[i] = byte(i) - } - err := enc.Encode(&a) - if err != nil { - t.Fatal("encode error:", err) - } - dec := NewDecoder(b) - x := new(GobTestArrayEncDec) - err = dec.Decode(x) - if err != nil { - t.Fatal("decode error:", err) - } - for i, v := range x.A.a { - if v != byte(i) { - t.Errorf("expected %x got %x", byte(i), v) - break - } - } -} - -// Test an indirection to a large field with methods. -func TestGobEncoderIndirectArrayField(t *testing.T) { - b := new(bytes.Buffer) - enc := NewEncoder(b) - var a GobTestIndirectArrayEncDec - a.X = 17 - var array ArrayStruct - ap := &array - app := &ap - a.A = &app - for i := range array.a { - array.a[i] = byte(i) - } - err := enc.Encode(a) - if err != nil { - t.Fatal("encode error:", err) - } - dec := NewDecoder(b) - x := new(GobTestIndirectArrayEncDec) - err = dec.Decode(x) - if err != nil { - t.Fatal("decode error:", err) - } - for i, v := range (***x.A).a { - if v != byte(i) { - t.Errorf("expected %x got %x", byte(i), v) - break - } - } -} - -// As long as the fields have the same name and implement the -// interface, we can cross-connect them. Not sure it's useful -// and may even be bad but it works and it's hard to prevent -// without exposing the contents of the object, which would -// defeat the purpose. -func TestGobEncoderFieldsOfDifferentType(t *testing.T) { - // first, string in field to byte in field - b := new(bytes.Buffer) - enc := NewEncoder(b) - err := enc.Encode(GobTest1{17, &StringStruct{"ABC"}}) - if err != nil { - t.Fatal("encode error:", err) - } - dec := NewDecoder(b) - x := new(GobTest0) - err = dec.Decode(x) - if err != nil { - t.Fatal("decode error:", err) - } - if x.G.a != 'A' { - t.Errorf("expected 'A' got %c", x.G.a) - } - // now the other direction, byte in field to string in field - b.Reset() - err = enc.Encode(GobTest0{17, &ByteStruct{'X'}}) - if err != nil { - t.Fatal("encode error:", err) - } - y := new(GobTest1) - err = dec.Decode(y) - if err != nil { - t.Fatal("decode error:", err) - } - if y.G.s != "XYZ" { - t.Fatalf("expected `XYZ` got %q", y.G.s) - } -} - -// Test that we can encode a value and decode into a pointer. -func TestGobEncoderValueEncoder(t *testing.T) { - // first, string in field to byte in field - b := new(bytes.Buffer) - enc := NewEncoder(b) - err := enc.Encode(GobTest4{17, ValueGobber("hello"), BinaryValueGobber("Καλημέρα"), TextValueGobber("こんにちは")}) - if err != nil { - t.Fatal("encode error:", err) - } - dec := NewDecoder(b) - x := new(GobTest5) - err = dec.Decode(x) - if err != nil { - t.Fatal("decode error:", err) - } - if *x.V != "hello" || *x.BV != "Καλημέρα" || *x.TV != "こんにちは" { - t.Errorf("expected `hello` got %s", *x.V) - } -} - -// Test that we can use a value then a pointer type of a GobEncoder -// in the same encoded value. Bug 4647. -func TestGobEncoderValueThenPointer(t *testing.T) { - v := ValueGobber("forty-two") - w := ValueGobber("six-by-nine") - bv := BinaryValueGobber("1nanocentury") - bw := BinaryValueGobber("πseconds") - tv := TextValueGobber("gravitationalacceleration") - tw := TextValueGobber("π²ft/s²") - - // this was a bug: encoding a GobEncoder by value before a GobEncoder - // pointer would cause duplicate type definitions to be sent. - - b := new(bytes.Buffer) - enc := NewEncoder(b) - if err := enc.Encode(GobTest6{42, v, &w, bv, &bw, tv, &tw}); err != nil { - t.Fatal("encode error:", err) - } - dec := NewDecoder(b) - x := new(GobTest6) - if err := dec.Decode(x); err != nil { - t.Fatal("decode error:", err) - } - - if got, want := x.V, v; got != want { - t.Errorf("v = %q, want %q", got, want) - } - if got, want := x.W, w; got == nil { - t.Errorf("w = nil, want %q", want) - } else if *got != want { - t.Errorf("w = %q, want %q", *got, want) - } - - if got, want := x.BV, bv; got != want { - t.Errorf("bv = %q, want %q", got, want) - } - if got, want := x.BW, bw; got == nil { - t.Errorf("bw = nil, want %q", want) - } else if *got != want { - t.Errorf("bw = %q, want %q", *got, want) - } - - if got, want := x.TV, tv; got != want { - t.Errorf("tv = %q, want %q", got, want) - } - if got, want := x.TW, tw; got == nil { - t.Errorf("tw = nil, want %q", want) - } else if *got != want { - t.Errorf("tw = %q, want %q", *got, want) - } -} - -// Test that we can use a pointer then a value type of a GobEncoder -// in the same encoded value. -func TestGobEncoderPointerThenValue(t *testing.T) { - v := ValueGobber("forty-two") - w := ValueGobber("six-by-nine") - bv := BinaryValueGobber("1nanocentury") - bw := BinaryValueGobber("πseconds") - tv := TextValueGobber("gravitationalacceleration") - tw := TextValueGobber("π²ft/s²") - - b := new(bytes.Buffer) - enc := NewEncoder(b) - if err := enc.Encode(GobTest7{42, &v, w, &bv, bw, &tv, tw}); err != nil { - t.Fatal("encode error:", err) - } - dec := NewDecoder(b) - x := new(GobTest7) - if err := dec.Decode(x); err != nil { - t.Fatal("decode error:", err) - } - - if got, want := x.V, v; got == nil { - t.Errorf("v = nil, want %q", want) - } else if *got != want { - t.Errorf("v = %q, want %q", *got, want) - } - if got, want := x.W, w; got != want { - t.Errorf("w = %q, want %q", got, want) - } - - if got, want := x.BV, bv; got == nil { - t.Errorf("bv = nil, want %q", want) - } else if *got != want { - t.Errorf("bv = %q, want %q", *got, want) - } - if got, want := x.BW, bw; got != want { - t.Errorf("bw = %q, want %q", got, want) - } - - if got, want := x.TV, tv; got == nil { - t.Errorf("tv = nil, want %q", want) - } else if *got != want { - t.Errorf("tv = %q, want %q", *got, want) - } - if got, want := x.TW, tw; got != want { - t.Errorf("tw = %q, want %q", got, want) - } -} - -func TestGobEncoderFieldTypeError(t *testing.T) { - // GobEncoder to non-decoder: error - b := new(bytes.Buffer) - enc := NewEncoder(b) - err := enc.Encode(GobTest1{17, &StringStruct{"ABC"}}) - if err != nil { - t.Fatal("encode error:", err) - } - dec := NewDecoder(b) - x := &GobTest2{} - err = dec.Decode(x) - if err == nil { - t.Fatal("expected decode error for mismatched fields (encoder to non-decoder)") - } - if strings.Index(err.Error(), "type") < 0 { - t.Fatal("expected type error; got", err) - } - // Non-encoder to GobDecoder: error - b.Reset() - err = enc.Encode(GobTest2{17, "ABC"}) - if err != nil { - t.Fatal("encode error:", err) - } - y := &GobTest1{} - err = dec.Decode(y) - if err == nil { - t.Fatal("expected decode error for mismatched fields (non-encoder to decoder)") - } - if strings.Index(err.Error(), "type") < 0 { - t.Fatal("expected type error; got", err) - } -} - -// Even though ByteStruct is a struct, it's treated as a singleton at the top level. -func TestGobEncoderStructSingleton(t *testing.T) { - b := new(bytes.Buffer) - enc := NewEncoder(b) - err := enc.Encode(&ByteStruct{'A'}) - if err != nil { - t.Fatal("encode error:", err) - } - dec := NewDecoder(b) - x := new(ByteStruct) - err = dec.Decode(x) - if err != nil { - t.Fatal("decode error:", err) - } - if x.a != 'A' { - t.Errorf("expected 'A' got %c", x.a) - } -} - -func TestGobEncoderNonStructSingleton(t *testing.T) { - b := new(bytes.Buffer) - enc := NewEncoder(b) - var g Gobber = 1234 - err := enc.Encode(&g) - if err != nil { - t.Fatal("encode error:", err) - } - dec := NewDecoder(b) - var x Gobber - err = dec.Decode(&x) - if err != nil { - t.Fatal("decode error:", err) - } - if x != 1234 { - t.Errorf("expected 1234 got %d", x) - } -} - -func TestGobEncoderIgnoreStructField(t *testing.T) { - b := new(bytes.Buffer) - // First a field that's a structure. - enc := NewEncoder(b) - err := enc.Encode(GobTest0{17, &ByteStruct{'A'}}) - if err != nil { - t.Fatal("encode error:", err) - } - dec := NewDecoder(b) - x := new(GobTestIgnoreEncoder) - err = dec.Decode(x) - if err != nil { - t.Fatal("decode error:", err) - } - if x.X != 17 { - t.Errorf("expected 17 got %c", x.X) - } -} - -func TestGobEncoderIgnoreNonStructField(t *testing.T) { - b := new(bytes.Buffer) - // First a field that's a structure. - enc := NewEncoder(b) - gobber := Gobber(23) - bgobber := BinaryGobber(24) - tgobber := TextGobber(25) - err := enc.Encode(GobTest3{17, &gobber, &bgobber, &tgobber}) - if err != nil { - t.Fatal("encode error:", err) - } - dec := NewDecoder(b) - x := new(GobTestIgnoreEncoder) - err = dec.Decode(x) - if err != nil { - t.Fatal("decode error:", err) - } - if x.X != 17 { - t.Errorf("expected 17 got %c", x.X) - } -} - -func TestGobEncoderIgnoreNilEncoder(t *testing.T) { - b := new(bytes.Buffer) - // First a field that's a structure. - enc := NewEncoder(b) - err := enc.Encode(GobTest0{X: 18}) // G is nil - if err != nil { - t.Fatal("encode error:", err) - } - dec := NewDecoder(b) - x := new(GobTest0) - err = dec.Decode(x) - if err != nil { - t.Fatal("decode error:", err) - } - if x.X != 18 { - t.Errorf("expected x.X = 18, got %v", x.X) - } - if x.G != nil { - t.Errorf("expected x.G = nil, got %v", x.G) - } -} - -type gobDecoderBug0 struct { - foo, bar string -} - -func (br *gobDecoderBug0) String() string { - return br.foo + "-" + br.bar -} - -func (br *gobDecoderBug0) GobEncode() ([]byte, error) { - return []byte(br.String()), nil -} - -func (br *gobDecoderBug0) GobDecode(b []byte) error { - br.foo = "foo" - br.bar = "bar" - return nil -} - -// This was a bug: the receiver has a different indirection level -// than the variable. -func TestGobEncoderExtraIndirect(t *testing.T) { - gdb := &gobDecoderBug0{"foo", "bar"} - buf := new(bytes.Buffer) - e := NewEncoder(buf) - if err := e.Encode(gdb); err != nil { - t.Fatalf("encode: %v", err) - } - d := NewDecoder(buf) - var got *gobDecoderBug0 - if err := d.Decode(&got); err != nil { - t.Fatalf("decode: %v", err) - } - if got.foo != gdb.foo || got.bar != gdb.bar { - t.Errorf("got = %q, want %q", got, gdb) - } -} - -// Another bug: this caused a crash with the new Go1 Time type. -// We throw in a gob-encoding array, to test another case of isZero, -// and a struct containing an nil interface, to test a third. -type isZeroBug struct { - T time.Time - S string - I int - A isZeroBugArray - F isZeroBugInterface -} - -type isZeroBugArray [2]uint8 - -// Receiver is value, not pointer, to test isZero of array. -func (a isZeroBugArray) GobEncode() (b []byte, e error) { - b = append(b, a[:]...) - return b, nil -} - -func (a *isZeroBugArray) GobDecode(data []byte) error { - if len(data) != len(a) { - return io.EOF - } - a[0] = data[0] - a[1] = data[1] - return nil -} - -type isZeroBugInterface struct { - I interface{} -} - -func (i isZeroBugInterface) GobEncode() (b []byte, e error) { - return []byte{}, nil -} - -func (i *isZeroBugInterface) GobDecode(data []byte) error { - return nil -} - -func TestGobEncodeIsZero(t *testing.T) { - x := isZeroBug{time.Now(), "hello", -55, isZeroBugArray{1, 2}, isZeroBugInterface{}} - b := new(bytes.Buffer) - enc := NewEncoder(b) - err := enc.Encode(x) - if err != nil { - t.Fatal("encode:", err) - } - var y isZeroBug - dec := NewDecoder(b) - err = dec.Decode(&y) - if err != nil { - t.Fatal("decode:", err) - } - if x != y { - t.Fatalf("%v != %v", x, y) - } -} - -func TestGobEncodePtrError(t *testing.T) { - var err error - b := new(bytes.Buffer) - enc := NewEncoder(b) - err = enc.Encode(&err) - if err != nil { - t.Fatal("encode:", err) - } - dec := NewDecoder(b) - err2 := fmt.Errorf("foo") - err = dec.Decode(&err2) - if err != nil { - t.Fatal("decode:", err) - } - if err2 != nil { - t.Fatalf("expected nil, got %v", err2) - } -} - -func TestNetIP(t *testing.T) { - // Encoding of net.IP{1,2,3,4} in Go 1.1. - enc := []byte{0x07, 0x0a, 0x00, 0x04, 0x01, 0x02, 0x03, 0x04} - - var ip net.IP - err := NewDecoder(bytes.NewReader(enc)).Decode(&ip) - if err != nil { - t.Fatalf("decode: %v", err) - } - if ip.String() != "1.2.3.4" { - t.Errorf("decoded to %v, want 1.2.3.4", ip.String()) - } -} diff --git a/src/pkg/encoding/gob/timing_test.go b/src/pkg/encoding/gob/timing_test.go deleted file mode 100644 index ec55c4d63..000000000 --- a/src/pkg/encoding/gob/timing_test.go +++ /dev/null @@ -1,133 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gob - -import ( - "bytes" - "io" - "os" - "runtime" - "testing" -) - -type Bench struct { - A int - B float64 - C string - D []byte -} - -func benchmarkEndToEnd(b *testing.B, ctor func() interface{}, pipe func() (r io.Reader, w io.Writer, err error)) { - b.RunParallel(func(pb *testing.PB) { - r, w, err := pipe() - if err != nil { - b.Fatal("can't get pipe:", err) - } - v := ctor() - enc := NewEncoder(w) - dec := NewDecoder(r) - for pb.Next() { - if err := enc.Encode(v); err != nil { - b.Fatal("encode error:", err) - } - if err := dec.Decode(v); err != nil { - b.Fatal("decode error:", err) - } - } - }) -} - -func BenchmarkEndToEndPipe(b *testing.B) { - benchmarkEndToEnd(b, func() interface{} { - return &Bench{7, 3.2, "now is the time", bytes.Repeat([]byte("for all good men"), 100)} - }, func() (r io.Reader, w io.Writer, err error) { - r, w, err = os.Pipe() - return - }) -} - -func BenchmarkEndToEndByteBuffer(b *testing.B) { - benchmarkEndToEnd(b, func() interface{} { - return &Bench{7, 3.2, "now is the time", bytes.Repeat([]byte("for all good men"), 100)} - }, func() (r io.Reader, w io.Writer, err error) { - var buf bytes.Buffer - return &buf, &buf, nil - }) -} - -func BenchmarkEndToEndSliceByteBuffer(b *testing.B) { - benchmarkEndToEnd(b, func() interface{} { - v := &Bench{7, 3.2, "now is the time", nil} - Register(v) - arr := make([]interface{}, 100) - for i := range arr { - arr[i] = v - } - return &arr - }, func() (r io.Reader, w io.Writer, err error) { - var buf bytes.Buffer - return &buf, &buf, nil - }) -} - -func TestCountEncodeMallocs(t *testing.T) { - if testing.Short() { - t.Skip("skipping malloc count in short mode") - } - if runtime.GOMAXPROCS(0) > 1 { - t.Skip("skipping; GOMAXPROCS>1") - } - - const N = 1000 - - var buf bytes.Buffer - enc := NewEncoder(&buf) - bench := &Bench{7, 3.2, "now is the time", []byte("for all good men")} - - allocs := testing.AllocsPerRun(N, func() { - err := enc.Encode(bench) - if err != nil { - t.Fatal("encode:", err) - } - }) - if allocs != 0 { - t.Fatalf("mallocs per encode of type Bench: %v; wanted 0\n", allocs) - } -} - -func TestCountDecodeMallocs(t *testing.T) { - if testing.Short() { - t.Skip("skipping malloc count in short mode") - } - if runtime.GOMAXPROCS(0) > 1 { - t.Skip("skipping; GOMAXPROCS>1") - } - - const N = 1000 - - var buf bytes.Buffer - enc := NewEncoder(&buf) - bench := &Bench{7, 3.2, "now is the time", []byte("for all good men")} - - // Fill the buffer with enough to decode - testing.AllocsPerRun(N, func() { - err := enc.Encode(bench) - if err != nil { - t.Fatal("encode:", err) - } - }) - - dec := NewDecoder(&buf) - allocs := testing.AllocsPerRun(N, func() { - *bench = Bench{} - err := dec.Decode(&bench) - if err != nil { - t.Fatal("decode:", err) - } - }) - if allocs != 4 { - t.Fatalf("mallocs per decode of type Bench: %v; wanted 4\n", allocs) - } -} diff --git a/src/pkg/encoding/gob/type.go b/src/pkg/encoding/gob/type.go deleted file mode 100644 index cad145279..000000000 --- a/src/pkg/encoding/gob/type.go +++ /dev/null @@ -1,893 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gob - -import ( - "encoding" - "errors" - "fmt" - "os" - "reflect" - "sync" - "unicode" - "unicode/utf8" -) - -// userTypeInfo stores the information associated with a type the user has handed -// to the package. It's computed once and stored in a map keyed by reflection -// type. -type userTypeInfo struct { - user reflect.Type // the type the user handed us - base reflect.Type // the base type after all indirections - indir int // number of indirections to reach the base type - externalEnc int // xGob, xBinary, or xText - externalDec int // xGob, xBinary or xText - encIndir int8 // number of indirections to reach the receiver type; may be negative - decIndir int8 // number of indirections to reach the receiver type; may be negative -} - -// externalEncoding bits -const ( - xGob = 1 + iota // GobEncoder or GobDecoder - xBinary // encoding.BinaryMarshaler or encoding.BinaryUnmarshaler - xText // encoding.TextMarshaler or encoding.TextUnmarshaler -) - -var ( - // Protected by an RWMutex because we read it a lot and write - // it only when we see a new type, typically when compiling. - userTypeLock sync.RWMutex - userTypeCache = make(map[reflect.Type]*userTypeInfo) -) - -// validType returns, and saves, the information associated with user-provided type rt. -// If the user type is not valid, err will be non-nil. To be used when the error handler -// is not set up. -func validUserType(rt reflect.Type) (ut *userTypeInfo, err error) { - userTypeLock.RLock() - ut = userTypeCache[rt] - userTypeLock.RUnlock() - if ut != nil { - return - } - // Now set the value under the write lock. - userTypeLock.Lock() - defer userTypeLock.Unlock() - if ut = userTypeCache[rt]; ut != nil { - // Lost the race; not a problem. - return - } - ut = new(userTypeInfo) - ut.base = rt - ut.user = rt - // A type that is just a cycle of pointers (such as type T *T) cannot - // be represented in gobs, which need some concrete data. We use a - // cycle detection algorithm from Knuth, Vol 2, Section 3.1, Ex 6, - // pp 539-540. As we step through indirections, run another type at - // half speed. If they meet up, there's a cycle. - slowpoke := ut.base // walks half as fast as ut.base - for { - pt := ut.base - if pt.Kind() != reflect.Ptr { - break - } - ut.base = pt.Elem() - if ut.base == slowpoke { // ut.base lapped slowpoke - // recursive pointer type. - return nil, errors.New("can't represent recursive pointer type " + ut.base.String()) - } - if ut.indir%2 == 0 { - slowpoke = slowpoke.Elem() - } - ut.indir++ - } - - if ok, indir := implementsInterface(ut.user, gobEncoderInterfaceType); ok { - ut.externalEnc, ut.encIndir = xGob, indir - } else if ok, indir := implementsInterface(ut.user, binaryMarshalerInterfaceType); ok { - ut.externalEnc, ut.encIndir = xBinary, indir - } - - // NOTE(rsc): Would like to allow MarshalText here, but results in incompatibility - // with older encodings for net.IP. See golang.org/issue/6760. - // } else if ok, indir := implementsInterface(ut.user, textMarshalerInterfaceType); ok { - // ut.externalEnc, ut.encIndir = xText, indir - // } - - if ok, indir := implementsInterface(ut.user, gobDecoderInterfaceType); ok { - ut.externalDec, ut.decIndir = xGob, indir - } else if ok, indir := implementsInterface(ut.user, binaryUnmarshalerInterfaceType); ok { - ut.externalDec, ut.decIndir = xBinary, indir - } - - // See note above. - // } else if ok, indir := implementsInterface(ut.user, textUnmarshalerInterfaceType); ok { - // ut.externalDec, ut.decIndir = xText, indir - // } - - userTypeCache[rt] = ut - return -} - -var ( - gobEncoderInterfaceType = reflect.TypeOf((*GobEncoder)(nil)).Elem() - gobDecoderInterfaceType = reflect.TypeOf((*GobDecoder)(nil)).Elem() - binaryMarshalerInterfaceType = reflect.TypeOf((*encoding.BinaryMarshaler)(nil)).Elem() - binaryUnmarshalerInterfaceType = reflect.TypeOf((*encoding.BinaryUnmarshaler)(nil)).Elem() - textMarshalerInterfaceType = reflect.TypeOf((*encoding.TextMarshaler)(nil)).Elem() - textUnmarshalerInterfaceType = reflect.TypeOf((*encoding.TextUnmarshaler)(nil)).Elem() -) - -// implementsInterface reports whether the type implements the -// gobEncoder/gobDecoder interface. -// It also returns the number of indirections required to get to the -// implementation. -func implementsInterface(typ, gobEncDecType reflect.Type) (success bool, indir int8) { - if typ == nil { - return - } - rt := typ - // The type might be a pointer and we need to keep - // dereferencing to the base type until we find an implementation. - for { - if rt.Implements(gobEncDecType) { - return true, indir - } - if p := rt; p.Kind() == reflect.Ptr { - indir++ - if indir > 100 { // insane number of indirections - return false, 0 - } - rt = p.Elem() - continue - } - break - } - // No luck yet, but if this is a base type (non-pointer), the pointer might satisfy. - if typ.Kind() != reflect.Ptr { - // Not a pointer, but does the pointer work? - if reflect.PtrTo(typ).Implements(gobEncDecType) { - return true, -1 - } - } - return false, 0 -} - -// userType returns, and saves, the information associated with user-provided type rt. -// If the user type is not valid, it calls error. -func userType(rt reflect.Type) *userTypeInfo { - ut, err := validUserType(rt) - if err != nil { - error_(err) - } - return ut -} - -// A typeId represents a gob Type as an integer that can be passed on the wire. -// Internally, typeIds are used as keys to a map to recover the underlying type info. -type typeId int32 - -var nextId typeId // incremented for each new type we build -var typeLock sync.Mutex // set while building a type -const firstUserId = 64 // lowest id number granted to user - -type gobType interface { - id() typeId - setId(id typeId) - name() string - string() string // not public; only for debugging - safeString(seen map[typeId]bool) string -} - -var types = make(map[reflect.Type]gobType) -var idToType = make(map[typeId]gobType) -var builtinIdToType map[typeId]gobType // set in init() after builtins are established - -func setTypeId(typ gobType) { - // When building recursive types, someone may get there before us. - if typ.id() != 0 { - return - } - nextId++ - typ.setId(nextId) - idToType[nextId] = typ -} - -func (t typeId) gobType() gobType { - if t == 0 { - return nil - } - return idToType[t] -} - -// string returns the string representation of the type associated with the typeId. -func (t typeId) string() string { - if t.gobType() == nil { - return "" - } - return t.gobType().string() -} - -// Name returns the name of the type associated with the typeId. -func (t typeId) name() string { - if t.gobType() == nil { - return "" - } - return t.gobType().name() -} - -// CommonType holds elements of all types. -// It is a historical artifact, kept for binary compatibility and exported -// only for the benefit of the package's encoding of type descriptors. It is -// not intended for direct use by clients. -type CommonType struct { - Name string - Id typeId -} - -func (t *CommonType) id() typeId { return t.Id } - -func (t *CommonType) setId(id typeId) { t.Id = id } - -func (t *CommonType) string() string { return t.Name } - -func (t *CommonType) safeString(seen map[typeId]bool) string { - return t.Name -} - -func (t *CommonType) name() string { return t.Name } - -// Create and check predefined types -// The string for tBytes is "bytes" not "[]byte" to signify its specialness. - -var ( - // Primordial types, needed during initialization. - // Always passed as pointers so the interface{} type - // goes through without losing its interfaceness. - tBool = bootstrapType("bool", (*bool)(nil), 1) - tInt = bootstrapType("int", (*int)(nil), 2) - tUint = bootstrapType("uint", (*uint)(nil), 3) - tFloat = bootstrapType("float", (*float64)(nil), 4) - tBytes = bootstrapType("bytes", (*[]byte)(nil), 5) - tString = bootstrapType("string", (*string)(nil), 6) - tComplex = bootstrapType("complex", (*complex128)(nil), 7) - tInterface = bootstrapType("interface", (*interface{})(nil), 8) - // Reserve some Ids for compatible expansion - tReserved7 = bootstrapType("_reserved1", (*struct{ r7 int })(nil), 9) - tReserved6 = bootstrapType("_reserved1", (*struct{ r6 int })(nil), 10) - tReserved5 = bootstrapType("_reserved1", (*struct{ r5 int })(nil), 11) - tReserved4 = bootstrapType("_reserved1", (*struct{ r4 int })(nil), 12) - tReserved3 = bootstrapType("_reserved1", (*struct{ r3 int })(nil), 13) - tReserved2 = bootstrapType("_reserved1", (*struct{ r2 int })(nil), 14) - tReserved1 = bootstrapType("_reserved1", (*struct{ r1 int })(nil), 15) -) - -// Predefined because it's needed by the Decoder -var tWireType = mustGetTypeInfo(reflect.TypeOf(wireType{})).id -var wireTypeUserInfo *userTypeInfo // userTypeInfo of (*wireType) - -func init() { - // Some magic numbers to make sure there are no surprises. - checkId(16, tWireType) - checkId(17, mustGetTypeInfo(reflect.TypeOf(arrayType{})).id) - checkId(18, mustGetTypeInfo(reflect.TypeOf(CommonType{})).id) - checkId(19, mustGetTypeInfo(reflect.TypeOf(sliceType{})).id) - checkId(20, mustGetTypeInfo(reflect.TypeOf(structType{})).id) - checkId(21, mustGetTypeInfo(reflect.TypeOf(fieldType{})).id) - checkId(23, mustGetTypeInfo(reflect.TypeOf(mapType{})).id) - - builtinIdToType = make(map[typeId]gobType) - for k, v := range idToType { - builtinIdToType[k] = v - } - - // Move the id space upwards to allow for growth in the predefined world - // without breaking existing files. - if nextId > firstUserId { - panic(fmt.Sprintln("nextId too large:", nextId)) - } - nextId = firstUserId - registerBasics() - wireTypeUserInfo = userType(reflect.TypeOf((*wireType)(nil))) -} - -// Array type -type arrayType struct { - CommonType - Elem typeId - Len int -} - -func newArrayType(name string) *arrayType { - a := &arrayType{CommonType{Name: name}, 0, 0} - return a -} - -func (a *arrayType) init(elem gobType, len int) { - // Set our type id before evaluating the element's, in case it's our own. - setTypeId(a) - a.Elem = elem.id() - a.Len = len -} - -func (a *arrayType) safeString(seen map[typeId]bool) string { - if seen[a.Id] { - return a.Name - } - seen[a.Id] = true - return fmt.Sprintf("[%d]%s", a.Len, a.Elem.gobType().safeString(seen)) -} - -func (a *arrayType) string() string { return a.safeString(make(map[typeId]bool)) } - -// GobEncoder type (something that implements the GobEncoder interface) -type gobEncoderType struct { - CommonType -} - -func newGobEncoderType(name string) *gobEncoderType { - g := &gobEncoderType{CommonType{Name: name}} - setTypeId(g) - return g -} - -func (g *gobEncoderType) safeString(seen map[typeId]bool) string { - return g.Name -} - -func (g *gobEncoderType) string() string { return g.Name } - -// Map type -type mapType struct { - CommonType - Key typeId - Elem typeId -} - -func newMapType(name string) *mapType { - m := &mapType{CommonType{Name: name}, 0, 0} - return m -} - -func (m *mapType) init(key, elem gobType) { - // Set our type id before evaluating the element's, in case it's our own. - setTypeId(m) - m.Key = key.id() - m.Elem = elem.id() -} - -func (m *mapType) safeString(seen map[typeId]bool) string { - if seen[m.Id] { - return m.Name - } - seen[m.Id] = true - key := m.Key.gobType().safeString(seen) - elem := m.Elem.gobType().safeString(seen) - return fmt.Sprintf("map[%s]%s", key, elem) -} - -func (m *mapType) string() string { return m.safeString(make(map[typeId]bool)) } - -// Slice type -type sliceType struct { - CommonType - Elem typeId -} - -func newSliceType(name string) *sliceType { - s := &sliceType{CommonType{Name: name}, 0} - return s -} - -func (s *sliceType) init(elem gobType) { - // Set our type id before evaluating the element's, in case it's our own. - setTypeId(s) - // See the comments about ids in newTypeObject. Only slices and - // structs have mutual recursion. - if elem.id() == 0 { - setTypeId(elem) - } - s.Elem = elem.id() -} - -func (s *sliceType) safeString(seen map[typeId]bool) string { - if seen[s.Id] { - return s.Name - } - seen[s.Id] = true - return fmt.Sprintf("[]%s", s.Elem.gobType().safeString(seen)) -} - -func (s *sliceType) string() string { return s.safeString(make(map[typeId]bool)) } - -// Struct type -type fieldType struct { - Name string - Id typeId -} - -type structType struct { - CommonType - Field []*fieldType -} - -func (s *structType) safeString(seen map[typeId]bool) string { - if s == nil { - return "" - } - if _, ok := seen[s.Id]; ok { - return s.Name - } - seen[s.Id] = true - str := s.Name + " = struct { " - for _, f := range s.Field { - str += fmt.Sprintf("%s %s; ", f.Name, f.Id.gobType().safeString(seen)) - } - str += "}" - return str -} - -func (s *structType) string() string { return s.safeString(make(map[typeId]bool)) } - -func newStructType(name string) *structType { - s := &structType{CommonType{Name: name}, nil} - // For historical reasons we set the id here rather than init. - // See the comment in newTypeObject for details. - setTypeId(s) - return s -} - -// newTypeObject allocates a gobType for the reflection type rt. -// Unless ut represents a GobEncoder, rt should be the base type -// of ut. -// This is only called from the encoding side. The decoding side -// works through typeIds and userTypeInfos alone. -func newTypeObject(name string, ut *userTypeInfo, rt reflect.Type) (gobType, error) { - // Does this type implement GobEncoder? - if ut.externalEnc != 0 { - return newGobEncoderType(name), nil - } - var err error - var type0, type1 gobType - defer func() { - if err != nil { - delete(types, rt) - } - }() - // Install the top-level type before the subtypes (e.g. struct before - // fields) so recursive types can be constructed safely. - switch t := rt; t.Kind() { - // All basic types are easy: they are predefined. - case reflect.Bool: - return tBool.gobType(), nil - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - return tInt.gobType(), nil - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - return tUint.gobType(), nil - - case reflect.Float32, reflect.Float64: - return tFloat.gobType(), nil - - case reflect.Complex64, reflect.Complex128: - return tComplex.gobType(), nil - - case reflect.String: - return tString.gobType(), nil - - case reflect.Interface: - return tInterface.gobType(), nil - - case reflect.Array: - at := newArrayType(name) - types[rt] = at - type0, err = getBaseType("", t.Elem()) - if err != nil { - return nil, err - } - // Historical aside: - // For arrays, maps, and slices, we set the type id after the elements - // are constructed. This is to retain the order of type id allocation after - // a fix made to handle recursive types, which changed the order in - // which types are built. Delaying the setting in this way preserves - // type ids while allowing recursive types to be described. Structs, - // done below, were already handling recursion correctly so they - // assign the top-level id before those of the field. - at.init(type0, t.Len()) - return at, nil - - case reflect.Map: - mt := newMapType(name) - types[rt] = mt - type0, err = getBaseType("", t.Key()) - if err != nil { - return nil, err - } - type1, err = getBaseType("", t.Elem()) - if err != nil { - return nil, err - } - mt.init(type0, type1) - return mt, nil - - case reflect.Slice: - // []byte == []uint8 is a special case - if t.Elem().Kind() == reflect.Uint8 { - return tBytes.gobType(), nil - } - st := newSliceType(name) - types[rt] = st - type0, err = getBaseType(t.Elem().Name(), t.Elem()) - if err != nil { - return nil, err - } - st.init(type0) - return st, nil - - case reflect.Struct: - st := newStructType(name) - types[rt] = st - idToType[st.id()] = st - for i := 0; i < t.NumField(); i++ { - f := t.Field(i) - if !isSent(&f) { - continue - } - typ := userType(f.Type).base - tname := typ.Name() - if tname == "" { - t := userType(f.Type).base - tname = t.String() - } - gt, err := getBaseType(tname, f.Type) - if err != nil { - return nil, err - } - // Some mutually recursive types can cause us to be here while - // still defining the element. Fix the element type id here. - // We could do this more neatly by setting the id at the start of - // building every type, but that would break binary compatibility. - if gt.id() == 0 { - setTypeId(gt) - } - st.Field = append(st.Field, &fieldType{f.Name, gt.id()}) - } - return st, nil - - default: - return nil, errors.New("gob NewTypeObject can't handle type: " + rt.String()) - } -} - -// isExported reports whether this is an exported - upper case - name. -func isExported(name string) bool { - rune, _ := utf8.DecodeRuneInString(name) - return unicode.IsUpper(rune) -} - -// isSent reports whether this struct field is to be transmitted. -// It will be transmitted only if it is exported and not a chan or func field -// or pointer to chan or func. -func isSent(field *reflect.StructField) bool { - if !isExported(field.Name) { - return false - } - // If the field is a chan or func or pointer thereto, don't send it. - // That is, treat it like an unexported field. - typ := field.Type - for typ.Kind() == reflect.Ptr { - typ = typ.Elem() - } - if typ.Kind() == reflect.Chan || typ.Kind() == reflect.Func { - return false - } - return true -} - -// getBaseType returns the Gob type describing the given reflect.Type's base type. -// typeLock must be held. -func getBaseType(name string, rt reflect.Type) (gobType, error) { - ut := userType(rt) - return getType(name, ut, ut.base) -} - -// getType returns the Gob type describing the given reflect.Type. -// Should be called only when handling GobEncoders/Decoders, -// which may be pointers. All other types are handled through the -// base type, never a pointer. -// typeLock must be held. -func getType(name string, ut *userTypeInfo, rt reflect.Type) (gobType, error) { - typ, present := types[rt] - if present { - return typ, nil - } - typ, err := newTypeObject(name, ut, rt) - if err == nil { - types[rt] = typ - } - return typ, err -} - -func checkId(want, got typeId) { - if want != got { - fmt.Fprintf(os.Stderr, "checkId: %d should be %d\n", int(got), int(want)) - panic("bootstrap type wrong id: " + got.name() + " " + got.string() + " not " + want.string()) - } -} - -// used for building the basic types; called only from init(). the incoming -// interface always refers to a pointer. -func bootstrapType(name string, e interface{}, expect typeId) typeId { - rt := reflect.TypeOf(e).Elem() - _, present := types[rt] - if present { - panic("bootstrap type already present: " + name + ", " + rt.String()) - } - typ := &CommonType{Name: name} - types[rt] = typ - setTypeId(typ) - checkId(expect, nextId) - userType(rt) // might as well cache it now - return nextId -} - -// Representation of the information we send and receive about this type. -// Each value we send is preceded by its type definition: an encoded int. -// However, the very first time we send the value, we first send the pair -// (-id, wireType). -// For bootstrapping purposes, we assume that the recipient knows how -// to decode a wireType; it is exactly the wireType struct here, interpreted -// using the gob rules for sending a structure, except that we assume the -// ids for wireType and structType etc. are known. The relevant pieces -// are built in encode.go's init() function. -// To maintain binary compatibility, if you extend this type, always put -// the new fields last. -type wireType struct { - ArrayT *arrayType - SliceT *sliceType - StructT *structType - MapT *mapType - GobEncoderT *gobEncoderType - BinaryMarshalerT *gobEncoderType - TextMarshalerT *gobEncoderType -} - -func (w *wireType) string() string { - const unknown = "unknown type" - if w == nil { - return unknown - } - switch { - case w.ArrayT != nil: - return w.ArrayT.Name - case w.SliceT != nil: - return w.SliceT.Name - case w.StructT != nil: - return w.StructT.Name - case w.MapT != nil: - return w.MapT.Name - case w.GobEncoderT != nil: - return w.GobEncoderT.Name - case w.BinaryMarshalerT != nil: - return w.BinaryMarshalerT.Name - case w.TextMarshalerT != nil: - return w.TextMarshalerT.Name - } - return unknown -} - -type typeInfo struct { - id typeId - encoder *encEngine - wire *wireType -} - -var typeInfoMap = make(map[reflect.Type]*typeInfo) // protected by typeLock - -// typeLock must be held. -func getTypeInfo(ut *userTypeInfo) (*typeInfo, error) { - rt := ut.base - if ut.externalEnc != 0 { - // We want the user type, not the base type. - rt = ut.user - } - info, ok := typeInfoMap[rt] - if ok { - return info, nil - } - info = new(typeInfo) - gt, err := getBaseType(rt.Name(), rt) - if err != nil { - return nil, err - } - info.id = gt.id() - - if ut.externalEnc != 0 { - userType, err := getType(rt.Name(), ut, rt) - if err != nil { - return nil, err - } - gt := userType.id().gobType().(*gobEncoderType) - switch ut.externalEnc { - case xGob: - info.wire = &wireType{GobEncoderT: gt} - case xBinary: - info.wire = &wireType{BinaryMarshalerT: gt} - case xText: - info.wire = &wireType{TextMarshalerT: gt} - } - typeInfoMap[ut.user] = info - return info, nil - } - - t := info.id.gobType() - switch typ := rt; typ.Kind() { - case reflect.Array: - info.wire = &wireType{ArrayT: t.(*arrayType)} - case reflect.Map: - info.wire = &wireType{MapT: t.(*mapType)} - case reflect.Slice: - // []byte == []uint8 is a special case handled separately - if typ.Elem().Kind() != reflect.Uint8 { - info.wire = &wireType{SliceT: t.(*sliceType)} - } - case reflect.Struct: - info.wire = &wireType{StructT: t.(*structType)} - } - typeInfoMap[rt] = info - return info, nil -} - -// Called only when a panic is acceptable and unexpected. -func mustGetTypeInfo(rt reflect.Type) *typeInfo { - t, err := getTypeInfo(userType(rt)) - if err != nil { - panic("getTypeInfo: " + err.Error()) - } - return t -} - -// GobEncoder is the interface describing data that provides its own -// representation for encoding values for transmission to a GobDecoder. -// A type that implements GobEncoder and GobDecoder has complete -// control over the representation of its data and may therefore -// contain things such as private fields, channels, and functions, -// which are not usually transmissible in gob streams. -// -// Note: Since gobs can be stored permanently, It is good design -// to guarantee the encoding used by a GobEncoder is stable as the -// software evolves. For instance, it might make sense for GobEncode -// to include a version number in the encoding. -type GobEncoder interface { - // GobEncode returns a byte slice representing the encoding of the - // receiver for transmission to a GobDecoder, usually of the same - // concrete type. - GobEncode() ([]byte, error) -} - -// GobDecoder is the interface describing data that provides its own -// routine for decoding transmitted values sent by a GobEncoder. -type GobDecoder interface { - // GobDecode overwrites the receiver, which must be a pointer, - // with the value represented by the byte slice, which was written - // by GobEncode, usually for the same concrete type. - GobDecode([]byte) error -} - -var ( - registerLock sync.RWMutex - nameToConcreteType = make(map[string]reflect.Type) - concreteTypeToName = make(map[reflect.Type]string) -) - -// RegisterName is like Register but uses the provided name rather than the -// type's default. -func RegisterName(name string, value interface{}) { - if name == "" { - // reserved for nil - panic("attempt to register empty name") - } - registerLock.Lock() - defer registerLock.Unlock() - ut := userType(reflect.TypeOf(value)) - // Check for incompatible duplicates. The name must refer to the - // same user type, and vice versa. - if t, ok := nameToConcreteType[name]; ok && t != ut.user { - panic(fmt.Sprintf("gob: registering duplicate types for %q: %s != %s", name, t, ut.user)) - } - if n, ok := concreteTypeToName[ut.base]; ok && n != name { - panic(fmt.Sprintf("gob: registering duplicate names for %s: %q != %q", ut.user, n, name)) - } - // Store the name and type provided by the user.... - nameToConcreteType[name] = reflect.TypeOf(value) - // but the flattened type in the type table, since that's what decode needs. - concreteTypeToName[ut.base] = name -} - -// Register records a type, identified by a value for that type, under its -// internal type name. That name will identify the concrete type of a value -// sent or received as an interface variable. Only types that will be -// transferred as implementations of interface values need to be registered. -// Expecting to be used only during initialization, it panics if the mapping -// between types and names is not a bijection. -func Register(value interface{}) { - // Default to printed representation for unnamed types - rt := reflect.TypeOf(value) - name := rt.String() - - // But for named types (or pointers to them), qualify with import path (but see inner comment). - // Dereference one pointer looking for a named type. - star := "" - if rt.Name() == "" { - if pt := rt; pt.Kind() == reflect.Ptr { - star = "*" - // NOTE: The following line should be rt = pt.Elem() to implement - // what the comment above claims, but fixing it would break compatibility - // with existing gobs. - // - // Given package p imported as "full/p" with these definitions: - // package p - // type T1 struct { ... } - // this table shows the intended and actual strings used by gob to - // name the types: - // - // Type Correct string Actual string - // - // T1 full/p.T1 full/p.T1 - // *T1 *full/p.T1 *p.T1 - // - // The missing full path cannot be fixed without breaking existing gob decoders. - rt = pt - } - } - if rt.Name() != "" { - if rt.PkgPath() == "" { - name = star + rt.Name() - } else { - name = star + rt.PkgPath() + "." + rt.Name() - } - } - - RegisterName(name, value) -} - -func registerBasics() { - Register(int(0)) - Register(int8(0)) - Register(int16(0)) - Register(int32(0)) - Register(int64(0)) - Register(uint(0)) - Register(uint8(0)) - Register(uint16(0)) - Register(uint32(0)) - Register(uint64(0)) - Register(float32(0)) - Register(float64(0)) - Register(complex64(0i)) - Register(complex128(0i)) - Register(uintptr(0)) - Register(false) - Register("") - Register([]byte(nil)) - Register([]int(nil)) - Register([]int8(nil)) - Register([]int16(nil)) - Register([]int32(nil)) - Register([]int64(nil)) - Register([]uint(nil)) - Register([]uint8(nil)) - Register([]uint16(nil)) - Register([]uint32(nil)) - Register([]uint64(nil)) - Register([]float32(nil)) - Register([]float64(nil)) - Register([]complex64(nil)) - Register([]complex128(nil)) - Register([]uintptr(nil)) - Register([]bool(nil)) - Register([]string(nil)) -} diff --git a/src/pkg/encoding/gob/type_test.go b/src/pkg/encoding/gob/type_test.go deleted file mode 100644 index e230d22d4..000000000 --- a/src/pkg/encoding/gob/type_test.go +++ /dev/null @@ -1,222 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package gob - -import ( - "bytes" - "reflect" - "testing" -) - -type typeT struct { - id typeId - str string -} - -var basicTypes = []typeT{ - {tBool, "bool"}, - {tInt, "int"}, - {tUint, "uint"}, - {tFloat, "float"}, - {tBytes, "bytes"}, - {tString, "string"}, -} - -func getTypeUnlocked(name string, rt reflect.Type) gobType { - typeLock.Lock() - defer typeLock.Unlock() - t, err := getBaseType(name, rt) - if err != nil { - panic("getTypeUnlocked: " + err.Error()) - } - return t -} - -// Sanity checks -func TestBasic(t *testing.T) { - for _, tt := range basicTypes { - if tt.id.string() != tt.str { - t.Errorf("checkType: expected %q got %s", tt.str, tt.id.string()) - } - if tt.id == 0 { - t.Errorf("id for %q is zero", tt.str) - } - } -} - -// Reregister some basic types to check registration is idempotent. -func TestReregistration(t *testing.T) { - newtyp := getTypeUnlocked("int", reflect.TypeOf(int(0))) - if newtyp != tInt.gobType() { - t.Errorf("reregistration of %s got new type", newtyp.string()) - } - newtyp = getTypeUnlocked("uint", reflect.TypeOf(uint(0))) - if newtyp != tUint.gobType() { - t.Errorf("reregistration of %s got new type", newtyp.string()) - } - newtyp = getTypeUnlocked("string", reflect.TypeOf("hello")) - if newtyp != tString.gobType() { - t.Errorf("reregistration of %s got new type", newtyp.string()) - } -} - -func TestArrayType(t *testing.T) { - var a3 [3]int - a3int := getTypeUnlocked("foo", reflect.TypeOf(a3)) - newa3int := getTypeUnlocked("bar", reflect.TypeOf(a3)) - if a3int != newa3int { - t.Errorf("second registration of [3]int creates new type") - } - var a4 [4]int - a4int := getTypeUnlocked("goo", reflect.TypeOf(a4)) - if a3int == a4int { - t.Errorf("registration of [3]int creates same type as [4]int") - } - var b3 [3]bool - a3bool := getTypeUnlocked("", reflect.TypeOf(b3)) - if a3int == a3bool { - t.Errorf("registration of [3]bool creates same type as [3]int") - } - str := a3bool.string() - expected := "[3]bool" - if str != expected { - t.Errorf("array printed as %q; expected %q", str, expected) - } -} - -func TestSliceType(t *testing.T) { - var s []int - sint := getTypeUnlocked("slice", reflect.TypeOf(s)) - var news []int - newsint := getTypeUnlocked("slice1", reflect.TypeOf(news)) - if sint != newsint { - t.Errorf("second registration of []int creates new type") - } - var b []bool - sbool := getTypeUnlocked("", reflect.TypeOf(b)) - if sbool == sint { - t.Errorf("registration of []bool creates same type as []int") - } - str := sbool.string() - expected := "[]bool" - if str != expected { - t.Errorf("slice printed as %q; expected %q", str, expected) - } -} - -func TestMapType(t *testing.T) { - var m map[string]int - mapStringInt := getTypeUnlocked("map", reflect.TypeOf(m)) - var newm map[string]int - newMapStringInt := getTypeUnlocked("map1", reflect.TypeOf(newm)) - if mapStringInt != newMapStringInt { - t.Errorf("second registration of map[string]int creates new type") - } - var b map[string]bool - mapStringBool := getTypeUnlocked("", reflect.TypeOf(b)) - if mapStringBool == mapStringInt { - t.Errorf("registration of map[string]bool creates same type as map[string]int") - } - str := mapStringBool.string() - expected := "map[string]bool" - if str != expected { - t.Errorf("map printed as %q; expected %q", str, expected) - } -} - -type Bar struct { - X string -} - -// This structure has pointers and refers to itself, making it a good test case. -type Foo struct { - A int - B int32 // will become int - C string - D []byte - E *float64 // will become float64 - F ****float64 // will become float64 - G *Bar - H *Bar // should not interpolate the definition of Bar again - I *Foo // will not explode -} - -func TestStructType(t *testing.T) { - sstruct := getTypeUnlocked("Foo", reflect.TypeOf(Foo{})) - str := sstruct.string() - // If we can print it correctly, we built it correctly. - expected := "Foo = struct { A int; B int; C string; D bytes; E float; F float; G Bar = struct { X string; }; H Bar; I Foo; }" - if str != expected { - t.Errorf("struct printed as %q; expected %q", str, expected) - } -} - -// Should be OK to register the same type multiple times, as long as they're -// at the same level of indirection. -func TestRegistration(t *testing.T) { - type T struct{ a int } - Register(new(T)) - Register(new(T)) -} - -type N1 struct{} -type N2 struct{} - -// See comment in type.go/Register. -func TestRegistrationNaming(t *testing.T) { - testCases := []struct { - t interface{} - name string - }{ - {&N1{}, "*gob.N1"}, - {N2{}, "encoding/gob.N2"}, - } - - for _, tc := range testCases { - Register(tc.t) - - tct := reflect.TypeOf(tc.t) - registerLock.RLock() - ct := nameToConcreteType[tc.name] - registerLock.RUnlock() - if ct != tct { - t.Errorf("nameToConcreteType[%q] = %v, want %v", tc.name, ct, tct) - } - // concreteTypeToName is keyed off the base type. - if tct.Kind() == reflect.Ptr { - tct = tct.Elem() - } - if n := concreteTypeToName[tct]; n != tc.name { - t.Errorf("concreteTypeToName[%v] got %v, want %v", tct, n, tc.name) - } - } -} - -func TestStressParallel(t *testing.T) { - type T2 struct{ A int } - c := make(chan bool) - const N = 10 - for i := 0; i < N; i++ { - go func() { - p := new(T2) - Register(p) - b := new(bytes.Buffer) - enc := NewEncoder(b) - err := enc.Encode(p) - if err != nil { - t.Error("encoder fail:", err) - } - dec := NewDecoder(b) - err = dec.Decode(p) - if err != nil { - t.Error("decoder fail:", err) - } - c <- true - }() - } - for i := 0; i < N; i++ { - <-c - } -} diff --git a/src/pkg/encoding/hex/hex.go b/src/pkg/encoding/hex/hex.go deleted file mode 100644 index d1fc7024a..000000000 --- a/src/pkg/encoding/hex/hex.go +++ /dev/null @@ -1,216 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package hex implements hexadecimal encoding and decoding. -package hex - -import ( - "bytes" - "errors" - "fmt" - "io" -) - -const hextable = "0123456789abcdef" - -// EncodedLen returns the length of an encoding of n source bytes. -func EncodedLen(n int) int { return n * 2 } - -// Encode encodes src into EncodedLen(len(src)) -// bytes of dst. As a convenience, it returns the number -// of bytes written to dst, but this value is always EncodedLen(len(src)). -// Encode implements hexadecimal encoding. -func Encode(dst, src []byte) int { - for i, v := range src { - dst[i*2] = hextable[v>>4] - dst[i*2+1] = hextable[v&0x0f] - } - - return len(src) * 2 -} - -// ErrLength results from decoding an odd length slice. -var ErrLength = errors.New("encoding/hex: odd length hex string") - -// InvalidByteError values describe errors resulting from an invalid byte in a hex string. -type InvalidByteError byte - -func (e InvalidByteError) Error() string { - return fmt.Sprintf("encoding/hex: invalid byte: %#U", rune(e)) -} - -func DecodedLen(x int) int { return x / 2 } - -// Decode decodes src into DecodedLen(len(src)) bytes, returning the actual -// number of bytes written to dst. -// -// If Decode encounters invalid input, it returns an error describing the failure. -func Decode(dst, src []byte) (int, error) { - if len(src)%2 == 1 { - return 0, ErrLength - } - - for i := 0; i < len(src)/2; i++ { - a, ok := fromHexChar(src[i*2]) - if !ok { - return 0, InvalidByteError(src[i*2]) - } - b, ok := fromHexChar(src[i*2+1]) - if !ok { - return 0, InvalidByteError(src[i*2+1]) - } - dst[i] = (a << 4) | b - } - - return len(src) / 2, nil -} - -// fromHexChar converts a hex character into its value and a success flag. -func fromHexChar(c byte) (byte, bool) { - switch { - case '0' <= c && c <= '9': - return c - '0', true - case 'a' <= c && c <= 'f': - return c - 'a' + 10, true - case 'A' <= c && c <= 'F': - return c - 'A' + 10, true - } - - return 0, false -} - -// EncodeToString returns the hexadecimal encoding of src. -func EncodeToString(src []byte) string { - dst := make([]byte, EncodedLen(len(src))) - Encode(dst, src) - return string(dst) -} - -// DecodeString returns the bytes represented by the hexadecimal string s. -func DecodeString(s string) ([]byte, error) { - src := []byte(s) - dst := make([]byte, DecodedLen(len(src))) - _, err := Decode(dst, src) - if err != nil { - return nil, err - } - return dst, nil -} - -// Dump returns a string that contains a hex dump of the given data. The format -// of the hex dump matches the output of `hexdump -C` on the command line. -func Dump(data []byte) string { - var buf bytes.Buffer - dumper := Dumper(&buf) - dumper.Write(data) - dumper.Close() - return string(buf.Bytes()) -} - -// Dumper returns a WriteCloser that writes a hex dump of all written data to -// w. The format of the dump matches the output of `hexdump -C` on the command -// line. -func Dumper(w io.Writer) io.WriteCloser { - return &dumper{w: w} -} - -type dumper struct { - w io.Writer - rightChars [18]byte - buf [14]byte - used int // number of bytes in the current line - n uint // number of bytes, total -} - -func toChar(b byte) byte { - if b < 32 || b > 126 { - return '.' - } - return b -} - -func (h *dumper) Write(data []byte) (n int, err error) { - // Output lines look like: - // 00000010 2e 2f 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d |./0123456789:;<=| - // ^ offset ^ extra space ^ ASCII of line. - for i := range data { - if h.used == 0 { - // At the beginning of a line we print the current - // offset in hex. - h.buf[0] = byte(h.n >> 24) - h.buf[1] = byte(h.n >> 16) - h.buf[2] = byte(h.n >> 8) - h.buf[3] = byte(h.n) - Encode(h.buf[4:], h.buf[:4]) - h.buf[12] = ' ' - h.buf[13] = ' ' - _, err = h.w.Write(h.buf[4:]) - if err != nil { - return - } - } - Encode(h.buf[:], data[i:i+1]) - h.buf[2] = ' ' - l := 3 - if h.used == 7 { - // There's an additional space after the 8th byte. - h.buf[3] = ' ' - l = 4 - } else if h.used == 15 { - // At the end of the line there's an extra space and - // the bar for the right column. - h.buf[3] = ' ' - h.buf[4] = '|' - l = 5 - } - _, err = h.w.Write(h.buf[:l]) - if err != nil { - return - } - n++ - h.rightChars[h.used] = toChar(data[i]) - h.used++ - h.n++ - if h.used == 16 { - h.rightChars[16] = '|' - h.rightChars[17] = '\n' - _, err = h.w.Write(h.rightChars[:]) - if err != nil { - return - } - h.used = 0 - } - } - return -} - -func (h *dumper) Close() (err error) { - // See the comments in Write() for the details of this format. - if h.used == 0 { - return - } - h.buf[0] = ' ' - h.buf[1] = ' ' - h.buf[2] = ' ' - h.buf[3] = ' ' - h.buf[4] = '|' - nBytes := h.used - for h.used < 16 { - l := 3 - if h.used == 7 { - l = 4 - } else if h.used == 15 { - l = 5 - } - _, err = h.w.Write(h.buf[:l]) - if err != nil { - return - } - h.used++ - } - h.rightChars[nBytes] = '|' - h.rightChars[nBytes+1] = '\n' - _, err = h.w.Write(h.rightChars[:nBytes+2]) - return -} diff --git a/src/pkg/encoding/hex/hex_test.go b/src/pkg/encoding/hex/hex_test.go deleted file mode 100644 index b969636cd..000000000 --- a/src/pkg/encoding/hex/hex_test.go +++ /dev/null @@ -1,153 +0,0 @@ -// Copyright 2009 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package hex - -import ( - "bytes" - "testing" -) - -type encDecTest struct { - enc string - dec []byte -} - -var encDecTests = []encDecTest{ - {"", []byte{}}, - {"0001020304050607", []byte{0, 1, 2, 3, 4, 5, 6, 7}}, - {"08090a0b0c0d0e0f", []byte{8, 9, 10, 11, 12, 13, 14, 15}}, - {"f0f1f2f3f4f5f6f7", []byte{0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7}}, - {"f8f9fafbfcfdfeff", []byte{0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff}}, - {"67", []byte{'g'}}, - {"e3a1", []byte{0xe3, 0xa1}}, -} - -func TestEncode(t *testing.T) { - for i, test := range encDecTests { - dst := make([]byte, EncodedLen(len(test.dec))) - n := Encode(dst, test.dec) - if n != len(dst) { - t.Errorf("#%d: bad return value: got: %d want: %d", i, n, len(dst)) - } - if string(dst) != test.enc { - t.Errorf("#%d: got: %#v want: %#v", i, dst, test.enc) - } - } -} - -func TestDecode(t *testing.T) { - // Case for decoding uppercase hex characters, since - // Encode always uses lowercase. - decTests := append(encDecTests, encDecTest{"F8F9FAFBFCFDFEFF", []byte{0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff}}) - for i, test := range decTests { - dst := make([]byte, DecodedLen(len(test.enc))) - n, err := Decode(dst, []byte(test.enc)) - if err != nil { - t.Errorf("#%d: bad return value: got:%d want:%d", i, n, len(dst)) - } else if !bytes.Equal(dst, test.dec) { - t.Errorf("#%d: got: %#v want: %#v", i, dst, test.dec) - } - } -} - -func TestEncodeToString(t *testing.T) { - for i, test := range encDecTests { - s := EncodeToString(test.dec) - if s != test.enc { - t.Errorf("#%d got:%s want:%s", i, s, test.enc) - } - } -} - -func TestDecodeString(t *testing.T) { - for i, test := range encDecTests { - dst, err := DecodeString(test.enc) - if err != nil { - t.Errorf("#%d: unexpected err value: %s", i, err) - continue - } - if !bytes.Equal(dst, test.dec) { - t.Errorf("#%d: got: %#v want: #%v", i, dst, test.dec) - } - } -} - -type errTest struct { - in string - err string -} - -var errTests = []errTest{ - {"0", "encoding/hex: odd length hex string"}, - {"0g", "encoding/hex: invalid byte: U+0067 'g'"}, - {"00gg", "encoding/hex: invalid byte: U+0067 'g'"}, - {"0\x01", "encoding/hex: invalid byte: U+0001"}, -} - -func TestInvalidErr(t *testing.T) { - for i, test := range errTests { - dst := make([]byte, DecodedLen(len(test.in))) - _, err := Decode(dst, []byte(test.in)) - if err == nil { - t.Errorf("#%d: expected error; got none", i) - } else if err.Error() != test.err { - t.Errorf("#%d: got: %v want: %v", i, err, test.err) - } - } -} - -func TestInvalidStringErr(t *testing.T) { - for i, test := range errTests { - _, err := DecodeString(test.in) - if err == nil { - t.Errorf("#%d: expected error; got none", i) - } else if err.Error() != test.err { - t.Errorf("#%d: got: %v want: %v", i, err, test.err) - } - } -} - -func TestDumper(t *testing.T) { - var in [40]byte - for i := range in { - in[i] = byte(i + 30) - } - - for stride := 1; stride < len(in); stride++ { - var out bytes.Buffer - dumper := Dumper(&out) - done := 0 - for done < len(in) { - todo := done + stride - if todo > len(in) { - todo = len(in) - } - dumper.Write(in[done:todo]) - done = todo - } - - dumper.Close() - if !bytes.Equal(out.Bytes(), expectedHexDump) { - t.Errorf("stride: %d failed. got:\n%s\nwant:\n%s", stride, out.Bytes(), expectedHexDump) - } - } -} - -func TestDump(t *testing.T) { - var in [40]byte - for i := range in { - in[i] = byte(i + 30) - } - - out := []byte(Dump(in[:])) - if !bytes.Equal(out, expectedHexDump) { - t.Errorf("got:\n%s\nwant:\n%s", out, expectedHexDump) - } -} - -var expectedHexDump = []byte(`00000000 1e 1f 20 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d |.. !"#$%&'()*+,-| -00000010 2e 2f 30 31 32 33 34 35 36 37 38 39 3a 3b 3c 3d |./0123456789:;<=| -00000020 3e 3f 40 41 42 43 44 45 |>?@ABCDE| -`) diff --git a/src/pkg/encoding/json/bench_test.go b/src/pkg/encoding/json/bench_test.go deleted file mode 100644 index 29dbc26d4..000000000 --- a/src/pkg/encoding/json/bench_test.go +++ /dev/null @@ -1,189 +0,0 @@ -// Copyright 2011 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Large data benchmark. -// The JSON data is a summary of agl's changes in the -// go, webkit, and chromium open source projects. -// We benchmark converting between the JSON form -// and in-memory data structures. - -package json - -import ( - "bytes" - "compress/gzip" - "io/ioutil" - "os" - "testing" -) - -type codeResponse struct { - Tree *codeNode `json:"tree"` - Username string `json:"username"` -} - -type codeNode struct { - Name string `json:"name"` - Kids []*codeNode `json:"kids"` - CLWeight float64 `json:"cl_weight"` - Touches int `json:"touches"` - MinT int64 `json:"min_t"` - MaxT int64 `json:"max_t"` - MeanT int64 `json:"mean_t"` -} - -var codeJSON []byte -var codeStruct codeResponse - -func codeInit() { - f, err := os.Open("testdata/code.json.gz") - if err != nil { - panic(err) - } - defer f.Close() - gz, err := gzip.NewReader(f) - if err != nil { - panic(err) - } - data, err := ioutil.ReadAll(gz) - if err != nil { - panic(err) - } - - codeJSON = data - - if err := Unmarshal(codeJSON, &codeStruct); err != nil { - panic("unmarshal code.json: " + err.Error()) - } - - if data, err = Marshal(&codeStruct); err != nil { - panic("marshal code.json: " + err.Error()) - } - - if !bytes.Equal(data, codeJSON) { - println("different lengths", len(data), len(codeJSON)) - for i := 0; i < len(data) && i < len(codeJSON); i++ { - if data[i] != codeJSON[i] { - println("re-marshal: changed at byte", i) - println("orig: ", string(codeJSON[i-10:i+10])) - println("new: ", string(data[i-10:i+10])) - break - } - } - panic("re-marshal code.json: different result") - } -} - -func BenchmarkCodeEncoder(b *testing.B) { - if codeJSON == nil { - b.StopTimer() - codeInit() - b.StartTimer() - } - enc := NewEncoder(ioutil.Discard) - for i := 0; i < b.N; i++ { - if err := enc.Encode(&codeStruct); err != nil { - b.Fatal("Encode:", err) - } - } - b.SetBytes(int64(len(codeJSON))) -} - -func BenchmarkCodeMarshal(b *testing.B) { - if codeJSON == nil { - b.StopTimer() - codeInit() - b.StartTimer() - } - for i := 0; i < b.N; i++ { - if _, err := Marshal(&codeStruct); err != nil { - b.Fatal("Marshal:", err) - } - } - b.SetBytes(int64(len(codeJSON))) -} - -func BenchmarkCodeDecoder(b *testing.B) { - if codeJSON == nil { - b.StopTimer() - codeInit() - b.StartTimer() - } - var buf bytes.Buffer - dec := NewDecoder(&buf) - var r codeResponse - for i := 0; i < b.N; i++ { - buf.Write(codeJSON) - // hide EOF - buf.WriteByte('\n') - buf.WriteByte('\n') - buf.WriteByte('\n') - if err := dec.Decode(&r); err != nil { - b.Fatal("Decode:", err) - } - } - b.SetBytes(int64(len(codeJSON))) -} - -func BenchmarkCodeUnmarshal(b *testing.B) { - if codeJSON == nil { - b.StopTimer() - codeInit() - b.StartTimer() - } - for i := 0; i < b.N; i++ { - var r codeResponse - if err := Unmarshal(codeJSON, &r); err != nil { - b.Fatal("Unmmarshal:", err) - } - } - b.SetBytes(int64(len(codeJSON))) -} - -func BenchmarkCodeUnmarshalReuse(b *testing.B) { - if codeJSON == nil { - b.StopTimer() - codeInit() - b.StartTimer() - } - var r codeResponse - for i := 0; i < b.N; i++ { - if err := Unmarshal(codeJSON, &r); err != nil { - b.Fatal("Unmmarshal:", err) - } - } -} - -func BenchmarkUnmarshalString(b *testing.B) { - data := []byte(`"hello, world"`) - var s string - - for i := 0; i < b.N; i++ { - if err := Unmarshal(data, &s); err != nil { - b.Fatal("Unmarshal:", err) - } - } -} - -func BenchmarkUnmarshalFloat64(b *testing.B) { - var f float64 - data := []byte(`3.14`) - - for i := 0; i < b.N; i++ { - if err := Unmarshal(data, &f); err != nil { - b.Fatal("Unmarshal:", err) - } - } -} - -func BenchmarkUnmarshalInt64(b *testing.B) { - var x int64 - data := []byte(`3`) - - for i := 0; i < b.N; i++ { - if err := Unmarshal(data, &x); err != nil { - b.Fatal("Unmarshal:", err) - } - } -} diff --git a/src/pkg/encoding/json/decode.go b/src/pkg/encoding/json/decode.go deleted file mode 100644 index af1c908ad..000000000 --- a/src/pkg/encoding/json/decode.go +++ /dev/null @@ -1,1050 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Represents JSON data structure using native Go types: booleans, floats, -// strings, arrays, and maps. - -package json - -import ( - "bytes" - "encoding" - "encoding/base64" - "errors" - "fmt" - "reflect" - "runtime" - "strconv" - "unicode" - "unicode/utf16" - "unicode/utf8" -) - -// Unmarshal parses the JSON-encoded data and stores the result -// in the value pointed to by v. -// -// Unmarshal uses the inverse of the encodings that -// Marshal uses, allocating maps, slices, and pointers as necessary, -// with the following additional rules: -// -// To unmarshal JSON into a pointer, Unmarshal first handles the case of -// the JSON being the JSON literal null. In that case, Unmarshal sets -// the pointer to nil. Otherwise, Unmarshal unmarshals the JSON into -// the value pointed at by the pointer. If the pointer is nil, Unmarshal -// allocates a new value for it to point to. -// -// To unmarshal JSON into a struct, Unmarshal matches incoming object -// keys to the keys used by Marshal (either the struct field name or its tag), -// preferring an exact match but also accepting a case-insensitive match. -// -// To unmarshal JSON into an interface value, -// Unmarshal stores one of these in the interface value: -// -// bool, for JSON booleans -// float64, for JSON numbers -// string, for JSON strings -// []interface{}, for JSON arrays -// map[string]interface{}, for JSON objects -// nil for JSON null -// -// If a JSON value is not appropriate for a given target type, -// or if a JSON number overflows the target type, Unmarshal -// skips that field and completes the unmarshalling as best it can. -// If no more serious errors are encountered, Unmarshal returns -// an UnmarshalTypeError describing the earliest such error. -// -// The JSON null value unmarshals into an interface, map, pointer, or slice -// by setting that Go value to nil. Because null is often used in JSON to mean -// ``not present,'' unmarshaling a JSON null into any other Go type has no effect -// on the value and produces no error. -// -// When unmarshaling quoted strings, invalid UTF-8 or -// invalid UTF-16 surrogate pairs are not treated as an error. -// Instead, they are replaced by the Unicode replacement -// character U+FFFD. -// -func Unmarshal(data []byte, v interface{}) error { - // Check for well-formedness. - // Avoids filling out half a data structure - // before discovering a JSON syntax error. - var d decodeState - err := checkValid(data, &d.scan) - if err != nil { - return err - } - - d.init(data) - return d.unmarshal(v) -} - -// Unmarshaler is the interface implemented by objects -// that can unmarshal a JSON description of themselves. -// The input can be assumed to be a valid encoding of -// a JSON value. UnmarshalJSON must copy the JSON data -// if it wishes to retain the data after returning. -type Unmarshaler interface { - UnmarshalJSON([]byte) error -} - -// An UnmarshalTypeError describes a JSON value that was -// not appropriate for a value of a specific Go type. -type UnmarshalTypeError struct { - Value string // description of JSON value - "bool", "array", "number -5" - Type reflect.Type // type of Go value it could not be assigned to -} - -func (e *UnmarshalTypeError) Error() string { - return "json: cannot unmarshal " + e.Value + " into Go value of type " + e.Type.String() -} - -// An UnmarshalFieldError describes a JSON object key that -// led to an unexported (and therefore unwritable) struct field. -// (No longer used; kept for compatibility.) -type UnmarshalFieldError struct { - Key string - Type reflect.Type - Field reflect.StructField -} - -func (e *UnmarshalFieldError) Error() string { - return "json: cannot unmarshal object key " + strconv.Quote(e.Key) + " into unexported field " + e.Field.Name + " of type " + e.Type.String() -} - -// An InvalidUnmarshalError describes an invalid argument passed to Unmarshal. -// (The argument to Unmarshal must be a non-nil pointer.) -type InvalidUnmarshalError struct { - Type reflect.Type -} - -func (e *InvalidUnmarshalError) Error() string { - if e.Type == nil { - return "json: Unmarshal(nil)" - } - - if e.Type.Kind() != reflect.Ptr { - return "json: Unmarshal(non-pointer " + e.Type.String() + ")" - } - return "json: Unmarshal(nil " + e.Type.String() + ")" -} - -func (d *decodeState) unmarshal(v interface{}) (err error) { - defer func() { - if r := recover(); r != nil { - if _, ok := r.(runtime.Error); ok { - panic(r) - } - err = r.(error) - } - }() - - rv := reflect.ValueOf(v) - if rv.Kind() != reflect.Ptr || rv.IsNil() { - return &InvalidUnmarshalError{reflect.TypeOf(v)} - } - - d.scan.reset() - // We decode rv not rv.Elem because the Unmarshaler interface - // test must be applied at the top level of the value. - d.value(rv) - return d.savedError -} - -// A Number represents a JSON number literal. -type Number string - -// String returns the literal text of the number. -func (n Number) String() string { return string(n) } - -// Float64 returns the number as a float64. -func (n Number) Float64() (float64, error) { - return strconv.ParseFloat(string(n), 64) -} - -// Int64 returns the number as an int64. -func (n Number) Int64() (int64, error) { - return strconv.ParseInt(string(n), 10, 64) -} - -// decodeState represents the state while decoding a JSON value. -type decodeState struct { - data []byte - off int // read offset in data - scan scanner - nextscan scanner // for calls to nextValue - savedError error - tempstr string // scratch space to avoid some allocations - useNumber bool -} - -// errPhase is used for errors that should not happen unless -// there is a bug in the JSON decoder or something is editing -// the data slice while the decoder executes. -var errPhase = errors.New("JSON decoder out of sync - data changing underfoot?") - -func (d *decodeState) init(data []byte) *decodeState { - d.data = data - d.off = 0 - d.savedError = nil - return d -} - -// error aborts the decoding by panicking with err. -func (d *decodeState) error(err error) { - panic(err) -} - -// saveError saves the first err it is called with, -// for reporting at the end of the unmarshal. -func (d *decodeState) saveError(err error) { - if d.savedError == nil { - d.savedError = err - } -} - -// next cuts off and returns the next full JSON value in d.data[d.off:]. -// The next value is known to be an object or array, not a literal. -func (d *decodeState) next() []byte { - c := d.data[d.off] - item, rest, err := nextValue(d.data[d.off:], &d.nextscan) - if err != nil { - d.error(err) - } - d.off = len(d.data) - len(rest) - - // Our scanner has seen the opening brace/bracket - // and thinks we're still in the middle of the object. - // invent a closing brace/bracket to get it out. - if c == '{' { - d.scan.step(&d.scan, '}') - } else { - d.scan.step(&d.scan, ']') - } - - return item -} - -// scanWhile processes bytes in d.data[d.off:] until it -// receives a scan code not equal to op. -// It updates d.off and returns the new scan code. -func (d *decodeState) scanWhile(op int) int { - var newOp int - for { - if d.off >= len(d.data) { - newOp = d.scan.eof() - d.off = len(d.data) + 1 // mark processed EOF with len+1 - } else { - c := int(d.data[d.off]) - d.off++ - newOp = d.scan.step(&d.scan, c) - } - if newOp != op { - break - } - } - return newOp -} - -// value decodes a JSON value from d.data[d.off:] into the value. -// it updates d.off to point past the decoded value. -func (d *decodeState) value(v reflect.Value) { - if !v.IsValid() { - _, rest, err := nextValue(d.data[d.off:], &d.nextscan) - if err != nil { - d.error(err) - } - d.off = len(d.data) - len(rest) - - // d.scan thinks we're still at the beginning of the item. - // Feed in an empty string - the shortest, simplest value - - // so that it knows we got to the end of the value. - if d.scan.redo { - // rewind. - d.scan.redo = false - d.scan.step = stateBeginValue - } - d.scan.step(&d.scan, '"') - d.scan.step(&d.scan, '"') - - n := len(d.scan.parseState) - if n > 0 && d.scan.parseState[n-1] == parseObjectKey { - // d.scan thinks we just read an object key; finish the object - d.scan.step(&d.scan, ':') - d.scan.step(&d.scan, '"') - d.scan.step(&d.scan, '"') - d.scan.step(&d.scan, '}') - } - - return - } - - switch op := d.scanWhile(scanSkipSpace); op { - default: - d.error(errPhase) - - case scanBeginArray: - d.array(v) - - case scanBeginObject: - d.object(v) - - case scanBeginLiteral: - d.literal(v) - } -} - -// indirect walks down v allocating pointers as needed, -// until it gets to a non-pointer. -// if it encounters an Unmarshaler, indirect stops and returns that. -// if decodingNull is true, indirect stops at the last pointer so it can be set to nil. -func (d *decodeState) indirect(v reflect.Value, decodingNull bool) (Unmarshaler, encoding.TextUnmarshaler, reflect.Value) { - // If v is a named type and is addressable, - // start with its address, so that if the type has pointer methods, - // we find them. - if v.Kind() != reflect.Ptr && v.Type().Name() != "" && v.CanAddr() { - v = v.Addr() - } - for { - // Load value from interface, but only if the result will be - // usefully addressable. - if v.Kind() == reflect.Interface && !v.IsNil() { - e := v.Elem() - if e.Kind() == reflect.Ptr && !e.IsNil() && (!decodingNull || e.Elem().Kind() == reflect.Ptr) { - v = e - continue - } - } - - if v.Kind() != reflect.Ptr { - break - } - - if v.Elem().Kind() != reflect.Ptr && decodingNull && v.CanSet() { - break - } - if v.IsNil() { - v.Set(reflect.New(v.Type().Elem())) - } - if v.Type().NumMethod() > 0 { - if u, ok := v.Interface().(Unmarshaler); ok { - return u, nil, reflect.Value{} - } - if u, ok := v.Interface().(encoding.TextUnmarshaler); ok { - return nil, u, reflect.Value{} - } - } - v = v.Elem() - } - return nil, nil, v -} - -// array consumes an array from d.data[d.off-1:], decoding into the value v. -// the first byte of the array ('[') has been read already. -func (d *decodeState) array(v reflect.Value) { - // Check for unmarshaler. - u, ut, pv := d.indirect(v, false) - if u != nil { - d.off-- - err := u.UnmarshalJSON(d.next()) - if err != nil { - d.error(err) - } - return - } - if ut != nil { - d.saveError(&UnmarshalTypeError{"array", v.Type()}) - d.off-- - d.next() - return - } - - v = pv - - // Check type of target. - switch v.Kind() { - case reflect.Interface: - if v.NumMethod() == 0 { - // Decoding into nil interface? Switch to non-reflect code. - v.Set(reflect.ValueOf(d.arrayInterface())) - return - } - // Otherwise it's invalid. - fallthrough - default: - d.saveError(&UnmarshalTypeError{"array", v.Type()}) - d.off-- - d.next() - return - case reflect.Array: - case reflect.Slice: - break - } - - i := 0 - for { - // Look ahead for ] - can only happen on first iteration. - op := d.scanWhile(scanSkipSpace) - if op == scanEndArray { - break - } - - // Back up so d.value can have the byte we just read. - d.off-- - d.scan.undo(op) - - // Get element of array, growing if necessary. - if v.Kind() == reflect.Slice { - // Grow slice if necessary - if i >= v.Cap() { - newcap := v.Cap() + v.Cap()/2 - if newcap < 4 { - newcap = 4 - } - newv := reflect.MakeSlice(v.Type(), v.Len(), newcap) - reflect.Copy(newv, v) - v.Set(newv) - } - if i >= v.Len() { - v.SetLen(i + 1) - } - } - - if i < v.Len() { - // Decode into element. - d.value(v.Index(i)) - } else { - // Ran out of fixed array: skip. - d.value(reflect.Value{}) - } - i++ - - // Next token must be , or ]. - op = d.scanWhile(scanSkipSpace) - if op == scanEndArray { - break - } - if op != scanArrayValue { - d.error(errPhase) - } - } - - if i < v.Len() { - if v.Kind() == reflect.Array { - // Array. Zero the rest. - z := reflect.Zero(v.Type().Elem()) - for ; i < v.Len(); i++ { - v.Index(i).Set(z) - } - } else { - v.SetLen(i) - } - } - if i == 0 && v.Kind() == reflect.Slice { - v.Set(reflect.MakeSlice(v.Type(), 0, 0)) - } -} - -// object consumes an object from d.data[d.off-1:], decoding into the value v. -// the first byte of the object ('{') has been read already. -func (d *decodeState) object(v reflect.Value) { - // Check for unmarshaler. - u, ut, pv := d.indirect(v, false) - if u != nil { - d.off-- - err := u.UnmarshalJSON(d.next()) - if err != nil { - d.error(err) - } - return - } - if ut != nil { - d.saveError(&UnmarshalTypeError{"object", v.Type()}) - d.off-- - d.next() // skip over { } in input - return - } - v = pv - - // Decoding into nil interface? Switch to non-reflect code. - if v.Kind() == reflect.Interface && v.NumMethod() == 0 { - v.Set(reflect.ValueOf(d.objectInterface())) - return - } - - // Check type of target: struct or map[string]T - switch v.Kind() { - case reflect.Map: - // map must have string kind - t := v.Type() - if t.Key().Kind() != reflect.String { - d.saveError(&UnmarshalTypeError{"object", v.Type()}) - break - } - if v.IsNil() { - v.Set(reflect.MakeMap(t)) - } - case reflect.Struct: - - default: - d.saveError(&UnmarshalTypeError{"object", v.Type()}) - d.off-- - d.next() // skip over { } in input - return - } - - var mapElem reflect.Value - - for { - // Read opening " of string key or closing }. - op := d.scanWhile(scanSkipSpace) - if op == scanEndObject { - // closing } - can only happen on first iteration. - break - } - if op != scanBeginLiteral { - d.error(errPhase) - } - - // Read key. - start := d.off - 1 - op = d.scanWhile(scanContinue) - item := d.data[start : d.off-1] - key, ok := unquoteBytes(item) - if !ok { - d.error(errPhase) - } - - // Figure out field corresponding to key. - var subv reflect.Value - destring := false // whether the value is wrapped in a string to be decoded first - - if v.Kind() == reflect.Map { - elemType := v.Type().Elem() - if !mapElem.IsValid() { - mapElem = reflect.New(elemType).Elem() - } else { - mapElem.Set(reflect.Zero(elemType)) - } - subv = mapElem - } else { - var f *field - fields := cachedTypeFields(v.Type()) - for i := range fields { - ff := &fields[i] - if bytes.Equal(ff.nameBytes, key) { - f = ff - break - } - if f == nil && ff.equalFold(ff.nameBytes, key) { - f = ff - } - } - if f != nil { - subv = v - destring = f.quoted - for _, i := range f.index { - if subv.Kind() == reflect.Ptr { - if subv.IsNil() { - subv.Set(reflect.New(subv.Type().Elem())) - } - subv = subv.Elem() - } - subv = subv.Field(i) - } - } - } - - // Read : before value. - if op == scanSkipSpace { - op = d.scanWhile(scanSkipSpace) - } - if op != scanObjectKey { - d.error(errPhase) - } - - // Read value. - if destring { - d.value(reflect.ValueOf(&d.tempstr)) - d.literalStore([]byte(d.tempstr), subv, true) - d.tempstr = "" // Zero scratch space for successive values. - } else { - d.value(subv) - } - - // Write value back to map; - // if using struct, subv points into struct already. - if v.Kind() == reflect.Map { - kv := reflect.ValueOf(key).Convert(v.Type().Key()) - v.SetMapIndex(kv, subv) - } - - // Next token must be , or }. - op = d.scanWhile(scanSkipSpace) - if op == scanEndObject { - break - } - if op != scanObjectValue { - d.error(errPhase) - } - } -} - -// literal consumes a literal from d.data[d.off-1:], decoding into the value v. -// The first byte of the literal has been read already -// (that's how the caller knows it's a literal). -func (d *decodeState) literal(v reflect.Value) { - // All bytes inside literal return scanContinue op code. - start := d.off - 1 - op := d.scanWhile(scanContinue) - - // Scan read one byte too far; back up. - d.off-- - d.scan.undo(op) - - d.literalStore(d.data[start:d.off], v, false) -} - -// convertNumber converts the number literal s to a float64 or a Number -// depending on the setting of d.useNumber. -func (d *decodeState) convertNumber(s string) (interface{}, error) { - if d.useNumber { - return Number(s), nil - } - f, err := strconv.ParseFloat(s, 64) - if err != nil { - return nil, &UnmarshalTypeError{"number " + s, reflect.TypeOf(0.0)} - } - return f, nil -} - -var numberType = reflect.TypeOf(Number("")) - -// literalStore decodes a literal stored in item into v. -// -// fromQuoted indicates whether this literal came from unwrapping a -// string from the ",string" struct tag option. this is used only to -// produce more helpful error messages. -func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool) { - // Check for unmarshaler. - if len(item) == 0 { - //Empty string given - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - return - } - wantptr := item[0] == 'n' // null - u, ut, pv := d.indirect(v, wantptr) - if u != nil { - err := u.UnmarshalJSON(item) - if err != nil { - d.error(err) - } - return - } - if ut != nil { - if item[0] != '"' { - if fromQuoted { - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.saveError(&UnmarshalTypeError{"string", v.Type()}) - } - } - s, ok := unquoteBytes(item) - if !ok { - if fromQuoted { - d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.error(errPhase) - } - } - err := ut.UnmarshalText(s) - if err != nil { - d.error(err) - } - return - } - - v = pv - - switch c := item[0]; c { - case 'n': // null - switch v.Kind() { - case reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice: - v.Set(reflect.Zero(v.Type())) - // otherwise, ignore null for primitives/string - } - case 't', 'f': // true, false - value := c == 't' - switch v.Kind() { - default: - if fromQuoted { - d.saveError(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.saveError(&UnmarshalTypeError{"bool", v.Type()}) - } - case reflect.Bool: - v.SetBool(value) - case reflect.Interface: - if v.NumMethod() == 0 { - v.Set(reflect.ValueOf(value)) - } else { - d.saveError(&UnmarshalTypeError{"bool", v.Type()}) - } - } - - case '"': // string - s, ok := unquoteBytes(item) - if !ok { - if fromQuoted { - d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.error(errPhase) - } - } - switch v.Kind() { - default: - d.saveError(&UnmarshalTypeError{"string", v.Type()}) - case reflect.Slice: - if v.Type() != byteSliceType { - d.saveError(&UnmarshalTypeError{"string", v.Type()}) - break - } - b := make([]byte, base64.StdEncoding.DecodedLen(len(s))) - n, err := base64.StdEncoding.Decode(b, s) - if err != nil { - d.saveError(err) - break - } - v.Set(reflect.ValueOf(b[0:n])) - case reflect.String: - v.SetString(string(s)) - case reflect.Interface: - if v.NumMethod() == 0 { - v.Set(reflect.ValueOf(string(s))) - } else { - d.saveError(&UnmarshalTypeError{"string", v.Type()}) - } - } - - default: // number - if c != '-' && (c < '0' || c > '9') { - if fromQuoted { - d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.error(errPhase) - } - } - s := string(item) - switch v.Kind() { - default: - if v.Kind() == reflect.String && v.Type() == numberType { - v.SetString(s) - break - } - if fromQuoted { - d.error(fmt.Errorf("json: invalid use of ,string struct tag, trying to unmarshal %q into %v", item, v.Type())) - } else { - d.error(&UnmarshalTypeError{"number", v.Type()}) - } - case reflect.Interface: - n, err := d.convertNumber(s) - if err != nil { - d.saveError(err) - break - } - if v.NumMethod() != 0 { - d.saveError(&UnmarshalTypeError{"number", v.Type()}) - break - } - v.Set(reflect.ValueOf(n)) - - case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64: - n, err := strconv.ParseInt(s, 10, 64) - if err != nil || v.OverflowInt(n) { - d.saveError(&UnmarshalTypeError{"number " + s, v.Type()}) - break - } - v.SetInt(n) - - case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr: - n, err := strconv.ParseUint(s, 10, 64) - if err != nil || v.OverflowUint(n) { - d.saveError(&UnmarshalTypeError{"number " + s, v.Type()}) - break - } - v.SetUint(n) - - case reflect.Float32, reflect.Float64: - n, err := strconv.ParseFloat(s, v.Type().Bits()) - if err != nil || v.OverflowFloat(n) { - d.saveError(&UnmarshalTypeError{"number " + s, v.Type()}) - break - } - v.SetFloat(n) - } - } -} - -// The xxxInterface routines build up a value to be stored -// in an empty interface. They are not strictly necessary, -// but they avoid the weight of reflection in this common case. - -// valueInterface is like value but returns interface{} -func (d *decodeState) valueInterface() interface{} { - switch d.scanWhile(scanSkipSpace) { - default: - d.error(errPhase) - panic("unreachable") - case scanBeginArray: - return d.arrayInterface() - case scanBeginObject: - return d.objectInterface() - case scanBeginLiteral: - return d.literalInterface() - } -} - -// arrayInterface is like array but returns []interface{}. -func (d *decodeState) arrayInterface() []interface{} { - var v = make([]interface{}, 0) - for { - // Look ahead for ] - can only happen on first iteration. - op := d.scanWhile(scanSkipSpace) - if op == scanEndArray { - break - } - - // Back up so d.value can have the byte we just read. - d.off-- - d.scan.undo(op) - - v = append(v, d.valueInterface()) - - // Next token must be , or ]. - op = d.scanWhile(scanSkipSpace) - if op == scanEndArray { - break - } - if op != scanArrayValue { - d.error(errPhase) - } - } - return v -} - -// objectInterface is like object but returns map[string]interface{}. -func (d *decodeState) objectInterface() map[string]interface{} { - m := make(map[string]interface{}) - for { - // Read opening " of string key or closing }. - op := d.scanWhile(scanSkipSpace) - if op == scanEndObject { - // closing } - can only happen on first iteration. - break - } - if op != scanBeginLiteral { - d.error(errPhase) - } - - // Read string key. - start := d.off - 1 - op = d.scanWhile(scanContinue) - item := d.data[start : d.off-1] - key, ok := unquote(item) - if !ok { - d.error(errPhase) - } - - // Read : before value. - if op == scanSkipSpace { - op = d.scanWhile(scanSkipSpace) - } - if op != scanObjectKey { - d.error(errPhase) - } - - // Read value. - m[key] = d.valueInterface() - - // Next token must be , or }. - op = d.scanWhile(scanSkipSpace) - if op == scanEndObject { - break - } - if op != scanObjectValue { - d.error(errPhase) - } - } - return m -} - -// literalInterface is like literal but returns an interface value. -func (d *decodeState) literalInterface() interface{} { - // All bytes inside literal return scanContinue op code. - start := d.off - 1 - op := d.scanWhile(scanContinue) - - // Scan read one byte too far; back up. - d.off-- - d.scan.undo(op) - item := d.data[start:d.off] - - switch c := item[0]; c { - case 'n': // null - return nil - - case 't', 'f': // true, false - return c == 't' - - case '"': // string - s, ok := unquote(item) - if !ok { - d.error(errPhase) - } - return s - - default: // number - if c != '-' && (c < '0' || c > '9') { - d.error(errPhase) - } - n, err := d.convertNumber(string(item)) - if err != nil { - d.saveError(err) - } - return n - } -} - -// getu4 decodes \uXXXX from the beginning of s, returning the hex value, -// or it returns -1. -func getu4(s []byte) rune { - if len(s) < 6 || s[0] != '\\' || s[1] != 'u' { - return -1 - } - r, err := strconv.ParseUint(string(s[2:6]), 16, 64) - if err != nil { - return -1 - } - return rune(r) -} - -// unquote converts a quoted JSON string literal s into an actual string t. -// The rules are different than for Go, so cannot use strconv.Unquote. -func unquote(s []byte) (t string, ok bool) { - s, ok = unquoteBytes(s) - t = string(s) - return -} - -func unquoteBytes(s []byte) (t []byte, ok bool) { - if len(s) < 2 || s[0] != '"' || s[len(s)-1] != '"' { - return - } - s = s[1 : len(s)-1] - - // Check for unusual characters. If there are none, - // then no unquoting is needed, so return a slice of the - // original bytes. - r := 0 - for r < len(s) { - c := s[r] - if c == '\\' || c == '"' || c < ' ' { - break - } - if c < utf8.RuneSelf { - r++ - continue - } - rr, size := utf8.DecodeRune(s[r:]) - if rr == utf8.RuneError && size == 1 { - break - } - r += size - } - if r == len(s) { - return s, true - } - - b := make([]byte, len(s)+2*utf8.UTFMax) - w := copy(b, s[0:r]) - for r < len(s) { - // Out of room? Can only happen if s is full of - // malformed UTF-8 and we're replacing each - // byte with RuneError. - if w >= len(b)-2*utf8.UTFMax { - nb := make([]byte, (len(b)+utf8.UTFMax)*2) - copy(nb, b[0:w]) - b = nb - } - switch c := s[r]; { - case c == '\\': - r++ - if r >= len(s) { - return - } - switch s[r] { - default: - return - case '"', '\\', '/', '\'': - b[w] = s[r] - r++ - w++ - case 'b': - b[w] = '\b' - r++ - w++ - case 'f': - b[w] = '\f' - r++ - w++ - case 'n': - b[w] = '\n' - r++ - w++ - case 'r': - b[w] = '\r' - r++ - w++ - case 't': - b[w] = '\t' - r++ - w++ - case 'u': - r-- - rr := getu4(s[r:]) - if rr < 0 { - return - } - r += 6 - if utf16.IsSurrogate(rr) { - rr1 := getu4(s[r:]) - if dec := utf16.DecodeRune(rr, rr1); dec != unicode.ReplacementChar { - // A valid pair; consume. - r += 6 - w += utf8.EncodeRune(b[w:], dec) - break - } - // Invalid surrogate; fall back to replacement rune. - rr = unicode.ReplacementChar - } - w += utf8.EncodeRune(b[w:], rr) - } - - // Quote, control characters are invalid. - case c == '"', c < ' ': - return - - // ASCII - case c < utf8.RuneSelf: - b[w] = c - r++ - w++ - - // Coerce to well-formed UTF-8. - default: - rr, size := utf8.DecodeRune(s[r:]) - r += size - w += utf8.EncodeRune(b[w:], rr) - } - } - return b[0:w], true -} diff --git a/src/pkg/encoding/json/decode_test.go b/src/pkg/encoding/json/decode_test.go deleted file mode 100644 index 238a87fd6..000000000 --- a/src/pkg/encoding/json/decode_test.go +++ /dev/null @@ -1,1356 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package json - -import ( - "bytes" - "encoding" - "fmt" - "image" - "reflect" - "strings" - "testing" - "time" -) - -type T struct { - X string - Y int - Z int `json:"-"` -} - -type U struct { - Alphabet string `json:"alpha"` -} - -type V struct { - F1 interface{} - F2 int32 - F3 Number -} - -// ifaceNumAsFloat64/ifaceNumAsNumber are used to test unmarshaling with and -// without UseNumber -var ifaceNumAsFloat64 = map[string]interface{}{ - "k1": float64(1), - "k2": "s", - "k3": []interface{}{float64(1), float64(2.0), float64(3e-3)}, - "k4": map[string]interface{}{"kk1": "s", "kk2": float64(2)}, -} - -var ifaceNumAsNumber = map[string]interface{}{ - "k1": Number("1"), - "k2": "s", - "k3": []interface{}{Number("1"), Number("2.0"), Number("3e-3")}, - "k4": map[string]interface{}{"kk1": "s", "kk2": Number("2")}, -} - -type tx struct { - x int -} - -// A type that can unmarshal itself. - -type unmarshaler struct { - T bool -} - -func (u *unmarshaler) UnmarshalJSON(b []byte) error { - *u = unmarshaler{true} // All we need to see that UnmarshalJSON is called. - return nil -} - -type ustruct struct { - M unmarshaler -} - -type unmarshalerText struct { - T bool -} - -// needed for re-marshaling tests -func (u *unmarshalerText) MarshalText() ([]byte, error) { - return []byte(""), nil -} - -func (u *unmarshalerText) UnmarshalText(b []byte) error { - *u = unmarshalerText{true} // All we need to see that UnmarshalText is called. - return nil -} - -var _ encoding.TextUnmarshaler = (*unmarshalerText)(nil) - -type ustructText struct { - M unmarshalerText -} - -var ( - um0, um1 unmarshaler // target2 of unmarshaling - ump = &um1 - umtrue = unmarshaler{true} - umslice = []unmarshaler{{true}} - umslicep = new([]unmarshaler) - umstruct = ustruct{unmarshaler{true}} - - um0T, um1T unmarshalerText // target2 of unmarshaling - umpT = &um1T - umtrueT = unmarshalerText{true} - umsliceT = []unmarshalerText{{true}} - umslicepT = new([]unmarshalerText) - umstructT = ustructText{unmarshalerText{true}} -) - -// Test data structures for anonymous fields. - -type Point struct { - Z int -} - -type Top struct { - Level0 int - Embed0 - *Embed0a - *Embed0b `json:"e,omitempty"` // treated as named - Embed0c `json:"-"` // ignored - Loop - Embed0p // has Point with X, Y, used - Embed0q // has Point with Z, used -} - -type Embed0 struct { - Level1a int // overridden by Embed0a's Level1a with json tag - Level1b int // used because Embed0a's Level1b is renamed - Level1c int // used because Embed0a's Level1c is ignored - Level1d int // annihilated by Embed0a's Level1d - Level1e int `json:"x"` // annihilated by Embed0a.Level1e -} - -type Embed0a struct { - Level1a int `json:"Level1a,omitempty"` - Level1b int `json:"LEVEL1B,omitempty"` - Level1c int `json:"-"` - Level1d int // annihilated by Embed0's Level1d - Level1f int `json:"x"` // annihilated by Embed0's Level1e -} - -type Embed0b Embed0 - -type Embed0c Embed0 - -type Embed0p struct { - image.Point -} - -type Embed0q struct { - Point -} - -type Loop struct { - Loop1 int `json:",omitempty"` - Loop2 int `json:",omitempty"` - *Loop -} - -// From reflect test: -// The X in S6 and S7 annihilate, but they also block the X in S8.S9. -type S5 struct { - S6 - S7 - S8 -} - -type S6 struct { - X int -} - -type S7 S6 - -type S8 struct { - S9 -} - -type S9 struct { - X int - Y int -} - -// From reflect test: -// The X in S11.S6 and S12.S6 annihilate, but they also block the X in S13.S8.S9. -type S10 struct { - S11 - S12 - S13 -} - -type S11 struct { - S6 -} - -type S12 struct { - S6 -} - -type S13 struct { - S8 -} - -type unmarshalTest struct { - in string - ptr interface{} - out interface{} - err error - useNumber bool -} - -type Ambig struct { - // Given "hello", the first match should win. - First int `json:"HELLO"` - Second int `json:"Hello"` -} - -type XYZ struct { - X interface{} - Y interface{} - Z interface{} -} - -var unmarshalTests = []unmarshalTest{ - // basic types - {in: `true`, ptr: new(bool), out: true}, - {in: `1`, ptr: new(int), out: 1}, - {in: `1.2`, ptr: new(float64), out: 1.2}, - {in: `-5`, ptr: new(int16), out: int16(-5)}, - {in: `2`, ptr: new(Number), out: Number("2"), useNumber: true}, - {in: `2`, ptr: new(Number), out: Number("2")}, - {in: `2`, ptr: new(interface{}), out: float64(2.0)}, - {in: `2`, ptr: new(interface{}), out: Number("2"), useNumber: true}, - {in: `"a\u1234"`, ptr: new(string), out: "a\u1234"}, - {in: `"http:\/\/"`, ptr: new(string), out: "http://"}, - {in: `"g-clef: \uD834\uDD1E"`, ptr: new(string), out: "g-clef: \U0001D11E"}, - {in: `"invalid: \uD834x\uDD1E"`, ptr: new(string), out: "invalid: \uFFFDx\uFFFD"}, - {in: "null", ptr: new(interface{}), out: nil}, - {in: `{"X": [1,2,3], "Y": 4}`, ptr: new(T), out: T{Y: 4}, err: &UnmarshalTypeError{"array", reflect.TypeOf("")}}, - {in: `{"x": 1}`, ptr: new(tx), out: tx{}}, - {in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: float64(1), F2: int32(2), F3: Number("3")}}, - {in: `{"F1":1,"F2":2,"F3":3}`, ptr: new(V), out: V{F1: Number("1"), F2: int32(2), F3: Number("3")}, useNumber: true}, - {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsFloat64}, - {in: `{"k1":1,"k2":"s","k3":[1,2.0,3e-3],"k4":{"kk1":"s","kk2":2}}`, ptr: new(interface{}), out: ifaceNumAsNumber, useNumber: true}, - - // raw values with whitespace - {in: "\n true ", ptr: new(bool), out: true}, - {in: "\t 1 ", ptr: new(int), out: 1}, - {in: "\r 1.2 ", ptr: new(float64), out: 1.2}, - {in: "\t -5 \n", ptr: new(int16), out: int16(-5)}, - {in: "\t \"a\\u1234\" \n", ptr: new(string), out: "a\u1234"}, - - // Z has a "-" tag. - {in: `{"Y": 1, "Z": 2}`, ptr: new(T), out: T{Y: 1}}, - - {in: `{"alpha": "abc", "alphabet": "xyz"}`, ptr: new(U), out: U{Alphabet: "abc"}}, - {in: `{"alpha": "abc"}`, ptr: new(U), out: U{Alphabet: "abc"}}, - {in: `{"alphabet": "xyz"}`, ptr: new(U), out: U{}}, - - // syntax errors - {in: `{"X": "foo", "Y"}`, err: &SyntaxError{"invalid character '}' after object key", 17}}, - {in: `[1, 2, 3+]`, err: &SyntaxError{"invalid character '+' after array element", 9}}, - {in: `{"X":12x}`, err: &SyntaxError{"invalid character 'x' after object key:value pair", 8}, useNumber: true}, - - // raw value errors - {in: "\x01 42", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}}, - {in: " 42 \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 5}}, - {in: "\x01 true", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}}, - {in: " false \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 8}}, - {in: "\x01 1.2", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}}, - {in: " 3.4 \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 6}}, - {in: "\x01 \"string\"", err: &SyntaxError{"invalid character '\\x01' looking for beginning of value", 1}}, - {in: " \"string\" \x01", err: &SyntaxError{"invalid character '\\x01' after top-level value", 11}}, - - // array tests - {in: `[1, 2, 3]`, ptr: new([3]int), out: [3]int{1, 2, 3}}, - {in: `[1, 2, 3]`, ptr: new([1]int), out: [1]int{1}}, - {in: `[1, 2, 3]`, ptr: new([5]int), out: [5]int{1, 2, 3, 0, 0}}, - - // empty array to interface test - {in: `[]`, ptr: new([]interface{}), out: []interface{}{}}, - {in: `null`, ptr: new([]interface{}), out: []interface{}(nil)}, - {in: `{"T":[]}`, ptr: new(map[string]interface{}), out: map[string]interface{}{"T": []interface{}{}}}, - {in: `{"T":null}`, ptr: new(map[string]interface{}), out: map[string]interface{}{"T": interface{}(nil)}}, - - // composite tests - {in: allValueIndent, ptr: new(All), out: allValue}, - {in: allValueCompact, ptr: new(All), out: allValue}, - {in: allValueIndent, ptr: new(*All), out: &allValue}, - {in: allValueCompact, ptr: new(*All), out: &allValue}, - {in: pallValueIndent, ptr: new(All), out: pallValue}, - {in: pallValueCompact, ptr: new(All), out: pallValue}, - {in: pallValueIndent, ptr: new(*All), out: &pallValue}, - {in: pallValueCompact, ptr: new(*All), out: &pallValue}, - - // unmarshal interface test - {in: `{"T":false}`, ptr: &um0, out: umtrue}, // use "false" so test will fail if custom unmarshaler is not called - {in: `{"T":false}`, ptr: &ump, out: &umtrue}, - {in: `[{"T":false}]`, ptr: &umslice, out: umslice}, - {in: `[{"T":false}]`, ptr: &umslicep, out: &umslice}, - {in: `{"M":{"T":false}}`, ptr: &umstruct, out: umstruct}, - - // UnmarshalText interface test - {in: `"X"`, ptr: &um0T, out: umtrueT}, // use "false" so test will fail if custom unmarshaler is not called - {in: `"X"`, ptr: &umpT, out: &umtrueT}, - {in: `["X"]`, ptr: &umsliceT, out: umsliceT}, - {in: `["X"]`, ptr: &umslicepT, out: &umsliceT}, - {in: `{"M":"X"}`, ptr: &umstructT, out: umstructT}, - - { - in: `{ - "Level0": 1, - "Level1b": 2, - "Level1c": 3, - "x": 4, - "Level1a": 5, - "LEVEL1B": 6, - "e": { - "Level1a": 8, - "Level1b": 9, - "Level1c": 10, - "Level1d": 11, - "x": 12 - }, - "Loop1": 13, - "Loop2": 14, - "X": 15, - "Y": 16, - "Z": 17 - }`, - ptr: new(Top), - out: Top{ - Level0: 1, - Embed0: Embed0{ - Level1b: 2, - Level1c: 3, - }, - Embed0a: &Embed0a{ - Level1a: 5, - Level1b: 6, - }, - Embed0b: &Embed0b{ - Level1a: 8, - Level1b: 9, - Level1c: 10, - Level1d: 11, - Level1e: 12, - }, - Loop: Loop{ - Loop1: 13, - Loop2: 14, - }, - Embed0p: Embed0p{ - Point: image.Point{X: 15, Y: 16}, - }, - Embed0q: Embed0q{ - Point: Point{Z: 17}, - }, - }, - }, - { - in: `{"hello": 1}`, - ptr: new(Ambig), - out: Ambig{First: 1}, - }, - - { - in: `{"X": 1,"Y":2}`, - ptr: new(S5), - out: S5{S8: S8{S9: S9{Y: 2}}}, - }, - { - in: `{"X": 1,"Y":2}`, - ptr: new(S10), - out: S10{S13: S13{S8: S8{S9: S9{Y: 2}}}}, - }, - - // invalid UTF-8 is coerced to valid UTF-8. - { - in: "\"hello\xffworld\"", - ptr: new(string), - out: "hello\ufffdworld", - }, - { - in: "\"hello\xc2\xc2world\"", - ptr: new(string), - out: "hello\ufffd\ufffdworld", - }, - { - in: "\"hello\xc2\xffworld\"", - ptr: new(string), - out: "hello\ufffd\ufffdworld", - }, - { - in: "\"hello\\ud800world\"", - ptr: new(string), - out: "hello\ufffdworld", - }, - { - in: "\"hello\\ud800\\ud800world\"", - ptr: new(string), - out: "hello\ufffd\ufffdworld", - }, - { - in: "\"hello\\ud800\\ud800world\"", - ptr: new(string), - out: "hello\ufffd\ufffdworld", - }, - { - in: "\"hello\xed\xa0\x80\xed\xb0\x80world\"", - ptr: new(string), - out: "hello\ufffd\ufffd\ufffd\ufffd\ufffd\ufffdworld", - }, -} - -func TestMarshal(t *testing.T) { - b, err := Marshal(allValue) - if err != nil { - t.Fatalf("Marshal allValue: %v", err) - } - if string(b) != allValueCompact { - t.Errorf("Marshal allValueCompact") - diff(t, b, []byte(allValueCompact)) - return - } - - b, err = Marshal(pallValue) - if err != nil { - t.Fatalf("Marshal pallValue: %v", err) - } - if string(b) != pallValueCompact { - t.Errorf("Marshal pallValueCompact") - diff(t, b, []byte(pallValueCompact)) - return - } -} - -var badUTF8 = []struct { - in, out string -}{ - {"hello\xffworld", `"hello\ufffdworld"`}, - {"", `""`}, - {"\xff", `"\ufffd"`}, - {"\xff\xff", `"\ufffd\ufffd"`}, - {"a\xffb", `"a\ufffdb"`}, - {"\xe6\x97\xa5\xe6\x9c\xac\xff\xaa\x9e", `"日本\ufffd\ufffd\ufffd"`}, -} - -func TestMarshalBadUTF8(t *testing.T) { - for _, tt := range badUTF8 { - b, err := Marshal(tt.in) - if string(b) != tt.out || err != nil { - t.Errorf("Marshal(%q) = %#q, %v, want %#q, nil", tt.in, b, err, tt.out) - } - } -} - -func TestMarshalNumberZeroVal(t *testing.T) { - var n Number - out, err := Marshal(n) - if err != nil { - t.Fatal(err) - } - outStr := string(out) - if outStr != "0" { - t.Fatalf("Invalid zero val for Number: %q", outStr) - } -} - -func TestMarshalEmbeds(t *testing.T) { - top := &Top{ - Level0: 1, - Embed0: Embed0{ - Level1b: 2, - Level1c: 3, - }, - Embed0a: &Embed0a{ - Level1a: 5, - Level1b: 6, - }, - Embed0b: &Embed0b{ - Level1a: 8, - Level1b: 9, - Level1c: 10, - Level1d: 11, - Level1e: 12, - }, - Loop: Loop{ - Loop1: 13, - Loop2: 14, - }, - Embed0p: Embed0p{ - Point: image.Point{X: 15, Y: 16}, - }, - Embed0q: Embed0q{ - Point: Point{Z: 17}, - }, - } - b, err := Marshal(top) - if err != nil { - t.Fatal(err) - } - want := "{\"Level0\":1,\"Level1b\":2,\"Level1c\":3,\"Level1a\":5,\"LEVEL1B\":6,\"e\":{\"Level1a\":8,\"Level1b\":9,\"Level1c\":10,\"Level1d\":11,\"x\":12},\"Loop1\":13,\"Loop2\":14,\"X\":15,\"Y\":16,\"Z\":17}" - if string(b) != want { - t.Errorf("Wrong marshal result.\n got: %q\nwant: %q", b, want) - } -} - -func TestUnmarshal(t *testing.T) { - for i, tt := range unmarshalTests { - var scan scanner - in := []byte(tt.in) - if err := checkValid(in, &scan); err != nil { - if !reflect.DeepEqual(err, tt.err) { - t.Errorf("#%d: checkValid: %#v", i, err) - continue - } - } - if tt.ptr == nil { - continue - } - // v = new(right-type) - v := reflect.New(reflect.TypeOf(tt.ptr).Elem()) - dec := NewDecoder(bytes.NewReader(in)) - if tt.useNumber { - dec.UseNumber() - } - if err := dec.Decode(v.Interface()); !reflect.DeepEqual(err, tt.err) { - t.Errorf("#%d: %v want %v", i, err, tt.err) - continue - } - if !reflect.DeepEqual(v.Elem().Interface(), tt.out) { - t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), tt.out) - data, _ := Marshal(v.Elem().Interface()) - println(string(data)) - data, _ = Marshal(tt.out) - println(string(data)) - continue - } - - // Check round trip. - if tt.err == nil { - enc, err := Marshal(v.Interface()) - if err != nil { - t.Errorf("#%d: error re-marshaling: %v", i, err) - continue - } - vv := reflect.New(reflect.TypeOf(tt.ptr).Elem()) - dec = NewDecoder(bytes.NewReader(enc)) - if tt.useNumber { - dec.UseNumber() - } - if err := dec.Decode(vv.Interface()); err != nil { - t.Errorf("#%d: error re-unmarshaling %#q: %v", i, enc, err) - continue - } - if !reflect.DeepEqual(v.Elem().Interface(), vv.Elem().Interface()) { - t.Errorf("#%d: mismatch\nhave: %#+v\nwant: %#+v", i, v.Elem().Interface(), vv.Elem().Interface()) - t.Errorf(" In: %q", strings.Map(noSpace, string(in))) - t.Errorf("Marshal: %q", strings.Map(noSpace, string(enc))) - continue - } - } - } -} - -func TestUnmarshalMarshal(t *testing.T) { - initBig() - var v interface{} - if err := Unmarshal(jsonBig, &v); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - b, err := Marshal(v) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - if !bytes.Equal(jsonBig, b) { - t.Errorf("Marshal jsonBig") - diff(t, b, jsonBig) - return - } -} - -var numberTests = []struct { - in string - i int64 - intErr string - f float64 - floatErr string -}{ - {in: "-1.23e1", intErr: "strconv.ParseInt: parsing \"-1.23e1\": invalid syntax", f: -1.23e1}, - {in: "-12", i: -12, f: -12.0}, - {in: "1e1000", intErr: "strconv.ParseInt: parsing \"1e1000\": invalid syntax", floatErr: "strconv.ParseFloat: parsing \"1e1000\": value out of range"}, -} - -// Independent of Decode, basic coverage of the accessors in Number -func TestNumberAccessors(t *testing.T) { - for _, tt := range numberTests { - n := Number(tt.in) - if s := n.String(); s != tt.in { - t.Errorf("Number(%q).String() is %q", tt.in, s) - } - if i, err := n.Int64(); err == nil && tt.intErr == "" && i != tt.i { - t.Errorf("Number(%q).Int64() is %d", tt.in, i) - } else if (err == nil && tt.intErr != "") || (err != nil && err.Error() != tt.intErr) { - t.Errorf("Number(%q).Int64() wanted error %q but got: %v", tt.in, tt.intErr, err) - } - if f, err := n.Float64(); err == nil && tt.floatErr == "" && f != tt.f { - t.Errorf("Number(%q).Float64() is %g", tt.in, f) - } else if (err == nil && tt.floatErr != "") || (err != nil && err.Error() != tt.floatErr) { - t.Errorf("Number(%q).Float64() wanted error %q but got: %v", tt.in, tt.floatErr, err) - } - } -} - -func TestLargeByteSlice(t *testing.T) { - s0 := make([]byte, 2000) - for i := range s0 { - s0[i] = byte(i) - } - b, err := Marshal(s0) - if err != nil { - t.Fatalf("Marshal: %v", err) - } - var s1 []byte - if err := Unmarshal(b, &s1); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !bytes.Equal(s0, s1) { - t.Errorf("Marshal large byte slice") - diff(t, s0, s1) - } -} - -type Xint struct { - X int -} - -func TestUnmarshalInterface(t *testing.T) { - var xint Xint - var i interface{} = &xint - if err := Unmarshal([]byte(`{"X":1}`), &i); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if xint.X != 1 { - t.Fatalf("Did not write to xint") - } -} - -func TestUnmarshalPtrPtr(t *testing.T) { - var xint Xint - pxint := &xint - if err := Unmarshal([]byte(`{"X":1}`), &pxint); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if xint.X != 1 { - t.Fatalf("Did not write to xint") - } -} - -func TestEscape(t *testing.T) { - const input = `"foobar"` + " [\u2028 \u2029]" - const expected = `"\"foobar\"\u003chtml\u003e [\u2028 \u2029]"` - b, err := Marshal(input) - if err != nil { - t.Fatalf("Marshal error: %v", err) - } - if s := string(b); s != expected { - t.Errorf("Encoding of [%s]:\n got [%s]\nwant [%s]", input, s, expected) - } -} - -// WrongString is a struct that's misusing the ,string modifier. -type WrongString struct { - Message string `json:"result,string"` -} - -type wrongStringTest struct { - in, err string -} - -var wrongStringTests = []wrongStringTest{ - {`{"result":"x"}`, `json: invalid use of ,string struct tag, trying to unmarshal "x" into string`}, - {`{"result":"foo"}`, `json: invalid use of ,string struct tag, trying to unmarshal "foo" into string`}, - {`{"result":"123"}`, `json: invalid use of ,string struct tag, trying to unmarshal "123" into string`}, -} - -// If people misuse the ,string modifier, the error message should be -// helpful, telling the user that they're doing it wrong. -func TestErrorMessageFromMisusedString(t *testing.T) { - for n, tt := range wrongStringTests { - r := strings.NewReader(tt.in) - var s WrongString - err := NewDecoder(r).Decode(&s) - got := fmt.Sprintf("%v", err) - if got != tt.err { - t.Errorf("%d. got err = %q, want %q", n, got, tt.err) - } - } -} - -func noSpace(c rune) rune { - if isSpace(c) { - return -1 - } - return c -} - -type All struct { - Bool bool - Int int - Int8 int8 - Int16 int16 - Int32 int32 - Int64 int64 - Uint uint - Uint8 uint8 - Uint16 uint16 - Uint32 uint32 - Uint64 uint64 - Uintptr uintptr - Float32 float32 - Float64 float64 - - Foo string `json:"bar"` - Foo2 string `json:"bar2,dummyopt"` - - IntStr int64 `json:",string"` - - PBool *bool - PInt *int - PInt8 *int8 - PInt16 *int16 - PInt32 *int32 - PInt64 *int64 - PUint *uint - PUint8 *uint8 - PUint16 *uint16 - PUint32 *uint32 - PUint64 *uint64 - PUintptr *uintptr - PFloat32 *float32 - PFloat64 *float64 - - String string - PString *string - - Map map[string]Small - MapP map[string]*Small - PMap *map[string]Small - PMapP *map[string]*Small - - EmptyMap map[string]Small - NilMap map[string]Small - - Slice []Small - SliceP []*Small - PSlice *[]Small - PSliceP *[]*Small - - EmptySlice []Small - NilSlice []Small - - StringSlice []string - ByteSlice []byte - - Small Small - PSmall *Small - PPSmall **Small - - Interface interface{} - PInterface *interface{} - - unexported int -} - -type Small struct { - Tag string -} - -var allValue = All{ - Bool: true, - Int: 2, - Int8: 3, - Int16: 4, - Int32: 5, - Int64: 6, - Uint: 7, - Uint8: 8, - Uint16: 9, - Uint32: 10, - Uint64: 11, - Uintptr: 12, - Float32: 14.1, - Float64: 15.1, - Foo: "foo", - Foo2: "foo2", - IntStr: 42, - String: "16", - Map: map[string]Small{ - "17": {Tag: "tag17"}, - "18": {Tag: "tag18"}, - }, - MapP: map[string]*Small{ - "19": {Tag: "tag19"}, - "20": nil, - }, - EmptyMap: map[string]Small{}, - Slice: []Small{{Tag: "tag20"}, {Tag: "tag21"}}, - SliceP: []*Small{{Tag: "tag22"}, nil, {Tag: "tag23"}}, - EmptySlice: []Small{}, - StringSlice: []string{"str24", "str25", "str26"}, - ByteSlice: []byte{27, 28, 29}, - Small: Small{Tag: "tag30"}, - PSmall: &Small{Tag: "tag31"}, - Interface: 5.2, -} - -var pallValue = All{ - PBool: &allValue.Bool, - PInt: &allValue.Int, - PInt8: &allValue.Int8, - PInt16: &allValue.Int16, - PInt32: &allValue.Int32, - PInt64: &allValue.Int64, - PUint: &allValue.Uint, - PUint8: &allValue.Uint8, - PUint16: &allValue.Uint16, - PUint32: &allValue.Uint32, - PUint64: &allValue.Uint64, - PUintptr: &allValue.Uintptr, - PFloat32: &allValue.Float32, - PFloat64: &allValue.Float64, - PString: &allValue.String, - PMap: &allValue.Map, - PMapP: &allValue.MapP, - PSlice: &allValue.Slice, - PSliceP: &allValue.SliceP, - PPSmall: &allValue.PSmall, - PInterface: &allValue.Interface, -} - -var allValueIndent = `{ - "Bool": true, - "Int": 2, - "Int8": 3, - "Int16": 4, - "Int32": 5, - "Int64": 6, - "Uint": 7, - "Uint8": 8, - "Uint16": 9, - "Uint32": 10, - "Uint64": 11, - "Uintptr": 12, - "Float32": 14.1, - "Float64": 15.1, - "bar": "foo", - "bar2": "foo2", - "IntStr": "42", - "PBool": null, - "PInt": null, - "PInt8": null, - "PInt16": null, - "PInt32": null, - "PInt64": null, - "PUint": null, - "PUint8": null, - "PUint16": null, - "PUint32": null, - "PUint64": null, - "PUintptr": null, - "PFloat32": null, - "PFloat64": null, - "String": "16", - "PString": null, - "Map": { - "17": { - "Tag": "tag17" - }, - "18": { - "Tag": "tag18" - } - }, - "MapP": { - "19": { - "Tag": "tag19" - }, - "20": null - }, - "PMap": null, - "PMapP": null, - "EmptyMap": {}, - "NilMap": null, - "Slice": [ - { - "Tag": "tag20" - }, - { - "Tag": "tag21" - } - ], - "SliceP": [ - { - "Tag": "tag22" - }, - null, - { - "Tag": "tag23" - } - ], - "PSlice": null, - "PSliceP": null, - "EmptySlice": [], - "NilSlice": null, - "StringSlice": [ - "str24", - "str25", - "str26" - ], - "ByteSlice": "Gxwd", - "Small": { - "Tag": "tag30" - }, - "PSmall": { - "Tag": "tag31" - }, - "PPSmall": null, - "Interface": 5.2, - "PInterface": null -}` - -var allValueCompact = strings.Map(noSpace, allValueIndent) - -var pallValueIndent = `{ - "Bool": false, - "Int": 0, - "Int8": 0, - "Int16": 0, - "Int32": 0, - "Int64": 0, - "Uint": 0, - "Uint8": 0, - "Uint16": 0, - "Uint32": 0, - "Uint64": 0, - "Uintptr": 0, - "Float32": 0, - "Float64": 0, - "bar": "", - "bar2": "", - "IntStr": "0", - "PBool": true, - "PInt": 2, - "PInt8": 3, - "PInt16": 4, - "PInt32": 5, - "PInt64": 6, - "PUint": 7, - "PUint8": 8, - "PUint16": 9, - "PUint32": 10, - "PUint64": 11, - "PUintptr": 12, - "PFloat32": 14.1, - "PFloat64": 15.1, - "String": "", - "PString": "16", - "Map": null, - "MapP": null, - "PMap": { - "17": { - "Tag": "tag17" - }, - "18": { - "Tag": "tag18" - } - }, - "PMapP": { - "19": { - "Tag": "tag19" - }, - "20": null - }, - "EmptyMap": null, - "NilMap": null, - "Slice": null, - "SliceP": null, - "PSlice": [ - { - "Tag": "tag20" - }, - { - "Tag": "tag21" - } - ], - "PSliceP": [ - { - "Tag": "tag22" - }, - null, - { - "Tag": "tag23" - } - ], - "EmptySlice": null, - "NilSlice": null, - "StringSlice": null, - "ByteSlice": null, - "Small": { - "Tag": "" - }, - "PSmall": null, - "PPSmall": { - "Tag": "tag31" - }, - "Interface": null, - "PInterface": 5.2 -}` - -var pallValueCompact = strings.Map(noSpace, pallValueIndent) - -func TestRefUnmarshal(t *testing.T) { - type S struct { - // Ref is defined in encode_test.go. - R0 Ref - R1 *Ref - R2 RefText - R3 *RefText - } - want := S{ - R0: 12, - R1: new(Ref), - R2: 13, - R3: new(RefText), - } - *want.R1 = 12 - *want.R3 = 13 - - var got S - if err := Unmarshal([]byte(`{"R0":"ref","R1":"ref","R2":"ref","R3":"ref"}`), &got); err != nil { - t.Fatalf("Unmarshal: %v", err) - } - if !reflect.DeepEqual(got, want) { - t.Errorf("got %+v, want %+v", got, want) - } -} - -// Test that the empty string doesn't panic decoding when ,string is specified -// Issue 3450 -func TestEmptyString(t *testing.T) { - type T2 struct { - Number1 int `json:",string"` - Number2 int `json:",string"` - } - data := `{"Number1":"1", "Number2":""}` - dec := NewDecoder(strings.NewReader(data)) - var t2 T2 - err := dec.Decode(&t2) - if err == nil { - t.Fatal("Decode: did not return error") - } - if t2.Number1 != 1 { - t.Fatal("Decode: did not set Number1") - } -} - -// Test that the returned error is non-nil when trying to unmarshal null string into int, for successive ,string option -// Issue 7046 -func TestNullString(t *testing.T) { - type T struct { - A int `json:",string"` - B int `json:",string"` - } - data := []byte(`{"A": "1", "B": null}`) - var s T - err := Unmarshal(data, &s) - if err == nil { - t.Fatalf("expected error; got %v", s) - } -} - -func intp(x int) *int { - p := new(int) - *p = x - return p -} - -func intpp(x *int) **int { - pp := new(*int) - *pp = x - return pp -} - -var interfaceSetTests = []struct { - pre interface{} - json string - post interface{} -}{ - {"foo", `"bar"`, "bar"}, - {"foo", `2`, 2.0}, - {"foo", `true`, true}, - {"foo", `null`, nil}, - - {nil, `null`, nil}, - {new(int), `null`, nil}, - {(*int)(nil), `null`, nil}, - {new(*int), `null`, new(*int)}, - {(**int)(nil), `null`, nil}, - {intp(1), `null`, nil}, - {intpp(nil), `null`, intpp(nil)}, - {intpp(intp(1)), `null`, intpp(nil)}, -} - -func TestInterfaceSet(t *testing.T) { - for _, tt := range interfaceSetTests { - b := struct{ X interface{} }{tt.pre} - blob := `{"X":` + tt.json + `}` - if err := Unmarshal([]byte(blob), &b); err != nil { - t.Errorf("Unmarshal %#q: %v", blob, err) - continue - } - if !reflect.DeepEqual(b.X, tt.post) { - t.Errorf("Unmarshal %#q into %#v: X=%#v, want %#v", blob, tt.pre, b.X, tt.post) - } - } -} - -// JSON null values should be ignored for primitives and string values instead of resulting in an error. -// Issue 2540 -func TestUnmarshalNulls(t *testing.T) { - jsonData := []byte(`{ - "Bool" : null, - "Int" : null, - "Int8" : null, - "Int16" : null, - "Int32" : null, - "Int64" : null, - "Uint" : null, - "Uint8" : null, - "Uint16" : null, - "Uint32" : null, - "Uint64" : null, - "Float32" : null, - "Float64" : null, - "String" : null}`) - - nulls := All{ - Bool: true, - Int: 2, - Int8: 3, - Int16: 4, - Int32: 5, - Int64: 6, - Uint: 7, - Uint8: 8, - Uint16: 9, - Uint32: 10, - Uint64: 11, - Float32: 12.1, - Float64: 13.1, - String: "14"} - - err := Unmarshal(jsonData, &nulls) - if err != nil { - t.Errorf("Unmarshal of null values failed: %v", err) - } - if !nulls.Bool || nulls.Int != 2 || nulls.Int8 != 3 || nulls.Int16 != 4 || nulls.Int32 != 5 || nulls.Int64 != 6 || - nulls.Uint != 7 || nulls.Uint8 != 8 || nulls.Uint16 != 9 || nulls.Uint32 != 10 || nulls.Uint64 != 11 || - nulls.Float32 != 12.1 || nulls.Float64 != 13.1 || nulls.String != "14" { - - t.Errorf("Unmarshal of null values affected primitives") - } -} - -func TestStringKind(t *testing.T) { - type stringKind string - - var m1, m2 map[stringKind]int - m1 = map[stringKind]int{ - "foo": 42, - } - - data, err := Marshal(m1) - if err != nil { - t.Errorf("Unexpected error marshalling: %v", err) - } - - err = Unmarshal(data, &m2) - if err != nil { - t.Errorf("Unexpected error unmarshalling: %v", err) - } - - if !reflect.DeepEqual(m1, m2) { - t.Error("Items should be equal after encoding and then decoding") - } - -} - -var decodeTypeErrorTests = []struct { - dest interface{} - src string -}{ - {new(string), `{"user": "name"}`}, // issue 4628. - {new(error), `{}`}, // issue 4222 - {new(error), `[]`}, - {new(error), `""`}, - {new(error), `123`}, - {new(error), `true`}, -} - -func TestUnmarshalTypeError(t *testing.T) { - for _, item := range decodeTypeErrorTests { - err := Unmarshal([]byte(item.src), item.dest) - if _, ok := err.(*UnmarshalTypeError); !ok { - t.Errorf("expected type error for Unmarshal(%q, type %T): got %T", - item.src, item.dest, err) - } - } -} - -var unmarshalSyntaxTests = []string{ - "tru", - "fals", - "nul", - "123e", - `"hello`, - `[1,2,3`, - `{"key":1`, - `{"key":1,`, -} - -func TestUnmarshalSyntax(t *testing.T) { - var x interface{} - for _, src := range unmarshalSyntaxTests { - err := Unmarshal([]byte(src), &x) - if _, ok := err.(*SyntaxError); !ok { - t.Errorf("expected syntax error for Unmarshal(%q): got %T", src, err) - } - } -} - -// Test handling of unexported fields that should be ignored. -// Issue 4660 -type unexportedFields struct { - Name string - m map[string]interface{} `json:"-"` - m2 map[string]interface{} `json:"abcd"` -} - -func TestUnmarshalUnexported(t *testing.T) { - input := `{"Name": "Bob", "m": {"x": 123}, "m2": {"y": 456}, "abcd": {"z": 789}}` - want := &unexportedFields{Name: "Bob"} - - out := &unexportedFields{} - err := Unmarshal([]byte(input), out) - if err != nil { - t.Errorf("got error %v, expected nil", err) - } - if !reflect.DeepEqual(out, want) { - t.Errorf("got %q, want %q", out, want) - } -} - -// Time3339 is a time.Time which encodes to and from JSON -// as an RFC 3339 time in UTC. -type Time3339 time.Time - -func (t *Time3339) UnmarshalJSON(b []byte) error { - if len(b) < 2 || b[0] != '"' || b[len(b)-1] != '"' { - return fmt.Errorf("types: failed to unmarshal non-string value %q as an RFC 3339 time", b) - } - tm, err := time.Parse(time.RFC3339, string(b[1:len(b)-1])) - if err != nil { - return err - } - *t = Time3339(tm) - return nil -} - -func TestUnmarshalJSONLiteralError(t *testing.T) { - var t3 Time3339 - err := Unmarshal([]byte(`"0000-00-00T00:00:00Z"`), &t3) - if err == nil { - t.Fatalf("expected error; got time %v", time.Time(t3)) - } - if !strings.Contains(err.Error(), "range") { - t.Errorf("got err = %v; want out of range error", err) - } -} - -// Test that extra object elements in an array do not result in a -// "data changing underfoot" error. -// Issue 3717 -func TestSkipArrayObjects(t *testing.T) { - json := `[{}]` - var dest [0]interface{} - - err := Unmarshal([]byte(json), &dest) - if err != nil { - t.Errorf("got error %q, want nil", err) - } -} - -// Test semantics of pre-filled struct fields and pre-filled map fields. -// Issue 4900. -func TestPrefilled(t *testing.T) { - ptrToMap := func(m map[string]interface{}) *map[string]interface{} { return &m } - - // Values here change, cannot reuse table across runs. - var prefillTests = []struct { - in string - ptr interface{} - out interface{} - }{ - { - in: `{"X": 1, "Y": 2}`, - ptr: &XYZ{X: float32(3), Y: int16(4), Z: 1.5}, - out: &XYZ{X: float64(1), Y: float64(2), Z: 1.5}, - }, - { - in: `{"X": 1, "Y": 2}`, - ptr: ptrToMap(map[string]interface{}{"X": float32(3), "Y": int16(4), "Z": 1.5}), - out: ptrToMap(map[string]interface{}{"X": float64(1), "Y": float64(2), "Z": 1.5}), - }, - } - - for _, tt := range prefillTests { - ptrstr := fmt.Sprintf("%v", tt.ptr) - err := Unmarshal([]byte(tt.in), tt.ptr) // tt.ptr edited here - if err != nil { - t.Errorf("Unmarshal: %v", err) - } - if !reflect.DeepEqual(tt.ptr, tt.out) { - t.Errorf("Unmarshal(%#q, %s): have %v, want %v", tt.in, ptrstr, tt.ptr, tt.out) - } - } -} - -var invalidUnmarshalTests = []struct { - v interface{} - want string -}{ - {nil, "json: Unmarshal(nil)"}, - {struct{}{}, "json: Unmarshal(non-pointer struct {})"}, - {(*int)(nil), "json: Unmarshal(nil *int)"}, -} - -func TestInvalidUnmarshal(t *testing.T) { - buf := []byte(`{"a":"1"}`) - for _, tt := range invalidUnmarshalTests { - err := Unmarshal(buf, tt.v) - if err == nil { - t.Errorf("Unmarshal expecting error, got nil") - continue - } - if got := err.Error(); got != tt.want { - t.Errorf("Unmarshal = %q; want %q", got, tt.want) - } - } -} diff --git a/src/pkg/encoding/json/encode.go b/src/pkg/encoding/json/encode.go deleted file mode 100644 index b63538c92..000000000 --- a/src/pkg/encoding/json/encode.go +++ /dev/null @@ -1,1175 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package json implements encoding and decoding of JSON objects as defined in -// RFC 4627. The mapping between JSON objects and Go values is described -// in the documentation for the Marshal and Unmarshal functions. -// -// See "JSON and Go" for an introduction to this package: -// http://golang.org/doc/articles/json_and_go.html -package json - -import ( - "bytes" - "encoding" - "encoding/base64" - "math" - "reflect" - "runtime" - "sort" - "strconv" - "strings" - "sync" - "unicode" - "unicode/utf8" -) - -// Marshal returns the JSON encoding of v. -// -// Marshal traverses the value v recursively. -// If an encountered value implements the Marshaler interface -// and is not a nil pointer, Marshal calls its MarshalJSON method -// to produce JSON. The nil pointer exception is not strictly necessary -// but mimics a similar, necessary exception in the behavior of -// UnmarshalJSON. -// -// Otherwise, Marshal uses the following type-dependent default encodings: -// -// Boolean values encode as JSON booleans. -// -// Floating point, integer, and Number values encode as JSON numbers. -// -// String values encode as JSON strings coerced to valid UTF-8, -// replacing invalid bytes with the Unicode replacement rune. -// The angle brackets "<" and ">" are escaped to "\u003c" and "\u003e" -// to keep some browsers from misinterpreting JSON output as HTML. -// Ampersand "&" is also escaped to "\u0026" for the same reason. -// -// Array and slice values encode as JSON arrays, except that -// []byte encodes as a base64-encoded string, and a nil slice -// encodes as the null JSON object. -// -// Struct values encode as JSON objects. Each exported struct field -// becomes a member of the object unless -// - the field's tag is "-", or -// - the field is empty and its tag specifies the "omitempty" option. -// The empty values are false, 0, any -// nil pointer or interface value, and any array, slice, map, or string of -// length zero. The object's default key string is the struct field name -// but can be specified in the struct field's tag value. The "json" key in -// the struct field's tag value is the key name, followed by an optional comma -// and options. Examples: -// -// // Field is ignored by this package. -// Field int `json:"-"` -// -// // Field appears in JSON as key "myName". -// Field int `json:"myName"` -// -// // Field appears in JSON as key "myName" and -// // the field is omitted from the object if its value is empty, -// // as defined above. -// Field int `json:"myName,omitempty"` -// -// // Field appears in JSON as key "Field" (the default), but -// // the field is skipped if empty. -// // Note the leading comma. -// Field int `json:",omitempty"` -// -// The "string" option signals that a field is stored as JSON inside a -// JSON-encoded string. It applies only to fields of string, floating point, -// or integer types. This extra level of encoding is sometimes used when -// communicating with JavaScript programs: -// -// Int64String int64 `json:",string"` -// -// The key name will be used if it's a non-empty string consisting of -// only Unicode letters, digits, dollar signs, percent signs, hyphens, -// underscores and slashes. -// -// Anonymous struct fields are usually marshaled as if their inner exported fields -// were fields in the outer struct, subject to the usual Go visibility rules amended -// as described in the next paragraph. -// An anonymous struct field with a name given in its JSON tag is treated as -// having that name, rather than being anonymous. -// -// The Go visibility rules for struct fields are amended for JSON when -// deciding which field to marshal or unmarshal. If there are -// multiple fields at the same level, and that level is the least -// nested (and would therefore be the nesting level selected by the -// usual Go rules), the following extra rules apply: -// -// 1) Of those fields, if any are JSON-tagged, only tagged fields are considered, -// even if there are multiple untagged fields that would otherwise conflict. -// 2) If there is exactly one field (tagged or not according to the first rule), that is selected. -// 3) Otherwise there are multiple fields, and all are ignored; no error occurs. -// -// Handling of anonymous struct fields is new in Go 1.1. -// Prior to Go 1.1, anonymous struct fields were ignored. To force ignoring of -// an anonymous struct field in both current and earlier versions, give the field -// a JSON tag of "-". -// -// Map values encode as JSON objects. -// The map's key type must be string; the object keys are used directly -// as map keys. -// -// Pointer values encode as the value pointed to. -// A nil pointer encodes as the null JSON object. -// -// Interface values encode as the value contained in the interface. -// A nil interface value encodes as the null JSON object. -// -// Channel, complex, and function values cannot be encoded in JSON. -// Attempting to encode such a value causes Marshal to return -// an UnsupportedTypeError. -// -// JSON cannot represent cyclic data structures and Marshal does not -// handle them. Passing cyclic structures to Marshal will result in -// an infinite recursion. -// -func Marshal(v interface{}) ([]byte, error) { - e := &encodeState{} - err := e.marshal(v) - if err != nil { - return nil, err - } - return e.Bytes(), nil -} - -// MarshalIndent is like Marshal but applies Indent to format the output. -func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error) { - b, err := Marshal(v) - if err != nil { - return nil, err - } - var buf bytes.Buffer - err = Indent(&buf, b, prefix, indent) - if err != nil { - return nil, err - } - return buf.Bytes(), nil -} - -// HTMLEscape appends to dst the JSON-encoded src with <, >, &, U+2028 and U+2029 -// characters inside string literals changed to \u003c, \u003e, \u0026, \u2028, \u2029 -// so that the JSON will be safe to embed inside HTML `, - []string{ - `"\u003cb\u003e \"foo%\" O'Reilly \u0026bar;"`, - `"a[href =~ \"//example.com\"]#foo"`, - `"Hello, \u003cb\u003eWorld\u003c/b\u003e \u0026amp;tc!"`, - `" dir=\"ltr\""`, - // Not escaped. - `c && alert("Hello, World!");`, - // Escape sequence not over-escaped. - `"Hello, World & O'Reilly\x21"`, - `"greeting=H%69\u0026addressee=(World)"`, - }, - }, - { - `