Skip to content

Commit 9377a5d

Browse files
committed
[SDK] Ensure TraceId is portable on big-endian architectures
1 parent 6fed48c commit 9377a5d

File tree

2 files changed

+8
-3
lines changed

2 files changed

+8
-3
lines changed

sdk/src/trace/samplers/trace_id_ratio.cc

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,13 @@ uint64_t CalculateThresholdFromBuffer(const trace_api::TraceId &trace_id) noexce
5656
// We only use the first 8 bytes of TraceId.
5757
static_assert(trace_api::TraceId::kSize >= 8, "TraceID must be at least 8 bytes long.");
5858

59-
uint64_t res = 0;
60-
std::memcpy(&res, &trace_id, 8);
59+
// Always interpret as big-endian
60+
const uint8_t *data = trace_id.Id().data();
61+
uint64_t res = 0;
62+
for (int i = 0; i < 8; ++i)
63+
{
64+
res = (res << 8) | data[i];
65+
}
6166

6267
double ratio = static_cast<double>(res) / static_cast<double>(UINT64_MAX);
6368

sdk/test/trace/trace_id_ratio_sampler_test.cc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -99,7 +99,7 @@ TEST(TraceIdRatioBasedSampler, ShouldSampleWithoutContext)
9999
ASSERT_EQ(Decision::RECORD_AND_SAMPLE, sampling_result.decision);
100100
ASSERT_EQ(nullptr, sampling_result.attributes);
101101

102-
constexpr uint8_t buf[] = {0, 0, 0, 0, 0, 0, 0, 0x80, 0, 0, 0, 0, 0, 0, 0, 0};
102+
constexpr uint8_t buf[] = {0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
103103
trace_api::TraceId valid_trace_id(buf);
104104

105105
sampling_result = s1.ShouldSample(trace_api::SpanContext::GetInvalid(), valid_trace_id, "",

0 commit comments

Comments
 (0)