dgryski / semgrep-go

Go rules for semgrep and go-ruleguard
MIT License
457 stars 37 forks source link

Check against calls of already deferred functions before return #20

Open ainar-g opened 3 years ago

ainar-g commented 3 years ago

Consider a piece code like this:

func f() (err error) {
        v := open()
        defer v.close()

        err = do1(v)
        if err != nil {
                return fmt.Errorf("thing 1: %w", err)
        }

        err = do2(v)
        if err != nil {
                // Sic!
                v.close()
                return fmt.Errorf("thing 2: %w", err)
        }

        err = do3(v)
        if err != nil {
                return fmt.Errorf("thing 3: %w", err)
        }

        return nil
}

The defer was probably added later, and the developer who added the defer probably forgot to remove the v.close() in the second error check. Depending on what v.close() does, it can either have no consequences, be intentional and have a purpose, or crash the program. So I think this could be marked as suspicious.