Repository navigation
Fix BZ 68436 - don't warn when driverClassName is not set - #3
Closed
rvullriede wants to merge 20 commits into
Closed
rvullriede wants to merge 20 commits into
rvullriede wants to merge 20 commits into
Conversation
SimpleInstanceManager.newInstance(String) dereferenced the thread context class loader without a null check. Thread.getContextClassLoader() is documented to return null in some cases and NullPointerException is not part of the InstanceManager.newInstance(String) contract, so a raw NPE could escape to callers. Fall back to the class loader of SimpleInstanceManager when the thread context class loader is null, matching the established pattern used by JspRuntimeContext and Registry. This turns the previous undeclared NPE into the contract-declared ClassNotFoundException when the class cannot be resolved, and has no effect on the normal case where the thread context class loader is set.
In setProperty(), the loop that matches single-argument setters initialised the success flag to true and only cleared it for the supported parameter types (int/Integer/long/Long/boolean/Boolean/ InetAddress) when value conversion or host resolution failed. For a setter whose parameter type was not one of those, the default branch merely logged a trace message, leaving the flag set, so the code invoked the method reflectively with a null argument and returned true. Callers such as SetPropertiesRule, Connector.setAttribute, AbstractEndpoint, WebdavServlet.init and FilterBase therefore skipped their error paths and a misconfiguration went unnoticed, with the targeted property silently set to null. Mark unsupported parameter types as not ok so the setter is not invoked. The property now falls back to the generic setProperty(name, value) handler when the target provides one and invokeSetProperty is true, or the method returns false so the caller can report the failure. As a side benefit, an unsupported overload can no longer shadow a supported overload of the same setter, and digester generated code no longer emits an empty statement for such properties. Adds regression tests covering both the no-fallback and the setProperty-fallback cases.
findDeadlock() called ThreadMXBean.findDeadlockedThreads() twice, using the first result only for a null check and passing the second, independent snapshot to getThreadInfo(). If the deadlock was resolved between the two calls the second call returned null and getThreadInfo() threw a NullPointerException. Reuse the ids from the first snapshot so there is no time-of-check/time-of-use window between the calls. In addition, ThreadMXBean.getThreadInfo(long[], boolean, boolean) is documented to return null array elements for thread ids that are no longer alive, for example threads that died after the deadlock snapshot. getThreadDump(ThreadInfo[]) passed those elements straight to getThreadDump(ThreadInfo) which dereferences getThreadName(), also throwing a NullPointerException. Skip null entries. Since the deadlock genuinely existed at snapshot time, the deadlock message is still reported; in the extreme case where all threads died the message is followed by an empty dump rather than crashing. findDeadlock() runs on every Manager /threaddump request via Diagnostics.getThreadDump(). The dumpAllThreads() path used by the same method never returns null elements, so the new guard is a no-op there. Verified with TestManagerWebapp which requests /manager/text/threaddump.
The byte emission loop right-shifted the value on each iteration while also shifting by 8 * (valueSize - 1) of the already shifted value, so every content byte received a copy of the most significant byte: writeInteger(0x1234) produced 02 02 12 12 instead of 02 02 12 34 and writeInteger(256) produced 02 02 01 01 instead of 02 02 01 00. Only single byte values and values whose bytes are all equal were encoded correctly. Emit the bytes by shifting the unmodified value. Also add the leading zero byte that DER (X.6.90) requires for positive INTEGER values whose most significant content bit is set. Without it, writeInteger(128) produced 02 01 80 which decodes as -128. While testing the fix, two related infinite loops were found and fixed. The value size calculation loops in both writeInteger() and writeTag() test (value >> (size * 8)) > 0 without an upper bound. Since the Java shift distance is evaluated modulo 32, once the size counter reaches 4 the shift distance wraps back to 0 and the loop never terminates: writeInteger() spun forever for values >= 0x1000000 and writeTag() for data lengths >= 0x1000000. The size counters are now bounded (4 bytes is the maximum for any non-negative int value or any Java array length) and the shifts are unsigned. Adds TestAsn1Writer with explicit expected encodings, an exhaustive round-trip of the values 0 to 65535 plus transition boundaries and fixed-seed random values, comparing the content octets against BigInteger.toByteArray() (canonical minimal DER) and decoding the result with Asn1Parser, and a regression test for the 16 MiB length case in writeTag(). Output for the only in-repo callers, PEMFile with values 0 and 1, is byte-identical to before; TestPEMFile passes.
When a custom WAR separator is configured via the org.apache.tomcat.util.buf.UriUtil.WAR_SEPARATOR system property, PATTERN_CUSTOM matches the full separator (custom + "/") but REPLACE_CUSTOM percent-encoded only the custom part. The replaceAll in makeSafeForJarUrl therefore deleted the trailing '/' of the separator, silently rewriting any file path containing the separator sequence to a different, non-existent path and producing a broken jar:file: URL. Fix this by appending a literal '/' to REPLACE_CUSTOM so the escaped replacement keeps the separator's trailing slash, consistent with the default handling where "*/" is replaced with "%2a/". As a side effect, an empty custom separator now behaves as a no-op instead of stripping every '/' from the path. Add a regression test asserting the full expected JAR URL with the '@' separator, using the String overload of buildJarUrl so the expected value is independent of platform-specific File.toURI() behaviour.
…oss calls UEncoder.encodeURL() recycled the internal byte and char chunks but not the per-instance C2BConverter. C2BConverter retains characters that could not yet be encoded (such as a high surrogate not followed by a low surrogate) in a private leftovers buffer. A string ending with such a character therefore left it in the converter, and the next encodeURL() call on the same instance silently paired the leftover with the start of the new, unrelated string, corrupting the result. For example, encoding "ab\uD800" followed by "\uDC00cd" produced %f0%90%80%80cd (U+10000) instead of %3fcd. Fix this by calling c2b.recycle() whenever an existing converter is reused. C2BConverter.recycle() resets the charset encoder and clears the leftovers buffer. Add a regression test that compares the second call's result with that of a fresh encoder.
get() promoted every long-term store hit into eden unconditionally, while only put() trims eden. A workload with more reads than writes of distinct keys could therefore grow eden far beyond the size documented as the maximum size of the eden space, with each entry pinning a previously weakly-reachable key with a strong reference until the next put-triggered promotion and clear. For example, with a configured size of 10, 100 puts followed by 100 gets left eden holding 100 entries. Fix this by promoting into eden from get() only while eden has room, i.e. when its size is below the configured size. The check-then-act race is benign: it is the same pattern already used by put() and any transient overshoot is bounded by the number of concurrent readers and is cleared by the next promotion. Entries that are not promoted remain available through the long-term store, so lookups are unaffected. Add TestConcurrentCache covering basic operation, promotion to the long-term store, promotion back into eden while there is room, and the eden size bound.
setLimit() only stored the limit field while push() consulted the limit only when the backing array was already full. A stack with the default capacity of 128 and a newly configured limit of, say, 10 therefore kept accepting pushes until it held 128 elements, ignoring the limit. For the HTTP/2 recycled Request/Response pool, whose limit is set from the connector's maxConnections, this allowed the pool to hold up to 128 entries when maxConnections was configured below 128. Fix this by shrinking the stack in setLimit() when the new limit is lower than the current capacity. The most recently pushed elements are retained and any remaining, older elements are discarded along with the old backing array, which releases their references. As follow-up work prompted by review, make expand() able to grow from a zero capacity array using Math.max(1, size * 2). Shrinking to a limit of zero and later raising the limit previously produced an ArrayIndexOutOfBoundsException on the next push, and the same latent problem existed for a stack constructed with a zero size. Add tests for shrinking below the capacity and below the element count, for the unlimited limit and for zero-then-raise. All assertions fail against the previous implementation where applicable.
The public constructor accepted values it could not handle. A zero initial size produced a queue whose first offer() threw ArrayIndexOutOfBoundsException, and a negative value produced NegativeArraySizeException from the array allocation. Neither state is usable, and a zero-size queue cannot recover since expand() doubles the current size. Reject non-positive values with IllegalArgumentException using a localized message from a new LocalStrings bundle for the org.apache.tomcat.util.collections package, following the StringManager pattern used by other util packages. No in-tree caller is affected; the only production instantiation uses the default constructor. Add tests for rejected zero and negative sizes, for the smallest valid size of one, and add the missing @test annotation to testPollEmpty which previously prevented it from running.
The class extends AbstractMap and only overrode entrySet(), so keySet()
returned the AbstractMap view whose contains() delegates to the map's
case-insensitive containsKey() while remove(Object) iterates the keys
comparing them with String.equals(). For a stored key "a",
keySet().contains("A") returned true but keySet().remove("A")
returned false and left the entry in place, violating the Set contract
for callers that remove keys via the view with different casing.
Override keySet() with a KeySet view backed by the same live map as the
entry set. Its iterator reports keys in their original case, contains()
and remove() are case-insensitive, removal correctly reports success
even for entries with a null value, null and non-String arguments return
false, and clear() empties the backing map. Non-String and null keys are
never stored since put() rejects null keys and Key.getInstance() returns
null for other types.
Add tests for case-insensitive removal of a set object, rejection of
null and non-String keys, original-case keys from the iterator and
clearing via the view.
The constant concatenated the Java EE 5 namespace and the schema file name without the '/' separator, producing the malformed URL http://java.sun.com/xml/ns/javaeejavaee_web_services_1_2.xsd instead of http://java.sun.com/xml/ns/javaee/javaee_web_services_1_2.xsd used by the specification and by DigesterFactory when registering the schema. The constant is currently unreferenced - DigesterFactory registers the web services schemas via bare file names - so there is no functional impact today. The correction removes a latent copy-paste defect from this public constants class and aligns the value with all sibling constants, which use the namespace plus "/filename".
The parser registers addCallMethod for <tag-plugin> with two parameters taken from the child element bodies. CallMethodRule always invokes the method when it expects more than one parameter, passing null for parameters whose element is absent. As a result, a <tag-plugin> element that omitted <tag-class> or <plugin-class> stored a map entry with a null key or value. The sole consumer, Jasper's TagPluginManager, then either called loadClass(null), which produced a raw NullPointerException surfaced as an unhelpful JasperException during JSP translation, or silently stored an entry under a null key that could never match a tag handler class. Fix this by ignoring entries with a null or empty tag class or plugin class and logging a localized warning via StringManager, using a new resource bundle for the org.apache.tomcat.util.descriptor.tagplugin package. Complete entries in the same descriptor are still registered. Document the behaviour in the addPlugin() Javadoc. Add tests covering direct calls with missing values and the parsing of a descriptor mixing incomplete and complete entries.
TldCache shares a single TldParser, and therefore a single Digester, across all cached TLDs. Digester is documented as single-threaded but the re-parse path in getTaglibXml() was only protected by a per-entry lock. Two threads recompiling JSPs that referenced two different TLDs whose last modified time had changed since the startup scan could call tldParser.parse() concurrently on the same Digester. Observed failure modes included Xerces rejecting the reentrant parse (FWK005: parse may not be called while parsing) and a NullPointerException after a concurrent digester.reset() from the finally block of the other parse, with the corrupted result being cached until the next change. Fix this by serializing all re-parses on the shared parser's monitor. The monitor is taken while holding the per-entry lock, and no path takes the two locks in the opposite order, so no deadlock is possible. Correct the class Javadoc, which previously claimed the opposite thread-safety behaviour.
JSP.7.3.2 only permits version information and a short name in an implicit.tld file. The web application TLD scanner previously parsed these files with the full TldRuleSet at start-up. That allowed elements which the specification forbids in an implicit TLD to take effect: a <uri> element caused the URI to be registered so that the file could be used for URI based taglib directives, and a <listener> element caused JasperInitializer to register the listener with the context, aborting start-up when the class could not be instantiated. TldScanner now owns a second TldParser built with the existing ImplicitTldRuleSet - the same rule set already used by ImplicitTagLibraryInfo when a tag file is translated - and uses it for resources whose web application path is an implicit.tld below /WEB-INF/tags. An implicit TLD which is not specification compliant is now rejected at scan time: the scanner logs a warning naming the resource and continues, so such a file can no longer register a URI, cache a tag library or contribute listeners, and cannot prevent the web application from starting. If the tag library is actually used via tagdir, the same error is reported at translation time as before. Explicit taglib mappings in web.xml (scanJspConfig) deliberately keep using the lenient parser since an explicit mapping is an administrator decision and <listener> is legitimate in a regular TLD. Also replace the /WEB-INF/tags/ and /implicit.tld literals in scanResourcePaths() with the new WEB_INF_TAGS and IMPLICIT_TLD constants, now used by both code paths.
TldResourcePath accepted a null URL without complaint and then failed later with a NullPointerException in toExternalForm(), openStream(), equals() or hashCode() when the value was first used. One caller made this reachable in normal operation. TldScanner resolved a TLD listed by ServletContext.getResourcePaths() with ServletContext.getResource() and passed the result straight to the constructor. The two calls are not atomic: a TLD removed from an exploded web application between them resolved to null, the resulting NullPointerException was thrown out of the scan and, since JasperInitializer.onStartup() only catches IOException and SAXException, it aborted context start-up with an opaque error. Both constructors now throw an IllegalArgumentException with a readable, localised message when the URL is null, mirroring the validation style used elsewhere in the utility packages. In addition, TldScanner.parseTld(String) now checks for the vanished resource and skips it with a warning, in the same way as scanJspConfig() handles a taglib-location in web.xml that does not exist, so the race becomes a startup warning rather than a failure. Tests: TestTldResourcePath covers the constructor rejection and the methods the invariant protects; TestTldScanner covers the scan-time warn-and-skip of a resource that disappeared.
The port-component-ref mappings of a <service-ref> (the Service
Endpoint Interface to port-component-link associations) were stored in
the generic properties map inherited from ResourceBase, via
addPortcomponent() -> setProperty(). The same map also holds the
<mapped-name> value, which MappedNameRule stores under the key
mappedName for every resource that allows that element. Since
getServiceendpoints() simply returned listProperties(), any
<service-ref> that declared a <mapped-name> - which is legal per the
Servlet specification - was reported as having a bogus service endpoint
named mappedName, whose port-component-link was the mapped-name
value.
That bogus endpoint leaked to several consumers:
* NamingContextListener.addService() bound a
SERVICEENDPOINTINTERFACE/PORTCOMPONENTLINK pair for mappedName
into the application's JNDI ServiceRef.
* WebXml.toXml() serialized an extra
<port-component-ref><service-endpoint-interface>mappedName
</service-endpoint-interface>...</port-component-ref> element into
the effective web.xml.
* ContextService.toString() printed mappedName as an endpoint, as did
the storeconfig output for a global ServiceRef.
Port-component mappings now live in a dedicated map, kept separate from
the generic properties, and are included in equals()/hashCode().
WebXml.toXml() reads the port link through getPortlink() rather than by
treating the endpoint name as a property key; the mapped-name element
continues to be read from the mappedName property. As a side effect,
endpoint names are no longer emitted as generic attributes when a global
<ServiceRef> is written by storeconfig.
Tests: TestWebXml now checks that a service-ref with a mapped-name
reports only its real endpoint, retains the mapped-name as a property,
and serializes a single correct port-component-ref in the effective
web.xml.
FilterDef.asyncSupportedBoolean defaulted to true and any value
other than "false"/"no" was parsed as true. The Servlet specification
defaults filters to not supporting async processing.
The web.xml path masked the incorrect default because ContextConfig
normalises a missing async-supported element to "false", but filters
registered dynamically through ServletContext.addFilter() that never
called Dynamic.setAsyncSupported(true) were treated as async supported,
so ApplicationFilterChain applied them to ASYNC and ERROR dispatches
contrary to the specification.
The boolean field could also disagree with the stored string: values
such as "yes" or "1" returned true from getAsyncSupportedBoolean() but
false from the getAsyncSupported().equals("true") checks used elsewhere,
so the same filter was inconsistently treated as async supported and
async unsupported.
asyncSupportedBoolean now defaults to false and the setter derives it
with "true".equalsIgnoreCase(), consistent with ServletDef and the
Boolean parsing used by the other descriptor setters. The string value
is stored unchanged so a storeconfig round-trip preserves the original
descriptor value.
This is a user-visible behaviour change: dynamically registered filters
now require an explicit setAsyncSupported(true) to receive async and
error dispatches. Annotation-defined filters and the shipped filter
definitions are unaffected. Adds tests for the default and the full
setter matrix, plus a changelog entry.
SecurityRoleRef.equals(Object) compared getClass() on the argument without a null check, so equals(null) dereferenced null and threw NullPointerException, violating the Object.equals contract which requires false for a null argument. Replace the getClass() comparison with an instanceof pattern match, consistent with LoginConfig in the same package, which handles both the null argument and foreign types by returning false. There are no subclasses of SecurityRoleRef in the tree, so behaviour is unchanged for all non-null inputs; hashCode is untouched and remains consistent with equals. No internal call site passes null (HashSet operations null-guard the query key), so this is a latent robustness fix. Adds TestSecurityRoleRef covering the null argument, the field comparison matrix and equality of instances with null fields.
SessionConfig.setCookieMaxAge(String) stored the raw string and getCookieMaxAge() parsed it lazily. The value is copied verbatim by ContextConfig into the runtime SessionCookieConfig, where ApplicationSessionCookieConfig.getMaxAge() parses it again on every session cookie creation. Web.xml XSD validation is off by default, so an invalid value such as "abc" passed parsing and then threw a raw NumberFormatException on every session creation and session id change for the application, instead of failing the deployment. The setter now validates the value with Integer.valueOf() before storing it, consistently with setSessionTimeout() in the same class. The digester wraps the resulting NumberFormatException into a SAX parse error that reports the location in the descriptor and fails the deployment cleanly. Valid values, including negative ones used to disable cookie expiry, are stored unchanged. The generic cookie attribute path (SessionConfig.setCookieAttribute, the descriptor mirror of SessionCookieConfig.setAttribute) accepts arbitrary strings and remains unvalidated, which is pre-existing and mirrors the programmatic API. Adds TestSessionConfig for the setter and parse level tests in TestWebXmlParser covering valid, invalid and empty max-age elements.
rvullriede
force-pushed
the
fix/bz-68436-null-driver-warning
branch
from
October 14, 2026 20:14
54f573b to
bbbc610
Compare
Owner
Author
|
Merged upstream as apache#1084. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
https://bz.apache.org/bugzilla/show_bug.cgi?id=68436
Leaving
driverClassNameunset and relying onDriverManageris a valid configuration, but it logs a warning for every new connection. Log it at debug level with clearer wording, as suggested in the bug. The existing "Instantiating driver using class" debug message moves into the branch where there is a class to instantiate.