CapstoneDisassembler.hpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. #pragma once
  2. #include <capstone/capstone.h>
  3. #include "ExceptionCapstone.hpp"
  4. #include "ResourceObject.hpp"
  5. struct CapstoneHandleTraits {
  6. using HandleType = csh;
  7. static inline const HandleType InvalidValue = 0;
  8. static inline void Releasor(HandleType Handle) {
  9. cs_close(&Handle);
  10. }
  11. };
  12. template<typename __Type>
  13. struct CapstoneMallocTraits {
  14. using HandleType = __Type*;
  15. static inline const HandleType InvalidValue = nullptr;
  16. static inline void Releasor(HandleType Handle) {
  17. cs_free(Handle, 1);
  18. }
  19. };
  20. class CapstoneDisassembler {
  21. friend class CapstoneEngine;
  22. public:
  23. struct Context {
  24. union {
  25. const uint8_t* ConstPtr;
  26. uint8_t* Ptr;
  27. } Opcode;
  28. size_t OpcodesSize;
  29. uint64_t Address;
  30. bool operator==(const Context& Other) const noexcept;
  31. bool operator!=(const Context& Other) const noexcept;
  32. };
  33. static inline Context InvalidContext = {};
  34. private:
  35. const CapstoneEngine& _EngineRef;
  36. Context _Context;
  37. ResourceObject<CapstoneMallocTraits<cs_insn>> _InsnObj;
  38. cs_insn* _InsnPtr;
  39. explicit CapstoneDisassembler(const CapstoneEngine& Engine);
  40. public:
  41. void SetContext(const uint8_t* Opcodes, size_t Size, uint64_t Address = 0) noexcept;
  42. void SetContext(const Context& Context) noexcept;
  43. const Context& GetContext() const noexcept;
  44. bool Next() noexcept;
  45. cs_insn* Instruction() const noexcept;
  46. Context InstructionContext() const noexcept;
  47. };
  48. class CapstoneEngine {
  49. private:
  50. ResourceObject<CapstoneHandleTraits> _EngineObj;
  51. public:
  52. CapstoneEngine(cs_arch ArchType, cs_mode Mode);
  53. operator csh() const noexcept;
  54. void Option(cs_opt_type Type, size_t Value);
  55. CapstoneDisassembler CreateDisassembler() const;
  56. };