fix: prevent nil pointer dereference in getFuncDoc when parsing depen… #2044
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
#2042
Fix nil pointer dereference in getFuncDoc function when parsing dependencies
Problem
When parsing dependencies with
ParseDependency
enabled, swag encounters a segmentation fault due to nil pointer dereferences in thegetFuncDoc
function. This occurs when the parser encounters AST nodes from standard library types (likeatomic.Int32
,json.scanner
,ecdh.PrivateKey
, etc.) that don't have all their fields properly initialized.Error Stack Trace:
Root Cause
The
getFuncDoc
function was accessing AST node fields without proper nil checks:*ast.GenDecl
case, it accessedastDecl.Specs[0]
without checking ifastDecl.Specs
was empty*ast.ValueSpec
case, it accessedastDecl.Values[0]
without checking ifastDecl.Values
was emptyvalue.Obj.Decl
without checking ifvalue.Obj
orvalue.Obj.Decl
were nilWhen parsing dependencies, especially standard library packages, these AST nodes may not have all fields initialized, leading to nil pointer dereferences.
Solution
Added comprehensive nil checks in the
getFuncDoc
function:if len(astDecl.Specs) == 0
before accessingastDecl.Specs[0]
if len(astDecl.Values) == 0
before accessingastDecl.Values[0]
value.Obj == nil || value.Obj.Decl == nil
Changes Made
parser.go
at lines 1052, 1062, and 1066Testing
This fix resolves the segmentation fault when running swag with dependency parsing enabled. The parser now gracefully skips over problematic AST nodes instead of crashing.
Impact
This is a critical stability fix that allows swag to successfully parse projects with dependencies without crashing.