From 8b61b0a195bd731d93ef72ed44d0e5028db3385d Mon Sep 17 00:00:00 2001 From: wangtsingx Date: Mon, 13 Jul 2026 16:23:21 +0800 Subject: [PATCH] fix: nil pointer dereference in containerIDFromMountInfo When os.Open fails in containerIDFromMountInfo, the returned *os.File is nil. The deferred closure that calls f.Close() was registered before the error check, causing a nil pointer panic when the mountinfo file cannot be opened. Move the error check before the defer registration to prevent the panic. Also clean up the error handling by removing the now-unnecessary errs variable and using fmt.Errorf directly. --- pkg/host/info.go | 12 +++++------- pkg/host/info_test.go | 8 ++++++++ 2 files changed, 13 insertions(+), 7 deletions(-) diff --git a/pkg/host/info.go b/pkg/host/info.go index 7c8ec5c47..bbbf0b450 100644 --- a/pkg/host/info.go +++ b/pkg/host/info.go @@ -267,19 +267,17 @@ func containsContainerReference(cgroupFile string) (bool, error) { // Supports cgroup v1 and v2. Reading "/proc/1/cpuset" would only work for cgroups v1 // mountInfo is the path: "/proc/self/mountinfo" func containerIDFromMountInfo(mountInfo string) (string, error) { - var errs error mInfoFile, err := os.Open(mountInfo) + if err != nil { + return "", fmt.Errorf("container ID not found in %s: %w", mountInfo, err) + } defer func(f *os.File) { closeErr := f.Close() if closeErr != nil { - errs = errors.Join(err, closeErr) + err = errors.Join(err, closeErr) } }(mInfoFile) - if err != nil { - return "", errors.Join(errs, err) - } - fileScanner := bufio.NewScanner(mInfoFile) fileScanner.Split(bufio.ScanLines) @@ -298,7 +296,7 @@ func containerIDFromMountInfo(mountInfo string) (string, error) { } } - return "", errors.Join(errs, fmt.Errorf("container ID not found in %s", mountInfo)) + return "", fmt.Errorf("container ID not found in %s", mountInfo) } // containerIDFromPatterns checks a word against multiple regex patterns to extract the container ID. diff --git a/pkg/host/info_test.go b/pkg/host/info_test.go index c0a24bc19..4d3d6d54e 100644 --- a/pkg/host/info_test.go +++ b/pkg/host/info_test.go @@ -637,6 +637,14 @@ func TestInfo_ParseOsReleaseFile(t *testing.T) { } } +func TestInfo_containerIDFromMountInfo(t *testing.T) { + t.Run("Test 1: non-existent mountinfo file returns error without panic", func(t *testing.T) { + _, err := containerIDFromMountInfo("/non/existent/mountinfo/path") + require.Error(t, err) + assert.Contains(t, err.Error(), "container ID not found in") + }) +} + func TestInfo_containerIDFromECS(t *testing.T) { ctx := context.Background()