Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ReinterpretAsInt causing undefind behavior + segfaulting on release mode #362

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
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
25 changes: 21 additions & 4 deletions mjpc/utilities.cc
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
#include "mjpc/utilities.h"

#include <algorithm>
#include <bit>
#include <cerrno>
#include <cmath>
#include <cstdint>
Expand Down Expand Up @@ -115,12 +116,28 @@ void Clamp(double* x, const double* bounds, int n) {
}
}

int ReinterpretAsInt(double value) {
return *std::launder(reinterpret_cast<const int*>(&value));
int64_t ReinterpretAsInt(double value) {
static_assert(sizeof(double) == sizeof(int64_t),
"double and int64_t must have same size");
#if defined(__cpp_lib_bit_cast)
return std::bit_cast<int64_t>(value);
JafarAbdi marked this conversation as resolved.
Show resolved Hide resolved
#else
int64_t dst;
std::memcpy(&dst, &value, sizeof(int64_t));
return dst;
#endif
}

double ReinterpretAsDouble(int64_t value) {
return *std::launder(reinterpret_cast<const double*>(&value));
static_assert(sizeof(double) == sizeof(int64_t),
"double and int64_t must have same size");
#if defined(__cpp_lib_bit_cast)
return std::bit_cast<double>(value);
#else
double dst;
std::memcpy(&dst, &value, sizeof(double));
return dst;
#endif
}

absl::flat_hash_map<std::string, std::vector<std::string>>
Expand Down Expand Up @@ -225,7 +242,7 @@ int ParameterIndex(const mjModel* model, std::string_view name) {
double DefaultResidualSelection(const mjModel* m, int numeric_index) {
// list selections are stored as ints, but numeric values are doubles.
int64_t value = m->numeric_data[m->numeric_adr[numeric_index]];
return *std::launder(reinterpret_cast<const double*>(&value));
return ReinterpretAsDouble(value);
}

int CostTermByName(const mjModel* m, const std::string& name) {
Expand Down
4 changes: 2 additions & 2 deletions mjpc/utilities.h
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,8 @@ T GetNumberOrDefault(T default_value, const mjModel* m, std::string_view name) {
return GetNumber<T>(m, name).value_or(default_value);
}

// reinterpret double as int
int ReinterpretAsInt(double value);
// reinterpret double as int64_t
int64_t ReinterpretAsInt(double value);

// reinterpret int64_t as double
double ReinterpretAsDouble(int64_t value);
Expand Down
Loading