Add 'projects/rocprofiler-sdk/' from commit 'bf0fad1d5406fbc51403ba1aa9621a9d4a9bce2b'

git-subtree-dir: projects/rocprofiler-sdk
git-subtree-mainline: 50a90550e9
git-subtree-split: bf0fad1d54
This commit is contained in:
systems-assistant[bot]
2025-07-22 22:52:46 +00:00
1272 zmienionych plików z 230117 dodań i 0 usunięć
@@ -0,0 +1,6 @@
#
#
#
add_subdirectory(buffering)
add_subdirectory(common)
add_subdirectory(codeobj)
@@ -0,0 +1,27 @@
#
#
#
project(rocprofiler-sdk-tests-buffering LANGUAGES C CXX)
include(GoogleTest)
set(buffering_sources buffering-serial.cpp buffering-parallel.cpp buffering-save-load.cpp)
add_executable(buffering-test)
target_sources(buffering-test PRIVATE ${buffering_sources})
target_link_libraries(
buffering-test
PRIVATE rocprofiler-sdk::rocprofiler-sdk-headers
rocprofiler-sdk::rocprofiler-sdk-common-library GTest::gtest
GTest::gtest_main)
gtest_add_tests(
TARGET buffering-test
SOURCES ${buffering_sources}
TEST_LIST buffering-tests_TESTS
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
set_tests_properties(
${buffering-tests_TESTS}
PROPERTIES TIMEOUT 360 LABELS "unittests" FAIL_REGULAR_EXPRESSION
"${ROCPROFILER_DEFAULT_FAIL_REGEX}")
@@ -0,0 +1,222 @@
// MIT License
//
// Copyright (c) 2023-2025 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "buffering.hpp"
#include "lib/common/container/record_header_buffer.hpp"
#include "lib/common/mpl.hpp"
#include "lib/common/units.hpp"
#include <gtest/gtest.h>
#include <pthread.h>
#include <cstdint>
#include <cstdlib>
#include <limits>
#include <typeinfo>
#include <utility>
namespace
{
namespace test = ::rocprofiler::test;
namespace units = ::rocprofiler::common::units;
namespace mpl = ::rocprofiler::common::mpl;
using record_header_buffer_t = rocprofiler::common::container::record_header_buffer;
// this function returns a random array of values specific to template instantiation
template <typename Tp, size_t N>
auto&
get_generated_array()
{
static auto _value = []() {
auto _v = test::raw_array<Tp, N>{};
test::generate(_v, Tp{0}, std::numeric_limits<Tp>::max());
return _v;
}();
return _value;
}
// these are the array size variants. we use the units to scale up
// but technically the data size of the raw_array will be multiplied
// by sizeof(Tp)
constexpr auto test_data_sizes = std::index_sequence<1 * units::byte,
2 * units::byte,
3 * units::byte,
4 * units::byte,
8 * units::byte,
16 * units::kilobyte,
20 * units::kilobyte,
24 * units::kilobyte,
32 * units::kilobyte,
56 * units::kilobyte,
64 * units::kilobyte,
91 * units::kilobyte,
128 * units::kilobyte,
387 * units::kilobyte,
693 * units::kilobyte>{};
// this is the list of array data types we will generate. Effectively, there
// will be one raw array for each combination of these types and the test data sizes
// (i.e. there will be unique 160 arrays of different types and sizes)
using test_data_types = mpl::type_list<int8_t,
uint8_t,
int16_t,
uint16_t,
int32_t,
uint32_t,
int64_t,
uint64_t,
float,
double>;
// this function creates a thread for each data size for a given type.
// all threads are detached and will wait at the first barrier until all
// threads have reached it, race to emplace their data in the shared
// buffer and then wait at the second barrier until all the threads have
// emplacing the data and the main thread has also reached the second
// barrier.
template <typename Tp, size_t... Idx>
void
launch_threads(record_header_buffer_t& _buf,
pthread_barrier_t& _race_barrier,
pthread_barrier_t& _done_barrier,
std::index_sequence<Idx...>)
{
auto _launch =
[](record_header_buffer_t* _buf_v, auto* _race_barrier_v, auto* _done_barrier_v, auto* _v) {
pthread_barrier_wait(_race_barrier_v);
EXPECT_TRUE(_buf_v->emplace(*_v));
pthread_barrier_wait(_done_barrier_v);
};
(std::thread{_launch, &_buf, &_race_barrier, &_done_barrier, &get_generated_array<Tp, Idx>()}
.detach(),
...);
}
// expansion for each type
template <typename... Tp, size_t... Idx>
void
launch_threads(record_header_buffer_t& _buf,
pthread_barrier_t& _race_barrier,
pthread_barrier_t& _done_barrier,
mpl::type_list<Tp...>,
std::index_sequence<Idx...> _seq)
{
(launch_threads<Tp>(_buf, _race_barrier, _done_barrier, _seq), ...);
}
// computes the size of every raw_array size for a given type
template <typename Tp, size_t... Idx>
constexpr size_t get_data_size(std::index_sequence<Idx...>)
{
size_t _v = 0;
((_v += sizeof(get_generated_array<Tp, Idx>())), ...);
return _v;
}
// expansion for each type
template <typename... Tp, size_t... Idx>
constexpr size_t
get_data_size(mpl::type_list<Tp...>, std::index_sequence<Idx...> _seq)
{
size_t _v = 0;
((_v += get_data_size<Tp>(_seq)), ...);
return _v;
}
// validates that the raw array extracted out of the buffer is equal
// to the raw array that was placed in the buffer
template <typename Tp, size_t N>
void
validate(const std::vector<rocprofiler_record_header_t*>& _headers)
{
using data_type = test::raw_array<Tp, N>;
auto& _ref_data = get_generated_array<Tp, N>();
for(auto* itr : _headers)
{
if(itr->hash == typeid(data_type).hash_code())
{
auto* _data = static_cast<data_type*>(itr->payload);
EXPECT_EQ(_ref_data, *_data)
<< "\nREF: " << _ref_data.to_string() << "\nINP: " << _data->to_string();
}
}
}
// expansion for every raw array size for a given data type
template <typename Tp, size_t... Idx>
void
validate(const std::vector<rocprofiler_record_header_t*>& _headers, std::index_sequence<Idx...>)
{
(validate<Tp, Idx>(_headers), ...);
}
// expansion for each raw array type
template <typename... Tp, size_t... Idx>
void
validate(const std::vector<rocprofiler_record_header_t*>& _headers,
mpl::type_list<Tp...>,
std::index_sequence<Idx...> _seq)
{
(validate<Tp>(_headers, _seq), ...);
}
} // namespace
TEST(buffering, parallel)
{
// this test launches 160 threads, each with a randomly generated array of data
// and has them contend for emplacing their data in the same buffer. The purpose
// of this test is to validate that multiple threads can write to the same
// (lock-free) buffer without any data corruption or loss.
constexpr auto num_variants = test_data_types::size() * test_data_sizes.size();
constexpr auto data_size = get_data_size(test_data_types{}, test_data_sizes);
EXPECT_EQ(num_variants, 150);
// make a buffer large enough to hold all the data we generate
auto _buffer = record_header_buffer_t{data_size};
// create a barrier that all child threads will wait and then race to enqueue their data in the
// buffer i.e., we want to maximize contention on inserting into buffer
auto _data_race_barrier = pthread_barrier_t{};
pthread_barrier_init(&_data_race_barrier, nullptr, num_variants);
// a barrier to signal that all threads have completed placing their data in the buffer
auto _emplaced_barrier = pthread_barrier_t{};
pthread_barrier_init(&_emplaced_barrier, nullptr, num_variants + 1);
// launch 160 threads
launch_threads(
_buffer, _data_race_barrier, _emplaced_barrier, test_data_types{}, test_data_sizes);
// wait for all the threads to complete
pthread_barrier_wait(&_emplaced_barrier);
// designates that buffer should be cleared after invoking functor
using clear_buffer_t = std::true_type;
// verify the data pulled out the buffer matches the data put in by the threads
_buffer.process_record_headers(clear_buffer_t{}, [](auto&& _records) {
validate(_records, test_data_types{}, test_data_sizes);
});
}
@@ -0,0 +1,276 @@
// MIT License
//
// Copyright (c) 2023-2025 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "buffering.hpp"
#include "lib/common/container/record_header_buffer.hpp"
#include "lib/common/mpl.hpp"
#include "lib/common/units.hpp"
#include <gtest/gtest.h>
#include <pthread.h>
#include <cstdint>
#include <cstdlib>
#include <fstream>
#include <limits>
#include <typeinfo>
#include <utility>
namespace
{
namespace test = ::rocprofiler::test;
namespace units = ::rocprofiler::common::units;
namespace mpl = ::rocprofiler::common::mpl;
using record_header_buffer_t = rocprofiler::common::container::record_header_buffer;
// this function returns a random array of values specific to template instantiation
template <typename Tp, size_t N>
auto&
get_generated_array()
{
static auto _value = []() {
auto _v = test::raw_array<Tp, N>{};
test::generate(_v, Tp{0}, std::numeric_limits<Tp>::max());
return _v;
}();
return _value;
}
// these are the array size variants. we use the units to scale up
// but technically the data size of the raw_array will be multiplied
// by sizeof(Tp)
constexpr auto test_data_sizes = std::index_sequence<1 * units::byte,
2 * units::byte,
3 * units::byte,
4 * units::byte,
8 * units::byte,
16 * units::kilobyte,
20 * units::kilobyte,
24 * units::kilobyte,
32 * units::kilobyte,
56 * units::kilobyte,
64 * units::kilobyte,
91 * units::kilobyte>{};
// this is the list of array data types we will generate. Effectively, there
// will be one raw array for each combination of these types and the test data sizes
// (i.e. there will be unique 160 arrays of different types and sizes)
using test_data_types = mpl::type_list<int8_t,
uint8_t,
int16_t,
uint16_t,
int32_t,
uint32_t,
int64_t,
uint64_t,
float,
double>;
// this function creates a thread for each data size for a given type.
// all threads are detached and will wait at the first barrier until all
// threads have reached it, race to emplace their data in the shared
// buffer and then wait at the second barrier until all the threads have
// emplacing the data and the main thread has also reached the second
// barrier.
template <typename Tp, size_t... Idx>
void
launch(record_header_buffer_t* _buf, pthread_barrier_t* _done_barrier, std::index_sequence<Idx...>)
{
auto _launch = [](record_header_buffer_t* _buf_v, auto* _v) {
EXPECT_TRUE(_buf_v->emplace(*_v));
};
(_launch(_buf, &get_generated_array<Tp, Idx>()), ...);
pthread_barrier_wait(_done_barrier);
}
// expansion for each type
template <typename... Tp, size_t... Idx>
void
launch_threads(record_header_buffer_t& _buf,
pthread_barrier_t& _done_barrier,
mpl::type_list<Tp...>,
std::index_sequence<Idx...> _seq)
{
((std::thread{launch<Tp, Idx...>, &_buf, &_done_barrier, _seq}.detach()), ...);
}
// computes the size of every raw_array size for a given type
template <typename Tp, size_t... Idx>
constexpr size_t get_data_size(std::index_sequence<Idx...>)
{
size_t _v = 0;
((_v += sizeof(get_generated_array<Tp, Idx>())), ...);
return _v;
}
// expansion for each type
template <typename... Tp, size_t... Idx>
constexpr size_t
get_data_size(mpl::type_list<Tp...>, std::index_sequence<Idx...> _seq)
{
size_t _v = 0;
((_v += get_data_size<Tp>(_seq)), ...);
return _v;
}
// validates that the raw array extracted out of the buffer is equal
// to the raw array that was placed in the buffer
template <typename Tp, size_t N>
void
validate(const std::vector<rocprofiler_record_header_t*>& _headers)
{
using data_type = test::raw_array<Tp, N>;
auto& _ref_data = get_generated_array<Tp, N>();
for(auto* itr : _headers)
{
if(itr->hash == typeid(data_type).hash_code())
{
auto* _data = static_cast<data_type*>(itr->payload);
ASSERT_TRUE(_data != nullptr);
EXPECT_EQ(_ref_data, *_data);
}
}
}
// expansion for every raw array size for a given data type
template <typename Tp, size_t... Idx>
void
validate(const std::vector<rocprofiler_record_header_t*>& _headers, std::index_sequence<Idx...>)
{
(validate<Tp, Idx>(_headers), ...);
}
// expansion for each raw array type
template <typename... Tp, size_t... Idx>
void
validate(const std::vector<rocprofiler_record_header_t*>& _headers,
mpl::type_list<Tp...>,
std::index_sequence<Idx...> _seq)
{
(validate<Tp>(_headers, _seq), ...);
}
} // namespace
TEST(buffering, save_load)
{
// this test launches 10 threads for each of the data types in test_data_types. Each thread
// randomly generates 12 array of data of differing sizes and contends with the other threads
// for emplacing the data in the same buffer. The purpose of this test is test the thread-safety
// in a slightly different way, save it to a file backing, clear it, restore it from the file,
// and move it to another object and ensure that the data after the save + load + move matches
// the original data placed into the buffer without any data corruption or loss
// designates that buffer should not be cleared after invoking functor
constexpr auto clear_buffer_v = std::false_type{};
constexpr auto num_variants = test_data_types::size() * test_data_sizes.size();
constexpr auto data_size = get_data_size(test_data_types{}, test_data_sizes);
EXPECT_EQ(num_variants, 120);
// make a buffer large enough to hold all the data we generate
auto _buffer = record_header_buffer_t{};
EXPECT_FALSE(_buffer.is_allocated());
EXPECT_EQ(_buffer.size(), 0);
EXPECT_EQ(_buffer.count(), 0);
EXPECT_EQ(_buffer.free(), 0);
EXPECT_EQ(_buffer.capacity(), 0);
EXPECT_TRUE(_buffer.is_empty());
EXPECT_TRUE(_buffer.is_full());
// allocate the buffer
ASSERT_TRUE(_buffer.allocate(data_size)) << "buffer failed to allocate";
EXPECT_EQ(_buffer.size(), 0);
EXPECT_EQ(_buffer.count(), 0);
EXPECT_GE(_buffer.free(), data_size);
EXPECT_GE(_buffer.capacity(), data_size);
EXPECT_TRUE(_buffer.is_empty());
EXPECT_FALSE(_buffer.is_full());
// a barrier to signal that all threads have completed placing their data in the buffer
auto _emplaced_barrier = pthread_barrier_t{};
pthread_barrier_init(&_emplaced_barrier, nullptr, test_data_types::size() + 1);
// launch 160 threads
launch_threads(_buffer, _emplaced_barrier, test_data_types{}, test_data_sizes);
// wait for all the threads to complete
pthread_barrier_wait(&_emplaced_barrier);
// verify the data, at a high-level is correct
EXPECT_EQ(_buffer.size(), num_variants);
EXPECT_GE(_buffer.count(), data_size);
EXPECT_GE(_buffer.free(), 0);
EXPECT_GE(_buffer.capacity(), data_size);
EXPECT_FALSE(_buffer.is_empty());
// verify the data pulled out the buffer matches the data put in
_buffer.process_record_headers(clear_buffer_v, [](auto&& _records) {
validate(_records, test_data_types{}, test_data_sizes);
});
// save the data to a binary file and clear the buffer so it can "receive" new data (in theory)
{
auto _ofs = std::fstream{};
_ofs.open("buffer-save-load.dat", std::ios::out);
_buffer.save(_ofs);
EXPECT_EQ(_buffer.clear(), num_variants);
}
// verify that the buffer is empty
EXPECT_EQ(_buffer.get_num_record_headers(), 0) << "buffer was not cleared properly";
// load the data back from the binary file
{
auto _ifs = std::fstream{};
_ifs.open("buffer-save-load.dat", std::ios::in);
_buffer.load(_ifs);
}
// verify that, at a high level, all the data was preserved
ASSERT_EQ(_buffer.get_num_record_headers(), num_variants)
<< "buffer was not saved/loaded properly";
// verify the data is entirely correct
_buffer.process_record_headers(clear_buffer_v, [](auto&& _records) {
validate(_records, test_data_types{}, test_data_sizes);
});
// move the data into another instance of record_header_buffer_t
auto _buffer_v = record_header_buffer_t{std::move(_buffer)};
// make sure the move emptied out the old object and populated the new object
ASSERT_EQ(_buffer.get_num_record_headers(), 0) << "buffer was not moved properly";
ASSERT_EQ(_buffer_v.get_num_record_headers(), num_variants) << "buffer was not moved properly";
// validate the data in the new object
// verify the data pulled out the buffer matches the data put in by the threads
_buffer.process_record_headers(clear_buffer_v, [](auto&& _records) {
validate(_records, test_data_types{}, test_data_sizes);
});
// make sure reset works when empty and when full
EXPECT_EQ(_buffer.reset(), 0) << "buffer should be empty after move";
EXPECT_EQ(_buffer_v.reset(), num_variants);
}
@@ -0,0 +1,183 @@
// MIT License
//
// Copyright (c) 2023-2025 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "buffering.hpp"
#include "lib/common/container/record_header_buffer.hpp"
#include <gtest/gtest.h>
#include <pthread.h>
#include <cstdint>
#include <cstdlib>
#include <random>
#include <typeinfo>
namespace
{
namespace test = ::rocprofiler::test;
using uint_raw_array_t = test::raw_array<uint64_t, 32>;
using flt_raw_array_t = test::raw_array<double, 64>;
using record_header_buffer_t = rocprofiler::common::container::record_header_buffer;
// generates an array with random data
template <typename Tp, size_t N>
auto
generate_array(Tp _low = 0UL, Tp _high = 1000UL)
{
auto _v = test::raw_array<Tp, N>{};
test::generate(_v, _low, _high);
return _v;
}
// pulls out a raw array of the given type and puts back into a vector
template <typename Tp>
void
extract_header(std::vector<Tp>& _arr, rocprofiler_record_header_t* _hdr)
{
if(_hdr->hash == typeid(Tp).hash_code())
{
auto* _v = reinterpret_cast<Tp*>(_hdr->payload);
_arr.emplace_back(*_v);
}
else
{
GTEST_FAIL() << __PRETTY_FUNCTION__ << " failed";
}
}
} // namespace
TEST(buffering, serial)
{
// this test verifies that the buffering system is ordered properly
// and does not suffer from data loss or data corruption. We generate
// 240 raw arrays of data where 120 of them are twice as large as the
// the other 120 raw array and these two arrays contain data of different
// types. For each iteration, we randomize whether the uint64_t array with
// 32 elements or whether the double array with 64 elements gets inserted
// first. We then pull all the data back out of the buffer and verify
// that no arrays were lost and that none of the data was corrupted.
uint64_t n = 120;
// storage of the original data put into the buffer
auto _ui_history = std::vector<uint_raw_array_t>{};
auto _ui_result = std::vector<uint_raw_array_t>{};
// storage of the data extracted from the buffer
auto _fp_history = std::vector<flt_raw_array_t>{};
auto _fp_result = std::vector<flt_raw_array_t>{};
// a buffer to hold all the data
auto _buffer = record_header_buffer_t{n * (sizeof(uint_raw_array_t) + sizeof(flt_raw_array_t))};
// RNG use to make the ordering of the different sized records inconsistent
auto _gen = std::mt19937_64{std::random_device{}()};
auto _rng = std::uniform_int_distribution<short>{0, 1};
for(uint64_t i = 0; i < n; ++i)
{
// generate a 32*8 byte array
auto _u = generate_array<uint64_t, 32>();
// generate a 64*8 byte array
auto _f = generate_array<double, 64>();
// store the original data
_ui_history.emplace_back(_u);
_fp_history.emplace_back(_f);
EXPECT_EQ(_u, _ui_history.back()) << "uint not equal after emplace_back";
EXPECT_EQ(_f, _fp_history.back()) << "float not equal after emplace_back";
// randomize sequence of insertion into buffer
if(_rng(_gen) % 2 == 0)
{
_buffer.emplace(_u);
_buffer.emplace(_f);
}
else
{
_buffer.emplace(_f);
_buffer.emplace(_u);
}
EXPECT_EQ(_u, _ui_history.back()) << "uint not equal after emplace_back";
EXPECT_EQ(_f, _fp_history.back()) << "float not equal after emplace_back";
}
// designates that buffer should be cleared after invoking functor
constexpr auto clear_buffer_v = std::true_type{};
// get the records out of the buffer
auto _num_headers = _buffer.process_record_headers(
clear_buffer_v,
[](auto&& _headers, auto& _ui_result_v, auto& _fp_result_v) {
for(auto* itr : _headers)
{
ASSERT_TRUE(itr->payload) << "nullptr to payload not expected";
if(itr->hash == typeid(uint_raw_array_t).hash_code())
{
extract_header(_ui_result_v, itr);
}
else if(itr->hash == typeid(flt_raw_array_t).hash_code())
{
extract_header(_fp_result_v, itr);
}
else
{
GTEST_FAIL() << "unknown type id hash code: " << std::to_string(itr->hash);
}
}
},
_ui_result,
_fp_result);
ASSERT_EQ(_ui_history.size() + _fp_history.size(), _num_headers)
<< "UINT: " << _ui_history.size() << " + FLOAT: " << _fp_history.size()
<< " != HEADERS: " << _num_headers;
// validate that we got the same number of records out that we put in
ASSERT_EQ(_ui_history.size(), _ui_result.size())
<< "UINT: " << _ui_history.size() << " vs. " << _ui_result.size();
ASSERT_EQ(_fp_history.size(), _fp_result.size())
<< "FLOAT: " << _fp_history.size() << " vs. " << _fp_result.size();
// validate there was no data corruption or data loss from storage in the buffer
for(size_t i = 0; i < n; ++i)
{
auto& _ui_lhs = _ui_history.at(i);
auto& _ui_rhs = _ui_result.at(i);
auto& _fp_lhs = _fp_history.at(i);
auto& _fp_rhs = _fp_result.at(i);
EXPECT_EQ(_ui_lhs, _ui_rhs) << "\n"
<< "UINT LHS:\n"
<< _ui_lhs.to_string() << "\n"
<< "UINT RHS:\n"
<< _ui_rhs.to_string() << "\n";
EXPECT_EQ(_fp_lhs, _fp_rhs) << "\n"
<< "FLOAT LHS:\n"
<< _fp_lhs.to_string() << "\n"
<< "FLOAT RHS:\n"
<< _fp_rhs.to_string() << "\n";
}
}
@@ -0,0 +1,105 @@
// MIT License
//
// Copyright (c) 2023-2025 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#pragma once
#include "lib/common/container/record_header_buffer.hpp"
#include <random>
#include <string>
#include <type_traits>
namespace rocprofiler
{
namespace test
{
template <typename Tp, size_t N>
struct raw_array
{
raw_array() = default;
~raw_array() = default;
raw_array(const raw_array&) = default;
raw_array(raw_array&&) noexcept = default;
raw_array& operator=(const raw_array&) = default;
raw_array& operator=(raw_array&&) noexcept = default;
bool operator==(const raw_array<Tp, N>& rhs) const;
bool operator!=(const raw_array<Tp, N>& rhs) const { return !(*this == rhs); }
Tp& operator[](size_t n) { return data[n]; }
Tp operator[](size_t n) const { return data[n]; }
std::string to_string() const;
Tp data[N];
};
template <typename Tp, size_t N>
bool
raw_array<Tp, N>::operator==(const raw_array<Tp, N>& rhs) const
{
for(size_t i = 0; i < N; ++i)
{
if constexpr(std::is_integral_v<Tp>)
{
if((*this)[i] != rhs[i]) return false;
}
else
{
auto _diff = (*this)[i] - rhs[i];
if(_diff < Tp{0.0}) _diff *= Tp{-1.0};
if(_diff > std::numeric_limits<Tp>::round_error()) return false;
}
}
return true;
}
template <typename Tp, size_t N>
std::string
raw_array<Tp, N>::to_string() const
{
auto _ss = std::stringstream{};
for(size_t i = 0; i < N; ++i)
{
_ss << " " << std::setw(8) << std::fixed << std::setprecision(3) << (*this)[i];
if(i % 16 == 15) _ss << "\n";
}
return _ss.str();
}
template <typename Tp, size_t N>
auto
generate(raw_array<Tp, N>& _v, Tp _min, Tp _max)
{
using rng_t = std::conditional_t<std::is_integral<Tp>::value,
std::uniform_int_distribution<Tp>,
std::uniform_real_distribution<Tp>>;
auto _rd = std::random_device{};
auto _gen = std::mt19937_64{_rd()};
auto _rng = rng_t{_min, _max};
for(size_t i = 0; i < N; ++i)
_v[i] = _rng(_gen);
}
} // namespace test
} // namespace rocprofiler
@@ -0,0 +1,37 @@
rocprofiler_deactivate_clang_tidy()
include(GoogleTest)
add_executable(codeobj-library-test)
set(CODEOBJ_LIB_TEST_SOURCES "codeobj_library_test.cpp")
target_sources(codeobj-library-test PRIVATE ${CODEOBJ_LIB_TEST_SOURCES})
target_link_libraries(
codeobj-library-test
PRIVATE rocprofiler-sdk::rocprofiler-sdk-static-library
rocprofiler-sdk::rocprofiler-sdk-glog
rocprofiler-sdk::rocprofiler-sdk-hsa-runtime
rocprofiler-sdk::rocprofiler-sdk-hip
rocprofiler-sdk::rocprofiler-sdk-common-library
GTest::gtest
GTest::gtest_main
rocprofiler-sdk::rocprofiler-sdk-amd-comgr
rocprofiler-sdk::rocprofiler-sdk-dw
rocprofiler-sdk::rocprofiler-sdk-elf)
gtest_add_tests(
TARGET codeobj-library-test
SOURCES ${CODEOBJ_LIB_TEST_SOURCES}
TEST_LIST codeobj-library-test_TESTS
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
set_tests_properties(
${codeobj-library-test_TESTS}
PROPERTIES TIMEOUT 10 LABELS "unittests" FAIL_REGULAR_EXPRESSION
"${ROCPROFILER_DEFAULT_FAIL_REGEX}")
target_compile_definitions(codeobj-library-test
PRIVATE -DCODEOBJ_BINARY_DIR=\"${CMAKE_CURRENT_BINARY_DIR}/\")
configure_file(smallkernel.bin smallkernel.bin COPYONLY)
configure_file(hipcc_output.s hipcc_output.s COPYONLY)
@@ -0,0 +1,264 @@
// MIT License
//
// Copyright (c) 2023-2025 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <fstream>
#include <rocprofiler-sdk/cxx/codeobj/code_printing.hpp>
#include <string_view>
#include <vector>
#ifndef CODEOBJ_BINARY_DIR
static_assert(false && "Please define CODEOBJ_BINARY_DIR to codeobj tests binary, "
"e.g. ../source/lib/tests/codeobj/");
#endif
namespace rocprofiler
{
namespace testing
{
namespace codeobjhelper
{
std::string
removeNull(std::string_view s)
{
std::string u(s);
while(u.find("null") != std::string::npos)
u = u.substr(0, u.find("null")) + "0x0" + u.substr(u.find("null") + 4);
return u;
}
static const std::vector<std::string>&
GetHipccOutput()
{
static std::vector<std::string> result = []() {
std::ifstream file(CODEOBJ_BINARY_DIR "hipcc_output.s");
std::vector<std::string> ret;
while(file.good())
{
std::string s;
getline(file, s);
ret.push_back(removeNull(s));
}
return ret;
}();
return result;
}
static const std::vector<char>&
GetCodeobjContents()
{
static std::vector<char> buffer = []() {
std::string filename = CODEOBJ_BINARY_DIR "smallkernel.bin";
std::ifstream file(filename.data(), std::ios::binary);
using iterator_t = std::istreambuf_iterator<char>;
return std::vector<char>(iterator_t(file), iterator_t());
}();
return buffer;
}
} // namespace codeobjhelper
} // namespace testing
} // namespace rocprofiler
TEST(codeobj_library, segment_test)
{
using CodeobjTableTranslator = rocprofiler::sdk::codeobj::segment::CodeobjTableTranslator;
CodeobjTableTranslator table;
std::unordered_set<size_t> used_addr{};
for(size_t ITER = 0; ITER < 50; ITER++)
{
for(int j = 0; j < 2500; j++)
{
size_t addr = rand() % 10000000;
size_t size = 1;
if(used_addr.find(addr) != used_addr.end()) continue;
used_addr.insert(addr);
table.insert({addr, size, 0});
}
ASSERT_NE(table.begin(), table.end());
{
auto it = std::next(table.begin());
while(it != table.end())
{
ASSERT_LT(*std::prev(it), *it);
it++;
}
}
std::vector<size_t> addr_leftover(used_addr.begin(), used_addr.end());
for(size_t i = 0; i < 2400; i++)
{
size_t idx = rand() % addr_leftover.size();
auto addr = addr_leftover.at(idx);
ASSERT_EQ(table.remove(addr), true);
addr_leftover.erase(addr_leftover.begin() + idx);
used_addr.erase(addr);
}
}
}
namespace disassembly = rocprofiler::sdk::codeobj::disassembly;
namespace codeobjhelper = rocprofiler::testing::codeobjhelper;
using CodeobjDecoderComponent = rocprofiler::sdk::codeobj::disassembly::CodeobjDecoderComponent;
using LoadedCodeobjDecoder = rocprofiler::sdk::codeobj::disassembly::LoadedCodeobjDecoder;
TEST(codeobj_library, file_opens)
{
ASSERT_NE(codeobjhelper::GetHipccOutput().size(), 0);
ASSERT_NE(codeobjhelper::GetCodeobjContents().size(), 0);
}
TEST(codeobj_library, decoder_component)
{
const std::vector<std::string>& hiplines = codeobjhelper::GetHipccOutput();
const std::vector<char>& objdata = codeobjhelper::GetCodeobjContents();
constexpr size_t loaded_offset = 0x3000;
CodeobjDecoderComponent component(objdata.data(), objdata.size());
std::string kernel_with_protocol = "file://" CODEOBJ_BINARY_DIR "smallkernel.bin";
LoadedCodeobjDecoder loadecomp(kernel_with_protocol.data(), loaded_offset, objdata.size());
ASSERT_EQ(component.m_symbol_map.size(), 1);
for(auto& [kaddr, symbol] : component.m_symbol_map)
{
ASSERT_NE(symbol.name.find("reproducible_runtime"), std::string::npos);
ASSERT_NE(symbol.mem_size, 0);
size_t it = 0;
size_t vaddr = kaddr;
while(vaddr < kaddr + symbol.mem_size)
{
if(!component.va2fo(vaddr))
{
ASSERT_NE(0, 0);
}
uint64_t faddr = *component.va2fo(vaddr);
ASSERT_EQ(faddr - symbol.faddr, vaddr - kaddr);
auto instruction = component.disassemble_instruction(faddr, vaddr);
auto loaded_instruction = loadecomp.get(vaddr + loaded_offset);
ASSERT_NE(codeobjhelper::removeNull(instruction->inst).find(hiplines.at(it)),
std::string::npos);
ASSERT_EQ(instruction->inst, loaded_instruction->inst);
vaddr += instruction->size;
it++;
}
}
}
TEST(codeobj_library, loaded_codeobj_component)
{
const std::vector<char>& objdata = rocprofiler::testing::codeobjhelper::GetCodeobjContents();
constexpr size_t offset = 0x1000;
constexpr size_t memsize = 0x1000;
LoadedCodeobjDecoder decoder((const void*) objdata.data(), objdata.size(), offset, memsize);
for(auto& [kaddr, symbol] : decoder.getSymbolMap())
{
ASSERT_NE(symbol.name.find("reproducible_runtime"), std::string::npos);
ASSERT_NE(symbol.mem_size, 0);
}
}
TEST(codeobj_library, codeobj_map_test)
{
using marker_id_t = rocprofiler::sdk::codeobj::segment::marker_id_t;
const std::vector<char>& objdata = rocprofiler::testing::codeobjhelper::GetCodeobjContents();
constexpr size_t laddr1 = 0x1000;
constexpr size_t laddr3 = 0x3000;
uint64_t kaddr = [&objdata]() {
CodeobjDecoderComponent comp(objdata.data(), objdata.size());
for(auto& [addr, _] : comp.m_symbol_map)
return addr;
return 0ul;
}();
EXPECT_NE(kaddr, 0);
disassembly::CodeobjMap map;
const void* objdataptr = (const void*) objdata.data();
map.addDecoder(objdataptr, objdata.size(), marker_id_t{1}, laddr1, objdata.size());
map.addDecoder(objdataptr, objdata.size(), marker_id_t{3}, laddr3, objdata.size());
EXPECT_EQ(map.get(marker_id_t{1}, kaddr)->inst, map.get(marker_id_t{3}, kaddr)->inst);
ASSERT_EQ(map.removeDecoderbyId(1), true);
ASSERT_EQ(map.removeDecoderbyId(3), true);
ASSERT_EQ(map.removeDecoderbyId(1), false);
}
TEST(codeobj_library, codeobj_table_test)
{
using marker_id_t = rocprofiler::sdk::codeobj::segment::marker_id_t;
const std::vector<std::string>& hiplines = codeobjhelper::GetHipccOutput();
const std::vector<char>& objdata = codeobjhelper::GetCodeobjContents();
constexpr size_t laddr1 = 0x1000;
constexpr size_t laddr3 = 0x3000;
disassembly::CodeobjAddressTranslate map;
uint64_t kaddr = 0, memsize = 0;
std::tie(kaddr, memsize) = [&objdata]() {
CodeobjDecoderComponent comp(objdata.data(), objdata.size());
for(auto& [addr, symbol] : comp.m_symbol_map)
return std::pair<uint64_t, uint64_t>(addr, symbol.mem_size);
return std::pair<uint64_t, uint64_t>(0, 0);
}();
ASSERT_NE(kaddr, 0);
ASSERT_NE(memsize, 0);
map.addDecoder((const void*) objdata.data(), objdata.size(), marker_id_t{1}, laddr1, 0x2000);
map.addDecoder((const void*) objdata.data(), objdata.size(), marker_id_t{3}, laddr3, 0x2000);
EXPECT_NE(map.get(laddr1 + kaddr).get(), nullptr);
EXPECT_NE(map.get(laddr3 + kaddr).get(), nullptr);
EXPECT_EQ(map.get(laddr1 + kaddr)->inst, map.get(laddr3 + kaddr)->inst);
size_t it = 0;
size_t vaddr = kaddr;
while(vaddr < kaddr + memsize)
{
auto instruction = map.get(laddr1 + vaddr);
ASSERT_NE(codeobjhelper::removeNull(instruction->inst).find(hiplines.at(it)),
std::string::npos);
vaddr += instruction->size;
it++;
}
ASSERT_EQ(map.removeDecoderbyId(1), true);
ASSERT_EQ(map.removeDecoderbyId(3), true);
ASSERT_EQ(map.removeDecoderbyId(1), false);
}
@@ -0,0 +1,17 @@
s_load_b64 s[0:1], s[0:1], 0x0
s_getreg_b32 s2, hwreg(HW_REG_SHADER_CYCLES, 0, 20)
s_waitcnt vmcnt(0) lgkmcnt(0)
s_waitcnt_vscnt null, 0x0
s_barrier
s_waitcnt vmcnt(0) lgkmcnt(0)
s_waitcnt_vscnt null, 0x0
buffer_gl0_inv
s_getreg_b32 s3, hwreg(HW_REG_SHADER_CYCLES, 0, 20)
s_delay_alu instid0(SALU_CYCLE_1) | instskip(SKIP_1) | instid1(SALU_CYCLE_1)
s_sub_u32 s4, s3, s2
s_subb_u32 s5, 0, 0
v_cmp_lt_i64_e64 s3, s[4:5], s[0:1]
s_delay_alu instid0(VALU_DEP_1)
s_and_b32 vcc_lo, exec_lo, s3
s_cbranch_vccnz 65520
s_endpgm
Plik binarny nie jest wyświetlany.
@@ -0,0 +1,31 @@
#
# Tests for the common library
#
project(rocprofiler-sdk-tests-common LANGUAGES C CXX)
include(GoogleTest)
set(common_sources c_array.cpp demangling.cpp environment.cpp md5sum.cpp mpl.cpp
parse.cpp sha256.cpp uuid_v7.cpp)
add_executable(common-tests)
target_sources(common-tests PRIVATE ${common_sources})
target_link_libraries(
common-tests
PRIVATE rocprofiler-sdk::rocprofiler-sdk-headers
rocprofiler-sdk::rocprofiler-sdk-common-library
rocprofiler-sdk::rocprofiler-sdk-output-library
rocprofiler-sdk::rocprofiler-sdk-cereal
GTest::gtest
GTest::gtest_main)
gtest_add_tests(
TARGET common-tests
SOURCES ${common_sources}
TEST_LIST common-tests_TESTS
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR})
set_tests_properties(
${common-tests_TESTS}
PROPERTIES TIMEOUT 45 LABELS "unittests" FAIL_REGULAR_EXPRESSION
"${ROCPROFILER_DEFAULT_FAIL_REGEX}" ENVIRONMENT "TEST_LOG_LEVEL=info")
@@ -0,0 +1,138 @@
// MIT License
//
// Copyright (c) 2023-2025 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <rocprofiler-sdk/cxx/container/c_array.hpp>
#include <rocprofiler-sdk/cxx/serialization.hpp>
#include <gtest/gtest.h>
#include <sstream>
#include <vector>
namespace
{
template <typename Tp>
void
compare_serialization_of_vector_and_c_array(std::vector<Tp>& vec)
{
std::stringstream ss_vec;
{
cereal::BinaryOutputArchive oarchive(ss_vec);
save(oarchive, vec);
}
std::stringstream ss_arr;
{
cereal::BinaryOutputArchive oarchive(ss_arr);
auto arr = rocprofiler::sdk::container::make_c_array(vec.data(), vec.size());
save(oarchive, arr);
}
ASSERT_EQ(ss_vec.str(), ss_arr.str());
}
template <typename Tp>
void
compare_serialization_of_vector_and_c_array_of_pointers(std::vector<Tp>& vec)
{
std::vector<Tp*> ptrs;
ptrs.reserve(vec.size());
for(auto& val : vec)
ptrs.emplace_back(&val);
std::stringstream ss_vec;
{
cereal::BinaryOutputArchive oarchive(ss_vec);
save(oarchive, vec);
}
std::stringstream ss_arr;
{
cereal::BinaryOutputArchive oarchive(ss_arr);
auto arr = rocprofiler::sdk::container::make_c_array(ptrs.data(), ptrs.size());
save(oarchive, arr);
}
ASSERT_EQ(ss_vec.str(), ss_arr.str());
}
} // namespace
TEST(common, c_array)
{
std::vector<int> vec{1, 2, 3, 4, 5};
auto arr = rocprofiler::sdk::container::make_c_array(vec.data(), vec.size());
// Validate size
ASSERT_EQ(arr.size(), vec.size());
// Test operator[] and at()
for(size_t i = 0; i < arr.size(); ++i)
{
EXPECT_EQ(arr[i], vec[i]);
EXPECT_EQ(arr.at(i), vec.at(i));
}
// Bounds checking on at()
EXPECT_THROW(arr.at(arr.size()), std::out_of_range);
// Test slice
auto sub_arr = arr.slice(1, 4); // should contain 2, 3, 4
ASSERT_EQ(sub_arr.size(), 3);
EXPECT_EQ(sub_arr[0], 2);
EXPECT_EQ(sub_arr[2], 4);
// Test pop_front()
arr.pop_front(); // drops 1
ASSERT_EQ(arr.size(), 4);
EXPECT_EQ(arr[0], 2);
// Test pop_back()
arr.pop_back(); // drops 5
ASSERT_EQ(arr.size(), 3);
EXPECT_EQ(arr[2], 4);
// Test iterators
int expected[] = {2, 3, 4};
int idx = 0;
for(auto v : arr)
{
EXPECT_EQ(v, expected[idx++]);
}
// Const iterator
const auto& const_arr = arr;
idx = 0;
for(auto v : const_arr)
{
EXPECT_EQ(v, expected[idx++]);
}
// Test implicit cast to pointer
int* ptr = arr;
EXPECT_EQ(ptr[0], 2);
EXPECT_EQ(ptr[2], 4);
// Test Serialization.
compare_serialization_of_vector_and_c_array(vec);
compare_serialization_of_vector_and_c_array_of_pointers(vec);
}
@@ -0,0 +1,95 @@
// MIT License
//
// Copyright (c) 2023-2025 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "lib/common/demangle.hpp"
#include <gtest/gtest.h>
#include <string_view>
#include <utility>
TEST(common, demangling)
{
// the purpose of this test is to verify the cxx_demangle function.
// We want to make sure that the function produces the right demangling
// when it is a correctly mangled string and does not change the string
// when demangling fails
using strview_pair_t = std::pair<std::string_view, std::string_view>;
for(auto [mangled, demangled] :
{strview_pair_t{"_ZN11rocprofiler8internal18correlation_config22get_unique_internal_idEv",
"rocprofiler::internal::correlation_config::get_unique_internal_id()"},
strview_pair_t{"_ZN11rocprofiler8internal18get_active_configsEv",
"rocprofiler::internal::get_active_configs()"},
strview_pair_t{"_ZN11rocprofiler8internal22get_registered_configsEv",
"rocprofiler::internal::get_registered_configs()"},
strview_pair_t{
"_ZZN11rocprofiler8internal18correlation_config22get_unique_internal_idEvE2_v",
"rocprofiler::internal::correlation_config::get_unique_internal_id()::_v"},
strview_pair_t{"_ZZN11rocprofiler8internal18get_active_configsEvE2_v",
"rocprofiler::internal::get_active_configs()::_v"},
strview_pair_t{"_ZZN11rocprofiler8internal22get_registered_configsEvE2_v",
"rocprofiler::internal::get_registered_configs()::_v"}})
{
// verify the demangling works
EXPECT_EQ(rocprofiler::common::cxx_demangle(mangled), demangled)
<< "failed to demangle '" << mangled << "'";
// verify we get same string in when improperly mangled string
auto bad_mangled = std::string{"_Z"} + std::string{mangled};
EXPECT_EQ(rocprofiler::common::cxx_demangle(bad_mangled), bad_mangled)
<< "demangling succeeded for '" << bad_mangled << "'";
}
}
TEST(common, truncate)
{
// this test is verify that the truncate_name function correctly finds the function
// name in a complex template instantiation
auto mangled = std::string_view{"_ZSt16__do_uninit_copyIPKSt4pairINSt7__cxx1112basic_"
"stringIcSt11char_traitsIcESaIcEEES6_EPS7_ET0_T_SC_SB_"};
auto untruncated = std::string_view{
"std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> "
">, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >* "
"std::__do_uninit_copy<std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, "
"std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, "
"std::allocator<char> > > const*, std::pair<std::__cxx11::basic_string<char, "
"std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, "
"std::char_traits<char>, std::allocator<char> > "
">*>(std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, "
"std::allocator<char> >, std::__cxx11::basic_string<char, std::char_traits<char>, "
"std::allocator<char> > > const*, std::pair<std::__cxx11::basic_string<char, "
"std::char_traits<char>, std::allocator<char> >, std::__cxx11::basic_string<char, "
"std::char_traits<char>, std::allocator<char> > > const*, "
"std::pair<std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> "
">, std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> > >*)"};
EXPECT_EQ(rocprofiler::common::cxx_demangle(mangled), untruncated);
EXPECT_EQ(rocprofiler::common::truncate_name(untruncated),
std::string_view{"__do_uninit_copy"});
EXPECT_EQ(rocprofiler::common::truncate_name(rocprofiler::common::cxx_demangle(mangled)),
std::string_view{"__do_uninit_copy"});
}
@@ -0,0 +1,160 @@
// MIT License
//
// Copyright (c) 2023-2025 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "lib/common/environment.hpp"
#include <fmt/format.h>
#include <gtest/gtest.h>
namespace
{
bool _common_environment_test_init_logging = (rocprofiler::common::init_logging("TEST"), true);
}
TEST(common, environment)
{
using rocprofiler::common::env_config;
using rocprofiler::common::get_env;
enum TestBareEnum : unsigned short // NOLINT(performance-enum-size)
{
BZero = 0,
BOne = 1,
};
enum class TestClassEnum : unsigned short // NOLINT(performance-enum-size)
{
CZero = 0,
COne = 1,
};
//
// int testing section
//
EXPECT_EQ(get_env("ROCPROFILER_ENV_TEST_INT", 0), 0);
setenv("ROCPROFILER_ENV_TEST_INT", "1", 1);
EXPECT_EQ(get_env("ROCPROFILER_ENV_TEST_INT", 0), 1);
env_config{"ROCPROFILER_ENV_TEST_INT", "2"}();
EXPECT_EQ(get_env("ROCPROFILER_ENV_TEST_INT", 0), 1);
env_config{"ROCPROFILER_ENV_TEST_INT", "2", 1}();
EXPECT_EQ(get_env("ROCPROFILER_ENV_TEST_INT", 0), 2);
//
// enum testing section
//
EXPECT_EQ(get_env("ROCPROFILER_ENV_TEST_BARE_ENUM", BZero), BZero);
env_config{"ROCPROFILER_ENV_TEST_BARE_ENUM", "1", 1}();
EXPECT_EQ(get_env("ROCPROFILER_ENV_TEST_BARE_ENUM", BZero), BOne);
EXPECT_EQ(get_env("ROCPROFILER_ENV_TEST_CLASS_ENUM", TestClassEnum::CZero),
TestClassEnum::CZero);
env_config{"ROCPROFILER_ENV_TEST_CLASS_ENUM", "1", 1}();
EXPECT_EQ(get_env("ROCPROFILER_ENV_TEST_CLASS_ENUM", TestClassEnum::CZero),
TestClassEnum::COne);
//
// string testing section
//
EXPECT_EQ(get_env("ROCPROFILER_ENV_TEST_STR", "nostr"), std::string_view{"nostr"});
env_config{"ROCPROFILER_ENV_TEST_STR", "hasstr", 0}();
EXPECT_EQ(get_env("ROCPROFILER_ENV_TEST_STR", "nostr"), std::string_view{"hasstr"});
//
// bool testing section
//
EXPECT_FALSE(get_env("ROCPROFILER_ENV_TEST_BOOL", false));
env_config{"ROCPROFILER_ENV_TEST_BOOL", "YES", 1}();
EXPECT_TRUE(get_env("ROCPROFILER_ENV_TEST_BOOL", false));
env_config{"ROCPROFILER_ENV_TEST_BOOL", "yes", 1}();
EXPECT_TRUE(get_env("ROCPROFILER_ENV_TEST_BOOL", false));
env_config{"ROCPROFILER_ENV_TEST_BOOL", "y", 1}();
EXPECT_TRUE(get_env("ROCPROFILER_ENV_TEST_BOOL", false));
env_config{"ROCPROFILER_ENV_TEST_BOOL", "true", 1}();
EXPECT_TRUE(get_env("ROCPROFILER_ENV_TEST_BOOL", false));
env_config{"ROCPROFILER_ENV_TEST_BOOL", "on", 1}();
EXPECT_TRUE(get_env("ROCPROFILER_ENV_TEST_BOOL", false));
env_config{"ROCPROFILER_ENV_TEST_BOOL", "no", 1}();
EXPECT_FALSE(get_env("ROCPROFILER_ENV_TEST_BOOL", true));
env_config{"ROCPROFILER_ENV_TEST_BOOL", "false", 1}();
EXPECT_FALSE(get_env("ROCPROFILER_ENV_TEST_BOOL", true));
env_config{"ROCPROFILER_ENV_TEST_BOOL", "0", 1}();
EXPECT_FALSE(get_env("ROCPROFILER_ENV_TEST_BOOL", true));
for(auto n : {1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
{
env_config{"ROCPROFILER_ENV_TEST_BOOL", std::to_string(n), 1}();
EXPECT_TRUE(get_env("ROCPROFILER_ENV_TEST_BOOL", false));
}
}
TEST(common, environment_push_pop)
{
using rocprofiler::common::env_config;
using rocprofiler::common::env_store;
using rocprofiler::common::get_env;
namespace common = ::rocprofiler::common;
common::set_env("ROCPROFILER_ENV_TEST_A", "0", 1);
common::set_env("ROCPROFILER_ENV_TEST_B", "2", 1);
auto _store = env_store{{env_config{"ROCPROFILER_ENV_TEST_A", "1"},
env_config{"ROCPROFILER_ENV_TEST_B", "2", 1},
env_config{"ROCPROFILER_ENV_TEST_C", "3", 0}}};
for(size_t i = 0; i < 5; ++i)
{
EXPECT_EQ(get_env("ROCPROFILER_ENV_TEST_A", 3), 0) << fmt::format("iteration={}", i);
EXPECT_EQ(get_env("ROCPROFILER_ENV_TEST_B", 0), 2) << fmt::format("iteration={}", i);
EXPECT_EQ(get_env("ROCPROFILER_ENV_TEST_C", 1), 1) << fmt::format("iteration={}", i);
EXPECT_FALSE(_store.is_pushed()) << fmt::format("iteration={}", i);
EXPECT_TRUE(_store.push()) << fmt::format("iteration={}", i);
EXPECT_FALSE(_store.push()) << fmt::format("iteration={}", i);
EXPECT_EQ(get_env("ROCPROFILER_ENV_TEST_A", 3), 1) << fmt::format("iteration={}", i);
EXPECT_EQ(get_env("ROCPROFILER_ENV_TEST_B", 0), 2) << fmt::format("iteration={}", i);
EXPECT_EQ(get_env("ROCPROFILER_ENV_TEST_C", 1), 3) << fmt::format("iteration={}", i);
EXPECT_TRUE(_store.is_pushed()) << fmt::format("iteration={}", i);
EXPECT_TRUE(_store.pop()) << fmt::format("iteration={}", i);
EXPECT_FALSE(_store.pop()) << fmt::format("iteration={}", i);
EXPECT_EQ(get_env("ROCPROFILER_ENV_TEST_A", 3), 0) << fmt::format("iteration={}", i);
EXPECT_EQ(get_env("ROCPROFILER_ENV_TEST_B", 0), 2) << fmt::format("iteration={}", i);
EXPECT_EQ(get_env("ROCPROFILER_ENV_TEST_C", 0), 0) << fmt::format("iteration={}", i);
}
}
@@ -0,0 +1,58 @@
// MIT License
//
// Copyright (c) 2023-2025 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "lib/common/md5sum.hpp"
#include <fmt/format.h>
#include <gtest/gtest.h>
#include <cstddef>
#include <cstdint>
#include <sstream>
#include <string>
TEST(common, md5sum)
{
auto _val = rocprofiler::common::md5sum{};
_val.update(234234);
_val.finalize();
auto _hex_digest = _val.hexdigest();
EXPECT_EQ(_hex_digest, "5cdf897625070d805f3fb2469b08eebb");
auto read_hex = [](std::string&& _inp) {
int _ret = 0;
std::stringstream{_inp} >> std::hex >> _ret;
return _ret;
};
auto _raw_digest = _val.rawdigest();
for(size_t i = 0; i < _raw_digest.size(); ++i)
{
auto _sub = _hex_digest.substr(i * 2, 2);
auto _extract = read_hex(fmt::format("0x{}", _sub));
int _raw = _raw_digest.at(i);
EXPECT_EQ(_raw, _extract) << fmt::format(
"i={}, raw[i]={}, hex={}, hexdigest={}", i, _raw, _sub, _hex_digest);
}
}
@@ -0,0 +1,70 @@
// MIT License
//
// Copyright (c) 2023-2025 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "lib/common/mpl.hpp"
#include <gtest/gtest.h>
#include <tuple>
TEST(common, mpl)
{
namespace mpl = ::rocprofiler::common::mpl;
struct Foo;
using test_type_list_t = mpl::type_list<int, long, int, Foo, Foo*>;
using test_tuple_t = std::tuple<int, long, int, Foo, Foo*>;
EXPECT_EQ(mpl::size_of<test_type_list_t>::value, 5);
EXPECT_EQ(mpl::size_of<test_tuple_t>::value, 5);
{
constexpr bool _foo_p_is_one_of = mpl::is_one_of<Foo*, test_type_list_t>::value;
constexpr bool _int_is_one_of = mpl::is_one_of<int, test_type_list_t>::value;
constexpr bool _double_is_one_of = mpl::is_one_of<double, test_type_list_t>::value;
EXPECT_TRUE(_foo_p_is_one_of);
EXPECT_TRUE(_int_is_one_of);
EXPECT_FALSE(_double_is_one_of);
constexpr auto _foo_p_index_of = mpl::index_of<Foo*, test_type_list_t>::value;
constexpr auto _int_index_of = mpl::index_of<int, test_type_list_t>::value;
EXPECT_EQ(_foo_p_index_of, 4);
EXPECT_EQ(_int_index_of, 0);
}
{
constexpr bool _foo_p_is_one_of = mpl::is_one_of<Foo*, test_tuple_t>::value;
constexpr bool _int_is_one_of = mpl::is_one_of<int, test_tuple_t>::value;
constexpr bool _double_is_one_of = mpl::is_one_of<double, test_tuple_t>::value;
EXPECT_TRUE(_foo_p_is_one_of);
EXPECT_TRUE(_int_is_one_of);
EXPECT_FALSE(_double_is_one_of);
constexpr auto _foo_p_index_of = mpl::index_of<Foo*, test_tuple_t>::value;
constexpr auto _int_index_of = mpl::index_of<int, test_tuple_t>::value;
EXPECT_EQ(_foo_p_index_of, 4);
EXPECT_EQ(_int_index_of, 0);
}
}
@@ -0,0 +1,70 @@
// MIT License
//
// Copyright (c) 2023-2025 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include <rocprofiler-sdk/cxx/details/tokenize.hpp>
#include <fmt/format.h>
#include <gtest/gtest.h>
#include <cstddef>
#include <cstdint>
#include <sstream>
#include <string>
namespace sdk = ::rocprofiler::sdk;
TEST(parse, tokenize_characters)
{
auto tokenized = sdk::parse::tokenize(std::string_view{"0, GPU-DEADBEEFDEADBEEF,, -1"}, ", ");
ASSERT_EQ(tokenized.size(), 3)
<< fmt::format("TOKENIZED: '{}'", fmt::join(tokenized.begin(), tokenized.end(), "' | '"));
EXPECT_EQ(tokenized.at(0), "0");
EXPECT_EQ(tokenized.at(1), "GPU-DEADBEEFDEADBEEF");
EXPECT_EQ(tokenized.at(2), "-1");
}
TEST(parse, tokenize_strings)
{
auto tokenized = sdk::parse::tokenize(std::string_view{"0, GPU-DEADBEEFDEADBEEF, -1, 8"},
std::vector<std::string_view>{", "});
ASSERT_EQ(tokenized.size(), 4)
<< fmt::format("TOKENIZED: '{}'", fmt::join(tokenized.begin(), tokenized.end(), "' | '"));
EXPECT_EQ(tokenized.at(0), "0");
EXPECT_EQ(tokenized.at(1), "GPU-DEADBEEFDEADBEEF");
EXPECT_EQ(tokenized.at(2), "-1");
EXPECT_EQ(tokenized.at(3), "8");
}
TEST(parse, strip)
{
auto test_message = std::string{" \t\v\f TEST MESSAGE\n\r\n "};
auto stripped_message = sdk::parse::strip(std::string{test_message}, " \t\n\v\f\r");
auto expected_message = std::string{"TEST MESSAGE"};
EXPECT_EQ(stripped_message, expected_message)
<< fmt::format("Expected '{}' after stripping '{}'\nResult: '{}'",
expected_message,
test_message,
stripped_message);
}
@@ -0,0 +1,57 @@
// MIT License
//
// Copyright (c) 2023-2025 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "lib/common/sha256.hpp"
#include <fmt/format.h>
#include <gtest/gtest.h>
#include <cstddef>
#include <cstdint>
#include <sstream>
#include <string>
TEST(common, sha256)
{
auto _val = rocprofiler::common::sha256{};
_val.update("rocprofiler-sdk|rocprofiler-sdk-roctx|rocprofiler-sdk-rocpd");
auto _hex_digest = _val.hexdigest();
EXPECT_EQ(_hex_digest, "e58b701acc3c524f881e49fff2833879eb17975b6a072d9ecc27de5a5344aefc");
auto read_hex = [](std::string&& _inp) {
uint32_t _ret = 0;
std::stringstream{_inp} >> std::hex >> _ret;
return _ret;
};
auto _raw_digest = _val.rawdigest();
for(size_t i = 0; i < _raw_digest.size(); ++i)
{
auto _sub = _hex_digest.substr(i * 8, 8);
auto _extract = read_hex(fmt::format("0x{}", _sub));
int _raw = _raw_digest.at(i);
EXPECT_EQ(_raw, _extract) << fmt::format(
"i={}, raw[i]={}, hex={}, hexdigest={}", i, _raw, _sub, _hex_digest);
}
}
@@ -0,0 +1,80 @@
// MIT License
//
// Copyright (c) 2023-2025 Advanced Micro Devices, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
#include "lib/common/uuid_v7.hpp"
#include "lib/common/utility.hpp"
#include "lib/output/node_info.hpp"
#include <fmt/format.h>
#include <gtest/gtest.h>
#include <cstddef>
#include <cstdint>
#include <sstream>
#include <string>
TEST(common, uuid_v7)
{
namespace common = ::rocprofiler::common;
namespace tool = ::rocprofiler::tool;
auto _node_data = tool::read_node_info();
const auto& _mach_id = _node_data.machine_id;
auto _this_pid = getpid();
auto _this_ppid = getppid();
auto _init_ns = common::timestamp_ns();
auto _ticks = common::get_process_start_ticks_since_boot(_this_pid);
auto get_uuid_v7 = [&_mach_id, &_this_pid, &_this_ppid, &_ticks](auto _timestamp_ns) {
auto _seed = common::compute_system_seed(_mach_id, _this_pid, _this_ppid, _ticks);
return common::generate_uuid_v7(_timestamp_ns, _seed);
};
auto reference_uuid_v7 = get_uuid_v7(_init_ns);
// uuid v7 has millisecond precision
std::this_thread::sleep_for(std::chrono::milliseconds{5});
for(size_t i = 0; i < 1000; ++i)
{
auto varying_ns = common::timestamp_ns();
auto varying_uuid_v7 = get_uuid_v7(varying_ns);
EXPECT_NE(reference_uuid_v7, varying_uuid_v7)
<< fmt::format("machine-id={}, pid={}, ppid={}, ticks={}, init_ns={}, varying_ns={}",
_mach_id,
_this_pid,
_this_ppid,
_ticks,
_init_ns,
varying_ns);
// UUIDv7 is supposed to be lexicographically sortable
EXPECT_LT(reference_uuid_v7, varying_uuid_v7)
<< fmt::format("machine-id={}, pid={}, ppid={}, ticks={}, init_ns={}, varying_ns={}",
_mach_id,
_this_pid,
_this_ppid,
_ticks,
_init_ns,
varying_ns);
}
}