Home /Modules/decompiler/output.cpp

output.cpp

decompiler/src/output.cpp · 288 line(s) · c

#include "sleela/decompiler/output.hpp"
#include <algorithm>
#include <cctype>
#include <iomanip>
#include <sstream>
#include <stdexcept>
#include <string>

namespace sleela::decompiler {
namespace {

// --- small formatting helpers ------------------------------------------------------------
std::string sanitize(std::string s) {
    for (char& c : s) if (!(std::isalnum(static_cast<unsigned char>(c)) || c == '_')) c = '_';
    if (s.empty() || std::isdigit(static_cast<unsigned char>(s.front()))) s = "_" + s;
    return s;
}
std::string hex0x(std::uint64_t v) { std::ostringstream s; s << "0x" << std::hex << v; return s.str(); }
std::string hexpad(std::uint64_t v, int w) { std::ostringstream s; s << std::hex << std::setw(w) << std::setfill('0') << v; return s.str(); }
std::string bytes_hex(const std::vector<std::uint8_t>& b, std::size_t maxn = 10) {
    std::ostringstream s; std::size_t n = std::min(b.size(), maxn);
    for (std::size_t i = 0; i < n; ++i) { if (i) s << ' '; s << hexpad(b[i], 2); }
    if (b.size() > maxn) s << " ..."; return s.str();
}
std::string guard_macro(const std::string& base) {
    std::string g = "SLECOMPILER_" + sanitize(base) + "_H";
    for (char& c : g) c = static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
    return g;
}
std::string arch_name(Architecture a) {
    switch (a) { case Architecture::X86: return "x86"; case Architecture::X86_64: return "x86-64";
        case Architecture::ARM: return "ARM (A32/Thumb)"; case Architecture::ARM64: return "AArch64 (ARM64)";
        default: return "unknown"; }
}
std::string format_name(Format f) {
    switch (f) { case Format::ELF: return "ELF"; case Format::PE: return "PE/COFF"; case Format::MachO: return "Mach-O";
        case Format::GNUArchive: return "GNU archive"; case Format::Raw: return "raw"; default: return "unknown"; }
}

// Confidence -> evidence word, so a reviewer can weigh each line.
const char* evidence_word(double c) {
    if (c >= 0.90) return "observed";
    if (c >= 0.75) return "decoded";
    if (c >= 0.40) return "inferred";
    return "unknown";
}

// A banner carried by every artifact we emit, establishing provenance up front.
// `top`/`bot` are the rule lines; `mid` is the per-line comment prefix (e.g. " *", "//").
void banner(std::ostream& out, const Artifact& a, const char* top, const char* mid,
            const char* bot, const char* title) {
    out << top << "\n"
        << mid << " " << title << "\n"
        << mid << "\n"
        << mid << " Generated by Slecompiler (MEARVK LLC). Evidence-derived reconstruction;\n"
        << mid << " NOT a guarantee of the original source. Recovered declarations preserve\n"
        << mid << " provenance and distinguish observed evidence from inference.\n"
        << mid << "\n"
        << mid << " input    : " << a.name() << "\n"
        << mid << " format   : " << format_name(a.format()) << "\n"
        << mid << " arch     : " << arch_name(a.architecture()) << "\n"
        << mid << " sha256   : " << a.sha256() << "\n"
        << bot << "\n\n";
}

// Render the per-function evidence block (instruction table + CFG note) as line comments.
// `lc` is the full line-comment lead (indent + comment marker) for the target language, so
// every emitted evidence line is itself a valid comment in that language.
void function_evidence(std::ostream& out, const std::string& lc, const Symbol& f,
                       const std::vector<Instruction>& ins, const DecompilationOptions& opt) {
    // Collect the instructions that belong to this function window (>= f.address).
    std::vector<const Instruction*> body;
    for (const auto& i : ins) if (i.address >= f.address) body.push_back(&i);
    std::sort(body.begin(), body.end(), [](const Instruction* x, const Instruction* y){ return x->address < y->address; });
    // Trim at the first return so the table stays tight around the function.
    std::size_t count = body.size();
    for (std::size_t k = 0; k < body.size(); ++k) { if (body[k]->is_return) { count = k + 1; break; } }
    if (opt.emit_cfg_summary) {
        std::size_t branches = 0, calls = 0, rets = 0;
        for (std::size_t k = 0; k < count; ++k) { branches += body[k]->is_branch; calls += body[k]->is_call; rets += body[k]->is_return; }
        out << lc << "control flow: " << count << " insn, " << branches << " branch, "
            << calls << " call, " << rets << " return\n";
    }
    if (opt.emit_instruction_evidence && count) {
        out << lc << "evidence (address | bytes | instruction | basis):\n";
        for (std::size_t k = 0; k < count && k < 64; ++k) {
            const auto& i = *body[k];
            std::ostringstream row;
            row << lc << "  " << hexpad(i.address, 8) << "  "
                << std::left << std::setw(23) << bytes_hex(i.bytes) << "  "
                << std::left << std::setw(28) << (i.text.empty() ? i.mnemonic : i.text) << "  "
                << evidence_word(i.provenance.confidence);
            out << row.str() << "\n";
        }
        if (count > 64) out << lc << "  ... (" << (count - 64) << " more)\n";
    }
}

// Find a lifted SLIR function matching an entry address.
const Function* lifted_for(const Module* mod, std::uint64_t address) {
    if (!mod) return nullptr;
    for (const auto& f : mod->functions) if (f.address == address) return &f;
    return nullptr;
}
// Render a function's lifted SLIR statements, indented by `ind`. Returns true if it wrote
// a body, false if there was nothing lifted (caller then emits the fallback note).
bool lifted_body(std::ostream& out, const std::string& ind, const Function* f,
                 const std::string& comment_prefix = "") {
    if (!f) return false;
    std::size_t stmts = 0;
    for (const auto& blk : f->blocks) for (const auto& o : blk.operations) if (!o.text.empty()) ++stmts;
    if (!stmts) return false;
    for (const auto& blk : f->blocks)
        for (const auto& o : blk.operations)
            if (!o.text.empty()) out << ind << comment_prefix << o.text << "\n";
    return true;
}

// --- C / C++ ------------------------------------------------------------------------------
std::string emit_c_like(const Artifact& a, const std::vector<Instruction>& ins,
                        const std::vector<Symbol>& funcs, const DecompilationOptions& opt, bool cpp,
                        const Module* mod = nullptr) {
    std::ostringstream out;
    banner(out, a, "/* ----------------------------------------------------------------------- */",
           " *", " */", cpp ? "Slecompiler reconstruction (C++)" : "Slecompiler reconstruction (C)");
    const std::string header = sanitize(opt.source_name) + (cpp ? ".hpp" : ".h");
    out << "#include \"" << header << "\"\n\n";
    if (cpp) out << "#include <cstdint>\n#include <cstddef>\n\nnamespace slecompiler {\n\n";
    else out << "#include <stdint.h>\n#include <stddef.h>\n\n";

    if (funcs.empty()) {
        out << "/**\n * @brief Analysis window with no recovered function boundary.\n"
            << " * @note  Instruction evidence is retained below for review.\n */\n";
        out << "void slecompiler_decompiled(void) {\n";
        function_evidence(out, "    // ", {"window", ins.empty() ? 0 : ins.front().address, false, {}}, ins, opt);
        out << "}\n";
    }
    for (const auto& f : funcs) {
        out << "/**\n";
        out << " * @brief Recovered native function `" << f.name << "`.\n";
        out << " * @note  Entry " << hex0x(f.address) << "; " << evidence_word(f.provenance.confidence) << " evidence.\n";
        out << " */\n";
        out << "void " << sanitize(f.name) << "(void) {\n";
        if (!lifted_body(out, "    ", lifted_for(mod, f.address)))
            out << "    /* Body not yet lifted to statements; see evidence below. */\n";
        out << "\n";
        function_evidence(out, "    // ", f, ins, opt);
        out << "}\n\n";
    }
    if (cpp) out << "} // namespace slecompiler\n";
    return out.str();
}

std::string emit_c_header(const Artifact& a, const std::vector<Symbol>& funcs,
                          const DecompilationOptions& opt, bool cpp) {
    std::ostringstream out;
    banner(out, a, "/* ----------------------------------------------------------------------- */",
           " *", " */", cpp ? "Slecompiler reconstruction header (C++)" : "Slecompiler reconstruction header (C)");
    const std::string g = guard_macro(opt.source_name);
    out << "#ifndef " << g << "\n#define " << g << "\n\n";
    if (cpp) out << "#include <cstdint>\n\nnamespace slecompiler {\n\n";
    else out << "#include <stdint.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n";
    if (funcs.empty()) out << "/* No function boundary was recovered for the selected window. */\n";
    for (const auto& f : funcs) {
        out << "/** Recovered native function `" << f.name << "` (entry " << hex0x(f.address)
            << ", " << evidence_word(f.provenance.confidence) << "). */\n";
        out << "void " << sanitize(f.name) << "(void);\n\n";
    }
    if (cpp) out << "} // namespace slecompiler\n";
    else out << "#ifdef __cplusplus\n}\n#endif\n";
    out << "\n#endif /* " << g << " */\n";
    return out.str();
}

// --- Java ---------------------------------------------------------------------------------
std::string emit_java(const Artifact& a, const std::vector<Instruction>& ins,
                      const std::vector<Symbol>& funcs, const DecompilationOptions& opt,
                      const Module* mod = nullptr) {
    std::ostringstream out;
    banner(out, a, "// ----------------------------------------------------------------------- //",
           "//", "// ----------------------------------------------------------------------- //",
           "Slecompiler reconstruction (Java)");
    const std::string cls = sanitize(opt.source_name);
    out << "public final class " << cls << " {\n";
    out << "    private " << cls << "() { /* static holder */ }\n\n";
    for (const auto& f : funcs) {
        out << "    /**\n";
        out << "     * Recovered native function {@code " << f.name << "}.\n";
        out << "     * <p>Entry " << hex0x(f.address) << "; " << evidence_word(f.provenance.confidence) << " evidence.\n";
        out << "     */\n";
        out << "    public static void " << sanitize(f.name) << "() {\n";
        if (!lifted_body(out, "        ", lifted_for(mod, f.address)))
            out << "        // Body not yet lifted to statements; see evidence below.\n";
        out << "\n";
        function_evidence(out, "        // ", f, ins, opt);
        out << "    }\n\n";
    }
    if (funcs.empty()) {
        out << "    public static void decompiled() {\n";
        function_evidence(out, "        // ", {"window", ins.empty() ? 0 : ins.front().address, false, {}}, ins, opt);
        out << "    }\n";
    }
    out << "}\n";
    return out.str();
}

// --- Sleela -------------------------------------------------------------------------------
std::string emit_sleela(const Artifact& a, const std::vector<Instruction>& ins,
                        const std::vector<Symbol>& funcs, const DecompilationOptions& opt,
                        const Module* mod = nullptr) {
    std::ostringstream out;
    banner(out, a, "< ----------------------------------------------------------------------- >",
           "<", "< ----------------------------------------------------------------------- >",
           "Slecompiler reconstruction (Sleela)");
    out << "module " << sanitize(opt.source_name) << " {\n";
    for (const auto& f : funcs) {
        out << "  << recovered native function " << f.name << " @ " << hex0x(f.address)
            << " (" << evidence_word(f.provenance.confidence) << ") >>\n";
        out << "  function " << sanitize(f.name) << "() {\n";
        // Lifted statements are shown as Sleela `<` annotations (the lift targets a neutral
        // pseudo-C form, not Sleela grammar), so the emitted module stays lexically valid.
        if (!lifted_body(out, "    < ", lifted_for(mod, f.address)))
            out << "    << body not yet lifted to statements; see evidence below >>\n";
        out << "\n";
        function_evidence(out, "    < ", f, ins, opt);
        out << "  }\n\n";
    }
    if (funcs.empty()) {
        out << "  function decompiled() {\n";
        function_evidence(out, "    < ", {"window", ins.empty() ? 0 : ins.front().address, false, {}}, ins, opt);
        out << "  }\n";
    }
    out << "}\n";
    return out.str();
}
} // namespace

std::string SourceEmitter::language_name(SourceLanguage l) {
    switch (l) { case SourceLanguage::Java: return "java"; case SourceLanguage::Sleela: return "sleela";
        case SourceLanguage::C: return "c"; case SourceLanguage::CPlusPlus: return "c++"; }
    return "unknown";
}
std::string SourceEmitter::extension(SourceLanguage l) {
    switch (l) { case SourceLanguage::Java: return ".java"; case SourceLanguage::Sleela: return ".sleela";
        case SourceLanguage::C: return ".c"; case SourceLanguage::CPlusPlus: return ".cpp"; }
    return ".txt";
}
std::string SourceEmitter::header_extension(SourceLanguage l) {
    switch (l) { case SourceLanguage::C: return ".h"; case SourceLanguage::CPlusPlus: return ".hpp";
        case SourceLanguage::Java: return ".java"; case SourceLanguage::Sleela: return ".sleela"; }
    return ".h";
}
std::string SourceEmitter::emit(const Artifact& a, const std::vector<Instruction>& ins,
                                const ControlFlowGraph& cfg, const std::vector<Symbol>& funcs,
                                const DecompilationOptions& options) {
    (void)cfg;
    switch (options.language) {
        case SourceLanguage::Java: return emit_java(a, ins, funcs, options);
        case SourceLanguage::Sleela: return emit_sleela(a, ins, funcs, options);
        case SourceLanguage::C: return emit_c_like(a, ins, funcs, options, false);
        case SourceLanguage::CPlusPlus: return emit_c_like(a, ins, funcs, options, true);
    }
    throw std::invalid_argument("unsupported source output language");
}
std::string SourceEmitter::emit(const Artifact& a, const std::vector<Instruction>& ins,
                                const ControlFlowGraph& cfg, const std::vector<Symbol>& funcs,
                                const Module& module, const DecompilationOptions& options) {
    (void)cfg;
    switch (options.language) {
        case SourceLanguage::Java: return emit_java(a, ins, funcs, options, &module);
        case SourceLanguage::Sleela: return emit_sleela(a, ins, funcs, options, &module);
        case SourceLanguage::C: return emit_c_like(a, ins, funcs, options, false, &module);
        case SourceLanguage::CPlusPlus: return emit_c_like(a, ins, funcs, options, true, &module);
    }
    throw std::invalid_argument("unsupported source output language");
}
std::string SourceEmitter::emit_header(const Artifact& a, const std::vector<Symbol>& funcs,
                                       const DecompilationOptions& options) {
    switch (options.language) {
        case SourceLanguage::C: return emit_c_header(a, funcs, options, false);
        case SourceLanguage::CPlusPlus: return emit_c_header(a, funcs, options, true);
        case SourceLanguage::Java: { std::vector<Instruction> none; return emit_java(a, none, funcs, options); }
        case SourceLanguage::Sleela: { std::vector<Instruction> none; return emit_sleela(a, none, funcs, options); }
    }
    throw std::invalid_argument("unsupported header output language");
}
} // namespace sleela::decompiler