github.com/hxx258456/ccgo@v0.0.5-0.20230213014102-48b35f46f66f/gmtls/link_test.go (about) 1 // Copyright 2022 s1ren@github.com/hxx258456. 2 3 /* 4 gmtls是基于`golang/go`的`tls`包实现的国密改造版本。 5 对应版权声明: thrid_licenses/github.com/golang/go/LICENSE 6 */ 7 8 package gmtls 9 10 import ( 11 "bytes" 12 "os" 13 "os/exec" 14 "path/filepath" 15 "testing" 16 17 "github.com/hxx258456/ccgo/internal/testenv" 18 ) 19 20 // Tests that the linker is able to remove references to the Client or Server if unused. 21 func TestLinkerGC(t *testing.T) { 22 if testing.Short() { 23 t.Skip("skipping in short mode") 24 } 25 t.Parallel() 26 goBin := testenv.GoToolPath(t) 27 testenv.MustHaveGoBuild(t) 28 29 tests := []struct { 30 name string 31 program string 32 want []string 33 bad []string 34 }{ 35 { 36 name: "empty_import", 37 program: `package main 38 import _ "crypto/tls" 39 func main() {} 40 `, 41 bad: []string{ 42 "tls.(*Conn)", 43 "type.crypto/tls.clientHandshakeState", 44 "type.crypto/tls.serverHandshakeState", 45 }, 46 }, 47 { 48 name: "client_and_server", 49 program: `package main 50 import "crypto/tls" 51 func main() { 52 tls.Dial("", "", nil) 53 tls.Server(nil, nil) 54 } 55 `, 56 want: []string{ 57 "crypto/tls.(*Conn).clientHandshake", 58 "crypto/tls.(*Conn).serverHandshake", 59 }, 60 }, 61 { 62 name: "only_client", 63 program: `package main 64 import "crypto/tls" 65 func main() { tls.Dial("", "", nil) } 66 `, 67 want: []string{ 68 "crypto/tls.(*Conn).clientHandshake", 69 }, 70 bad: []string{ 71 "crypto/tls.(*Conn).serverHandshake", 72 }, 73 }, 74 // TODO: add only_server like func main() { tls.Server(nil, nil) } 75 // That currently brings in the client via Conn.handleRenegotiation. 76 77 } 78 tmpDir := t.TempDir() 79 goFile := filepath.Join(tmpDir, "x.go") 80 exeFile := filepath.Join(tmpDir, "x.exe") 81 for _, tt := range tests { 82 t.Run(tt.name, func(t *testing.T) { 83 if err := os.WriteFile(goFile, []byte(tt.program), 0644); err != nil { 84 t.Fatal(err) 85 } 86 _ = os.Remove(exeFile) 87 cmd := exec.Command(goBin, "build", "-o", "x.exe", "x.go") 88 cmd.Dir = tmpDir 89 if out, err := cmd.CombinedOutput(); err != nil { 90 t.Fatalf("compile: %v, %s", err, out) 91 } 92 93 cmd = exec.Command(goBin, "tool", "nm", "x.exe") 94 cmd.Dir = tmpDir 95 nm, err := cmd.CombinedOutput() 96 if err != nil { 97 t.Fatalf("nm: %v, %s", err, nm) 98 } 99 for _, sym := range tt.want { 100 if !bytes.Contains(nm, []byte(sym)) { 101 t.Errorf("expected symbol %q not found", sym) 102 } 103 } 104 for _, sym := range tt.bad { 105 if bytes.Contains(nm, []byte(sym)) { 106 t.Errorf("unexpected symbol %q found", sym) 107 } 108 } 109 }) 110 } 111 }