Skip to content

Commit

Permalink
added FP fixes for racy append to slice and map rules
Browse files Browse the repository at this point in the history
  • Loading branch information
hex0punk committed Oct 4, 2023
1 parent 626932d commit eb47f6e
Show file tree
Hide file tree
Showing 4 changed files with 59 additions and 0 deletions.
25 changes: 25 additions & 0 deletions go/racy-append-to-slice.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,9 @@ func main() {

res6 := appendToSlice_FP4()
printResults(res6)

res7 := appendToSlice_FP5()
printResults(res7)
}

func appendToSlice1() []int {
Expand Down Expand Up @@ -146,6 +149,28 @@ func appendToSlice_FP4() []int {
return r
}

func appendToSlice_FP5() []int {
// FP: The `append` is done inside a defer lock
var wg sync.WaitGroup
var rMut sync.Mutex
var r []int
for i := 0; i < 10; i++ {
wg.Add(1)
go func(iCpy int) {
defer wg.Done()
m := iCpy * 2
// ok: racy-append-to-slice
rMut.Lock()
defer rMut.Unlock()
r = append(r, m)
}(i)
}

wg.Wait()

return r
}

func printResults(results []int) {
for v, _ := range results {
fmt.Println(v)
Expand Down
4 changes: 4 additions & 0 deletions go/racy-append-to-slice.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -48,3 +48,7 @@ rules:
$MUTEX.Lock()
...
$MUTEX.Unlock()
- pattern-not-inside: |
$MUTEX.Lock()
defer $MUTEX.Unlock()
...
26 changes: 26 additions & 0 deletions go/racy-write-to-map.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ func main() {
fmt.Println("appendToMap_FP4:")
res6 := appendToMap_FP4()
printMap(res6)

fmt.Println("appendToMap_FP5:")
res7 := appendToMap_FP5()
printMap(res7)
}

func appendToMap1() map[int]string {
Expand Down Expand Up @@ -160,6 +164,28 @@ func appendToMap_FP4() map[int]string {
return r
}

func appendToMap_FP5() map[int]string {
// FP: The map write is done inside a defer lock
var wg sync.WaitGroup
r := make(map[int]string)
var rMut sync.Mutex

for i := 0; i < 10; i++ {
wg.Add(1)
go func(iCpy int) {
defer wg.Done()
// ok: racy-write-to-map
rMut.Lock()
defer rMut.Unlock()
r[iCpy] = fmt.Sprintf("number-%d", iCpy)
}(i)
}

wg.Wait()

return r
}

func printMap(results map[int]string) {
for k, v := range results {
fmt.Printf("key: %d, val: %s\n", k, v)
Expand Down
4 changes: 4 additions & 0 deletions go/racy-write-to-map.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,7 @@ rules:
$MUTEX.Lock()
...
$MUTEX.Unlock()
- pattern-not-inside: |
$MUTEX.Lock()
defer $MUTEX.Unlock()
...

0 comments on commit eb47f6e

Please sign in to comment.