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

Open Beginner friendly
#171 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

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

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.

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

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:

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.

Dominant language
Java
Stars
27
Forks
31
PR merge metrics
No merged PRs in 30d

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from apache/maven-toolchains-plugin

All issues in apache/maven-toolchains-plugin

Similar issues

More Java issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.