Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 108 additions & 0 deletions socorro/lib/libjava.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
contents.
"""

from glom import glom
from more_itertools import peekable


Expand Down Expand Up @@ -102,3 +103,110 @@ def parse_java_stack_trace(text):
new_exc.additional.append(line)

return new_exc


def format_exception_class(stacktrace) -> str:
"""
Build the outermost exception's fully qualified Java class name.

The client splits the class name at its last ``.`` into ``module`` and ``type``.
- https://searchfox.org/firefox-main/rev/09b86521110cb23b77f5385a0e02aa4013a41f97/mobile/android/android-components/components/support/base/src/main/java/mozilla/components/support/base/ext/Throwable.kt#58-60
Kotlin writes nested classes with ``.`` instead of Java's ``$``, so this
puts the ``$`` back when ``module`` ends in a class name.

Returns ``""`` if ``module`` or ``type`` is missing.
"""
exception_module = stacktrace.get("module", "")
exception_type = stacktrace.get("type", "")

if not exception_module or not exception_type:
# We can't build a class name without its components.
return ""

# Java naming conventions make packages lowercase (e.g. java.lang, android.view),
# and classes start with an uppercase letter (e.g. WindowManager).
# If the last part of `exception_module` starts with an uppercase letter, it's a
# class, so the exception is nested inside it and needs a $.
last_segment = exception_module.rsplit(".", 1)[-1]
separator = "$" if last_segment[:1].isupper() else "."
return f"{exception_module}{separator}{exception_type}"


def format_frame(frame) -> str:
"""
Format a ``java_exception`` frame as a Java stack trace line.

Matches the format of Java's ``StackTraceElement.toString()``, which is what
crash reports' ``JavaStackTrace`` crash annotation uses:
* ``at <module>.<function>(<filename>:<lineno>)``
* ``(Native Method)`` if the method is native (``lineno == -2``)
* ``(Unknown Source:<lineno>)`` if there's no ``filename`` but there is a line
number, or ``(Unknown Source)`` if there's neither.
* ``(<filename>)`` if there's a ``filename`` but no usable line number.

See https://developer.android.com/reference/java/lang/StackTraceElement

:arg frame: a frame dict from ``java_exception`` (keys: ``module``,
``function``, ``filename``, ``lineno``; all optional)

:returns: the stack trace line without the leading tab
"""
module = frame.get("module", "")
function = frame.get("function", "")
if module and function:
name = f"{module}.{function}"
elif module:
name = module
elif function:
name = function
else:
name = ""

lineno = frame.get("lineno")
filename = frame.get("filename")

has_lineno = lineno is not None and lineno >= 0
if lineno == -2:
location = "Native Method"
elif not filename:
location = f"Unknown Source:{lineno}" if has_lineno else "Unknown Source"
elif has_lineno:
location = f"{filename}:{lineno}"
else:
location = filename

return f"at {name}({location})"


def java_stack_trace_from_java_exception(java_exception) -> str | None:
"""
``JavaSignatureTool`` currently builds the signature from
``processed_crash.java_stack_trace``. This helper builds ``java_stack_trace``
from ``processed_crash.java_exception``.

Expects ``java_exception`` has been validated against the processed crash
schema.
"""
# Get the stacktrace for the outermost exception, since that's what we use to generate
# signatures for Java crashes:
Comment on lines +190 to +191

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In implementing this, I realized that our signature generation algorithm for Java crashes uses the outermost exception information (the exception class and the top frame in that exception's stackframe) rather than the innermost exception (often considered the root cause).

In an effort to keep signature generation working as it currently does, I won't change that here. I imagine this is mentioned in one or more of the "improve java crash signatures" tickets Willkg filed ages ago. I'll find it and add it to the optional 7 Milestone, as we likely want to use the innermost exception for signature generation rather than the outermost exception. In the processed_crash.schema.yaml file for java_exception, Willkg added a note that he wasn't sure what the ordering of values was, so perhaps that's why it ended up this way.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The meta bug for improving Java crash report signatures is bug-1693693.

The bug about the order of the exception chain in JavaException is bug-1888997.

The bug about using the innermost or deepest exception for signature generation for Java crashes rather than the outermost is bug-1698623.

I've added the latter two bugs to Milestone 7.

# - https://searchfox.org/firefox-main/rev/09b86521110cb23b77f5385a0e02aa4013a41f97/mobile/android/android-components/components/support/base/src/main/java/mozilla/components/support/base/ext/Throwable.kt#20-26
# - https://github.com/mozilla-services/socorro/blob/c02928fda86ee0aad5eb6e0c68a51ff5bd4ef6a9/socorro/signature/rules.py#L425-L504
# The outermost exception is the last exception in the list per:
# - https://searchfox.org/firefox-main/rev/09b86521110cb23b77f5385a0e02aa4013a41f97/mobile/android/android-components/components/support/base/src/main/java/mozilla/components/support/base/ext/Throwable.kt#74-85
# - https://searchfox.org/firefox-main/rev/09b86521110cb23b77f5385a0e02aa4013a41f97/mobile/android/android-components/components/support/base/src/main/java/mozilla/components/support/base/ext/Throwable.kt#30-72
stacktrace = glom(java_exception, "exception.values.-1.stacktrace", default=None)
if not stacktrace:
return None

# Line 1 of `java_stack_trace`: the exception's fully qualified class name.
exception_class = format_exception_class(stacktrace)
if not exception_class:
return None

# Lines 2+ of `java_stack_trace`: one line per frame, with the top frame first.
# Only the top frame (line 2) affects the signature. The rest are included, so
# `java_stack_trace` is complete. With no frames, `java_stack_trace` is just the
# class name.
frames = stacktrace.get("frames") or []
frame_lines = [f"\t{format_frame(frame)}" for frame in frames]
return "\n".join([exception_class, *frame_lines])
6 changes: 5 additions & 1 deletion socorro/mozilla_rulesets.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@
IdentifierRule,
OSInfoRule,
)
from socorro.processor.rules.java import JavaStackTraceRule
from socorro.processor.rules.java import (
JavaStackTraceFromJavaExceptionRule,
JavaStackTraceRule,
)
from socorro.processor.rules.memory_report_extraction import MemoryReportExtraction
from socorro.processor.rules.mozilla import (
AccessibilityRule,
Expand Down Expand Up @@ -106,6 +109,7 @@
PHCRule(),
BreadcrumbsRule(schema=get_schema("processed_crash.schema.yaml")),
JavaStackTraceRule(),
JavaStackTraceFromJavaExceptionRule(),
Comment thread
biancadanforth marked this conversation as resolved.
Resolved
MacBootArgsRule(),
MacCrashInfoRule(),
MozCrashReasonRule(),
Expand Down
40 changes: 40 additions & 0 deletions socorro/processor/rules/java.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,43 @@ def action(self, raw_crash, dumps, processed_crash, tmpdir, status):
java_stack_trace = "malformed"

processed_crash["java_stack_trace"] = java_stack_trace


class JavaStackTraceFromJavaExceptionRule(Rule):
"""Build ``java_stack_trace`` from ``java_exception`` if it's missing.

Crash pings don't include the ``JavaStackTrace`` annotation, only
``JavaException``, and some crash reports have ``JavaException`` without
``JavaStackTrace``. Building ``java_stack_trace`` from ``java_exception`` lets
signature generation use ``JavaSignatureTool`` for these crashes, so they get
the same signatures as crashes with a ``JavaStackTrace`` annotation.

This never overwrites an existing ``java_stack_trace``.

Note: This rule must run after ``CopyFromRawCrashRule`` (which copies
``java_exception`` into the processed crash) and ``JavaStackTraceRule`` (so a
``java_stack_trace`` from a ``JavaStackTrace`` annotation takes precedence), and
before ``SignatureGeneratorRule``.

"""

def predicate(self, raw_crash, dumps, processed_crash, tmpdir, status):
return bool(processed_crash.get("java_exception")) and not processed_crash.get(
"java_stack_trace"
)

def action(self, raw_crash, dumps, processed_crash, tmpdir, status):
java_stack_trace = libjava.java_stack_trace_from_java_exception(
processed_crash["java_exception"]
)
if java_stack_trace is None:
status.add_note(
"JavaStackTraceFromJavaExceptionRule: could not build java_stack_trace"
)
return

processed_crash["java_stack_trace"] = java_stack_trace
status.add_note(
"JavaStackTraceFromJavaExceptionRule: built java_stack_trace from "
+ "java_exception"
)
5 changes: 4 additions & 1 deletion socorro/schemas/processed_crash.schema.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2718,9 +2718,12 @@ properties:
permissions: ["public"]
source_annotation: JavaException
java_stack_trace:
description: >
description: |

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't update the docs in docs/crashpings.rst, because there's lots of information there that is stale. I added a note to CRINGE-391 which is a docs update ticket.

The unstructured `JavaStackTrace` crash annotation without the exception
value.

If there's no `JavaStackTrace` annotation (e.g. for crash pings), this is
built from `java_exception` instead.
type: string
permissions: ["public"]
java_stack_trace_raw:
Expand Down
99 changes: 99 additions & 0 deletions socorro/tests/conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -437,3 +437,102 @@ def storage_helper():
"""Generate and return a queue helper using env config."""
with GcsHelper() as helper:
yield helper


@pytest.fixture
def java_exception():
"""Return a realistic processed_crash.java_exception value.

This is from a real Fenix crash with the signature
"java.lang.RuntimeException: at
android.app.servertransaction.PendingTransactionActions$StopInfo.run(PendingTransactionActions.java)",
with frames trimmed to 4 per exception. It includes:

* a chain of two exceptions: values[0] is the root cause
(TransactionTooLargeException) and values[1], the last element, is the
outermost exception (RuntimeException)
* a nested class in a frame module: PendingTransactionActions$StopInfo
* a native frame (lineno: -2) in the root cause
* a package-level exception class: java.lang + RuntimeException, joined with "."

See also ``java_exception`` in ``processed_crash.schema.yaml``.

"""
return {
"exception": {
"values": [
{
"stacktrace": {
"frames": [
{
"module": "android.os.BinderProxy",
"function": "transactNative",
"in_app": False,
"lineno": -2,
"filename": "BinderProxy.java",
},
{
"module": "android.os.BinderProxy",
"function": "transact",
"in_app": True,
"lineno": 639,
"filename": "BinderProxy.java",
},
{
"module": "android.app.IActivityClientController$Stub$Proxy",
"function": "activityStopped",
"in_app": True,
"lineno": 1459,
"filename": "IActivityClientController.java",
},
{
"module": "android.app.ActivityClient",
"function": "activityStopped",
"in_app": True,
"lineno": 112,
"filename": "ActivityClient.java",
},
],
"type": "TransactionTooLargeException",
"module": "android.os",
}
},
{
"stacktrace": {
"frames": [
{
"module": "android.app.servertransaction.PendingTransactionActions$StopInfo",
"function": "run",
"in_app": True,
"lineno": 146,
"filename": "PendingTransactionActions.java",
},
{
"module": "android.os.Handler",
"function": "handleCallback",
"in_app": True,
"lineno": 958,
"filename": "Handler.java",
},
{
"module": "android.os.Handler",
"function": "dispatchMessage",
"in_app": True,
"lineno": 99,
"filename": "Handler.java",
},
{
"module": "android.os.Looper",
"function": "loopOnce",
"in_app": True,
"lineno": 222,
"filename": "Looper.java",
},
],
"type": "RuntimeException",
"module": "java.lang",
}
},
]
}
}
Loading