Skip to content

Commit

Permalink
[c2cpg] Fixed NPE in case of broken catch clauses (joernio#4493)
Browse files Browse the repository at this point in the history
  • Loading branch information
max-leuthaeuser authored Apr 26, 2024
1 parent 568c363 commit 00cfa4d
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,9 @@ trait AstCreatorHelper(implicit withSchemaValidation: ValidationMode) { this: As
protected def nullSafeAst(node: IASTExpression): Ast =
Option(node).map(astForNode).getOrElse(Ast())

protected def nullSafeAst(node: IASTDeclaration): Seq[Ast] =
Option(node).map(astsForDeclaration).getOrElse(Seq.empty)

protected def nullSafeAst(node: IASTStatement, argIndex: Int = -1): Seq[Ast] = {
Option(node).map(astsForStatement(_, argIndex)).getOrElse(Seq.empty)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -133,8 +133,8 @@ trait AstForStatementsCreator(implicit withSchemaValidation: ValidationMode) { t
private def astForCatchHandler(catchHandler: ICPPASTCatchHandler, argIndex: Int): Ast = {
val catchNode =
controlStructureNode(catchHandler, ControlStructureTypes.CATCH, "catch").order(argIndex).argumentIndex(argIndex)
val declAst = astsForDeclaration(catchHandler.getDeclaration)
val bodyAst = astsForStatement(catchHandler.getCatchBody)
val declAst = nullSafeAst(catchHandler.getDeclaration)
val bodyAst = nullSafeAst(catchHandler.getCatchBody)
Ast(catchNode).withChildren(declAst).withChildren(bodyAst)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1263,6 +1263,31 @@ class AstCreationPassTests extends AstC2CpgSuite {
}
}

"be correct for try with multiple catches and broken catch clause" in {
val cpg: Cpg = code(
"""
|int main() {
| try {}
| catch (int a) {}
| catch (...) {}
|}
|""".stripMargin,
"file.cpp"
)
inside(cpg.controlStructure.isTry.l) { case List(t) =>
val List(tryBlock) = t.astChildren.isBlock.l
tryBlock.order shouldBe 1
tryBlock.astChildren shouldBe empty
val List(catchA, catchB) = t.astChildren.isControlStructure.isCatch.l
catchA.order shouldBe 2
catchA.ast.isBlock.astChildren shouldBe empty
catchA.ast.isLocal.name.l shouldBe List("a")
catchB.order shouldBe 3
catchB.ast.isBlock.astChildren shouldBe empty
catchB.ast.isLocal shouldBe empty
}
}

"be correct for constructor initializer" in {
val cpg = code(
"""
Expand Down

0 comments on commit 00cfa4d

Please sign in to comment.