gvisor.dev/gvisor@v0.0.0-20240520182842-f9d4d51c7e0f/tools/checklocks/test/globals.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 20 "gvisor.dev/gvisor/tools/checklocks/test/crosspkg" 21 ) 22 23 var ( 24 globalMu sync.Mutex 25 globalRWMu sync.RWMutex 26 ) 27 28 var globalStruct struct { 29 mu sync.Mutex 30 // +checklocks:mu 31 guardedField int 32 } 33 34 var otherStruct struct { 35 // +checklocks:globalMu 36 guardedField1 int 37 // +checklocks:globalRWMu 38 guardedField2 int 39 // +checklocks:globalStruct.mu 40 guardedField3 int 41 } 42 43 func testGlobalValid() { 44 globalMu.Lock() 45 otherStruct.guardedField1 = 1 46 globalMu.Unlock() 47 48 globalRWMu.Lock() 49 otherStruct.guardedField2 = 1 50 globalRWMu.Unlock() 51 52 globalRWMu.RLock() 53 _ = otherStruct.guardedField2 54 globalRWMu.RUnlock() 55 56 globalStruct.mu.Lock() 57 globalStruct.guardedField = 1 58 otherStruct.guardedField3 = 1 59 globalStruct.mu.Unlock() 60 } 61 62 // +checklocks:globalStruct.mu 63 func testGlobalValidPreconditions0() { 64 globalStruct.guardedField = 1 65 } 66 67 // +checklocks:globalMu 68 func testGlobalValidPreconditions1() { 69 otherStruct.guardedField1 = 1 70 } 71 72 // +checklocks:globalRWMu 73 func testGlobalValidPreconditions2() { 74 otherStruct.guardedField2 = 1 75 } 76 77 // +checklocks:globalStruct.mu 78 func testGlobalValidPreconditions3() { 79 otherStruct.guardedField3 = 1 80 } 81 82 func testGlobalInvalid() { 83 globalStruct.guardedField = 1 // +checklocksfail 84 otherStruct.guardedField1 = 1 // +checklocksfail 85 otherStruct.guardedField2 = 1 // +checklocksfail 86 otherStruct.guardedField3 = 1 // +checklocksfail 87 } 88 89 func testCrosspkgGlobalValid() { 90 crosspkg.FooMu.Lock() 91 crosspkg.Foo = 1 92 crosspkg.FooMu.Unlock() 93 } 94 95 func testCrosspkgGlobalInvalid() { 96 crosspkg.Foo = 1 // +checklocksfail 97 }