|
| 1 | +// evmone: Fast Ethereum Virtual Machine implementation |
| 2 | +// Copyright 2021 The evmone Authors. |
| 3 | +// SPDX-License-Identifier: Apache-2.0 |
| 4 | + |
| 5 | +#include "tracing.hpp" |
| 6 | +#include <evmc/hex.hpp> |
| 7 | +#include <stack> |
| 8 | + |
| 9 | +namespace evmone |
| 10 | +{ |
| 11 | +namespace |
| 12 | +{ |
| 13 | +std::string get_name(const char* const* names, uint8_t opcode) |
| 14 | +{ |
| 15 | + const auto name = names[opcode]; |
| 16 | + return (name != nullptr) ? name : "0x" + evmc::hex(opcode); |
| 17 | +} |
| 18 | + |
| 19 | +/// @see create_histogram_tracer() |
| 20 | +class HistogramTracer : public Tracer |
| 21 | +{ |
| 22 | + struct Context |
| 23 | + { |
| 24 | + const int32_t depth; |
| 25 | + const uint8_t* const code; |
| 26 | + const char* const* const opcode_names; |
| 27 | + uint32_t counts[256]{}; |
| 28 | + |
| 29 | + Context(int32_t _depth, const uint8_t* _code, const char* const* _opcode_names) noexcept |
| 30 | + : depth{_depth}, code{_code}, opcode_names{_opcode_names} |
| 31 | + {} |
| 32 | + }; |
| 33 | + |
| 34 | + std::stack<Context> m_contexts; |
| 35 | + std::ostream& m_out; |
| 36 | + |
| 37 | + void on_execution_start( |
| 38 | + evmc_revision rev, const evmc_message& msg, bytes_view code) noexcept override |
| 39 | + { |
| 40 | + m_contexts.emplace(msg.depth, code.data(), evmc_get_instruction_names_table(rev)); |
| 41 | + } |
| 42 | + |
| 43 | + void on_instruction_start(uint32_t pc) noexcept override |
| 44 | + { |
| 45 | + auto& ctx = m_contexts.top(); |
| 46 | + ++ctx.counts[ctx.code[pc]]; |
| 47 | + } |
| 48 | + |
| 49 | + void on_execution_end(const evmc_result& /*result*/) noexcept override |
| 50 | + { |
| 51 | + const auto& ctx = m_contexts.top(); |
| 52 | + const auto names = ctx.opcode_names; |
| 53 | + |
| 54 | + m_out << "--- # HISTOGRAM depth=" << ctx.depth << "\nopcode,count\n"; |
| 55 | + for (size_t i = 0; i < std::size(ctx.counts); ++i) |
| 56 | + { |
| 57 | + if (ctx.counts[i] != 0) |
| 58 | + m_out << get_name(names, static_cast<uint8_t>(i)) << ',' << ctx.counts[i] << '\n'; |
| 59 | + } |
| 60 | + |
| 61 | + m_contexts.pop(); |
| 62 | + } |
| 63 | + |
| 64 | +public: |
| 65 | + explicit HistogramTracer(std::ostream& out) noexcept : m_out{out} {} |
| 66 | +}; |
| 67 | +} // namespace |
| 68 | + |
| 69 | +std::unique_ptr<Tracer> create_histogram_tracer(std::ostream& out) |
| 70 | +{ |
| 71 | + return std::make_unique<HistogramTracer>(out); |
| 72 | +} |
| 73 | +} // namespace evmone |
0 commit comments