Skip to content
This repository was archived by the owner on Aug 30, 2023. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from 7 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
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import android.content.Context;
import io.sentry.core.ILogger;
import io.sentry.core.MainEventProcessor;
import io.sentry.core.SentryLevel;
import io.sentry.core.SentryOptions;
import java.io.File;
Expand All @@ -20,22 +21,19 @@ static void init(SentryOptions options, Context context, ILogger logger) {
options.setSentryClientName("sentry.java.android/0.0.1");

ManifestMetadataReader.applyMetadata(context, options);
createsEnvelopeDirPath(options, context);

if (options.isEnableNdk()) {
try {
// create sentry-envelopes folder for NDK envelopes
createsEnvelopeDirPath(options, context);

// TODO: Create Integrations interface and use that to initialize NDK
Class<?> cls = Class.forName("io.sentry.android.ndk.SentryNdk");

// TODO: temporary hack
String cacheDirPath = context.getCacheDir().getAbsolutePath() + "/sentry-envelopes";
File f = new File(cacheDirPath);
f.mkdirs();

Method method = cls.getMethod("init", SentryOptions.class, String.class);
Object[] args = new Object[2];
args[0] = options;
args[1] = cacheDirPath;
args[1] = options.getCacheDirPath();
method.invoke(null, args);
} catch (ClassNotFoundException exc) {
options.getLogger().log(SentryLevel.ERROR, "Failed to load SentryNdk.");
Expand All @@ -44,8 +42,8 @@ static void init(SentryOptions options, Context context, ILogger logger) {
}
}

options.addEventProcessor(new DefaultAndroidEventProcessor(context, options));
options.setSerializer(new AndroidSerializer(options.getLogger()));
addProcessors(options, context);
}

private static void createsEnvelopeDirPath(SentryOptions options, Context context) {
Expand All @@ -56,4 +54,9 @@ private static void createsEnvelopeDirPath(SentryOptions options, Context contex
}
options.setCacheDirPath(envelopesDir.getAbsolutePath());
}

private static void addProcessors(SentryOptions options, Context context) {
options.addEventProcessor(new MainEventProcessor(options));
options.addEventProcessor(new DefaultAndroidEventProcessor(context, options));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ import io.sentry.core.SentryOptions
import java.io.File
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import org.junit.runner.RunWith
Expand All @@ -36,7 +35,7 @@ class AndroidOptionsInitializerTest {
val loggerField = logger.get(sentryOptions)
val innerLogger = loggerField.javaClass.declaredFields.first { it.name == "logger" }
innerLogger.isAccessible = true
assertEquals(AndroidLogger::class, innerLogger.get(loggerField)::class)
assertTrue(innerLogger.get(loggerField) is AndroidLogger)
}

@Test
Expand All @@ -46,7 +45,20 @@ class AndroidOptionsInitializerTest {
val mockLogger = mock<ILogger>()

AndroidOptionsInitializer.init(sentryOptions, mockContext, mockLogger)
val actual = sentryOptions.eventProcessors.firstOrNull { it::class == DefaultAndroidEventProcessor::class }
val actual = sentryOptions.eventProcessors.any { it is DefaultAndroidEventProcessor }
assertNotNull(actual)
}

@Test
fun `MainEventProcessor added to processors list and its the 1st`() {
val sentryOptions = SentryOptions()
val mockContext = mock<Context> {
on { applicationContext } doReturn context
}
val mockLogger = mock<ILogger>()

AndroidOptionsInitializer.init(sentryOptions, mockContext, mockLogger)
val actual = sentryOptions.eventProcessors.firstOrNull { it is DefaultAndroidEventProcessor }
assertNotNull(actual)
}

Expand Down
40 changes: 40 additions & 0 deletions sentry-core/src/main/java/io/sentry/core/MainEventProcessor.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package io.sentry.core;

import io.sentry.core.exception.SentryExceptionReader;
import io.sentry.core.protocol.Message;
import io.sentry.core.protocol.SentryException;
import io.sentry.core.protocol.SentryStackFrame;
import io.sentry.core.protocol.SentryStackTrace;
import io.sentry.core.util.Objects;
import java.util.ArrayList;
import java.util.List;

public class MainEventProcessor implements EventProcessor {

private final SentryOptions options;

public MainEventProcessor(SentryOptions options) {
this.options = Objects.requireNonNull(options, "The SentryOptions is required.");
}

@Override
public SentryEvent process(SentryEvent event) {
Throwable throwable = event.getThrowable();
if (throwable != null) {

if (event.getMessage() == null) {
event.setMessage(getMessage(throwable));
}

event.setException(SentryExceptionReader.sentryExceptionReader(throwable));
}

return event;
}

private Message getMessage(Throwable throwable) {
Message message = new Message();
message.setFormatted(throwable.getMessage());
return message;
}
}
13 changes: 7 additions & 6 deletions sentry-core/src/main/java/io/sentry/core/SentryEvent.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public class SentryEvent implements IUnknownPropertiesConsumer {
private String dist;
private String logger;
private SentryValues<SentryThread> threads;
private SentryValues<SentryException> exceptions;
private SentryValues<SentryException> exception;
private SentryLevel level;
private String transaction;
private String environment;
Expand All @@ -32,6 +32,7 @@ public class SentryEvent implements IUnknownPropertiesConsumer {
private Map<String, String> tags = new HashMap<>();
private Map<String, Object> extra = new HashMap<>();
private Map<String, Object> unknown;
// TODO modules is missing?

SentryEvent(SentryId eventId, Date timestamp) {
this.eventId = eventId;
Expand Down Expand Up @@ -115,12 +116,12 @@ public void setThreads(List<SentryThread> threads) {
this.threads = new SentryValues<>(threads);
}

public List<SentryException> getExceptions() {
return exceptions.getValues();
public List<SentryException> getException() {
return exception.getValues();
}

public void setExceptions(List<SentryException> exceptions) {
this.exceptions = new SentryValues<>(exceptions);
public void setException(List<SentryException> exception) {
this.exception = new SentryValues<>(exception);
}

public void setEventId(SentryId eventId) {
Expand All @@ -140,7 +141,7 @@ public void setThreads(SentryValues<SentryThread> threads) {
}

public void setExceptions(SentryValues<SentryException> exceptions) {
this.exceptions = exceptions;
this.exception = exceptions;
}

public SentryLevel getLevel() {
Expand Down
12 changes: 6 additions & 6 deletions sentry-core/src/main/java/io/sentry/core/SentryValues.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,16 @@
import java.util.List;

class SentryValues<T> {
private List<T> items;
private List<T> values;

public SentryValues(List<T> items) {
if (items == null) {
items = new ArrayList<>(0);
public SentryValues(List<T> values) {
if (values == null) {
values = new ArrayList<>(0);
}
this.items = items;
this.values = values;
}

public List<T> getValues() {
return items;
return values;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package io.sentry.core.exception;

import io.sentry.core.protocol.Mechanism;

/**
* A throwable decorator that holds an {@link io.sentry.core.protocol.Mechanism} related to the decorated {@link Throwable}.
*/
public final class ExceptionMechanismThrowable extends Throwable {
private static final long serialVersionUID = 100L;

private final Mechanism exceptionMechanism;
private final Throwable throwable;

/**
* A {@link Throwable} that decorates another with a Sentry {@link Mechanism}.
* @param mechanism The {@link Mechanism}.
* @param throwable The {@link java.lang.Throwable}.
*/
public ExceptionMechanismThrowable(Mechanism mechanism, Throwable throwable) {
this.exceptionMechanism = mechanism;
this.throwable = throwable;
}

public Mechanism getExceptionMechanism() {
return exceptionMechanism;
}

public Throwable getThrowable() {
return throwable;
}
}
111 changes: 111 additions & 0 deletions sentry-core/src/main/java/io/sentry/core/exception/FrameCache.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package io.sentry.core.exception;

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;

/**
* Utility class used by the Sentry Java Agent to store per-frame local variable
* information for the last thrown exception.
*/
public final class FrameCache {
private static Set<String> appPackages = new HashSet<>();

private static ThreadLocal<WeakHashMap<Throwable, SentryFrame[]>> cache =
new ThreadLocal<WeakHashMap<Throwable, SentryFrame[]>>() {
@Override
protected WeakHashMap<Throwable, SentryFrame[]> initialValue() {
return new WeakHashMap<>();
}
};

/**
* Utility class, no public ctor.
*/
private FrameCache() {

}

/**
* Store the per-frame local variable information for the last exception thrown on this thread.
*
* @param throwable Throwable that the provided {@link SentryFrame}s represent.
* @param frames Array of {@link SentryFrame}s to store
*/
public static void add(Throwable throwable, SentryFrame[] frames) {
Map<Throwable, SentryFrame[]> weakMap = cache.get();
weakMap.put(throwable, frames);
}

/**
* Retrieve the per-frame local variable information for the last exception thrown on this thread.
*
* @param throwable Throwable to look up cached {@link SentryFrame}s for.
* @return Array of {@link SentryFrame}s
*/
public static SentryFrame[] get(Throwable throwable) {
Map<Throwable, SentryFrame[]> weakMap = cache.get();
return weakMap.get(throwable);
}

/**
* Check whether the provided {@link Throwable} should be cached or not. Called by
* the native agent code so that the Java side (this code) can check the existing
* cache and user configuration, such as which packages are "in app".
*
* @param throwable Throwable to be checked
* @param numFrames Number of frames in the Throwable's stacktrace
* @return true if the Throwable should be processed and cached
*/
public static boolean shouldCacheThrowable(Throwable throwable, int numFrames) {
// only cache frames when 'in app' packages are provided
if (appPackages.isEmpty()) {
return false;
}

// many libraries/frameworks seem to rethrow the same object with trimmed
// stacktraces, which means later ("smaller") throws would overwrite the existing
// object in cache. for this reason we prefer the throw with the greatest stack
// length...
Map<Throwable, SentryFrame[]> weakMap = cache.get();
SentryFrame[] existing = weakMap.get(throwable);
if (existing != null && numFrames <= existing.length) {
return false;
}

// check each frame against all "in app" package prefixes
for (StackTraceElement stackTraceElement : throwable.getStackTrace()) {
for (String appFrame : appPackages) {
if (stackTraceElement.getClassName().startsWith(appFrame)) {
return true;
}
}
}

return false;
}

/**
* Add an "in app" package prefix to the set of packages for which exception
* local variables will be cached.
*
* When an exception is thrown it must contain at least one frame that originates
* from a package in this set, otherwise local variable information will not be
* cached. See {@link FrameCache#shouldCacheThrowable(Throwable, int)}.
*
* @param newAppPackage package prefix to add to the set
*/
public static void addAppPackage(String newAppPackage) {
appPackages.add(newAppPackage);
}

/**
* This method is meant for cleaner testing. Don't attempt to use it in production.
*/
// visible for testing
static void reset() {
cache.get().clear();
appPackages.clear();
}
}
Loading