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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

- Profiling: No longer crash on API 35+ devices whose framework can't load `ProfilingManager`. Perfetto profiling is turned off on those devices instead ([#6742](https://github.com/getsentry/sentry-java/pull/6742))
- Android: Out-of-process crash reporting now supports Android 5.0 (API level 21) and later, previously required Android 11 (API level 30) ([#6614](https://github.com/getsentry/sentry-java/pull/6614))
- Android profiling: Uploading a Perfetto profile chunk now keeps the trace in memory once instead of up to three times, lowering peak memory use for traces up to 50 MB ([#6743](https://github.com/getsentry/sentry-java/pull/6743))

### Dependencies

Expand Down
54 changes: 44 additions & 10 deletions sentry/src/main/java/io/sentry/SentryEnvelopeItem.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
Expand Down Expand Up @@ -406,23 +407,15 @@ private static void ensureAttachmentSizeLimit(
String.format("Failed to serialize perfetto profile chunk\n%s", e.getMessage()));
}

// Read binary Perfetto trace
final byte[] traceBytes;
// [JSON metadata bytes][raw .pftrace binary bytes]
try {
traceBytes = readBytesFromFile(traceFile.getPath(), MAX_PROFILE_CHUNK_SIZE);
return readFileAfterPrefix(metadataBytes, traceFile, MAX_PROFILE_CHUNK_SIZE);
} catch (IOException e) {
throw new SentryEnvelopeException(
String.format("Failed to read perfetto trace file\n%s", e.getMessage()));
} finally {
traceFile.delete();
}

// Concatenate: [JSON metadata bytes][raw .pftrace binary bytes]
final byte[] payload = new byte[metadataBytes.length + traceBytes.length];
System.arraycopy(metadataBytes, 0, payload, 0, metadataBytes.length);
System.arraycopy(traceBytes, 0, payload, metadataBytes.length, traceBytes.length);

return payload;
});

SentryEnvelopeItemHeader itemHeader =
Expand All @@ -443,6 +436,47 @@ private static void ensureAttachmentSizeLimit(
return new SentryEnvelopeItem(itemHeader, () -> cachedItem.getBytes());
}

/**
* Reads {@code file} into a new array that starts with {@code prefix}. The file is read straight
* into its place in the result, so a large trace is held in memory once instead of being copied
* through intermediate buffers.
*/
private static byte[] readFileAfterPrefix(
Comment thread
romtsn marked this conversation as resolved.
Resolved
final byte[] prefix, final @NotNull File file, final long maxFileLength) throws IOException {
if (!file.isFile() || !file.canRead()) {
throw new IOException(
String.format("Reading file '%s' failed, because it's not a readable file.", file));
}
final long fileLength = file.length();
if (fileLength > maxFileLength) {
throw new IOException(
String.format(
"Reading file failed, because size located at '%s' with %d bytes is bigger "
+ "than the maximum allowed size of %d bytes.",
file, fileLength, maxFileLength));
}

final byte[] result = new byte[prefix.length + (int) fileLength];
System.arraycopy(prefix, 0, result, 0, prefix.length);
try (final FileInputStream input = new FileInputStream(file)) {
int offset = prefix.length;
while (offset < result.length) {
final int read = input.read(result, offset, result.length - offset);
if (read == -1) {
throw new IOException(
String.format(
"Reading file '%s' failed, because it got shorter while reading.", file));
}
offset += read;
}
if (input.read() != -1) {
throw new IOException(
String.format("Reading file '%s' failed, because it got longer while reading.", file));
}
}
return result;
}

public static @NotNull SentryEnvelopeItem fromProfilingTrace(
final @NotNull ProfilingTraceData profilingTraceData,
final long maxTraceFileSize,
Expand Down
44 changes: 44 additions & 0 deletions sentry/src/test/java/io/sentry/SentryEnvelopeItemTest.kt
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package io.sentry

import com.google.common.truth.Truth.assertThat
import io.sentry.exception.SentryEnvelopeException
import io.sentry.protocol.ReplayRecordingSerializationTest
import io.sentry.protocol.SentryId
Expand All @@ -14,10 +15,12 @@ import java.io.File
import java.io.IOException
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.io.RandomAccessFile
import java.io.StringWriter
import java.nio.charset.Charset
import java.nio.file.Files
import java.util.concurrent.Callable
import kotlin.random.Random
import kotlin.test.AfterTest
import kotlin.test.Test
import kotlin.test.assertEquals
Expand Down Expand Up @@ -675,6 +678,47 @@ class SentryEnvelopeItemTest {
)
}

@Test
fun `fromPerfettoProfileChunk keeps a multi-megabyte trace intact after the metadata`() {
val traceFile = tmpDir.newFile("trace.pftrace")
val traceBytes = Random(42).nextBytes(3 * 1024 * 1024 + 17)
traceFile.writeBytes(traceBytes)

val item =
SentryEnvelopeItem.fromPerfettoProfileChunk(perfettoChunk(traceFile), fixture.serializer)

val payload = item.data
val metaLength = item.header.metaLength!!
assertThat(payload.size).isEqualTo(metaLength + traceBytes.size)
assertThat(payload.copyOfRange(metaLength, payload.size)).isEqualTo(traceBytes)
assertThat(traceFile.exists()).isFalse()
}

@Test
fun `fromPerfettoProfileChunk with trace over 50MB throws and deletes the file`() {
val traceFile = tmpDir.newFile("trace.pftrace")
RandomAccessFile(traceFile, "rw").use { it.setLength(50L * 1024 * 1024 + 1) }

val item =
SentryEnvelopeItem.fromPerfettoProfileChunk(perfettoChunk(traceFile), fixture.serializer)

val exception = assertFailsWith<SentryEnvelopeException> { item.data }
assertThat(exception.message).contains("bigger than the maximum allowed size")
assertThat(traceFile.exists()).isFalse()
}

private fun perfettoChunk(traceFile: File): ProfileChunk =
ProfileChunk.Builder(
SentryId(),
SentryId(),
emptyMap(),
traceFile,
SentryNanotimeDate(),
ProfileChunk.PLATFORM_ANDROID,
)
.setContentType(ProfileChunk.CONTENT_TYPE_PERFETTO)
.build(fixture.options)

@Test
fun `fromPerfettoProfileChunk with missing file throws`() {
val traceFile = File("nonexistent.pftrace")
Expand Down
Loading