trailofbits / semgrep-rules

Semgrep queries developed by Trail of Bits.
GNU Affero General Public License v3.0
317 stars 33 forks source link

`iterate-over-empty-map` warning on map initialised at the declaration #36

Open NitriKx opened 1 year ago

NitriKx commented 1 year ago

Hello,

I'm struggling to understand why the following code function has a iterate-over-empty-map:

func iter2(){
    m := map[string]int {
        "toto": 1
    }

    fmt.Println("iterating")
    for v := range m {
        fmt.Println("map item: ", v)
    }
}

Could you help me with that? 🙏 cc @Caomoji

GrosQuildu commented 1 year ago

Interesting. Looks like Semgrep coerces map[$T1]$T2{} and make(map[$T1]$T2). Probably a Semgrep bug? Simple repro is that both queries below matches all three code lines:

- pattern: |
    $C = map[$T1] $T2{...}
- pattern: |
    $C = make(map[$T1] $T2, ...)
func main() {
    m := make(map[string]int)
    m2 := map[string]int{}
    m3 := map[string]int{"a":1}
}

Will report that upstream, unless @Vasco-jofra has some thoughts here.

GrosQuildu commented 11 months ago

https://github.com/returntocorp/semgrep/issues/8980

GrosQuildu commented 9 months ago

Waiting for upstream fix. More tests for the future:

func iter1_2(){
       // ruleid: iterate-over-empty-map
       m := make(map[string]int, 5)
       for v := range m {
               fmt.Println("map item: ", v)
       }
}

func iter1_3(){
       // ruleid: iterate-over-empty-map
       m := map[string]int{}
       for v := range m {
               fmt.Println("map item: ", v)
       }
}

func iter1_FP_5(){
       // ok: iterate-over-empty-map
       m := make(map[string]int, 1)

       m["v1"]--

       for v := range m {
               fmt.Println("map item: ", v)
       }
}

func iter1_FP_6(){
       // ok: iterate-over-empty-map
       m := map[string]int{"test": 1}
       for v := range m {
               fmt.Println("map item: ", v)
       }
}
mschwager commented 3 months ago

I just ran into this too. I wrote a test here so we'll know when this is fixed upstream: https://github.com/trailofbits/semgrep-rules/pull/62

The above issue is very similar, or a dupe of https://github.com/semgrep/semgrep/issues/9558