gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/tools/checklocks/test/atomics.go (about) 1 // Copyright 2020 The gVisor Authors. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package test 16 17 import ( 18 "sync" 19 "sync/atomic" 20 ) 21 22 type atomicStruct struct { 23 accessedNormally int32 24 25 // +checkatomic 26 accessedAtomically int32 27 28 // +checklocksignore 29 ignored int32 30 31 wrapper atomic.Int32 // safe without any annotations 32 } 33 34 func testNormalAccess(tc *atomicStruct, v chan int32, p chan *int32) { 35 v <- tc.accessedNormally 36 p <- &tc.accessedNormally 37 } 38 39 func testAtomicAccess(tc *atomicStruct, v chan int32) { 40 v <- atomic.LoadInt32(&tc.accessedAtomically) 41 } 42 43 func testAtomicAccessInvalid(tc *atomicStruct, v chan int32) { 44 v <- atomic.LoadInt32(&tc.accessedNormally) // +checklocksfail 45 } 46 47 func testNormalAccessInvalid(tc *atomicStruct, v chan int32, p chan *int32) { 48 v <- tc.accessedAtomically // +checklocksfail 49 p <- &tc.accessedAtomically // +checklocksfail 50 } 51 52 func testIgnored(tc *atomicStruct, v chan int32, p chan *int32) { 53 v <- atomic.LoadInt32(&tc.ignored) 54 v <- tc.ignored 55 p <- &tc.ignored 56 } 57 58 type atomicMixedStruct struct { 59 mu sync.Mutex 60 61 // +checkatomic 62 // +checklocks:mu 63 accessedMixed int32 64 } 65 66 func testAtomicMixedValidRead(tc *atomicMixedStruct, v chan int32) { 67 v <- atomic.LoadInt32(&tc.accessedMixed) 68 } 69 70 func testAtomicMixedInvalidRead(tc *atomicMixedStruct, v chan int32, p chan *int32) { 71 v <- tc.accessedMixed // +checklocksfail 72 p <- &tc.accessedMixed // +checklocksfail 73 } 74 75 func testAtomicMixedValidLockedWrite(tc *atomicMixedStruct, v chan int32, p chan *int32) { 76 tc.mu.Lock() 77 atomic.StoreInt32(&tc.accessedMixed, 1) 78 tc.mu.Unlock() 79 } 80 81 func testAtomicMixedInvalidLockedWrite(tc *atomicMixedStruct, v chan int32, p chan *int32) { 82 tc.mu.Lock() 83 tc.accessedMixed = 1 // +checklocksfail:2 84 tc.mu.Unlock() 85 } 86 87 func testAtomicMixedInvalidAtomicWrite(tc *atomicMixedStruct, v chan int32, p chan *int32) { 88 atomic.StoreInt32(&tc.accessedMixed, 1) // +checklocksfail 89 } 90 91 func testAtomicMixedInvalidWrite(tc *atomicMixedStruct, v chan int32, p chan *int32) { 92 tc.accessedMixed = 1 // +checklocksfail:2 93 } 94 95 func testAtomicWrapper(tc *atomicStruct, v chan int32) { 96 v <- tc.wrapper.Load() 97 v <- tc.wrapper.Add(33) 98 tc.wrapper.Store(44) 99 }