Skip to content

fix When parsing {}, the parser enters startLabelName state with p.cu…#906

Open
GuoFlight wants to merge 1 commit into
prometheus:mainfrom
GuoFlight:main
Open

fix When parsing {}, the parser enters startLabelName state with p.cu…#906
GuoFlight wants to merge 1 commit into
prometheus:mainfrom
GuoFlight:main

Conversation

@GuoFlight
Copy link
Copy Markdown

@GuoFlight GuoFlight commented May 12, 2026

expfmt: panic in TextParser.startLabelName when parsing empty braces "{}"

Title: expfmt: panic in TextParser.startLabelName when parsing empty braces "{}"

What happened?

  • Parsing malformed input {} causes a panic due to nil pointer dereference in startLabelName().

    How to reproduce it?

  package main

  import (
      "bytes"
      "fmt"

      dto "github.com/prometheus/client_model/go"
      "github.com/prometheus/common/expfmt"
  )

  func main() {
      buf := bytes.NewBuffer([]byte(`{}`))
      decoder := expfmt.NewDecoder(buf, expfmt.NewFormat(expfmt.TypeUnknown))
      var mf dto.MetricFamily
      if err := decoder.Decode(&mf); err != nil {
          fmt.Printf("Error: %v\n", err)
      }
  }

Stack trace:

  panic: runtime error: invalid memory address or nil pointer dereference
  [signal SIGSEGV: segmentation violation code=0x2 addr=0x30 pc=0x...]

  goroutine 1 [running]:
  github.com/prometheus/common/expfmt.(*TextParser).startLabelName(0x...)
      expfmt/text_parse.go:341 +0x44
  github.com/prometheus/common/expfmt.(*TextParser).TextToMetricFamilies(0x..., ...)
      expfmt/text_parse.go:118 +0x54
  github.com/prometheus/common/expfmt.(*textDecoder).Decode(0x..., 0x...)
      expfmt/decode.go:155 +0x74

Root cause

In expfmt/text_parse.go, the startLabelName() function accesses p.currentMetric.Label without checking if p.currentMetric is nil:

  if p.currentByte == '}' {
      p.currentMetric.Label = append(p.currentMetric.Label, p.currentLabelPairs...)  // Line 341 - PANIC here
      ...
  }

When parsing {}, the parser enters startLabelName state with p.currentMetric == nil, causing the crash.

Expected behavior

  • Return a parse error instead of panicking, similar to other malformed inputs.

Suggested fix

  • Add a nil check before accessing p.currentMetric:
  if p.currentByte == '}' {
      if p.currentMetric == nil {
          p.parseError("unexpected '}' without metric name")
          p.currentLabelPairs = nil
          return nil
      }
      p.currentMetric.Label = append(p.currentMetric.Label, p.currentLabelPairs...)
      ...
  }

Sources:

…rrentMetric == nil, causing the crash.

Signed-off-by: 京城郭少 <39666162+GuoFlight@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant