Skip to content

Commit b7b0278

Browse files
strophymarcalff
andauthored
[SDK] Ensure TraceId is portable on big-endian architectures (#3543)
Co-authored-by: Marc Alff <[email protected]>
1 parent 8608773 commit b7b0278

File tree

2 files changed

+9
-4
lines changed

2 files changed

+9
-4
lines changed

sdk/src/trace/samplers/trace_id_ratio.cc

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,11 @@
44

55
#include <cmath>
66
#include <cstdint>
7-
#include <cstring>
87
#include <map>
98
#include <memory>
109
#include <string>
1110

11+
#include "opentelemetry/nostd/span.h"
1212
#include "opentelemetry/nostd/string_view.h"
1313
#include "opentelemetry/sdk/trace/sampler.h"
1414
#include "opentelemetry/sdk/trace/samplers/trace_id_ratio.h"
@@ -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)