midout.cpp 2.5 KB
Newer Older
J
jiakai 已提交
1 2
#include "midout.h"

3 4 5 6
// to avoid linking error for empty lib on some stupid platforms
void midout_empty() {
}

J
jiakai 已提交
7 8 9 10
#ifdef MIDOUT_PROFILING
#include <vector>
#include <unordered_set>
#include <algorithm>
J
jiakai 已提交
11
#include <mutex>
J
jiakai 已提交
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47

#include <cstdio>
#include <cstdlib>
#include <cstring>

#include <sys/types.h>
#include <unistd.h>

#ifdef __GNUG__
#include <cstdlib>
#include <memory>
#include <cxxabi.h>

std::string demangle(const char* name) {
    int status;

    std::unique_ptr<char, void(*)(void*)> res {
        abi::__cxa_demangle(name, NULL, NULL, &status),
        std::free
    };

    if (status) {
        fprintf(stderr, "midout: failed to demangle\n");
        abort();
    }

    return res.get();
}

#else
#error "unsupported compiler: can not demangle type name"
#endif

namespace {
    class UsedTypes {
        std::unordered_set<const char*> m_types;
J
jiakai 已提交
48
        std::mutex m_mtx;
J
jiakai 已提交
49 50 51 52

        public:

            void add(const char *type) {
J
jiakai 已提交
53
                std::lock_guard<std::mutex> guard{m_mtx};
J
jiakai 已提交
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
                m_types.insert(type);
            }

            ~UsedTypes() {
                auto output_fname = getenv("MIDOUT_OUTPUT");
                char output_fname_storage[256];
                if (!output_fname) {
                    output_fname = output_fname_storage;
                    snprintf(output_fname, sizeof(output_fname_storage),
                            "midout_trace.%d", static_cast<int>(getpid()));
                }
                FILE *fout = fopen(output_fname, "w");
                if (!fout) {
                    fprintf(stderr,
                            "midout: failed to open output file %s: %s\n",
                            output_fname, strerror(errno));
                }
J
jiakai 已提交
71
                fprintf(fout, "midout_trace v0\n");
J
jiakai 已提交
72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
                std::vector<std::string> sorted_types;
                sorted_types.reserve(m_types.size());
                for (auto &&i: m_types) {
                    sorted_types.emplace_back(demangle(i));
                }
                std::sort(sorted_types.begin(), sorted_types.end());
                for (auto &&i: sorted_types) {
                    fputs(i.c_str(), fout);
                    fputc('\n', fout);
                }
                fclose(fout);
                fprintf(stderr, "midout: %zu items written to %s\n",
                        sorted_types.size(), output_fname);
            }
    };
    UsedTypes g_used_types;
}

void midout::on_region_used(const std::type_info &type) {
    g_used_types.add(type.name());
}

#endif  // MIDOUT_PROFILING