codeql icon indicating copy to clipboard operation
codeql copied to clipboard

Struct Path Retrieval for Fields in Go

Open TwinIsland opened this issue 1 year ago • 2 comments

Description of the issue I’m currently working on building a tool and need help getting the full struct path for struct field in CodeQL.

For example, consider the following Go code:

	t3 := PtrStruct{type2_ptr: &MyType2{
		id: 2,
	}}

I have DataFlow::Node for the id field and want to retrieve its full struct path as string, i.e. PtrStruct.type2_ptr.id.

Here’s my current approach:

class StructFieldNode extends DataFlow::Node {
  StructFieldNode() {
    exists(KeyValueExpr pair | this.asExpr() = pair.getValue() |
      exists(StructLit all | pair = all.getAnElement())
    )
  }

  StructFieldNode get_parent() {
    exists(Write w, Field f, DataFlow::Node base, DataFlow::Node value |
      w.writesField(base, f, value) and
      value = this
    |
      base instanceof StructFieldNode and base = result
    )
  }

  Field get_field() {
    exists(Write w, Field f, DataFlow::Node base, DataFlow::Node value |
      w.writesField(base, f, value) and
      value = this
    |
      f = result
    )
  }

  string pp() {
    this.get_parent().(StructFieldNode).pp() + "." + this.get_field().getName() = result
    or
    exists(DeclaredType dall |
      exists(StructType sall | sall = dall.getSpec().getTypeExpr().getType() |
        sall.getOwnField(this.get_field().getName(), _) = this.get_field()
      )
    |
      dall + "." + this.get_field().getName() = result
    )
  }
}

This approach sometimes fails, particularly when the field write involves a pointer type. I would appreciate any advice or alternative solutions to address this issue. Thanks!!!

TwinIsland avatar Aug 13 '24 07:08 TwinIsland

Could you provide an example where this fails, and the output you would like to see?

smowton avatar Aug 16 '24 09:08 smowton

You may need to be careful with embedded fields, otherwise you could have the same field having two different paths depending on how it is referred to.

owen-mc avatar Aug 16 '24 13:08 owen-mc

This issue is stale because it has been open 14 days with no activity. Comment or remove the Stale label in order to avoid having this issue closed in 7 days.

github-actions[bot] avatar Sep 11 '24 01:09 github-actions[bot]

This issue was closed because it has been inactive for 7 days.

github-actions[bot] avatar Sep 18 '24 01:09 github-actions[bot]