Skip to content
Open
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
18 changes: 17 additions & 1 deletion ddprof-lib/src/main/cpp/context.h
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
#define _CONTEXT_H

#include "arch.h"
#include <cassert>

static const u32 DD_TAGS_CAPACITY = 10;

Expand All @@ -29,9 +30,24 @@ class alignas(DEFAULT_CACHE_LINE_SIZE) Context {
public:
u64 spanId;
u64 rootSpanId;
private:
Tag tags[DD_TAGS_CAPACITY];

Tag get_tag(int i) { return tags[i]; }
static bool isValidIndex(int i) {
return i >= 0 && (u32)i < DD_TAGS_CAPACITY;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LOW (test-adequacy, mutation-testing): No test in this PR would detect removing the i >= 0 && part of the bounds check in isValidIndex.

Suggestion: add a test verifying isValidIndex rejects negative indices.

}
public:
u32 getTag(int i) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LOW (consistency): getTag/setTag take a signed int index while both call sites (flightRecorder.cpp:2117 and threadLocalData.cpp:142) iterate with size_t, producing an implicit narrowing conversion on every call and requiring the extra i >= 0 half of isValidIndex. The neighboring, equivalent accessor ProfiledThread::getOtelTagEncoding (threadLocalData.h:404) already uses an unsigned index with a single-sided check.

Suggestion: take the index as u32 (or size_t) in both getTag/setTag and isValidIndex; isValidIndex then reduces to a single i < DD_TAGS_CAPACITY comparison.

assert(isValidIndex(i));
return isValidIndex(i) ? tags[i].value : 0;
}

void setTag(int i, u32 value) {
assert(isValidIndex(i));
if (isValidIndex(i)) {
tags[i].value = value;
}
}
};

#endif /* _CONTEXT_H */
2 changes: 1 addition & 1 deletion ddprof-lib/src/main/cpp/flightRecorder.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2115,7 +2115,7 @@ void Recording::writeContextSnapshot(Buffer *buf, Context &context) {
buf->putVar64(context.rootSpanId);

for (size_t i = 0; i < Profiler::instance()->numContextAttributes(); i++) {
buf->putVar32(context.get_tag(i).value);
buf->putVar32(context.getTag(i));
}
}

Expand Down
5 changes: 5 additions & 0 deletions ddprof-lib/src/main/cpp/profiler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1632,6 +1632,11 @@ Error Profiler::start(Arguments &args, bool reset) {
// Always enable library trap to catch wasmtime loading and patch its broken sigaction
switchLibraryTrap(true);

if (args._context_attributes.size() > DD_TAGS_CAPACITY) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

LOW (completeness): The DD_TAGS_CAPACITY invariant is enforced at a single call site deep inside Profiler::start() (after switchLibraryTrap/startRefresher), not at the point where the list is built in Arguments::parse (arguments.cpp:322/325), which still accepts an unbounded number of names. Any future reader of args._context_attributes added earlier in start() — or any other entry point feeding JfrMetadata::initialize — would see the uncapped list again.

Suggestion: apply (or additionally apply) the cap in Arguments::parse where _context_attributes is populated.

Log::warn("attributes: %zu attributes requested but capacity is %u; extra attributes will be ignored",
args._context_attributes.size(), DD_TAGS_CAPACITY);
args._context_attributes.resize(DD_TAGS_CAPACITY);
}
JfrMetadata::reset();
JfrMetadata::initialize(args._context_attributes);
_num_context_attributes = args._context_attributes.size();
Expand Down
2 changes: 1 addition & 1 deletion ddprof-lib/src/main/cpp/threadLocalData.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ Context ProfiledThread::snapshotContext(size_t numAttrs) {
ctx.rootSpanId = root_span_id;
size_t count = numAttrs < DD_TAGS_CAPACITY ? numAttrs : DD_TAGS_CAPACITY;
for (size_t i = 0; i < count; i++) {
ctx.tags[i].value = _otel_tag_encodings[i];
ctx.setTag(i, _otel_tag_encodings[i]);
}
}
return ctx;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/*
* Copyright 2026, Datadog, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.datadoghq.profiler;

import org.junitpioneer.jupiter.RetryingTest;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;

/**
* Regression test: {@code attributes=} used to accept more names than the native
* {@code DD_TAGS_CAPACITY} (context.h), and {@code Recording::writeContextSnapshot}
* (flightRecorder.cpp) looped over that unbounded count calling the unchecked
* {@code Context::get_tag(i)} on a fixed {@code Tag tags[DD_TAGS_CAPACITY]} array -
* reading past the {@code Context} struct into adjacent native memory on every
* {@code datadog.HeapLiveObject} event.
*
* <p>Requesting more attributes than the native capacity must no longer crash (an
* ASan build turns the out-of-bounds read into a heap-buffer-overflow abort) and the
* profiler must cap the attribute list it advertises/serializes at
* {@link JavaProfiler#MAX_CONTEXT_SLOTS}, keeping the JFR metadata schema and the
* per-event field count consistent. See {@link MaxContextSlotsTest} for the
* companion drift guard between {@code JavaProfiler.MAX_CONTEXT_SLOTS} and {@code DD_TAGS_CAPACITY}.
*/
public class TooManyContextAttributesTest extends AbstractProfilerTest {

private static final int REQUESTED_ATTRIBUTES = JavaProfiler.MAX_CONTEXT_SLOTS + 3;

@Override
protected String getProfilerCommand() {
String attrs = IntStream.range(0, REQUESTED_ATTRIBUTES)
.mapToObj(i -> "tag" + i)
.collect(Collectors.joining(";"));
// memory=...:L enables liveness tracking, which is the only path that writes
// datadog.HeapLiveObject events via the vulnerable Recording::writeContextSnapshot.
return "memory=256:L,attributes=" + attrs;
}

@Override
protected boolean isPlatformSupported() {
// Liveness tracking requires Java 11+ and specific JVM types (see LivenessTrackingTest).
return !(Platform.isJavaVersion(8) || Platform.isJ9() || Platform.isZing());
}

@RetryingTest(5)
public void moreAttributesThanCapacityDoesNotCrashAndIsCapped() throws Exception {
// Generate enough live allocation volume to clear the 256 KB sampling interval many
// times over, mirroring the workload LivenessTrackingTest uses to reliably produce
// datadog.HeapLiveObject samples.
List<byte[]> liveObjects = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
for (int j = 0; j < 10; j++) {
liveObjects.add(new byte[ThreadLocalRandom.current().nextInt(1024, 4096)]);
}
}
Thread.sleep(100);
for (int i = 0; i < 6; i++) {
System.gc();
Thread.sleep(100);
}
Thread.sleep(300);

stopProfiler();
assertFalse(liveObjects.isEmpty()); // keep allocations reachable through the GC/dump above

// If the pre-fix out-of-bounds read had fired, an ASan build would already have
// aborted the JVM above. On any build, a mismatched schema/field count would make
// this parse fail or throw - reaching here with samples already proves the fix.
JfrEvents liveObjectEvents = verifyEvents("datadog.HeapLiveObject", false);
assertTrue(liveObjectEvents.hasItems(), "expected datadog.HeapLiveObject samples");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

MEDIUM (robustness): The deterministic capping assertions run after a GC/timing-dependent assertion (liveObjectEvents.hasItems()). If no datadog.HeapLiveObject sample is produced on a given run, the test fails before ever checking that attributes= was capped at MAX_CONTEXT_SLOTS, so a flake and a real regression of the fix look identical.

Suggestion: reorder the method body so the deterministic jdk.ActiveSetting cap assertions run first, then assert liveObjectEvents.hasItems() last.


Set<String> recordedContextAttributes = new HashSet<>();
for (JfrEvent item : verifyEvents("jdk.ActiveSetting")) {
if ("contextattribute".equals(item.getString("name"))) {
recordedContextAttributes.add(item.getString("value"));
}
}
assertEquals(JavaProfiler.MAX_CONTEXT_SLOTS, recordedContextAttributes.size(),
"attributes= list must be capped at JavaProfiler.MAX_CONTEXT_SLOTS (" + JavaProfiler.MAX_CONTEXT_SLOTS
+ "), got: " + recordedContextAttributes);
for (int i = 0; i < JavaProfiler.MAX_CONTEXT_SLOTS; i++) {
assertTrue(recordedContextAttributes.contains("tag" + i),
"expected tag" + i + " to survive capping, got: " + recordedContextAttributes);
}
for (int i = JavaProfiler.MAX_CONTEXT_SLOTS; i < REQUESTED_ATTRIBUTES; i++) {
assertFalse(recordedContextAttributes.contains("tag" + i),
"tag" + i + " exceeds capacity and must have been dropped");
}
}
}
Loading