apache / apache/maven-toolchains-plugin

Infinite recursion risk in ToolchainDiscoverer.getCanonicalPath() for root paths

Open Beginner friendly
#171 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Java
Stars
27
Forks
31
PR merge metrics
No merged PRs in 30d

Description

## Summary

`ToolchainDiscoverer.getCanonicalPath()` has a recursive fallback that can cause infinite recursion or stack overflow for root paths where `path.getParent()` returns null.

## Location

`ToolchainDiscoverer.java:267-273`

https://github.com/apache/maven-toolchains-plugin/blob/master/src/main/java/org/apache/maven/plugins/toolchain/jdk/ToolchainDiscoverer.java#L267-L273

## Code

```java
private static Path getCanonicalPath(Path path) {
try {
return path.toRealPath();
} catch (IOException e) {
return getCanonicalPath(path.getParent()).resolve(path.getFileName());
}
}
```

## Problem

1. If `path` is a root directory (e.g. `/` on Linux or `C:\` on Windows), `path.getParent()` returns `null`. The recursive call `getCanonicalPath(null)` throws NPE.
2. If `path.getParent()` itself fails with IOException, this creates infinite recursion leading to stack overflow.
3. The recursive approach also has no depth limit, so deeply nested paths that fail `toRealPath()` will recurse until stack overflow.

## Impact

JDK discovery scanning directories like `/` or other root-relative paths could crash Maven with a stack overflow or NPE instead of gracefully skipping the problematic path.

## Suggested Fix

Replace recursion with iteration:

```java
private static Path getCanonicalPath(Path path) {
try {
return path.toRealPath();
} catch (IOException e) {
Path parent = path.getParent();
if (parent == null) {
return path;
}
return getCanonicalPath(parent).resolve(path.getFileName());
}
}
```

Or better, use a non-recursive loop with null checks to eliminate the recursion entirely.

Contributor guide

No contributing guide indexed for this repository

Research direction

Start with ToolchainDiscoverer.java:267-273 and inspect how getCanonicalPath() is used during JDK discovery. Exercise root and deeply nested paths whose toRealPath() calls fail, then verify the method returns safely without recursion, NPEs, or stack overflows.

Written by the indexing model from the issue text.

Assessment

Tech stack
java
Domain
build-system
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Quiet
Clarity
Clearly specified
Newbie friendliness
76/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.