Debian Codegraph @

encode_stack_copy_test.go

raw
1 package json_test
2
3 import (
4 stdjson "encoding/json"
5 "sync"
6 "testing"
7
8 "github.com/goccy/go-json"
9 )
10
11 // The stack of a goroutine is copied when it grows, and only the pointers are updated.
12 // The encoder must not read the value being encoded from the stack which has been freed.
13
14 type stackGrowingMarshaler struct{}
15
16 //go:noinline
17 func growStack(n int) int {
18 var pad [256]int
19 pad[n%256] = n
20 if n == 0 {
21 return pad[0]
22 }
23 return growStack(n-1) + pad[n%256]
24 }
25
26 // MarshalJSON grows the stack while the value which has it is being encoded,
27 // and makes the other goroutines reuse and overwrite the stack which has been freed.
28 func (stackGrowingMarshaler) MarshalJSON() ([]byte, error) {
29 growStack(200)
30 var wg sync.WaitGroup
31 for i := 0; i < 64; i++ {
32 wg.Add(1)
33 go func() {
34 defer wg.Done()
35 growStack(50)
36 }()
37 }
38 wg.Wait()
39 return []byte("1"), nil
40 }
41
42 type stackCopiedValue struct {
43 G stackGrowingMarshaler
44 A string
45 B int
46 C string
47 }
48
49 func TestEncodeWhileStackIsCopied(t *testing.T) {
50 expected, err := stdjson.Marshal(stackCopiedValue{A: "aaaaaaaaaaaaaaaa", B: 123456789, C: "cccccccccccccccc"})
51 if err != nil {
52 t.Fatal(err)
53 }
54 for _, test := range []struct {
55 name string
56 marshal func(any) ([]byte, error)
57 }{
58 {"Marshal", json.Marshal},
59 {"MarshalNoEscape", json.MarshalNoEscape},
60 {"MarshalIndent", func(v any) ([]byte, error) { return json.MarshalIndent(v, "", "") }},
61 } {
62 t.Run(test.name, func(t *testing.T) {
63 if test.name == "MarshalIndent" {
64 compact, err := stdjson.MarshalIndent(stackCopiedValue{A: "aaaaaaaaaaaaaaaa", B: 123456789, C: "cccccccccccccccc"}, "", "")
65 if err != nil {
66 t.Fatal(err)
67 }
68 expected = compact
69 }
70 var (
71 wg sync.WaitGroup
72 mu sync.Mutex
73 wrong []string
74 )
75 for i := 0; i < 200; i++ {
76 wg.Add(1)
77 // a new goroutine starts with a small stack.
78 go func() {
79 defer wg.Done()
80 v := stackCopiedValue{A: "aaaaaaaaaaaaaaaa", B: 123456789, C: "cccccccccccccccc"}
81 got, err := test.marshal(&v)
82 if err != nil || string(got) != string(expected) {
83 mu.Lock()
84 wrong = append(wrong, string(got))
85 mu.Unlock()
86 }
87 }()
88 }
89 wg.Wait()
90 if len(wrong) != 0 {
91 t.Fatalf("%d / 200 results are wrong. expected %s but got %s", len(wrong), expected, wrong[0])
92 }
93 })
94 }
95 }