Start library: working singleton class schema

This commit is contained in:
Théophile Bastian 2018-03-28 15:33:36 +02:00
parent 37c54424a3
commit 3932ee09e6
3 changed files with 101 additions and 0 deletions

27
Makefile Normal file
View file

@ -0,0 +1,27 @@
LIB_DIR=lib
TARGET=$(LIB_DIR)/libdwarfinterpret.so
SRC=src/DwarfInterpret.cpp
INCLUDE_DIR=include
CXX=g++
CXXFLAGS=-Wall -Wextra -O2 --std=c++14
CXXLIBS=-ldwarfpp -ldwarf -lelf -lc++fileno
CXXINCLUDE=-I$(INCLUDE_DIR)
OBJS = $(SRC:.cpp=.o)
###############################################################################
all: $(TARGET)
$(TARGET): $(OBJS)
mkdir -p "$$(dirname "$@")"
$(CXX) $(CXXFLAGS) $(CXXLIBS) $(CXXINCLUDE) $^ -shared -o "$@"
%.o: %.cpp
$(CXX) $(CXXFLAGS) $(CXXINCLUDE) -fPIC -c "$<" -o "$@"
clean:
rm -f $(OBJS) $(TARGET)

View file

@ -0,0 +1,35 @@
#pragma once
#include <string>
#include <memory>
#include <dwarfpp/root.hpp>
class DwarfInterpret {
/** Singleton class holding a Dwarf interpret.
* Must be first instanciated with the path to the binary being run, with a
* call to `instanciate`, and can afterwards be accessed with calls to
* `acquire`.
*/
public:
class NotInstanciated: public std::exception {};
class AlreadyInstanciated: public std::exception {};
DwarfInterpret(DwarfInterpret const&) = delete;
void operator=(DwarfInterpret const&) = delete;
static DwarfInterpret& acquire();
static DwarfInterpret& instanciate(const std::string& elf_path);
private:
DwarfInterpret(const std::string& elf_path);
private: // members
static std::unique_ptr<DwarfInterpret> instance;
dwarf::core::root_die root_die;
int elf_machine;
friend class std::unique_ptr<DwarfInterpret>;
};

39
src/DwarfInterpret.cpp Normal file
View file

@ -0,0 +1,39 @@
#include <DwarfInterpret.hpp>
#include <fstream>
#include <fileno.hpp>
#include <dwarfpp/lib.hpp>
#include <dwarfpp/regs.hpp>
#include <dwarfpp/frame.hpp>
#include <dwarfpp/attr.hpp>
#include <dwarfpp/frame.hpp>
#include <dwarfpp/root.hpp>
#include <gelf.h>
DwarfInterpret::DwarfInterpret(const std::string& elf_path)
: root_die(fileno(std::ifstream(elf_path)))
{
//std::ifstream file_in(elf_path);
//root_die = dwarf::core::root_die(fileno(file_in));
// FIXME this ^ deserves some checks. But this looks tedious.
GElf_Ehdr ehdr;
GElf_Ehdr *ret = gelf_getehdr(root_die.get_elf(), &ehdr);
assert(ret != 0);
elf_machine = ehdr.e_machine;
}
DwarfInterpret& DwarfInterpret::acquire() {
if(DwarfInterpret::instance == nullptr)
throw NotInstanciated();
return *(DwarfInterpret::instance);
}
DwarfInterpret& DwarfInterpret::instanciate(const std::string& elf_path) {
if(DwarfInterpret::instance != nullptr)
throw AlreadyInstanciated();
DwarfInterpret::instance = std::unique_ptr<DwarfInterpret>(
new DwarfInterpret(elf_path));
return *(DwarfInterpret::instance);
}