goplus / llgo

A Go compiler based on LLVM in order to better integrate Go with the C ecosystem including Python
Apache License 2.0
365 stars 26 forks source link

Unexcept nil pointer dereference with closure #804

Open luoliwoshang opened 2 months ago

luoliwoshang commented 2 months ago

An unexpected invalid memory address or nil pointer dereference error occurs when performing a nil check (== nil) on a variable within the switch statement cases inside a closure. This issue appears in all cases of the switch statement except for the first case. The program successfully executes the first case but panics when attempting to execute any subsequent case.

package main

import (
    "fmt"
)

func getList(kind int) {
    params := []int{}
    visit(kind, func(childKind int) {
        switch childKind {
        case 1:
            fmt.Printf("Case 1:params is nil: %t\n", params == nil)
            fmt.Printf("Length of params: %d\n", len(params))
        case 2:
            fmt.Printf("Case 2:params is nil: %t\n", params == nil)
            fmt.Printf("Length of params: %d\n", len(params))
                case 3:
            fmt.Printf("Case 3:params is nil: %t\n", params == nil)
            fmt.Printf("Length of params: %d\n", len(params))
        }
    })
}

func visit(kind int, visitor func(int)) {
    visitor(kind)
}

func main() {
    getList(1)
    getList(2)
}

Expected

❯ go run .
Case 1:params is nil: false
Length of params: 0
Case 2:params is nil: false
Length of params: 0

Actual Got

❯ llgo run .
Case 1:params is nil: false
Length of params: 0
panic: runtime error: invalid memory address or nil pointer dereference

This behavior is consistent whether using a switch statement or an if-else structure. For example, the following if-else structure exhibits the same behavior:

if childKind == 1 {
    fmt.Printf("Case 1:params is nil: %t\n", params == nil)
    fmt.Printf("Length of params: %d\n", len(params))
} else if childKind == 2 {
    fmt.Printf("Case 2:params is nil: %t\n", params == nil)
    fmt.Printf("Length of params: %d\n", len(params))
} else if childKind == 3 {
    fmt.Printf("Case 3:params is nil: %t\n", params == nil)
    fmt.Printf("Length of params: %d\n", len(params))
}

In this case, the first if statement (childKind == 1) executes successfully, but the program panics when trying to execute either of the else if statements.

Env

llgo version: Latest main branch, commit dbaf12b0435d97dcd0294828d9f2f03fdc13b053

luoliwoshang commented 2 months ago

https://github.com/goplus/llgo/pull/775 This PR can resolve this question