Skip to content

[bug] Missing defer for pf.Close() on error path in CPU profiling #1820

@docker-agent

Description

@docker-agent

🟠 high - bug

File: pkg/runtime/runtime.go (line 808)

Code

	// Start CPU profiling if requested
	if f.cpuProfile != "" {
		pf, err := os.Create(f.cpuProfile)
		if err != nil {
			return fmt.Errorf("failed to create CPU profile: %w", err)
		}
		if err := pprof.StartCPUProfile(pf); err != nil {
			pf.Close()
			return fmt.Errorf("failed to start CPU profile: %w", err)
		}
		defer pprof.StopCPUProfile()
		defer pf.Close()
		slog.Info("CPU profiling enabled", "file", f.cpuProfile)
	}

Problem

In the runOrExec function, if pprof.StartCPUProfile(pf) returns an error, pf.Close() is called directly. However, if the return statement is reached, the defer pf.Close() line, which is outside this if block, will not be executed. This means pf will not be closed if pprof.StartCPUProfile fails, leading to a file descriptor leak.

Suggested Fix

Move defer pf.Close() immediately after pf, err := os.Create(f.cpuProfile) to ensure the file is always closed, regardless of subsequent errors.


Found by nightly codebase scan

Metadata

Metadata

Assignees

No one assigned

    Labels

    automatedIssues created by cagentkind/bugSomething isn't working

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions