dgryski/semgrep-go

Check against calls of already deferred functions before return

ainar-g opened this issue · 0 comments

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.