1
0
mirror of synced 2025-02-17 18:59:21 +01:00

sys: Added clang-format file, formatted entire project

This commit is contained in:
WerWolv 2022-01-24 20:53:17 +01:00
parent a66fec489c
commit 0e08b0226b
168 changed files with 5178 additions and 4866 deletions

178
.clang-format Normal file
View File

@ -0,0 +1,178 @@
---
Language: Cpp
# BasedOnStyle: LLVM
AccessModifierOffset: -4
AlignAfterOpenBracket: Align
AlignArrayOfStructures: Left
AlignConsecutiveMacros: Consecutive
AlignConsecutiveAssignments: None
AlignConsecutiveBitFields: AcrossEmptyLinesAndComments
AlignConsecutiveDeclarations: None
AlignEscapedNewlines: Left
AlignOperands: Align
AlignTrailingComments: true
AllowAllArgumentsOnNextLine: true
AllowAllConstructorInitializersOnNextLine: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortEnumsOnASingleLine: false
AllowShortBlocksOnASingleLine: Always
AllowShortCaseLabelsOnASingleLine: false
AllowShortFunctionsOnASingleLine: All
AllowShortLambdasOnASingleLine: All
AllowShortIfStatementsOnASingleLine: AllIfsAndElse
AllowShortLoopsOnASingleLine: true
AlwaysBreakAfterDefinitionReturnType: None
AlwaysBreakAfterReturnType: None
AlwaysBreakBeforeMultilineStrings: false
AlwaysBreakTemplateDeclarations: Yes
AttributeMacros:
- __capability
BinPackArguments: false
BinPackParameters: false
BraceWrapping:
AfterCaseLabel: false
AfterClass: false
AfterControlStatement: Never
AfterEnum: false
AfterFunction: false
AfterNamespace: false
AfterObjCDeclaration: false
AfterStruct: false
AfterUnion: false
AfterExternBlock: false
BeforeCatch: false
BeforeElse: false
BeforeLambdaBody: false
BeforeWhile: false
IndentBraces: false
SplitEmptyFunction: false
SplitEmptyRecord: false
SplitEmptyNamespace: false
BreakBeforeBinaryOperators: None
BreakBeforeConceptDeclarations: false
BreakBeforeBraces: Attach
BreakBeforeInheritanceComma: false
BreakInheritanceList: AfterComma
BreakBeforeTernaryOperators: true
BreakConstructorInitializersBeforeComma: false
BreakConstructorInitializers: BeforeColon
BreakAfterJavaFieldAnnotations: false
BreakStringLiterals: false
ColumnLimit: 0
CommentPragmas: '^ IWYU pragma:'
CompactNamespaces: false
ConstructorInitializerAllOnOneLineOrOnePerLine: false
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Cpp11BracedListStyle: false
DeriveLineEnding: true
DerivePointerAlignment: false
DisableFormat: false
EmptyLineAfterAccessModifier: Never
EmptyLineBeforeAccessModifier: LogicalBlock
ExperimentalAutoDetectBinPacking: true
FixNamespaceComments: false
ForEachMacros:
- foreach
- Q_FOREACH
- BOOST_FOREACH
IfMacros:
- KJ_IF_MAYBE
IncludeBlocks: Regroup
IncludeCategories:
- Regex: '^"(llvm|llvm-c|clang|clang-c)/'
Priority: 2
SortPriority: 0
CaseSensitive: false
- Regex: '^(<|"(gtest|gmock|isl|json)/)'
Priority: 3
SortPriority: 0
CaseSensitive: false
- Regex: '.*'
Priority: 1
SortPriority: 0
CaseSensitive: false
IncludeIsMainRegex: '(Test)?$'
IncludeIsMainSourceRegex: ''
IndentAccessModifiers: false
IndentCaseLabels: false
IndentCaseBlocks: true
IndentGotoLabels: true
IndentPPDirectives: BeforeHash
IndentExternBlock: Indent
IndentRequires: false
IndentWidth: 4
IndentWrappedFunctionNames: false
InsertTrailingCommas: None
JavaScriptQuotes: Leave
JavaScriptWrapImports: true
KeepEmptyLinesAtTheStartOfBlocks: true
LambdaBodyIndentation: Signature
MacroBlockBegin: ''
MacroBlockEnd: ''
MaxEmptyLinesToKeep: 2
NamespaceIndentation: All
ObjCBinPackProtocolList: Auto
ObjCBlockIndentWidth: 4
ObjCBreakBeforeNestedBlockParam: true
ObjCSpaceAfterProperty: false
ObjCSpaceBeforeProtocolList: true
PenaltyBreakAssignment: 2
PenaltyBreakBeforeFirstCallParameter: 19
PenaltyBreakComment: 300
PenaltyBreakFirstLessLess: 120
PenaltyBreakString: 1000
PenaltyBreakTemplateDeclaration: 10
PenaltyExcessCharacter: 1000000
PenaltyReturnTypeOnItsOwnLine: 60
PenaltyIndentedWhitespace: 0
PointerAlignment: Right
PPIndentWidth: 4
ReferenceAlignment: Pointer
ReflowComments: true
ShortNamespaceLines: 5
SortIncludes: Never
SortJavaStaticImport: Before
SortUsingDeclarations: true
SpaceAfterCStyleCast: false
SpaceAfterLogicalNot: false
SpaceAfterTemplateKeyword: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeCaseColon: false
SpaceBeforeCpp11BracedList: true
SpaceBeforeCtorInitializerColon: true
SpaceBeforeInheritanceColon: true
SpaceBeforeParens: ControlStatements
SpaceAroundPointerQualifiers: Default
SpaceBeforeRangeBasedForLoopColon: true
SpaceInEmptyBlock: true
SpaceInEmptyParentheses: false
SpacesBeforeTrailingComments: 4
SpacesInAngles: Never
SpacesInConditionalStatement: false
SpacesInContainerLiterals: true
SpacesInCStyleCastParentheses: false
SpacesInLineCommentPrefix:
Minimum: 1
Maximum: -1
SpacesInParentheses: false
SpacesInSquareBrackets: false
SpaceBeforeSquareBrackets: false
BitFieldColonSpacing: Both
Standard: Latest
StatementAttributeLikeMacros:
- Q_EMIT
StatementMacros:
- Q_UNUSED
- QT_REQUIRE_VERSION
TabWidth: 4
UseCRLF: false
UseTab: Never
WhitespaceSensitiveMacros:
- STRINGIZE
- PP_STRINGIZE
- BOOST_PP_STRINGIZE
- NS_SWIFT_NAME
- CF_SWIFT_NAME
...

View File

@ -26,4 +26,3 @@ namespace hex {
}; };
} }

View File

@ -20,9 +20,15 @@ namespace hex {
class View; class View;
class LanguageDefinition; class LanguageDefinition;
namespace pl { class Evaluator; } namespace pl {
namespace dp { class Node; } class Evaluator;
namespace prv { class Provider; } }
namespace dp {
class Node;
}
namespace prv {
class Provider;
}
/* /*
The Content Registry is the heart of all features in ImHex that are in some way extendable by Plugins. The Content Registry is the heart of all features in ImHex that are in some way extendable by Plugins.
@ -33,7 +39,7 @@ namespace hex {
/* Settings Registry. Allows adding of new entries into the ImHex preferences window. */ /* Settings Registry. Allows adding of new entries into the ImHex preferences window. */
namespace Settings { namespace Settings {
using Callback = std::function<bool(const std::string&, nlohmann::json&)>; using Callback = std::function<bool(const std::string &, nlohmann::json &)>;
struct Entry { struct Entry {
std::string name; std::string name;
@ -48,15 +54,15 @@ namespace hex {
void write(const std::string &unlocalizedCategory, const std::string &unlocalizedName, i64 value); void write(const std::string &unlocalizedCategory, const std::string &unlocalizedName, i64 value);
void write(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::string &value); void write(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::string &value);
void write(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector<std::string>& value); void write(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector<std::string> &value);
i64 read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, i64 defaultValue); i64 read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, i64 defaultValue);
std::string read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::string &defaultValue); std::string read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::string &defaultValue);
std::vector<std::string> read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector<std::string>& defaultValue = { }); std::vector<std::string> read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector<std::string> &defaultValue = {});
std::map<std::string, std::vector<Entry>>& getEntries(); std::map<std::string, std::vector<Entry>> &getEntries();
nlohmann::json getSetting(const std::string &unlocalizedCategory, const std::string &unlocalizedName); nlohmann::json getSetting(const std::string &unlocalizedCategory, const std::string &unlocalizedName);
nlohmann::json& getSettingsData(); nlohmann::json &getSettingsData();
} }
/* Command Palette Command Registry. Allows adding of new commands to the command palette */ /* Command Palette Command Registry. Allows adding of new commands to the command palette */
@ -78,8 +84,9 @@ namespace hex {
ExecuteCallback executeCallback; ExecuteCallback executeCallback;
}; };
void add(Type type, const std::string &command, const std::string &unlocalizedDescription, const DisplayCallback &displayCallback, const ExecuteCallback &executeCallback = [](auto){}); void add(
std::vector<Entry>& getEntries(); Type type, const std::string &command, const std::string &unlocalizedDescription, const DisplayCallback &displayCallback, const ExecuteCallback &executeCallback = [](auto) {});
std::vector<Entry> &getEntries();
} }
/* Pattern Language Function Registry. Allows adding of new functions that may be used inside the pattern language */ /* Pattern Language Function Registry. Allows adding of new functions that may be used inside the pattern language */
@ -91,7 +98,7 @@ namespace hex {
constexpr static u32 NoParameters = 0x0000'0000; constexpr static u32 NoParameters = 0x0000'0000;
using Namespace = std::vector<std::string>; using Namespace = std::vector<std::string>;
using Callback = std::function<std::optional<hex::pl::Token::Literal>(hex::pl::Evaluator*, const std::vector<hex::pl::Token::Literal>&)>; using Callback = std::function<std::optional<hex::pl::Token::Literal>(hex::pl::Evaluator *, const std::vector<hex::pl::Token::Literal> &)>;
struct Function { struct Function {
u32 parameterCount; u32 parameterCount;
@ -101,7 +108,7 @@ namespace hex {
void addFunction(const Namespace &ns, const std::string &name, u32 parameterCount, const Callback &func); void addFunction(const Namespace &ns, const std::string &name, u32 parameterCount, const Callback &func);
void addDangerousFunction(const Namespace &ns, const std::string &name, u32 parameterCount, const Callback &func); void addDangerousFunction(const Namespace &ns, const std::string &name, u32 parameterCount, const Callback &func);
std::map<std::string, ContentRegistry::PatternLanguage::Function>& getFunctions(); std::map<std::string, ContentRegistry::PatternLanguage::Function> &getFunctions();
} }
/* View Registry. Allows adding of new windows */ /* View Registry. Allows adding of new windows */
@ -113,14 +120,14 @@ namespace hex {
} }
template<hex::derived_from<View> T, typename ... Args> template<hex::derived_from<View> T, typename... Args>
void add(Args&& ... args) { void add(Args &&...args) {
return impl::add(new T(std::forward<Args>(args)...)); return impl::add(new T(std::forward<Args>(args)...));
} }
std::map<std::string, View*>& getEntries(); std::map<std::string, View *> &getEntries();
View* getViewByName(const std::string &unlocalizedName); View *getViewByName(const std::string &unlocalizedName);
} }
@ -140,7 +147,7 @@ namespace hex {
void add(const std::string &unlocalizedName, const impl::Callback &function); void add(const std::string &unlocalizedName, const impl::Callback &function);
std::vector<impl::Entry>& getEntries(); std::vector<impl::Entry> &getEntries();
} }
/* Data Inspector Registry. Allows adding of new types to the data inspector */ /* Data Inspector Registry. Allows adding of new types to the data inspector */
@ -155,7 +162,7 @@ namespace hex {
namespace impl { namespace impl {
using DisplayFunction = std::function<std::string()>; using DisplayFunction = std::function<std::string()>;
using GeneratorFunction = std::function<DisplayFunction(const std::vector<u8>&, std::endian, NumberDisplayStyle)>; using GeneratorFunction = std::function<DisplayFunction(const std::vector<u8> &, std::endian, NumberDisplayStyle)>;
struct Entry { struct Entry {
std::string unlocalizedName; std::string unlocalizedName;
@ -167,7 +174,7 @@ namespace hex {
void add(const std::string &unlocalizedName, size_t requiredSize, impl::GeneratorFunction function); void add(const std::string &unlocalizedName, size_t requiredSize, impl::GeneratorFunction function);
std::vector<impl::Entry>& getEntries(); std::vector<impl::Entry> &getEntries();
} }
/* Data Processor Node Registry. Allows adding new processor nodes to be used in the data processor */ /* Data Processor Node Registry. Allows adding new processor nodes to be used in the data processor */
@ -175,7 +182,7 @@ namespace hex {
namespace impl { namespace impl {
using CreatorFunction = std::function<dp::Node*()>; using CreatorFunction = std::function<dp::Node *()>;
struct Entry { struct Entry {
std::string category; std::string category;
@ -188,20 +195,18 @@ namespace hex {
} }
template<hex::derived_from<dp::Node> T, typename ... Args> template<hex::derived_from<dp::Node> T, typename... Args>
void add(const std::string &unlocalizedCategory, const std::string &unlocalizedName, Args&& ... args) { void add(const std::string &unlocalizedCategory, const std::string &unlocalizedName, Args &&...args) {
add(impl::Entry{ unlocalizedCategory.c_str(), unlocalizedName.c_str(), add(impl::Entry { unlocalizedCategory.c_str(), unlocalizedName.c_str(), [=] {
[=]{
auto node = new T(std::forward<Args>(args)...); auto node = new T(std::forward<Args>(args)...);
node->setUnlocalizedName(unlocalizedName); node->setUnlocalizedName(unlocalizedName);
return node; return node;
} } });
});
} }
void addSeparator(); void addSeparator();
std::vector<impl::Entry>& getEntries(); std::vector<impl::Entry> &getEntries();
} }
@ -210,8 +215,8 @@ namespace hex {
void registerLanguage(const std::string &name, const std::string &languageCode); void registerLanguage(const std::string &name, const std::string &languageCode);
void addLocalizations(const std::string &languageCode, const LanguageDefinition &definition); void addLocalizations(const std::string &languageCode, const LanguageDefinition &definition);
std::map<std::string, std::string>& getLanguages(); std::map<std::string, std::string> &getLanguages();
std::map<std::string, std::vector<LanguageDefinition>>& getLanguageDefinitions(); std::map<std::string, std::vector<LanguageDefinition>> &getLanguageDefinitions();
} }
/* Interface Registry. Allows adding new items to various interfaces */ /* Interface Registry. Allows adding new items to various interfaces */
@ -255,15 +260,15 @@ namespace hex {
void addLayout(const std::string &unlocalizedName, const impl::LayoutFunction &function); void addLayout(const std::string &unlocalizedName, const impl::LayoutFunction &function);
std::multimap<u32, impl::MainMenuItem>& getMainMenuItems(); std::multimap<u32, impl::MainMenuItem> &getMainMenuItems();
std::multimap<u32, impl::MenuItem>& getMenuItems(); std::multimap<u32, impl::MenuItem> &getMenuItems();
std::vector<impl::DrawCallback>& getWelcomeScreenEntries(); std::vector<impl::DrawCallback> &getWelcomeScreenEntries();
std::vector<impl::DrawCallback>& getFooterItems(); std::vector<impl::DrawCallback> &getFooterItems();
std::vector<impl::DrawCallback>& getToolbarItems(); std::vector<impl::DrawCallback> &getToolbarItems();
std::vector<impl::SidebarItem>& getSidebarItems(); std::vector<impl::SidebarItem> &getSidebarItems();
std::vector<impl::Layout>& getLayouts(); std::vector<impl::Layout> &getLayouts();
} }
/* Provider Registry. Allows adding new data providers to be created from the UI */ /* Provider Registry. Allows adding new data providers to be created from the UI */
@ -277,7 +282,7 @@ namespace hex {
template<hex::derived_from<hex::prv::Provider> T> template<hex::derived_from<hex::prv::Provider> T>
void add(const std::string &unlocalizedName, bool addToList = true) { void add(const std::string &unlocalizedName, bool addToList = true) {
(void) EventManager::subscribe<RequestCreateProvider>([expectedName = unlocalizedName](const std::string &name, hex::prv::Provider **provider){ (void)EventManager::subscribe<RequestCreateProvider>([expectedName = unlocalizedName](const std::string &name, hex::prv::Provider **provider) {
if (name != expectedName) return; if (name != expectedName) return;
auto newProvider = new T(); auto newProvider = new T();
@ -292,7 +297,7 @@ namespace hex {
impl::addProviderName(unlocalizedName); impl::addProviderName(unlocalizedName);
} }
const std::vector<std::string>& getEntries(); const std::vector<std::string> &getEntries();
} }
@ -310,7 +315,7 @@ namespace hex {
void add(const std::string &unlocalizedName, const impl::Callback &callback); void add(const std::string &unlocalizedName, const impl::Callback &callback);
std::vector<impl::Entry>& getEntries(); std::vector<impl::Entry> &getEntries();
} }
@ -328,7 +333,7 @@ namespace hex {
void add(const std::vector<std::string> &extensions, const impl::Callback &callback); void add(const std::vector<std::string> &extensions, const impl::Callback &callback);
std::vector<impl::Entry>& getEntries(); std::vector<impl::Entry> &getEntries();
} }
}; };

View File

@ -30,7 +30,7 @@ namespace hex {
} }
} }
constexpr bool operator ==(const EventId &rhs) const = default; constexpr bool operator==(const EventId &rhs) const = default;
private: private:
u32 m_hash; u32 m_hash;
@ -40,11 +40,11 @@ namespace hex {
EventBase() noexcept = default; EventBase() noexcept = default;
}; };
template<typename ... Params> template<typename... Params>
struct Event : public EventBase { struct Event : public EventBase {
using Callback = std::function<void(Params...)>; using Callback = std::function<void(Params...)>;
explicit Event(Callback func) noexcept : m_func(std::move(func)) {} explicit Event(Callback func) noexcept : m_func(std::move(func)) { }
void operator()(Params... params) const noexcept { void operator()(Params... params) const noexcept {
this->m_func(params...); this->m_func(params...);
@ -56,7 +56,7 @@ namespace hex {
class EventManager { class EventManager {
public: public:
using EventList = std::list<std::pair<EventId, EventBase*>>; using EventList = std::list<std::pair<EventId, EventBase *>>;
template<typename E> template<typename E>
[[nodiscard]] static EventList::iterator subscribe(typename E::Callback function) { [[nodiscard]] static EventList::iterator subscribe(typename E::Callback function) {
@ -74,7 +74,7 @@ namespace hex {
template<typename E> template<typename E>
static void unsubscribe(void *token) noexcept { static void unsubscribe(void *token) noexcept {
auto iter = std::find_if(s_tokenStore.begin(), s_tokenStore.end(), [&](auto &item){ auto iter = std::find_if(s_tokenStore.begin(), s_tokenStore.end(), [&](auto &item) {
return item.first == token && item.second->first == E::id; return item.first == token && item.second->first == E::id;
}); });
@ -84,7 +84,7 @@ namespace hex {
} }
template<typename E> template<typename E>
static void post(auto&& ... args) noexcept { static void post(auto &&...args) noexcept {
for (const auto &[id, event] : s_events) { for (const auto &[id, event] : s_events) {
if (id == E::id) if (id == E::id)
(*reinterpret_cast<E *>(event))(std::forward<decltype(args)>(args)...); (*reinterpret_cast<E *>(event))(std::forward<decltype(args)>(args)...);
@ -92,25 +92,27 @@ namespace hex {
} }
private: private:
static std::map<void*, EventList::iterator> s_tokenStore; static std::map<void *, EventList::iterator> s_tokenStore;
static EventList s_events; static EventList s_events;
}; };
namespace pl { class PatternData; } namespace pl {
class PatternData;
}
/* Default Events */ /* Default Events */
EVENT_DEF(EventFileLoaded, fs::path); EVENT_DEF(EventFileLoaded, fs::path);
EVENT_DEF(EventFileUnloaded); EVENT_DEF(EventFileUnloaded);
EVENT_DEF(EventDataChanged); EVENT_DEF(EventDataChanged);
EVENT_DEF(EventPatternChanged, std::vector<pl::PatternData*>&); EVENT_DEF(EventPatternChanged, std::vector<pl::PatternData *> &);
EVENT_DEF(EventWindowClosing, GLFWwindow*); EVENT_DEF(EventWindowClosing, GLFWwindow *);
EVENT_DEF(EventRegionSelected, Region); EVENT_DEF(EventRegionSelected, Region);
EVENT_DEF(EventProjectFileStore); EVENT_DEF(EventProjectFileStore);
EVENT_DEF(EventProjectFileLoad); EVENT_DEF(EventProjectFileLoad);
EVENT_DEF(EventSettingsChanged); EVENT_DEF(EventSettingsChanged);
EVENT_DEF(EventAbnormalTermination, int); EVENT_DEF(EventAbnormalTermination, int);
EVENT_DEF(EventOSThemeChanged); EVENT_DEF(EventOSThemeChanged);
EVENT_DEF(EventProviderCreated, prv::Provider*); EVENT_DEF(EventProviderCreated, prv::Provider *);
EVENT_DEF(EventFrameBegin); EVENT_DEF(EventFrameBegin);
EVENT_DEF(EventFrameEnd); EVENT_DEF(EventFrameEnd);
@ -125,6 +127,6 @@ namespace hex {
EVENT_DEF(RequestOpenPopup, std::string); EVENT_DEF(RequestOpenPopup, std::string);
EVENT_DEF(RequestCreateProvider, std::string, hex::prv::Provider **); EVENT_DEF(RequestCreateProvider, std::string, hex::prv::Provider **);
EVENT_DEF(QuerySelection, Region&); EVENT_DEF(QuerySelection, Region &);
} }

View File

@ -12,7 +12,9 @@
namespace hex { namespace hex {
namespace prv { class Provider; } namespace prv {
class Provider;
}
namespace ImHexApi { namespace ImHexApi {
namespace Common { namespace Common {
@ -35,20 +37,20 @@ namespace hex {
void add(Region region, const std::string &name, const std::string &comment, u32 color = 0x00000000); void add(Region region, const std::string &name, const std::string &comment, u32 color = 0x00000000);
void add(u64 addr, size_t size, const std::string &name, const std::string &comment, u32 color = 0x00000000); void add(u64 addr, size_t size, const std::string &name, const std::string &comment, u32 color = 0x00000000);
std::list<Entry>& getEntries(); std::list<Entry> &getEntries();
}; };
namespace Provider { namespace Provider {
prv::Provider* get(); prv::Provider *get();
const std::vector<prv::Provider*>& getProviders(); const std::vector<prv::Provider *> &getProviders();
bool isValid(); bool isValid();
void add(prv::Provider *provider); void add(prv::Provider *provider);
template<hex::derived_from<prv::Provider> T> template<hex::derived_from<prv::Provider> T>
void add(auto&& ... args) { void add(auto &&...args) {
add(new T(std::forward<decltype(args)>(args)...)); add(new T(std::forward<decltype(args)>(args)...));
} }

View File

@ -131,9 +131,9 @@ namespace hex {
class Key { class Key {
public: public:
constexpr Key(Keys key) :m_key(static_cast<u32>(key)) { } constexpr Key(Keys key) : m_key(static_cast<u32>(key)) { }
auto operator<=>(const Key&) const = default; auto operator<=>(const Key &) const = default;
private: private:
u32 m_key; u32 m_key;
@ -141,7 +141,6 @@ namespace hex {
class Shortcut { class Shortcut {
public: public:
Shortcut operator+(const Key &other) const { Shortcut operator+(const Key &other) const {
Shortcut result = *this; Shortcut result = *this;
result.m_keys.insert(other); result.m_keys.insert(other);
@ -149,7 +148,7 @@ namespace hex {
return result; return result;
} }
Shortcut& operator+=(const Key &other) { Shortcut &operator+=(const Key &other) {
this->m_keys.insert(other); this->m_keys.insert(other);
return *this; return *this;
@ -162,6 +161,7 @@ namespace hex {
bool operator==(const Shortcut &other) const { bool operator==(const Shortcut &other) const {
return this->m_keys == other.m_keys; return this->m_keys == other.m_keys;
} }
private: private:
friend Shortcut operator+(const Key &lhs, const Key &rhs); friend Shortcut operator+(const Key &lhs, const Key &rhs);

View File

@ -8,21 +8,18 @@ namespace hex {
class Task { class Task {
public: public:
Task(const std::string& unlocalizedName, u64 maxValue); Task(const std::string &unlocalizedName, u64 maxValue);
~Task(); ~Task();
void setMaxValue(u64 maxValue); void setMaxValue(u64 maxValue);
void update(u64 currValue); void update(u64 currValue);
void finish(); void finish();
[[nodiscard]] [[nodiscard]] double getProgress() const;
double getProgress() const;
[[nodiscard]] [[nodiscard]] const std::string &getName() const;
const std::string& getName() const;
[[nodiscard]] [[nodiscard]] bool isPending() const;
bool isPending() const;
private: private:
std::string m_name; std::string m_name;

View File

@ -20,7 +20,8 @@ namespace hex::dp {
}; };
enum class IOType { enum class IOType {
In, Out In,
Out
}; };
Attribute(IOType ioType, Type type, std::string unlocalizedName); Attribute(IOType ioType, Type type, std::string unlocalizedName);
@ -31,21 +32,22 @@ namespace hex::dp {
[[nodiscard]] IOType getIOType() const { return this->m_ioType; } [[nodiscard]] IOType getIOType() const { return this->m_ioType; }
[[nodiscard]] Type getType() const { return this->m_type; } [[nodiscard]] Type getType() const { return this->m_type; }
[[nodiscard]] const std::string& getUnlocalizedName() const { return this->m_unlocalizedName; } [[nodiscard]] const std::string &getUnlocalizedName() const { return this->m_unlocalizedName; }
void addConnectedAttribute(u32 linkId, Attribute *to) { this->m_connectedAttributes.insert({ linkId, to }); } void addConnectedAttribute(u32 linkId, Attribute *to) { this->m_connectedAttributes.insert({ linkId, to }); }
void removeConnectedAttribute(u32 linkId) { this->m_connectedAttributes.erase(linkId); } void removeConnectedAttribute(u32 linkId) { this->m_connectedAttributes.erase(linkId); }
[[nodiscard]] std::map<u32, Attribute*>& getConnectedAttributes() { return this->m_connectedAttributes; } [[nodiscard]] std::map<u32, Attribute *> &getConnectedAttributes() { return this->m_connectedAttributes; }
[[nodiscard]] Node* getParentNode() { return this->m_parentNode; } [[nodiscard]] Node *getParentNode() { return this->m_parentNode; }
[[nodiscard]] std::optional<std::vector<u8>> &getOutputData() { return this->m_outputData; }
[[nodiscard]] std::optional<std::vector<u8>>& getOutputData() { return this->m_outputData; }
private: private:
u32 m_id; u32 m_id;
IOType m_ioType; IOType m_ioType;
Type m_type; Type m_type;
std::string m_unlocalizedName; std::string m_unlocalizedName;
std::map<u32, Attribute*> m_connectedAttributes; std::map<u32, Attribute *> m_connectedAttributes;
Node *m_parentNode = nullptr; Node *m_parentNode = nullptr;
std::optional<std::vector<u8>> m_outputData; std::optional<std::vector<u8>> m_outputData;

View File

@ -9,7 +9,10 @@
#include <nlohmann/json_fwd.hpp> #include <nlohmann/json_fwd.hpp>
namespace hex::prv { class Provider; class Overlay; } namespace hex::prv {
class Provider;
class Overlay;
}
namespace hex::dp { namespace hex::dp {
@ -22,11 +25,11 @@ namespace hex::dp {
[[nodiscard]] u32 getID() const { return this->m_id; } [[nodiscard]] u32 getID() const { return this->m_id; }
void setID(u32 id) { this->m_id = id; } void setID(u32 id) { this->m_id = id; }
[[nodiscard]] const std::string& getUnlocalizedName() const { return this->m_unlocalizedName; } [[nodiscard]] const std::string &getUnlocalizedName() const { return this->m_unlocalizedName; }
void setUnlocalizedName(const std::string &unlocalizedName) { this->m_unlocalizedName = unlocalizedName; } void setUnlocalizedName(const std::string &unlocalizedName) { this->m_unlocalizedName = unlocalizedName; }
[[nodiscard]] const std::string& getUnlocalizedTitle() const { return this->m_unlocalizedTitle; } [[nodiscard]] const std::string &getUnlocalizedTitle() const { return this->m_unlocalizedTitle; }
[[nodiscard]] std::vector<Attribute>& getAttributes() { return this->m_attributes; } [[nodiscard]] std::vector<Attribute> &getAttributes() { return this->m_attributes; }
void setCurrentOverlay(prv::Overlay *overlay) { void setCurrentOverlay(prv::Overlay *overlay) {
this->m_overlay = overlay; this->m_overlay = overlay;
@ -38,7 +41,7 @@ namespace hex::dp {
virtual void store(nlohmann::json &j) { } virtual void store(nlohmann::json &j) { }
virtual void load(nlohmann::json &j) { } virtual void load(nlohmann::json &j) { }
using NodeError = std::pair<Node*, std::string>; using NodeError = std::pair<Node *, std::string>;
void resetOutputData() { void resetOutputData() {
for (auto &attribute : this->m_attributes) for (auto &attribute : this->m_attributes)
@ -56,7 +59,7 @@ namespace hex::dp {
std::set<u32> m_processedInputs; std::set<u32> m_processedInputs;
prv::Overlay *m_overlay = nullptr; prv::Overlay *m_overlay = nullptr;
Attribute* getConnectedInputAttribute(u32 index) { Attribute *getConnectedInputAttribute(u32 index) {
if (index >= this->getAttributes().size()) if (index >= this->getAttributes().size())
throw std::runtime_error("Attribute index out of bounds!"); throw std::runtime_error("Attribute index out of bounds!");
@ -75,7 +78,6 @@ namespace hex::dp {
} }
protected: protected:
[[noreturn]] void throwNodeError(const std::string &message) { [[noreturn]] void throwNodeError(const std::string &message) {
throw NodeError(this, message); throw NodeError(this, message);
} }
@ -89,7 +91,6 @@ namespace hex::dp {
void setFloatOnOutput(u32 index, float floatingPoint); void setFloatOnOutput(u32 index, float floatingPoint);
void setOverlayData(u64 address, const std::vector<u8> &data); void setOverlayData(u64 address, const std::vector<u8> &data);
}; };
} }

View File

@ -113,21 +113,21 @@ namespace hex {
} }
#if defined(_LIBCPP_VERSION) && _LIBCPP_VERSION <= 12000 #if defined(_LIBCPP_VERSION) && _LIBCPP_VERSION <= 12000
#if __has_include(<concepts>) #if __has_include(<concepts>)
// Make sure we break when derived_from is implemented in libc++. Then we can fix a compatibility version above // Make sure we break when derived_from is implemented in libc++. Then we can fix a compatibility version above
#include <concepts> #include <concepts>
#endif #endif
// libcxx 12 still doesn't have many default concepts implemented, as a result we need to define it ourself using clang built-ins. // libcxx 12 still doesn't have many default concepts implemented, as a result we need to define it ourself using clang built-ins.
// [concept.derived] (patch from https://reviews.llvm.org/D74292) // [concept.derived] (patch from https://reviews.llvm.org/D74292)
namespace hex { namespace hex {
template<class _Dp, class _Bp> template<class _Dp, class _Bp>
concept derived_from = concept derived_from =
__is_base_of(_Bp, _Dp) && __is_convertible_to(const volatile _Dp*, const volatile _Bp*); __is_base_of(_Bp, _Dp) && __is_convertible_to(const volatile _Dp *, const volatile _Bp *);
} }
#else #else
// Assume supported // Assume supported
#include <concepts> #include <concepts>
namespace hex { namespace hex {
using std::derived_from; using std::derived_from;
} }
@ -153,10 +153,9 @@ namespace hex {
namespace hex { namespace hex {
template<typename T> template<typename T>
struct always_false : std::false_type {}; struct always_false : std::false_type { };
template<typename T, size_t Size> template<typename T, size_t Size>
concept has_size = sizeof(T) == Size; concept has_size = sizeof(T) == Size;
} }

View File

@ -7,23 +7,25 @@
#include <string> #include <string>
#include <vector> #include <vector>
namespace hex::prv { class Provider; } namespace hex::prv {
class Provider;
}
namespace hex::crypt { namespace hex::crypt {
void initialize(); void initialize();
void exit(); void exit();
u16 crc8(prv::Provider* &data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut); u16 crc8(prv::Provider *&data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut);
u16 crc16(prv::Provider* &data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut); u16 crc16(prv::Provider *&data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut);
u32 crc32(prv::Provider* &data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut); u32 crc32(prv::Provider *&data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut);
std::array<u8, 16> md5(prv::Provider* &data, u64 offset, size_t size); std::array<u8, 16> md5(prv::Provider *&data, u64 offset, size_t size);
std::array<u8, 20> sha1(prv::Provider* &data, u64 offset, size_t size); std::array<u8, 20> sha1(prv::Provider *&data, u64 offset, size_t size);
std::array<u8, 28> sha224(prv::Provider* &data, u64 offset, size_t size); std::array<u8, 28> sha224(prv::Provider *&data, u64 offset, size_t size);
std::array<u8, 32> sha256(prv::Provider* &data, u64 offset, size_t size); std::array<u8, 32> sha256(prv::Provider *&data, u64 offset, size_t size);
std::array<u8, 48> sha384(prv::Provider* &data, u64 offset, size_t size); std::array<u8, 48> sha384(prv::Provider *&data, u64 offset, size_t size);
std::array<u8, 64> sha512(prv::Provider* &data, u64 offset, size_t size); std::array<u8, 64> sha512(prv::Provider *&data, u64 offset, size_t size);
std::array<u8, 16> md5(const std::vector<u8> &data); std::array<u8, 16> md5(const std::vector<u8> &data);
std::array<u8, 20> sha1(const std::vector<u8> &data); std::array<u8, 20> sha1(const std::vector<u8> &data);

View File

@ -1,9 +1,9 @@
#pragma once #pragma once
#if __has_include(<capstone/capstone.h>) #if __has_include(<capstone/capstone.h>)
#include <capstone/capstone.h> #include <capstone/capstone.h>
#else #else
#include <capstone.h> #include <capstone.h>
#endif #endif
#include <hex.hpp> #include <hex.hpp>
@ -41,7 +41,7 @@ namespace hex {
return cs_support(toCapstoneArchictecture(architecture)); return cs_support(toCapstoneArchictecture(architecture));
} }
constexpr static const char * const ArchitectureNames[] = { "ARM32", "ARM64", "MIPS", "x86", "PowerPC", "Sparc", "SystemZ", "XCore", "68K", "TMS320C64x", "680X", "Ethereum", "MOS65XX", "WebAssembly", "Berkeley Packet Filter", "RISC-V" }; constexpr static const char *const ArchitectureNames[] = { "ARM32", "ARM64", "MIPS", "x86", "PowerPC", "Sparc", "SystemZ", "XCore", "68K", "TMS320C64x", "680X", "Ethereum", "MOS65XX", "WebAssembly", "Berkeley Packet Filter", "RISC-V" };
static inline i32 getArchitectureSupportedCount() { static inline i32 getArchitectureSupportedCount() {
static i32 supportedCount = -1; static i32 supportedCount = -1;

View File

@ -28,12 +28,12 @@ namespace hex {
explicit File(const fs::path &path, Mode mode) noexcept; explicit File(const fs::path &path, Mode mode) noexcept;
File() noexcept; File() noexcept;
File(const File&) = delete; File(const File &) = delete;
File(File &&other) noexcept; File(File &&other) noexcept;
~File(); ~File();
File& operator=(File &&other) noexcept; File &operator=(File &&other) noexcept;
[[nodiscard]] bool isValid() const { return this->m_file != nullptr; } [[nodiscard]] bool isValid() const { return this->m_file != nullptr; }
@ -56,7 +56,7 @@ namespace hex {
void remove(); void remove();
auto getHandle() { return this->m_file; } auto getHandle() { return this->m_file; }
const fs::path& getPath() { return this->m_path; } const fs::path &getPath() { return this->m_path; }
private: private:
FILE *m_file; FILE *m_file;

View File

@ -6,13 +6,13 @@
namespace hex { namespace hex {
template<typename ... Args> template<typename... Args>
inline std::string format(std::string_view format, Args ... args) { inline std::string format(std::string_view format, Args... args) {
return fmt::format(fmt::runtime(format), args...); return fmt::format(fmt::runtime(format), args...);
} }
template<typename ... Args> template<typename... Args>
inline void print(std::string_view format, Args ... args) { inline void print(std::string_view format, Args... args) {
fmt::print(fmt::runtime(format), args...); fmt::print(fmt::runtime(format), args...);
} }

View File

@ -11,7 +11,7 @@ namespace hex {
public: public:
LanguageDefinition(std::initializer_list<std::pair<std::string, std::string>> entries); LanguageDefinition(std::initializer_list<std::pair<std::string, std::string>> entries);
const std::map<std::string, std::string>& getEntries() const; const std::map<std::string, std::string> &getEntries() const;
private: private:
std::map<std::string, std::string> m_entries; std::map<std::string, std::string> m_entries;
@ -25,15 +25,15 @@ namespace hex {
operator std::string() const; operator std::string() const;
operator std::string_view() const; operator std::string_view() const;
operator const char*() const; operator const char *() const;
[[nodiscard]] const std::string& get() const; [[nodiscard]] const std::string &get() const;
static void loadLanguage(const std::string &language); static void loadLanguage(const std::string &language);
static const std::map<std::string, std::string>& getSupportedLanguages(); static const std::map<std::string, std::string> &getSupportedLanguages();
static void setFallbackLanguage(const std::string &language); static void setFallbackLanguage(const std::string &language);
static const std::string& getFallbackLanguage(); static const std::string &getFallbackLanguage();
private: private:
std::string m_unlocalizedString; std::string m_unlocalizedString;
@ -58,5 +58,4 @@ namespace hex {
} }
} }

View File

@ -4,20 +4,20 @@ namespace hex::literals {
/* Byte literals */ /* Byte literals */
constexpr static inline unsigned long long operator ""_Bytes(unsigned long long bytes) noexcept { constexpr static inline unsigned long long operator""_Bytes(unsigned long long bytes) noexcept {
return bytes; return bytes;
} }
constexpr static inline unsigned long long operator ""_KiB(unsigned long long kiB) noexcept { constexpr static inline unsigned long long operator""_KiB(unsigned long long kiB) noexcept {
return operator ""_Bytes(kiB * 1024); return operator""_Bytes(kiB * 1024);
} }
constexpr static inline unsigned long long operator ""_MiB(unsigned long long MiB) noexcept { constexpr static inline unsigned long long operator""_MiB(unsigned long long MiB) noexcept {
return operator ""_KiB(MiB * 1024); return operator""_KiB(MiB * 1024);
} }
constexpr static inline unsigned long long operator ""_GiB(unsigned long long GiB) noexcept { constexpr static inline unsigned long long operator""_GiB(unsigned long long GiB) noexcept {
return operator ""_MiB(GiB * 1024); return operator""_MiB(GiB * 1024);
} }
} }

View File

@ -10,7 +10,9 @@ typedef struct _object PyObject;
namespace hex { namespace hex {
namespace prv { class Provider; } namespace prv {
class Provider;
}
class LoaderScript { class LoaderScript {
public: public:
@ -19,17 +21,18 @@ namespace hex {
static bool processFile(const fs::path &scriptPath); static bool processFile(const fs::path &scriptPath);
static void setFilePath(const fs::path &filePath) { LoaderScript::s_filePath = filePath; } static void setFilePath(const fs::path &filePath) { LoaderScript::s_filePath = filePath; }
static void setDataProvider(prv::Provider* provider) { LoaderScript::s_dataProvider = provider; } static void setDataProvider(prv::Provider *provider) { LoaderScript::s_dataProvider = provider; }
private: private:
static inline fs::path s_filePath; static inline fs::path s_filePath;
static inline prv::Provider* s_dataProvider; static inline prv::Provider *s_dataProvider;
static PyObject* Py_getFilePath(PyObject *self, PyObject *args); static PyObject *Py_getFilePath(PyObject *self, PyObject *args);
static PyObject* Py_addPatch(PyObject *self, PyObject *args); static PyObject *Py_addPatch(PyObject *self, PyObject *args);
static PyObject* Py_addBookmark(PyObject *self, PyObject *args); static PyObject *Py_addBookmark(PyObject *self, PyObject *args);
static PyObject* Py_addStruct(PyObject *self, PyObject *args); static PyObject *Py_addStruct(PyObject *self, PyObject *args);
static PyObject* Py_addUnion(PyObject *self, PyObject *args); static PyObject *Py_addUnion(PyObject *self, PyObject *args);
}; };
} }

View File

@ -8,46 +8,46 @@ namespace hex::log {
FILE *getDestination(); FILE *getDestination();
bool isRedirected(); bool isRedirected();
template <typename... T> template<typename... T>
void print(fmt::format_string<T...> fmt, T&&... args) { void print(fmt::format_string<T...> fmt, T &&...args) {
fmt::print(getDestination(), fmt, args...); fmt::print(getDestination(), fmt, args...);
} }
template <typename S, typename... Args> template<typename S, typename... Args>
void print(const fmt::text_style& ts, const S& fmt, const Args&... args) { void print(const fmt::text_style &ts, const S &fmt, const Args &...args) {
if (isRedirected()) if (isRedirected())
fmt::print(getDestination(), fmt::runtime(fmt), args...); fmt::print(getDestination(), fmt::runtime(fmt), args...);
else else
fmt::print(getDestination(), ts, fmt, args...); fmt::print(getDestination(), ts, fmt, args...);
} }
void debug(const std::string &fmt, auto ... args) { void debug(const std::string &fmt, auto... args) {
#if defined(DEBUG) #if defined(DEBUG)
log::print(fg(fmt::color::green_yellow) | fmt::emphasis::bold, "[DEBUG] "); log::print(fg(fmt::color::green_yellow) | fmt::emphasis::bold, "[DEBUG] ");
log::print(fmt::runtime(fmt), args...); log::print(fmt::runtime(fmt), args...);
log::print("\n"); log::print("\n");
#endif #endif
} }
void info(const std::string &fmt, auto ... args) { void info(const std::string &fmt, auto... args) {
log::print(fg(fmt::color::cadet_blue) | fmt::emphasis::bold, "[INFO] "); log::print(fg(fmt::color::cadet_blue) | fmt::emphasis::bold, "[INFO] ");
log::print(fmt::runtime(fmt), args...); log::print(fmt::runtime(fmt), args...);
log::print("\n"); log::print("\n");
} }
void warn(const std::string &fmt, auto ... args) { void warn(const std::string &fmt, auto... args) {
log::print(fg(fmt::color::orange) | fmt::emphasis::bold, "[WARN] "); log::print(fg(fmt::color::orange) | fmt::emphasis::bold, "[WARN] ");
log::print(fmt::runtime(fmt), args...); log::print(fmt::runtime(fmt), args...);
log::print("\n"); log::print("\n");
} }
void error(const std::string &fmt, auto ... args) { void error(const std::string &fmt, auto... args) {
log::print(fg(fmt::color::red) | fmt::emphasis::bold, "[ERROR] "); log::print(fg(fmt::color::red) | fmt::emphasis::bold, "[ERROR] ");
log::print(fmt::runtime(fmt), args...); log::print(fmt::runtime(fmt), args...);
log::print("\n"); log::print("\n");
} }
void fatal(const std::string &fmt, auto ... args) { void fatal(const std::string &fmt, auto... args) {
log::print(fg(fmt::color::purple) | fmt::emphasis::bold, "[FATAL] "); log::print(fg(fmt::color::purple) | fmt::emphasis::bold, "[FATAL] ");
log::print(fmt::runtime(fmt), args...); log::print(fmt::runtime(fmt), args...);
log::print("\n"); log::print("\n");

View File

@ -7,7 +7,9 @@
#include <string> #include <string>
#include <vector> #include <vector>
namespace hex::prv { class Provider; } namespace hex::prv {
class Provider;
}
namespace hex::magic { namespace hex::magic {

View File

@ -41,19 +41,18 @@ namespace hex {
std::future<Response<std::string>> uploadFile(const std::string &url, const fs::path &filePath, u32 timeout = 2000); std::future<Response<std::string>> uploadFile(const std::string &url, const fs::path &filePath, u32 timeout = 2000);
std::future<Response<void>> downloadFile(const std::string &url, const fs::path &filePath, u32 timeout = 2000); std::future<Response<void>> downloadFile(const std::string &url, const fs::path &filePath, u32 timeout = 2000);
[[nodiscard]] [[nodiscard]] std::string encode(const std::string &input);
std::string encode(const std::string &input);
[[nodiscard]] [[nodiscard]] float getProgress() const { return this->m_progress; }
float getProgress() const { return this->m_progress; }
void cancel() { this->m_shouldCancel = true; } void cancel() { this->m_shouldCancel = true; }
private: private:
void setCommonSettings(std::string &response, const std::string &url, u32 timeout = 2000, const std::map<std::string, std::string> &extraHeaders = { }, const std::string &body = { }); void setCommonSettings(std::string &response, const std::string &url, u32 timeout = 2000, const std::map<std::string, std::string> &extraHeaders = {}, const std::string &body = {});
std::optional<i32> execute(); std::optional<i32> execute();
friend int progressCallback(void *contents, curl_off_t dlTotal, curl_off_t dlNow, curl_off_t ulTotal, curl_off_t ulNow); friend int progressCallback(void *contents, curl_off_t dlTotal, curl_off_t dlNow, curl_off_t ulTotal, curl_off_t ulNow);
private: private:
CURL *m_ctx; CURL *m_ctx;
curl_slist *m_headers = nullptr; curl_slist *m_headers = nullptr;

View File

@ -3,8 +3,8 @@
#if defined(OS_MACOS) #if defined(OS_MACOS)
#include <hex/helpers/paths.hpp> #include <hex/helpers/paths.hpp>
namespace hex { namespace hex {
std::string getMacExecutableDirectoryPath(); std::string getMacExecutableDirectoryPath();
std::string getMacApplicationSupportDirectoryPath(); std::string getMacApplicationSupportDirectoryPath();
} }
#endif #endif

View File

@ -17,7 +17,7 @@ namespace hex {
ProjectFile() = delete; ProjectFile() = delete;
static bool load(const fs::path &filePath); static bool load(const fs::path &filePath);
static bool store(fs::path filePath = { }); static bool store(fs::path filePath = {});
[[nodiscard]] static bool hasUnsavedChanges() { [[nodiscard]] static bool hasUnsavedChanges() {
return ProjectFile::s_hasUnsavedChanged; return ProjectFile::s_hasUnsavedChanged;
@ -32,7 +32,7 @@ namespace hex {
EventManager::post<RequestChangeWindowTitle>(fs::path(getFilePath()).filename().string()); EventManager::post<RequestChangeWindowTitle>(fs::path(getFilePath()).filename().string());
} }
[[nodiscard]] static const fs::path& getProjectFilePath() { [[nodiscard]] static const fs::path &getProjectFilePath() {
return ProjectFile::s_currProjectFilePath; return ProjectFile::s_currProjectFilePath;
} }
@ -41,7 +41,7 @@ namespace hex {
} }
[[nodiscard]] static const fs::path& getFilePath() { [[nodiscard]] static const fs::path &getFilePath() {
return ProjectFile::s_filePath; return ProjectFile::s_filePath;
} }
@ -52,7 +52,7 @@ namespace hex {
} }
[[nodiscard]] static const std::string& getPattern() { [[nodiscard]] static const std::string &getPattern() {
return ProjectFile::s_pattern; return ProjectFile::s_pattern;
} }
@ -62,7 +62,7 @@ namespace hex {
} }
[[nodiscard]] static const Patches& getPatches() { [[nodiscard]] static const Patches &getPatches() {
return ProjectFile::s_patches; return ProjectFile::s_patches;
} }
@ -72,7 +72,7 @@ namespace hex {
} }
[[nodiscard]] static const std::list<ImHexApi::Bookmarks::Entry>& getBookmarks() { [[nodiscard]] static const std::list<ImHexApi::Bookmarks::Entry> &getBookmarks() {
return ProjectFile::s_bookmarks; return ProjectFile::s_bookmarks;
} }
@ -82,7 +82,7 @@ namespace hex {
} }
[[nodiscard]] static const std::string& getDataProcessorContent() { [[nodiscard]] static const std::string &getDataProcessorContent() {
return ProjectFile::s_dataProcessorContent; return ProjectFile::s_dataProcessorContent;
} }

View File

@ -17,7 +17,9 @@
#include <nlohmann/json_fwd.hpp> #include <nlohmann/json_fwd.hpp>
namespace hex { class SharedData; } namespace hex {
class SharedData;
}
namespace hex::plugin::internal { namespace hex::plugin::internal {
void initializePlugin(SharedData &sharedData); void initializePlugin(SharedData &sharedData);
@ -25,23 +27,30 @@ namespace hex::plugin::internal {
namespace hex { namespace hex {
namespace prv { class Provider; } namespace prv {
namespace dp { class Node; } class Provider;
namespace pl { class PatternData; } }
namespace dp {
class Node;
}
namespace pl {
class PatternData;
}
class View; class View;
class SharedData { class SharedData {
SharedData() = default; SharedData() = default;
public: public:
SharedData(const SharedData&) = delete; SharedData(const SharedData &) = delete;
SharedData(SharedData&&) = delete; SharedData(SharedData &&) = delete;
friend class Window; friend class Window;
template<typename T> template<typename T>
static T& getVariable(std::string variableName) { static T &getVariable(std::string variableName) {
return std::any_cast<T&>(SharedData::sharedVariables[variableName]); return std::any_cast<T &>(SharedData::sharedVariables[variableName]);
} }
template<typename T> template<typename T>
@ -56,20 +65,20 @@ namespace hex {
public: public:
static std::vector<std::function<void()>> deferredCalls; static std::vector<std::function<void()>> deferredCalls;
static std::vector<prv::Provider*> providers; static std::vector<prv::Provider *> providers;
static u32 currentProvider; static u32 currentProvider;
static std::map<std::string, std::vector<ContentRegistry::Settings::Entry>> settingsEntries; static std::map<std::string, std::vector<ContentRegistry::Settings::Entry>> settingsEntries;
static nlohmann::json settingsJson; static nlohmann::json settingsJson;
static std::vector<ContentRegistry::CommandPaletteCommands::Entry> commandPaletteCommands; static std::vector<ContentRegistry::CommandPaletteCommands::Entry> commandPaletteCommands;
static std::map<std::string, ContentRegistry::PatternLanguage::Function> patternLanguageFunctions; static std::map<std::string, ContentRegistry::PatternLanguage::Function> patternLanguageFunctions;
static std::map<std::string, View*> views; static std::map<std::string, View *> views;
static std::vector<ContentRegistry::Tools::impl::Entry> toolsEntries; static std::vector<ContentRegistry::Tools::impl::Entry> toolsEntries;
static std::vector<ContentRegistry::DataInspector::impl::Entry> dataInspectorEntries; static std::vector<ContentRegistry::DataInspector::impl::Entry> dataInspectorEntries;
static u32 patternPaletteOffset; static u32 patternPaletteOffset;
static std::string popupMessage; static std::string popupMessage;
static std::list<ImHexApi::Bookmarks::Entry> bookmarkEntries; static std::list<ImHexApi::Bookmarks::Entry> bookmarkEntries;
static std::vector<pl::PatternData*> patternData; static std::vector<pl::PatternData *> patternData;
static u32 selectableFileIndex; static u32 selectableFileIndex;
static std::vector<fs::path> selectableFiles; static std::vector<fs::path> selectableFiles;
@ -93,7 +102,7 @@ namespace hex {
static std::map<Shortcut, std::function<void()>> globalShortcuts; static std::map<Shortcut, std::function<void()>> globalShortcuts;
static std::mutex tasksMutex; static std::mutex tasksMutex;
static std::list<Task*> runningTasks; static std::list<Task *> runningTasks;
static std::vector<std::string> providerNames; static std::vector<std::string> providerNames;

View File

@ -25,7 +25,7 @@ namespace hex {
class Socket { class Socket {
public: public:
Socket() = default; Socket() = default;
Socket(const Socket&) = delete; Socket(const Socket &) = delete;
Socket(Socket &&other); Socket(Socket &&other);
Socket(const std::string &address, u16 port); Socket(const std::string &address, u16 port);
@ -34,8 +34,7 @@ namespace hex {
void connect(const std::string &address, u16 port); void connect(const std::string &address, u16 port);
void disconnect(); void disconnect();
[[nodiscard]] [[nodiscard]] bool isConnected() const;
bool isConnected() const;
std::string readString(size_t size = 0x1000) const; std::string readString(size_t size = 0x1000) const;
std::vector<u8> readBytes(size_t size = 0x1000) const; std::vector<u8> readBytes(size_t size = 0x1000) const;
@ -45,11 +44,11 @@ namespace hex {
private: private:
bool m_connected = false; bool m_connected = false;
#if defined(OS_WINDOWS) #if defined(OS_WINDOWS)
SOCKET m_socket = SOCKET_NONE; SOCKET m_socket = SOCKET_NONE;
#else #else
int m_socket = SOCKET_NONE; int m_socket = SOCKET_NONE;
#endif #endif
}; };
} }

View File

@ -20,7 +20,7 @@
#include <nfd.hpp> #include <nfd.hpp>
#define TOKEN_CONCAT_IMPL(x, y) x ## y #define TOKEN_CONCAT_IMPL(x, y) x##y
#define TOKEN_CONCAT(x, y) TOKEN_CONCAT_IMPL(x, y) #define TOKEN_CONCAT(x, y) TOKEN_CONCAT_IMPL(x, y)
#define ANONYMOUS_VARIABLE(prefix) TOKEN_CONCAT(prefix, __COUNTER__) #define ANONYMOUS_VARIABLE(prefix) TOKEN_CONCAT(prefix, __COUNTER__)
@ -50,7 +50,7 @@ namespace hex {
[[nodiscard]] inline u64 extract(u32 from, u32 to, const std::vector<u8> &bytes) { [[nodiscard]] inline u64 extract(u32 from, u32 to, const std::vector<u8> &bytes) {
u8 index = 0; u8 index = 0;
while(from > 32 && to > 32) { while (from > 32 && to > 32) {
if (from - 8 < 0 || to - 8 < 0) if (from - 8 < 0 || to - 8 < 0)
return 0; return 0;
@ -71,17 +71,24 @@ namespace hex {
return (value ^ mask) - mask; return (value ^ mask) - mask;
} }
template<class... Ts> struct overloaded : Ts... { using Ts::operator()...; }; template<class... Ts>
template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>; struct overloaded : Ts... { using Ts::operator()...; };
template<class... Ts>
overloaded(Ts...) -> overloaded<Ts...>;
template<size_t Size> template<size_t Size>
struct SizeTypeImpl { }; struct SizeTypeImpl { };
template<> struct SizeTypeImpl<1> { using Type = u8; }; template<>
template<> struct SizeTypeImpl<2> { using Type = u16; }; struct SizeTypeImpl<1> { using Type = u8; };
template<> struct SizeTypeImpl<4> { using Type = u32; }; template<>
template<> struct SizeTypeImpl<8> { using Type = u64; }; struct SizeTypeImpl<2> { using Type = u16; };
template<> struct SizeTypeImpl<16> { using Type = u128; }; template<>
struct SizeTypeImpl<4> { using Type = u32; };
template<>
struct SizeTypeImpl<8> { using Type = u64; };
template<>
struct SizeTypeImpl<16> { using Type = u128; };
template<size_t Size> template<size_t Size>
using SizeType = typename SizeTypeImpl<Size>::Type; using SizeType = typename SizeTypeImpl<Size>::Type;
@ -102,12 +109,23 @@ namespace hex {
static_assert(always_false<T>::value, "Invalid type provided!"); static_assert(always_false<T>::value, "Invalid type provided!");
switch (Size) { switch (Size) {
case 1: swapped = unswapped; break; case 1:
case 2: swapped = __builtin_bswap16(unswapped); break; swapped = unswapped;
case 4: swapped = __builtin_bswap32(unswapped); break; break;
case 8: swapped = __builtin_bswap64(unswapped); break; case 2:
case 16: swapped = (u128(__builtin_bswap64(unswapped & 0xFFFF'FFFF'FFFF'FFFF)) << 64) | __builtin_bswap64(u128(unswapped) >> 64); break; swapped = __builtin_bswap16(unswapped);
default: __builtin_unreachable(); break;
case 4:
swapped = __builtin_bswap32(unswapped);
break;
case 8:
swapped = __builtin_bswap64(unswapped);
break;
case 16:
swapped = (u128(__builtin_bswap64(unswapped & 0xFFFF'FFFF'FFFF'FFFF)) << 64) | __builtin_bswap64(u128(unswapped) >> 64);
break;
default:
__builtin_unreachable();
} }
T result; T result;
@ -116,8 +134,7 @@ namespace hex {
return result; return result;
} }
[[nodiscard]] [[nodiscard]] constexpr u128 bitmask(u8 bits) {
constexpr u128 bitmask(u8 bits) {
return u128(-1) >> (128 - bits); return u128(-1) >> (128 - bits);
} }
@ -132,12 +149,23 @@ namespace hex {
u128 swapped; u128 swapped;
switch (size) { switch (size) {
case 1: swapped = unswapped; break; case 1:
case 2: swapped = __builtin_bswap16(unswapped); break; swapped = unswapped;
case 4: swapped = __builtin_bswap32(unswapped); break; break;
case 8: swapped = __builtin_bswap64(unswapped); break; case 2:
case 16: swapped = (u128(__builtin_bswap64(unswapped & 0xFFFF'FFFF'FFFF'FFFF)) << 64) | __builtin_bswap64(u128(unswapped) >> 64); break; swapped = __builtin_bswap16(unswapped);
default: __builtin_unreachable(); break;
case 4:
swapped = __builtin_bswap32(unswapped);
break;
case 8:
swapped = __builtin_bswap64(unswapped);
break;
case 16:
swapped = (u128(__builtin_bswap64(unswapped & 0xFFFF'FFFF'FFFF'FFFF)) << 64) | __builtin_bswap64(u128(unswapped) >> 64);
break;
default:
__builtin_unreachable();
} }
T result = 0; T result = 0;
@ -146,7 +174,7 @@ namespace hex {
return result; return result;
} }
template< class T > template<class T>
constexpr T bit_width(T x) noexcept { constexpr T bit_width(T x) noexcept {
return std::numeric_limits<T>::digits - std::countl_zero(x); return std::numeric_limits<T>::digits - std::countl_zero(x);
} }
@ -176,12 +204,12 @@ namespace hex {
auto byteString = std::string(string); auto byteString = std::string(string);
byteString.erase(std::remove(byteString.begin(), byteString.end(), ' '), byteString.end()); byteString.erase(std::remove(byteString.begin(), byteString.end(), ' '), byteString.end());
if ((byteString.length() % 2) != 0) return { }; if ((byteString.length() % 2) != 0) return {};
std::vector<u8> result; std::vector<u8> result;
for (u32 i = 0; i < byteString.length(); i += 2) { for (u32 i = 0; i < byteString.length(); i += 2) {
if (!std::isxdigit(byteString[i]) || !std::isxdigit(byteString[i + 1])) if (!std::isxdigit(byteString[i]) || !std::isxdigit(byteString[i + 1]))
return { }; return {};
result.push_back(std::strtoul(byteString.substr(i, 2).c_str(), nullptr, 16)); result.push_back(std::strtoul(byteString.substr(i, 2).c_str(), nullptr, 16));
} }
@ -208,7 +236,8 @@ namespace hex {
inline void trimRight(std::string &s) { inline void trimRight(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) { s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {
return !std::isspace(ch) && ch >= 0x20; return !std::isspace(ch) && ch >= 0x20;
}).base(), s.end()); }).base(),
s.end());
} }
inline void trim(std::string &s) { inline void trim(std::string &s) {
@ -240,7 +269,7 @@ namespace hex {
return iter != a.end(); return iter != a.end();
} }
template<typename T, typename ... VariantTypes> template<typename T, typename... VariantTypes>
T get_or(const std::variant<VariantTypes...> &variant, T alt) { T get_or(const std::variant<VariantTypes...> &variant, T alt) {
const T *value = std::get_if<T>(&variant); const T *value = std::get_if<T>(&variant);
if (value == nullptr) if (value == nullptr)
@ -253,30 +282,33 @@ namespace hex {
namespace scope_guard { namespace scope_guard {
#define SCOPE_GUARD ::hex::scope_guard::ScopeGuardOnExit() + [&]() #define SCOPE_GUARD ::hex::scope_guard::ScopeGuardOnExit() + [&]()
#define ON_SCOPE_EXIT auto ANONYMOUS_VARIABLE(SCOPE_EXIT_) = SCOPE_GUARD #define ON_SCOPE_EXIT auto ANONYMOUS_VARIABLE(SCOPE_EXIT_) = SCOPE_GUARD
template<class F> template<class F>
class ScopeGuard { class ScopeGuard {
private: private:
F m_func; F m_func;
bool m_active; bool m_active;
public: public:
constexpr ScopeGuard(F func) : m_func(std::move(func)), m_active(true) { } constexpr ScopeGuard(F func) : m_func(std::move(func)), m_active(true) { }
~ScopeGuard() { if (this->m_active) { this->m_func(); } } ~ScopeGuard() {
if (this->m_active) { this->m_func(); }
}
void release() { this->m_active = false; } void release() { this->m_active = false; }
ScopeGuard(ScopeGuard &&other) noexcept : m_func(std::move(other.m_func)), m_active(other.m_active) { ScopeGuard(ScopeGuard &&other) noexcept : m_func(std::move(other.m_func)), m_active(other.m_active) {
other.cancel(); other.cancel();
} }
ScopeGuard& operator=(ScopeGuard &&) = delete; ScopeGuard &operator=(ScopeGuard &&) = delete;
}; };
enum class ScopeGuardOnExit { }; enum class ScopeGuardOnExit { };
template <typename F> template<typename F>
constexpr ScopeGuard<F> operator+(ScopeGuardOnExit, F&& f) { constexpr ScopeGuard<F> operator+(ScopeGuardOnExit, F &&f) {
return ScopeGuard<F>(std::forward<F>(f)); return ScopeGuard<F>(std::forward<F>(f));
} }
@ -284,20 +316,20 @@ namespace hex {
namespace first_time_exec { namespace first_time_exec {
#define FIRST_TIME static auto ANONYMOUS_VARIABLE(FIRST_TIME_) = ::hex::first_time_exec::FirstTimeExecutor() + [&]() #define FIRST_TIME static auto ANONYMOUS_VARIABLE(FIRST_TIME_) = ::hex::first_time_exec::FirstTimeExecutor() + [&]()
template<class F> template<class F>
class FirstTimeExecute { class FirstTimeExecute {
public: public:
constexpr FirstTimeExecute(F func) { func(); } constexpr FirstTimeExecute(F func) { func(); }
FirstTimeExecute& operator=(FirstTimeExecute &&) = delete; FirstTimeExecute &operator=(FirstTimeExecute &&) = delete;
}; };
enum class FirstTimeExecutor { }; enum class FirstTimeExecutor { };
template <typename F> template<typename F>
constexpr FirstTimeExecute<F> operator+(FirstTimeExecutor, F&& f) { constexpr FirstTimeExecute<F> operator+(FirstTimeExecutor, F &&f) {
return FirstTimeExecute<F>(std::forward<F>(f)); return FirstTimeExecute<F>(std::forward<F>(f));
} }
@ -305,22 +337,23 @@ namespace hex {
namespace final_cleanup { namespace final_cleanup {
#define FINAL_CLEANUP static auto ANONYMOUS_VARIABLE(ON_EXIT_) = ::hex::final_cleanup::FinalCleanupExecutor() + [&]() #define FINAL_CLEANUP static auto ANONYMOUS_VARIABLE(ON_EXIT_) = ::hex::final_cleanup::FinalCleanupExecutor() + [&]()
template<class F> template<class F>
class FinalCleanupExecute { class FinalCleanupExecute {
F m_func; F m_func;
public: public:
constexpr FinalCleanupExecute(F func) : m_func(func) { } constexpr FinalCleanupExecute(F func) : m_func(func) { }
constexpr ~FinalCleanupExecute() { this->m_func(); } constexpr ~FinalCleanupExecute() { this->m_func(); }
FinalCleanupExecute& operator=(FinalCleanupExecute &&) = delete; FinalCleanupExecute &operator=(FinalCleanupExecute &&) = delete;
}; };
enum class FinalCleanupExecutor { }; enum class FinalCleanupExecutor { };
template <typename F> template<typename F>
constexpr FinalCleanupExecute<F> operator+(FinalCleanupExecutor, F&& f) { constexpr FinalCleanupExecute<F> operator+(FinalCleanupExecutor, F &&f) {
return FinalCleanupExecute<F>(std::forward<F>(f)); return FinalCleanupExecute<F>(std::forward<F>(f));
} }

File diff suppressed because it is too large Load Diff

View File

@ -13,7 +13,9 @@
#include <hex/helpers/fmt.hpp> #include <hex/helpers/fmt.hpp>
#include <hex/helpers/concepts.hpp> #include <hex/helpers/concepts.hpp>
namespace hex::prv { class Provider; } namespace hex::prv {
class Provider;
}
namespace hex::pl { namespace hex::pl {
@ -38,15 +40,17 @@ namespace hex::pl {
public: public:
Evaluator() = default; Evaluator() = default;
std::optional<std::vector<PatternData*>> evaluate(const std::vector<ASTNode*> &ast); std::optional<std::vector<PatternData *>> evaluate(const std::vector<ASTNode *> &ast);
[[nodiscard]] [[nodiscard]] LogConsole &getConsole() {
LogConsole& getConsole() {
return this->m_console; return this->m_console;
} }
struct Scope { PatternData *parent; std::vector<PatternData*>* scope; }; struct Scope {
void pushScope(PatternData *parent, std::vector<PatternData*> &scope) { PatternData *parent;
std::vector<PatternData *> *scope;
};
void pushScope(PatternData *parent, std::vector<PatternData *> &scope) {
if (this->m_scopes.size() > this->getEvaluationDepth()) if (this->m_scopes.size() > this->getEvaluationDepth())
LogConsole::abortEvaluation(hex::format("evaluation depth exceeded set limit of {}", this->getEvaluationDepth())); LogConsole::abortEvaluation(hex::format("evaluation depth exceeded set limit of {}", this->getEvaluationDepth()));
@ -59,11 +63,11 @@ namespace hex::pl {
this->m_scopes.pop_back(); this->m_scopes.pop_back();
} }
const Scope& getScope(i32 index) { const Scope &getScope(i32 index) {
return this->m_scopes[this->m_scopes.size() - 1 + index]; return this->m_scopes[this->m_scopes.size() - 1 + index];
} }
const Scope& getGlobalScope() { const Scope &getGlobalScope() {
return this->m_scopes.front(); return this->m_scopes.front();
} }
@ -83,8 +87,7 @@ namespace hex::pl {
this->m_inVariables = inVariables; this->m_inVariables = inVariables;
} }
[[nodiscard]] [[nodiscard]] std::map<std::string, Token::Literal> getOutVariables() const {
std::map<std::string, Token::Literal> getOutVariables() const {
std::map<std::string, Token::Literal> result; std::map<std::string, Token::Literal> result;
for (const auto &[name, offset] : this->m_outVariables) { for (const auto &[name, offset] : this->m_outVariables) {
@ -94,8 +97,7 @@ namespace hex::pl {
return result; return result;
} }
[[nodiscard]] [[nodiscard]] prv::Provider *getProvider() const {
prv::Provider *getProvider() const {
return this->m_provider; return this->m_provider;
} }
@ -103,8 +105,7 @@ namespace hex::pl {
this->m_defaultEndian = endian; this->m_defaultEndian = endian;
} }
[[nodiscard]] [[nodiscard]] std::endian getDefaultEndian() const {
std::endian getDefaultEndian() const {
return this->m_defaultEndian; return this->m_defaultEndian;
} }
@ -112,8 +113,7 @@ namespace hex::pl {
this->m_evalDepth = evalDepth; this->m_evalDepth = evalDepth;
} }
[[nodiscard]] [[nodiscard]] u64 getEvaluationDepth() const {
u64 getEvaluationDepth() const {
return this->m_evalDepth; return this->m_evalDepth;
} }
@ -121,8 +121,7 @@ namespace hex::pl {
this->m_arrayLimit = arrayLimit; this->m_arrayLimit = arrayLimit;
} }
[[nodiscard]] [[nodiscard]] u64 getArrayLimit() const {
u64 getArrayLimit() const {
return this->m_arrayLimit; return this->m_arrayLimit;
} }
@ -130,13 +129,11 @@ namespace hex::pl {
this->m_patternLimit = limit; this->m_patternLimit = limit;
} }
[[nodiscard]] [[nodiscard]] u64 getPatternLimit() {
u64 getPatternLimit() {
return this->m_patternLimit; return this->m_patternLimit;
} }
[[nodiscard]] [[nodiscard]] u64 getPatternCount() {
u64 getPatternCount() {
return this->m_currPatternCount; return this->m_currPatternCount;
} }
@ -144,36 +141,34 @@ namespace hex::pl {
this->m_loopLimit = limit; this->m_loopLimit = limit;
} }
[[nodiscard]] [[nodiscard]] u64 getLoopLimit() {
u64 getLoopLimit() {
return this->m_loopLimit; return this->m_loopLimit;
} }
u64& dataOffset() { return this->m_currOffset; } u64 &dataOffset() { return this->m_currOffset; }
bool addCustomFunction(const std::string &name, u32 numParams, const ContentRegistry::PatternLanguage::Callback &function) { bool addCustomFunction(const std::string &name, u32 numParams, const ContentRegistry::PatternLanguage::Callback &function) {
const auto [iter, inserted] = this->m_customFunctions.insert({ name, { numParams, function } }); const auto [iter, inserted] = this->m_customFunctions.insert({
name, {numParams, function}
});
return inserted; return inserted;
} }
[[nodiscard]] [[nodiscard]] const std::map<std::string, ContentRegistry::PatternLanguage::Function> &getCustomFunctions() const {
const std::map<std::string, ContentRegistry::PatternLanguage::Function>& getCustomFunctions() const {
return this->m_customFunctions; return this->m_customFunctions;
} }
[[nodiscard]] [[nodiscard]] std::vector<Token::Literal> &getStack() {
std::vector<Token::Literal>& getStack() {
return this->m_stack; return this->m_stack;
} }
[[nodiscard]] [[nodiscard]] const std::vector<Token::Literal> &getStack() const {
const std::vector<Token::Literal>& getStack() const {
return this->m_stack; return this->m_stack;
} }
void createVariable(const std::string &name, ASTNode *type, const std::optional<Token::Literal> &value = std::nullopt, bool outVariable = false); void createVariable(const std::string &name, ASTNode *type, const std::optional<Token::Literal> &value = std::nullopt, bool outVariable = false);
void setVariable(const std::string &name, const Token::Literal& value); void setVariable(const std::string &name, const Token::Literal &value);
void abort() { void abort() {
this->m_aborted = true; this->m_aborted = true;
@ -184,8 +179,7 @@ namespace hex::pl {
LogConsole::abortEvaluation("evaluation aborted by user"); LogConsole::abortEvaluation("evaluation aborted by user");
} }
[[nodiscard]] [[nodiscard]] std::optional<Token::Literal> getEnvVariable(const std::string &name) const {
std::optional<Token::Literal> getEnvVariable(const std::string &name) const {
if (this->m_envVariables.contains(name)) if (this->m_envVariables.contains(name))
return this->m_envVariables.at(name); return this->m_envVariables.at(name);
else else
@ -196,8 +190,7 @@ namespace hex::pl {
this->m_envVariables[name] = value; this->m_envVariables[name] = value;
} }
[[nodiscard]] [[nodiscard]] bool hasDangerousFunctionBeenCalled() const {
bool hasDangerousFunctionBeenCalled() const {
return this->m_dangerousFunctionCalled; return this->m_dangerousFunctionCalled;
} }
@ -210,8 +203,7 @@ namespace hex::pl {
this->m_dangerousFunctionCalled = false; this->m_dangerousFunctionCalled = false;
} }
[[nodiscard]] [[nodiscard]] DangerousFunctionPermission getDangerousFunctionPermission() const {
DangerousFunctionPermission getDangerousFunctionPermission() const {
return this->m_allowDangerousFunctions; return this->m_allowDangerousFunctions;
} }
@ -219,13 +211,11 @@ namespace hex::pl {
this->m_currControlFlowStatement = statement; this->m_currControlFlowStatement = statement;
} }
[[nodiscard]] [[nodiscard]] ControlFlowStatement getCurrentControlFlowStatement() const {
ControlFlowStatement getCurrentControlFlowStatement() const {
return this->m_currControlFlowStatement; return this->m_currControlFlowStatement;
} }
private: private:
void patternCreated(); void patternCreated();
void patternDestroyed(); void patternDestroyed();
@ -246,7 +236,7 @@ namespace hex::pl {
std::vector<Scope> m_scopes; std::vector<Scope> m_scopes;
std::map<std::string, ContentRegistry::PatternLanguage::Function> m_customFunctions; std::map<std::string, ContentRegistry::PatternLanguage::Function> m_customFunctions;
std::vector<ASTNode*> m_customFunctionDefinitions; std::vector<ASTNode *> m_customFunctionDefinitions;
std::vector<Token::Literal> m_stack; std::vector<Token::Literal> m_stack;
std::map<std::string, Token::Literal> m_envVariables; std::map<std::string, Token::Literal> m_envVariables;

View File

@ -16,8 +16,8 @@ namespace hex::pl {
Lexer() = default; Lexer() = default;
std::optional<std::vector<Token>> lex(const std::string& code); std::optional<std::vector<Token>> lex(const std::string &code);
const std::optional<LexerError>& getError() { return this->m_error; } const std::optional<LexerError> &getError() { return this->m_error; }
private: private:
std::optional<LexerError> m_error; std::optional<LexerError> m_error;

View File

@ -21,25 +21,21 @@ namespace hex::pl {
Error Error
}; };
[[nodiscard]] [[nodiscard]] const auto &getLog() const { return this->m_consoleLog; }
const auto& getLog() const { return this->m_consoleLog; }
using EvaluateError = std::pair<u32, std::string>; using EvaluateError = std::pair<u32, std::string>;
void log(Level level, const std::string &message); void log(Level level, const std::string &message);
[[noreturn]] [[noreturn]] static void abortEvaluation(const std::string &message);
static void abortEvaluation(const std::string &message);
[[noreturn]] [[noreturn]] static void abortEvaluation(const std::string &message, const ASTNode *node);
static void abortEvaluation(const std::string &message, const ASTNode *node);
void clear(); void clear();
void setHardError(const EvaluateError &error) { this->m_lastHardError = error; } void setHardError(const EvaluateError &error) { this->m_lastHardError = error; }
[[nodiscard]] [[nodiscard]] const std::optional<EvaluateError> &getLastHardError() { return this->m_lastHardError; };
const std::optional<EvaluateError>& getLastHardError() { return this->m_lastHardError; };
private: private:
std::vector<std::pair<Level, std::string>> m_consoleLog; std::vector<std::pair<Level, std::string>> m_consoleLog;

View File

@ -21,15 +21,15 @@ namespace hex::pl {
Parser() = default; Parser() = default;
~Parser() = default; ~Parser() = default;
std::optional<std::vector<ASTNode*>> parse(const std::vector<Token> &tokens); std::optional<std::vector<ASTNode *>> parse(const std::vector<Token> &tokens);
const std::optional<ParseError>& getError() { return this->m_error; } const std::optional<ParseError> &getError() { return this->m_error; }
private: private:
std::optional<ParseError> m_error; std::optional<ParseError> m_error;
TokenIter m_curr; TokenIter m_curr;
TokenIter m_originalPosition; TokenIter m_originalPosition;
std::unordered_map<std::string, ASTNode*> m_types; std::unordered_map<std::string, ASTNode *> m_types;
std::vector<TokenIter> m_matchedOptionals; std::vector<TokenIter> m_matchedOptionals;
std::vector<std::vector<std::string>> m_currNamespace; std::vector<std::vector<std::string>> m_currNamespace;
@ -37,13 +37,13 @@ namespace hex::pl {
return this->m_curr[index].lineNumber; return this->m_curr[index].lineNumber;
} }
auto* create(auto *node) { auto *create(auto *node) {
node->setLineNumber(this->getLineNumber(-1)); node->setLineNumber(this->getLineNumber(-1));
return node; return node;
} }
template<typename T> template<typename T>
const T& getValue(i32 index) const { const T &getValue(i32 index) const {
auto value = std::get_if<T>(&this->m_curr[index].value); auto value = std::get_if<T>(&this->m_curr[index].value);
if (value == nullptr) if (value == nullptr)
@ -67,63 +67,63 @@ namespace hex::pl {
return result; return result;
} }
ASTNode* parseFunctionCall(); ASTNode *parseFunctionCall();
ASTNode* parseStringLiteral(); ASTNode *parseStringLiteral();
std::string parseNamespaceResolution(); std::string parseNamespaceResolution();
ASTNode* parseScopeResolution(); ASTNode *parseScopeResolution();
ASTNode* parseRValue(ASTNodeRValue::Path &path); ASTNode *parseRValue(ASTNodeRValue::Path &path);
ASTNode* parseFactor(); ASTNode *parseFactor();
ASTNode* parseCastExpression(); ASTNode *parseCastExpression();
ASTNode* parseUnaryExpression(); ASTNode *parseUnaryExpression();
ASTNode* parseMultiplicativeExpression(); ASTNode *parseMultiplicativeExpression();
ASTNode* parseAdditiveExpression(); ASTNode *parseAdditiveExpression();
ASTNode* parseShiftExpression(); ASTNode *parseShiftExpression();
ASTNode* parseRelationExpression(); ASTNode *parseRelationExpression();
ASTNode* parseEqualityExpression(); ASTNode *parseEqualityExpression();
ASTNode* parseBinaryAndExpression(); ASTNode *parseBinaryAndExpression();
ASTNode* parseBinaryXorExpression(); ASTNode *parseBinaryXorExpression();
ASTNode* parseBinaryOrExpression(); ASTNode *parseBinaryOrExpression();
ASTNode* parseBooleanAnd(); ASTNode *parseBooleanAnd();
ASTNode* parseBooleanXor(); ASTNode *parseBooleanXor();
ASTNode* parseBooleanOr(); ASTNode *parseBooleanOr();
ASTNode* parseTernaryConditional(); ASTNode *parseTernaryConditional();
ASTNode* parseMathematicalExpression(); ASTNode *parseMathematicalExpression();
ASTNode* parseFunctionDefinition(); ASTNode *parseFunctionDefinition();
ASTNode* parseFunctionVariableDecl(); ASTNode *parseFunctionVariableDecl();
ASTNode* parseFunctionStatement(); ASTNode *parseFunctionStatement();
ASTNode* parseFunctionVariableAssignment(); ASTNode *parseFunctionVariableAssignment();
ASTNode* parseFunctionControlFlowStatement(); ASTNode *parseFunctionControlFlowStatement();
std::vector<ASTNode*> parseStatementBody(); std::vector<ASTNode *> parseStatementBody();
ASTNode* parseFunctionConditional(); ASTNode *parseFunctionConditional();
ASTNode* parseFunctionWhileLoop(); ASTNode *parseFunctionWhileLoop();
ASTNode* parseFunctionForLoop(); ASTNode *parseFunctionForLoop();
void parseAttribute(Attributable *currNode); void parseAttribute(Attributable *currNode);
ASTNode* parseConditional(); ASTNode *parseConditional();
ASTNode* parseWhileStatement(); ASTNode *parseWhileStatement();
ASTNodeTypeDecl* parseType(bool allowFunctionTypes = false); ASTNodeTypeDecl *parseType(bool allowFunctionTypes = false);
ASTNode* parseUsingDeclaration(); ASTNode *parseUsingDeclaration();
ASTNode* parsePadding(); ASTNode *parsePadding();
ASTNode* parseMemberVariable(ASTNodeTypeDecl *type); ASTNode *parseMemberVariable(ASTNodeTypeDecl *type);
ASTNode* parseMemberArrayVariable(ASTNodeTypeDecl *type); ASTNode *parseMemberArrayVariable(ASTNodeTypeDecl *type);
ASTNode* parseMemberPointerVariable(ASTNodeTypeDecl *type); ASTNode *parseMemberPointerVariable(ASTNodeTypeDecl *type);
ASTNode* parseMember(); ASTNode *parseMember();
ASTNode* parseStruct(); ASTNode *parseStruct();
ASTNode* parseUnion(); ASTNode *parseUnion();
ASTNode* parseEnum(); ASTNode *parseEnum();
ASTNode* parseBitfield(); ASTNode *parseBitfield();
ASTNode* parseVariablePlacement(ASTNodeTypeDecl *type); ASTNode *parseVariablePlacement(ASTNodeTypeDecl *type);
ASTNode* parseArrayVariablePlacement(ASTNodeTypeDecl *type); ASTNode *parseArrayVariablePlacement(ASTNodeTypeDecl *type);
ASTNode* parsePointerVariablePlacement(ASTNodeTypeDecl *type); ASTNode *parsePointerVariablePlacement(ASTNodeTypeDecl *type);
ASTNode* parsePlacement(); ASTNode *parsePlacement();
std::vector<ASTNode*> parseNamespace(); std::vector<ASTNode *> parseNamespace();
std::vector<ASTNode*> parseStatements(); std::vector<ASTNode *> parseStatements();
ASTNodeTypeDecl* addType(const std::string &name, ASTNode *node, std::optional<std::endian> endian = std::nullopt); ASTNodeTypeDecl *addType(const std::string &name, ASTNode *node, std::optional<std::endian> endian = std::nullopt);
std::vector<ASTNode*> parseTillToken(Token::Type endTokenType, const auto value) { std::vector<ASTNode *> parseTillToken(Token::Type endTokenType, const auto value) {
std::vector<ASTNode*> program; std::vector<ASTNode *> program;
auto guard = SCOPE_GUARD { auto guard = SCOPE_GUARD {
for (auto &node : program) for (auto &node : program)
delete node; delete node;
@ -147,7 +147,7 @@ namespace hex::pl {
/* Token consuming */ /* Token consuming */
enum class Setting{ }; enum class Setting { };
constexpr static auto Normal = static_cast<Setting>(0); constexpr static auto Normal = static_cast<Setting>(0);
constexpr static auto Not = static_cast<Setting>(1); constexpr static auto Not = static_cast<Setting>(1);
@ -173,7 +173,7 @@ namespace hex::pl {
} }
template<Setting S = Normal> template<Setting S = Normal>
bool sequence(Token::Type type, auto value, auto ... args) { bool sequence(Token::Type type, auto value, auto... args) {
if constexpr (S == Normal) { if constexpr (S == Normal) {
if (!peek(type, value)) { if (!peek(type, value)) {
reset(); reset();
@ -214,7 +214,7 @@ namespace hex::pl {
} }
template<Setting S = Normal> template<Setting S = Normal>
bool oneOf(Token::Type type, auto value, auto ... args) { bool oneOf(Token::Type type, auto value, auto... args) {
if constexpr (S == Normal) if constexpr (S == Normal)
return sequence<Normal>(type, value) || oneOf(args...); return sequence<Normal>(type, value) || oneOf(args...);
else if constexpr (S == Not) else if constexpr (S == Not)
@ -248,7 +248,6 @@ namespace hex::pl {
bool peek(Token::Type type, auto value, i32 index = 0) { bool peek(Token::Type type, auto value, i32 index = 0) {
return this->m_curr[index].type == type && this->m_curr[index] == value; return this->m_curr[index].type == type && this->m_curr[index] == value;
} }
}; };
} }

View File

@ -30,7 +30,7 @@ namespace hex::pl {
template<hex::has_size<1> T> template<hex::has_size<1> T>
std::string makeDisplayable(T *data, size_t size) { std::string makeDisplayable(T *data, size_t size) {
std::string result; std::string result;
for (T* c = data; c < (data + size); c++) { for (T *c = data; c < (data + size); c++) {
if (iscntrl(*c) || *c > 0x7F) if (iscntrl(*c) || *c > 0x7F)
result += " "; result += " ";
else else
@ -49,6 +49,7 @@ namespace hex::pl {
public: public:
[[nodiscard]] bool isInlined() const { return this->m_inlined; } [[nodiscard]] bool isInlined() const { return this->m_inlined; }
void setInlined(bool inlined) { this->m_inlined = inlined; } void setInlined(bool inlined) { this->m_inlined = inlined; }
private: private:
bool m_inlined = false; bool m_inlined = false;
}; };
@ -98,7 +99,7 @@ namespace hex::pl {
virtual ~PatternData() = default; virtual ~PatternData() = default;
virtual PatternData* clone() = 0; virtual PatternData *clone() = 0;
[[nodiscard]] u64 getOffset() const { return this->m_offset; } [[nodiscard]] u64 getOffset() const { return this->m_offset; }
virtual void setOffset(u64 offset) { this->m_offset = offset; } virtual void setOffset(u64 offset) { this->m_offset = offset; }
@ -106,17 +107,20 @@ namespace hex::pl {
[[nodiscard]] size_t getSize() const { return this->m_size; } [[nodiscard]] size_t getSize() const { return this->m_size; }
void setSize(size_t size) { this->m_size = size; } void setSize(size_t size) { this->m_size = size; }
[[nodiscard]] const std::string& getVariableName() const { return this->m_variableName; } [[nodiscard]] const std::string &getVariableName() const { return this->m_variableName; }
void setVariableName(std::string name) { this->m_variableName = std::move(name); } void setVariableName(std::string name) { this->m_variableName = std::move(name); }
[[nodiscard]] const std::optional<std::string>& getComment() const { return this->m_comment; } [[nodiscard]] const std::optional<std::string> &getComment() const { return this->m_comment; }
void setComment(std::string comment) { this->m_comment = std::move(comment); } void setComment(std::string comment) { this->m_comment = std::move(comment); }
[[nodiscard]] const std::string& getTypeName() const { return this->m_typeName; } [[nodiscard]] const std::string &getTypeName() const { return this->m_typeName; }
void setTypeName(std::string name) { this->m_typeName = std::move(name); } void setTypeName(std::string name) { this->m_typeName = std::move(name); }
[[nodiscard]] u32 getColor() const { return this->m_color; } [[nodiscard]] u32 getColor() const { return this->m_color; }
virtual void setColor(u32 color) { this->m_color = color; this->m_manualColor = true; } virtual void setColor(u32 color) {
this->m_color = color;
this->m_manualColor = true;
}
[[nodiscard]] bool hasOverriddenColor() const { return this->m_manualColor; } [[nodiscard]] bool hasOverriddenColor() const { return this->m_manualColor; }
[[nodiscard]] std::endian getEndian() const { return this->m_endian; } [[nodiscard]] std::endian getEndian() const { return this->m_endian; }
@ -125,18 +129,17 @@ namespace hex::pl {
[[nodiscard]] std::string getDisplayName() const { return this->m_displayName.value_or(this->m_variableName); } [[nodiscard]] std::string getDisplayName() const { return this->m_displayName.value_or(this->m_variableName); }
void setDisplayName(const std::string &name) { this->m_displayName = name; } void setDisplayName(const std::string &name) { this->m_displayName = name; }
[[nodiscard]] Evaluator* getEvaluator() const { return this->m_evaluator; } [[nodiscard]] Evaluator *getEvaluator() const { return this->m_evaluator; }
[[nodiscard]] const auto& getTransformFunction() const { return this->m_transformFunction; } [[nodiscard]] const auto &getTransformFunction() const { return this->m_transformFunction; }
void setTransformFunction(const ContentRegistry::PatternLanguage::Function &function) { this->m_transformFunction = function; } void setTransformFunction(const ContentRegistry::PatternLanguage::Function &function) { this->m_transformFunction = function; }
[[nodiscard]] const auto& getFormatterFunction() const { return this->m_formatterFunction; } [[nodiscard]] const auto &getFormatterFunction() const { return this->m_formatterFunction; }
void setFormatterFunction(const ContentRegistry::PatternLanguage::Function &function) { this->m_formatterFunction = function; } void setFormatterFunction(const ContentRegistry::PatternLanguage::Function &function) { this->m_formatterFunction = function; }
virtual void createEntry(prv::Provider* &provider) = 0; virtual void createEntry(prv::Provider *&provider) = 0;
[[nodiscard]] virtual std::string getFormattedName() const = 0; [[nodiscard]] virtual std::string getFormattedName() const = 0;
[[nodiscard]] [[nodiscard]] virtual const PatternData *getPattern(u64 offset) const {
virtual const PatternData* getPattern(u64 offset) const {
if (offset >= this->getOffset() && offset < (this->getOffset() + this->getSize()) && !this->isHidden()) if (offset >= this->getOffset() && offset < (this->getOffset() + this->getSize()) && !this->isHidden())
return this; return this;
else else
@ -154,31 +157,27 @@ namespace hex::pl {
virtual void sort(ImGuiTableSortSpecs *sortSpecs, prv::Provider *provider) { } virtual void sort(ImGuiTableSortSpecs *sortSpecs, prv::Provider *provider) { }
[[nodiscard]] [[nodiscard]] virtual std::string toString(prv::Provider *provider) const {
virtual std::string toString(prv::Provider *provider) const {
return hex::format("{} {} @ 0x{:X}", this->getTypeName(), this->getVariableName(), this->getOffset()); return hex::format("{} {} @ 0x{:X}", this->getTypeName(), this->getVariableName(), this->getOffset());
} }
static bool sortPatternDataTable(ImGuiTableSortSpecs *sortSpecs, prv::Provider *provider, pl::PatternData* left, pl::PatternData* right) { static bool sortPatternDataTable(ImGuiTableSortSpecs *sortSpecs, prv::Provider *provider, pl::PatternData *left, pl::PatternData *right) {
if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("name")) { if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("name")) {
if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending) if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending)
return left->getDisplayName() > right->getDisplayName(); return left->getDisplayName() > right->getDisplayName();
else else
return left->getDisplayName() < right->getDisplayName(); return left->getDisplayName() < right->getDisplayName();
} } else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("offset")) {
else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("offset")) {
if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending) if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending)
return left->getOffset() > right->getOffset(); return left->getOffset() > right->getOffset();
else else
return left->getOffset() < right->getOffset(); return left->getOffset() < right->getOffset();
} } else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("size")) {
else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("size")) {
if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending) if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending)
return left->getSize() > right->getSize(); return left->getSize() > right->getSize();
else else
return left->getSize() < right->getSize(); return left->getSize() < right->getSize();
} } else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("value")) {
else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("value")) {
size_t biggerSize = std::max(left->getSize(), right->getSize()); size_t biggerSize = std::max(left->getSize(), right->getSize());
std::vector<u8> leftBuffer(biggerSize, 0x00), rightBuffer(biggerSize, 0x00); std::vector<u8> leftBuffer(biggerSize, 0x00), rightBuffer(biggerSize, 0x00);
@ -194,14 +193,12 @@ namespace hex::pl {
return leftBuffer > rightBuffer; return leftBuffer > rightBuffer;
else else
return leftBuffer < rightBuffer; return leftBuffer < rightBuffer;
} } else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("type")) {
else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("type")) {
if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending) if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending)
return left->getTypeName() > right->getTypeName(); return left->getTypeName() > right->getTypeName();
else else
return left->getTypeName() < right->getTypeName(); return left->getTypeName() < right->getTypeName();
} } else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("color")) {
else if (sortSpecs->Specs->ColumnUserID == ImGui::GetID("color")) {
if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending) if (sortSpecs->Specs->SortDirection == ImGuiSortDirection_Ascending)
return left->getColor() > right->getColor(); return left->getColor() > right->getColor();
else else
@ -240,8 +237,7 @@ namespace hex::pl {
template<typename T> template<typename T>
[[nodiscard]] bool areCommonPropertiesEqual(const PatternData &other) const { [[nodiscard]] bool areCommonPropertiesEqual(const PatternData &other) const {
return return typeid(other) == typeid(std::remove_cvref_t<T>) &&
typeid(other) == typeid(std::remove_cvref_t<T>) &&
this->m_offset == other.m_offset && this->m_offset == other.m_offset &&
this->m_size == other.m_size && this->m_size == other.m_size &&
this->m_hidden == other.m_hidden && this->m_hidden == other.m_hidden &&
@ -252,8 +248,7 @@ namespace hex::pl {
this->m_local == other.m_local; this->m_local == other.m_local;
} }
[[nodiscard]] [[nodiscard]] std::string formatDisplayValue(const std::string &value, const Token::Literal &literal) const {
std::string formatDisplayValue(const std::string &value, const Token::Literal &literal) const {
if (!this->m_formatterFunction.has_value()) if (!this->m_formatterFunction.has_value())
return value; return value;
else { else {
@ -330,11 +325,11 @@ namespace hex::pl {
public: public:
PatternDataPadding(u64 offset, size_t size, Evaluator *evaluator) : PatternData(offset, size, evaluator, 0xFF000000) { } PatternDataPadding(u64 offset, size_t size, Evaluator *evaluator) : PatternData(offset, size, evaluator, 0xFF000000) { }
PatternData* clone() override { PatternData *clone() override {
return new PatternDataPadding(*this); return new PatternDataPadding(*this);
} }
void createEntry(prv::Provider* &provider) override { void createEntry(prv::Provider *&provider) override {
} }
[[nodiscard]] std::string getFormattedName() const override { [[nodiscard]] std::string getFormattedName() const override {
@ -358,11 +353,11 @@ namespace hex::pl {
delete this->m_pointedAt; delete this->m_pointedAt;
} }
PatternData* clone() override { PatternData *clone() override {
return new PatternDataPointer(*this); return new PatternDataPointer(*this);
} }
void createEntry(prv::Provider* &provider) override { void createEntry(prv::Provider *&provider) override {
u64 data = 0; u64 data = 0;
provider->read(this->getOffset(), &data, this->getSize()); provider->read(this->getOffset(), &data, this->getSize());
data = hex::changeEndianess(data, this->getSize(), this->getEndian()); data = hex::changeEndianess(data, this->getSize(), this->getEndian());
@ -397,11 +392,21 @@ namespace hex::pl {
[[nodiscard]] std::string getFormattedName() const override { [[nodiscard]] std::string getFormattedName() const override {
std::string result = this->m_pointedAt->getFormattedName() + "* : "; std::string result = this->m_pointedAt->getFormattedName() + "* : ";
switch (this->getSize()) { switch (this->getSize()) {
case 1: result += "u8"; break; case 1:
case 2: result += "u16"; break; result += "u8";
case 4: result += "u32"; break; break;
case 8: result += "u64"; break; case 2:
case 16: result += "u128"; break; result += "u16";
break;
case 4:
result += "u32";
break;
case 8:
result += "u64";
break;
case 16:
result += "u128";
break;
} }
return result; return result;
@ -421,7 +426,7 @@ namespace hex::pl {
return this->m_pointedAtAddress; return this->m_pointedAtAddress;
} }
[[nodiscard]] PatternData* getPointedAtPattern() { [[nodiscard]] PatternData *getPointedAtPattern() {
return this->m_pointedAt; return this->m_pointedAt;
} }
@ -432,7 +437,7 @@ namespace hex::pl {
[[nodiscard]] bool operator==(const PatternData &other) const override { [[nodiscard]] bool operator==(const PatternData &other) const override {
return areCommonPropertiesEqual<decltype(*this)>(other) && return areCommonPropertiesEqual<decltype(*this)>(other) &&
*static_cast<const PatternDataPointer*>(&other)->m_pointedAt == *this->m_pointedAt; *static_cast<const PatternDataPointer *>(&other)->m_pointedAt == *this->m_pointedAt;
} }
void rebase(u64 base) { void rebase(u64 base) {
@ -444,8 +449,7 @@ namespace hex::pl {
this->m_pointerBase = base; this->m_pointerBase = base;
} }
[[nodiscard]] [[nodiscard]] const PatternData *getPattern(u64 offset) const override {
const PatternData* getPattern(u64 offset) const override {
if (offset >= this->getOffset() && offset < (this->getOffset() + this->getSize()) && !this->isHidden()) if (offset >= this->getOffset() && offset < (this->getOffset() + this->getSize()) && !this->isHidden())
return this; return this;
else else
@ -464,11 +468,11 @@ namespace hex::pl {
PatternDataUnsigned(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) PatternDataUnsigned(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0)
: PatternData(offset, size, evaluator, color) { } : PatternData(offset, size, evaluator, color) { }
PatternData* clone() override { PatternData *clone() override {
return new PatternDataUnsigned(*this); return new PatternDataUnsigned(*this);
} }
void createEntry(prv::Provider* &provider) override { void createEntry(prv::Provider *&provider) override {
u128 data = 0; u128 data = 0;
provider->read(this->getOffset(), &data, this->getSize()); provider->read(this->getOffset(), &data, this->getSize());
data = hex::changeEndianess(data, this->getSize(), this->getEndian()); data = hex::changeEndianess(data, this->getSize(), this->getEndian());
@ -478,12 +482,18 @@ namespace hex::pl {
[[nodiscard]] std::string getFormattedName() const override { [[nodiscard]] std::string getFormattedName() const override {
switch (this->getSize()) { switch (this->getSize()) {
case 1: return "u8"; case 1:
case 2: return "u16"; return "u8";
case 4: return "u32"; case 2:
case 8: return "u64"; return "u16";
case 16: return "u128"; case 4:
default: return "Unsigned data"; return "u32";
case 8:
return "u64";
case 16:
return "u128";
default:
return "Unsigned data";
} }
} }
@ -495,11 +505,11 @@ namespace hex::pl {
PatternDataSigned(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) PatternDataSigned(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0)
: PatternData(offset, size, evaluator, color) { } : PatternData(offset, size, evaluator, color) { }
PatternData* clone() override { PatternData *clone() override {
return new PatternDataSigned(*this); return new PatternDataSigned(*this);
} }
void createEntry(prv::Provider* &provider) override { void createEntry(prv::Provider *&provider) override {
i128 data = 0; i128 data = 0;
provider->read(this->getOffset(), &data, this->getSize()); provider->read(this->getOffset(), &data, this->getSize());
data = hex::changeEndianess(data, this->getSize(), this->getEndian()); data = hex::changeEndianess(data, this->getSize(), this->getEndian());
@ -510,12 +520,18 @@ namespace hex::pl {
[[nodiscard]] std::string getFormattedName() const override { [[nodiscard]] std::string getFormattedName() const override {
switch (this->getSize()) { switch (this->getSize()) {
case 1: return "s8"; case 1:
case 2: return "s16"; return "s8";
case 4: return "s32"; case 2:
case 8: return "s64"; return "s16";
case 16: return "s128"; case 4:
default: return "Signed data"; return "s32";
case 8:
return "s64";
case 16:
return "s128";
default:
return "Signed data";
} }
} }
@ -527,31 +543,34 @@ namespace hex::pl {
PatternDataFloat(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) PatternDataFloat(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0)
: PatternData(offset, size, evaluator, color) { } : PatternData(offset, size, evaluator, color) { }
PatternData* clone() override { PatternData *clone() override {
return new PatternDataFloat(*this); return new PatternDataFloat(*this);
} }
void createEntry(prv::Provider* &provider) override { void createEntry(prv::Provider *&provider) override {
if (this->getSize() == 4) { if (this->getSize() == 4) {
u32 data = 0; u32 data = 0;
provider->read(this->getOffset(), &data, 4); provider->read(this->getOffset(), &data, 4);
data = hex::changeEndianess(data, 4, this->getEndian()); data = hex::changeEndianess(data, 4, this->getEndian());
this->createDefaultEntry(hex::format("{:e} (0x{:0{}X})", *reinterpret_cast<float*>(&data), data, this->getSize() * 2), *reinterpret_cast<float*>(&data)); this->createDefaultEntry(hex::format("{:e} (0x{:0{}X})", *reinterpret_cast<float *>(&data), data, this->getSize() * 2), *reinterpret_cast<float *>(&data));
} else if (this->getSize() == 8) { } else if (this->getSize() == 8) {
u64 data = 0; u64 data = 0;
provider->read(this->getOffset(), &data, 8); provider->read(this->getOffset(), &data, 8);
data = hex::changeEndianess(data, 8, this->getEndian()); data = hex::changeEndianess(data, 8, this->getEndian());
this->createDefaultEntry(hex::format("{:e} (0x{:0{}X})", *reinterpret_cast<double*>(&data), data, this->getSize() * 2), *reinterpret_cast<double*>(&data)); this->createDefaultEntry(hex::format("{:e} (0x{:0{}X})", *reinterpret_cast<double *>(&data), data, this->getSize() * 2), *reinterpret_cast<double *>(&data));
} }
} }
[[nodiscard]] std::string getFormattedName() const override { [[nodiscard]] std::string getFormattedName() const override {
switch (this->getSize()) { switch (this->getSize()) {
case 4: return "float"; case 4:
case 8: return "double"; return "float";
default: return "Floating point data"; case 8:
return "double";
default:
return "Floating point data";
} }
} }
@ -563,11 +582,11 @@ namespace hex::pl {
explicit PatternDataBoolean(u64 offset, Evaluator *evaluator, u32 color = 0) explicit PatternDataBoolean(u64 offset, Evaluator *evaluator, u32 color = 0)
: PatternData(offset, 1, evaluator, color) { } : PatternData(offset, 1, evaluator, color) { }
PatternData* clone() override { PatternData *clone() override {
return new PatternDataBoolean(*this); return new PatternDataBoolean(*this);
} }
void createEntry(prv::Provider* &provider) override { void createEntry(prv::Provider *&provider) override {
u8 boolean; u8 boolean;
provider->read(this->getOffset(), &boolean, 1); provider->read(this->getOffset(), &boolean, 1);
@ -591,11 +610,11 @@ namespace hex::pl {
explicit PatternDataCharacter(u64 offset, Evaluator *evaluator, u32 color = 0) explicit PatternDataCharacter(u64 offset, Evaluator *evaluator, u32 color = 0)
: PatternData(offset, 1, evaluator, color) { } : PatternData(offset, 1, evaluator, color) { }
PatternData* clone() override { PatternData *clone() override {
return new PatternDataCharacter(*this); return new PatternDataCharacter(*this);
} }
void createEntry(prv::Provider* &provider) override { void createEntry(prv::Provider *&provider) override {
char character; char character;
provider->read(this->getOffset(), &character, 1); provider->read(this->getOffset(), &character, 1);
@ -614,17 +633,17 @@ namespace hex::pl {
explicit PatternDataCharacter16(u64 offset, Evaluator *evaluator, u32 color = 0) explicit PatternDataCharacter16(u64 offset, Evaluator *evaluator, u32 color = 0)
: PatternData(offset, 2, evaluator, color) { } : PatternData(offset, 2, evaluator, color) { }
PatternData* clone() override { PatternData *clone() override {
return new PatternDataCharacter16(*this); return new PatternDataCharacter16(*this);
} }
void createEntry(prv::Provider* &provider) override { void createEntry(prv::Provider *&provider) override {
char16_t character; char16_t character;
provider->read(this->getOffset(), &character, 2); provider->read(this->getOffset(), &character, 2);
character = hex::changeEndianess(character, this->getEndian()); character = hex::changeEndianess(character, this->getEndian());
u128 literal = character; u128 literal = character;
this->createDefaultEntry(hex::format("'{0}'", std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}.to_bytes(character)), literal); this->createDefaultEntry(hex::format("'{0}'", std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> {}.to_bytes(character)), literal);
} }
[[nodiscard]] std::string getFormattedName() const override { [[nodiscard]] std::string getFormattedName() const override {
@ -636,7 +655,7 @@ namespace hex::pl {
provider->read(this->getOffset(), &character, 2); provider->read(this->getOffset(), &character, 2);
character = hex::changeEndianess(character, this->getEndian()); character = hex::changeEndianess(character, this->getEndian());
return std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}.to_bytes(character); return std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> {}.to_bytes(character);
} }
[[nodiscard]] bool operator==(const PatternData &other) const override { return areCommonPropertiesEqual<decltype(*this)>(other); } [[nodiscard]] bool operator==(const PatternData &other) const override { return areCommonPropertiesEqual<decltype(*this)>(other); }
@ -647,11 +666,11 @@ namespace hex::pl {
PatternDataString(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) PatternDataString(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0)
: PatternData(offset, size, evaluator, color) { } : PatternData(offset, size, evaluator, color) { }
PatternData* clone() override { PatternData *clone() override {
return new PatternDataString(*this); return new PatternDataString(*this);
} }
void createEntry(prv::Provider* &provider) override { void createEntry(prv::Provider *&provider) override {
auto size = std::min<size_t>(this->getSize(), 0x7F); auto size = std::min<size_t>(this->getSize(), 0x7F);
if (size == 0) if (size == 0)
@ -661,7 +680,7 @@ namespace hex::pl {
provider->read(this->getOffset(), buffer.data(), size); provider->read(this->getOffset(), buffer.data(), size);
std::erase_if(buffer, [](auto c){ std::erase_if(buffer, [](auto c) {
return c == 0x00; return c == 0x00;
}); });
@ -676,7 +695,7 @@ namespace hex::pl {
std::string buffer(this->getSize(), 0x00); std::string buffer(this->getSize(), 0x00);
provider->read(this->getOffset(), buffer.data(), buffer.size()); provider->read(this->getOffset(), buffer.data(), buffer.size());
std::erase_if(buffer, [](auto c){ std::erase_if(buffer, [](auto c) {
return c == 0x00; return c == 0x00;
}); });
@ -691,27 +710,27 @@ namespace hex::pl {
PatternDataString16(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) PatternDataString16(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0)
: PatternData(offset, size, evaluator, color) { } : PatternData(offset, size, evaluator, color) { }
PatternData* clone() override { PatternData *clone() override {
return new PatternDataString16(*this); return new PatternDataString16(*this);
} }
void createEntry(prv::Provider* &provider) override { void createEntry(prv::Provider *&provider) override {
auto size = std::min<size_t>(this->getSize(), 0x100); auto size = std::min<size_t>(this->getSize(), 0x100);
if (size == 0) if (size == 0)
return; return;
std::u16string buffer(this->getSize()/sizeof(char16_t), 0x00); std::u16string buffer(this->getSize() / sizeof(char16_t), 0x00);
provider->read(this->getOffset(), buffer.data(), size); provider->read(this->getOffset(), buffer.data(), size);
for (auto &c : buffer) for (auto &c : buffer)
c = hex::changeEndianess(c, 2, this->getEndian()); c = hex::changeEndianess(c, 2, this->getEndian());
std::erase_if(buffer, [](auto c){ std::erase_if(buffer, [](auto c) {
return c == 0x00; return c == 0x00;
}); });
auto utf8String = std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}.to_bytes(buffer); auto utf8String = std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> {}.to_bytes(buffer);
this->createDefaultEntry(hex::format("\"{0}\" {1}", utf8String, size > this->getSize() ? "(truncated)" : ""), utf8String); this->createDefaultEntry(hex::format("\"{0}\" {1}", utf8String, size > this->getSize() ? "(truncated)" : ""), utf8String);
} }
@ -721,30 +740,31 @@ namespace hex::pl {
} }
[[nodiscard]] std::string toString(prv::Provider *provider) const override { [[nodiscard]] std::string toString(prv::Provider *provider) const override {
std::u16string buffer(this->getSize()/sizeof(char16_t), 0x00); std::u16string buffer(this->getSize() / sizeof(char16_t), 0x00);
provider->read(this->getOffset(), buffer.data(), this->getSize()); provider->read(this->getOffset(), buffer.data(), this->getSize());
for (auto &c : buffer) for (auto &c : buffer)
c = hex::changeEndianess(c, 2, this->getEndian()); c = hex::changeEndianess(c, 2, this->getEndian());
std::erase_if(buffer, [](auto c){ std::erase_if(buffer, [](auto c) {
return c == 0x00; return c == 0x00;
}); });
return std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t>{}.to_bytes(buffer); return std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> {}.to_bytes(buffer);
} }
[[nodiscard]] bool operator==(const PatternData &other) const override { return areCommonPropertiesEqual<decltype(*this)>(other); } [[nodiscard]] bool operator==(const PatternData &other) const override { return areCommonPropertiesEqual<decltype(*this)>(other); }
}; };
class PatternDataDynamicArray : public PatternData, public Inlinable { class PatternDataDynamicArray : public PatternData,
public Inlinable {
public: public:
PatternDataDynamicArray(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) PatternDataDynamicArray(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0)
: PatternData(offset, size, evaluator, color) { : PatternData(offset, size, evaluator, color) {
} }
PatternDataDynamicArray(const PatternDataDynamicArray &other) : PatternData(other) { PatternDataDynamicArray(const PatternDataDynamicArray &other) : PatternData(other) {
std::vector<PatternData*> entries; std::vector<PatternData *> entries;
for (const auto &entry : other.m_entries) for (const auto &entry : other.m_entries)
entries.push_back(entry->clone()); entries.push_back(entry->clone());
@ -756,7 +776,7 @@ namespace hex::pl {
delete entry; delete entry;
} }
PatternData* clone() override { PatternData *clone() override {
return new PatternDataDynamicArray(*this); return new PatternDataDynamicArray(*this);
} }
@ -766,7 +786,7 @@ namespace hex::pl {
entry->setColor(color); entry->setColor(color);
} }
void createEntry(prv::Provider* &provider) override { void createEntry(prv::Provider *&provider) override {
if (this->m_entries.empty()) if (this->m_entries.empty())
return; return;
@ -836,11 +856,11 @@ namespace hex::pl {
PatternData::setOffset(offset); PatternData::setOffset(offset);
} }
[[nodiscard]] const std::vector<PatternData*>& getEntries() { [[nodiscard]] const std::vector<PatternData *> &getEntries() {
return this->m_entries; return this->m_entries;
} }
void setEntries(const std::vector<PatternData*> &entries) { void setEntries(const std::vector<PatternData *> &entries) {
this->m_entries = entries; this->m_entries = entries;
if (this->hasOverriddenColor()) { if (this->hasOverriddenColor()) {
@ -854,7 +874,7 @@ namespace hex::pl {
if (!areCommonPropertiesEqual<decltype(*this)>(other)) if (!areCommonPropertiesEqual<decltype(*this)>(other))
return false; return false;
auto &otherArray = *static_cast<const PatternDataDynamicArray*>(&other); auto &otherArray = *static_cast<const PatternDataDynamicArray *>(&other);
if (this->m_entries.size() != otherArray.m_entries.size()) if (this->m_entries.size() != otherArray.m_entries.size())
return false; return false;
@ -866,11 +886,10 @@ namespace hex::pl {
return true; return true;
} }
[[nodiscard]] [[nodiscard]] const PatternData *getPattern(u64 offset) const override {
const PatternData* getPattern(u64 offset) const override {
if (this->isHidden()) return nullptr; if (this->isHidden()) return nullptr;
auto iter = std::find_if(this->m_entries.begin(), this->m_entries.end(), [this, offset](PatternData *pattern){ auto iter = std::find_if(this->m_entries.begin(), this->m_entries.end(), [this, offset](PatternData *pattern) {
return offset >= pattern->getOffset() && offset < (pattern->getOffset() + pattern->getSize()); return offset >= pattern->getOffset() && offset < (pattern->getOffset() + pattern->getSize());
}); });
@ -881,11 +900,12 @@ namespace hex::pl {
} }
private: private:
std::vector<PatternData*> m_entries; std::vector<PatternData *> m_entries;
u64 m_displayEnd = 50; u64 m_displayEnd = 50;
}; };
class PatternDataStaticArray : public PatternData, public Inlinable { class PatternDataStaticArray : public PatternData,
public Inlinable {
public: public:
PatternDataStaticArray(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) PatternDataStaticArray(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0)
: PatternData(offset, size, evaluator, color) { : PatternData(offset, size, evaluator, color) {
@ -900,11 +920,11 @@ namespace hex::pl {
delete this->m_highlightTemplate; delete this->m_highlightTemplate;
} }
PatternData* clone() override { PatternData *clone() override {
return new PatternDataStaticArray(*this); return new PatternDataStaticArray(*this);
} }
void createEntry(prv::Provider* &provider) override { void createEntry(prv::Provider *&provider) override {
if (this->getEntryCount() == 0) if (this->getEntryCount() == 0)
return; return;
@ -988,7 +1008,7 @@ namespace hex::pl {
return this->m_template->getTypeName() + "[" + std::to_string(this->m_entryCount) + "]"; return this->m_template->getTypeName() + "[" + std::to_string(this->m_entryCount) + "]";
} }
[[nodiscard]] PatternData* getTemplate() const { [[nodiscard]] PatternData *getTemplate() const {
return this->m_template; return this->m_template;
} }
@ -1000,7 +1020,7 @@ namespace hex::pl {
this->m_entryCount = count; this->m_entryCount = count;
} }
void setEntries(PatternData* templ, size_t count) { void setEntries(PatternData *templ, size_t count) {
this->m_template = templ; this->m_template = templ;
this->m_highlightTemplate = this->m_template->clone(); this->m_highlightTemplate = this->m_template->clone();
this->m_entryCount = count; this->m_entryCount = count;
@ -1013,12 +1033,11 @@ namespace hex::pl {
if (!areCommonPropertiesEqual<decltype(*this)>(other)) if (!areCommonPropertiesEqual<decltype(*this)>(other))
return false; return false;
auto &otherArray = *static_cast<const PatternDataStaticArray*>(&other); auto &otherArray = *static_cast<const PatternDataStaticArray *>(&other);
return *this->m_template == *otherArray.m_template && this->m_entryCount == otherArray.m_entryCount; return *this->m_template == *otherArray.m_template && this->m_entryCount == otherArray.m_entryCount;
} }
[[nodiscard]] [[nodiscard]] const PatternData *getPattern(u64 offset) const override {
const PatternData* getPattern(u64 offset) const override {
if (this->isHidden()) return nullptr; if (this->isHidden()) return nullptr;
if (offset >= this->getOffset() && offset < (this->getOffset() + this->getSize())) { if (offset >= this->getOffset() && offset < (this->getOffset() + this->getSize())) {
@ -1036,10 +1055,11 @@ namespace hex::pl {
u64 m_displayEnd = 50; u64 m_displayEnd = 50;
}; };
class PatternDataStruct : public PatternData, public Inlinable { class PatternDataStruct : public PatternData,
public Inlinable {
public: public:
PatternDataStruct(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) PatternDataStruct(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0)
: PatternData(offset, size, evaluator, color){ : PatternData(offset, size, evaluator, color) {
} }
PatternDataStruct(const PatternDataStruct &other) : PatternData(other) { PatternDataStruct(const PatternDataStruct &other) : PatternData(other) {
@ -1053,11 +1073,11 @@ namespace hex::pl {
delete member; delete member;
} }
PatternData* clone() override { PatternData *clone() override {
return new PatternDataStruct(*this); return new PatternDataStruct(*this);
} }
void createEntry(prv::Provider* &provider) override { void createEntry(prv::Provider *&provider) override {
bool open = true; bool open = true;
if (!this->isInlined()) { if (!this->isInlined()) {
@ -1071,7 +1091,9 @@ namespace hex::pl {
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TextFormatted("0x{0:04X}", this->getSize()); ImGui::TextFormatted("0x{0:04X}", this->getSize());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TextFormattedColored(ImColor(0xFFD69C56), "struct"); ImGui::SameLine(); ImGui::TextUnformatted(this->getTypeName().c_str()); ImGui::TextFormattedColored(ImColor(0xFFD69C56), "struct");
ImGui::SameLine();
ImGui::TextUnformatted(this->getTypeName().c_str());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TextFormatted("{}", this->formatDisplayValue("{ ... }", this)); ImGui::TextFormatted("{}", this->formatDisplayValue("{ ... }", this));
} }
@ -1083,7 +1105,6 @@ namespace hex::pl {
if (!this->isInlined()) if (!this->isInlined())
ImGui::TreePop(); ImGui::TreePop();
} }
} }
void getHighlightedAddresses(std::map<u64, u32> &highlight) const override { void getHighlightedAddresses(std::map<u64, u32> &highlight) const override {
@ -1120,11 +1141,11 @@ namespace hex::pl {
return "struct " + PatternData::getTypeName(); return "struct " + PatternData::getTypeName();
} }
[[nodiscard]] const auto& getMembers() const { [[nodiscard]] const auto &getMembers() const {
return this->m_members; return this->m_members;
} }
void setMembers(const std::vector<PatternData*> & members) { void setMembers(const std::vector<PatternData *> &members) {
this->m_members.clear(); this->m_members.clear();
for (auto &member : members) { for (auto &member : members) {
@ -1140,7 +1161,7 @@ namespace hex::pl {
if (!areCommonPropertiesEqual<decltype(*this)>(other)) if (!areCommonPropertiesEqual<decltype(*this)>(other))
return false; return false;
auto &otherStruct = *static_cast<const PatternDataStruct*>(&other); auto &otherStruct = *static_cast<const PatternDataStruct *>(&other);
if (this->m_members.size() != otherStruct.m_members.size()) if (this->m_members.size() != otherStruct.m_members.size())
return false; return false;
@ -1152,11 +1173,10 @@ namespace hex::pl {
return true; return true;
} }
[[nodiscard]] [[nodiscard]] const PatternData *getPattern(u64 offset) const override {
const PatternData* getPattern(u64 offset) const override {
if (this->isHidden()) return nullptr; if (this->isHidden()) return nullptr;
auto iter = std::find_if(this->m_members.begin(), this->m_members.end(), [offset](PatternData *pattern){ auto iter = std::find_if(this->m_members.begin(), this->m_members.end(), [offset](PatternData *pattern) {
return offset >= pattern->getOffset() && offset < (pattern->getOffset() + pattern->getSize()); return offset >= pattern->getOffset() && offset < (pattern->getOffset() + pattern->getSize());
}); });
@ -1167,15 +1187,15 @@ namespace hex::pl {
} }
private: private:
std::vector<PatternData*> m_members; std::vector<PatternData *> m_members;
std::vector<PatternData*> m_sortedMembers; std::vector<PatternData *> m_sortedMembers;
}; };
class PatternDataUnion : public PatternData, public Inlinable { class PatternDataUnion : public PatternData,
public Inlinable {
public: public:
PatternDataUnion(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) PatternDataUnion(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0)
: PatternData(offset, size, evaluator, color) { : PatternData(offset, size, evaluator, color) {
} }
PatternDataUnion(const PatternDataUnion &other) : PatternData(other) { PatternDataUnion(const PatternDataUnion &other) : PatternData(other) {
@ -1189,11 +1209,11 @@ namespace hex::pl {
delete member; delete member;
} }
PatternData* clone() override { PatternData *clone() override {
return new PatternDataUnion(*this); return new PatternDataUnion(*this);
} }
void createEntry(prv::Provider* &provider) override { void createEntry(prv::Provider *&provider) override {
bool open = true; bool open = true;
if (!this->isInlined()) { if (!this->isInlined()) {
@ -1207,7 +1227,9 @@ namespace hex::pl {
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TextFormatted("0x{0:04X}", this->getSize()); ImGui::TextFormatted("0x{0:04X}", this->getSize());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TextFormattedColored(ImColor(0xFFD69C56), "union"); ImGui::SameLine(); ImGui::TextUnformatted(PatternData::getTypeName().c_str()); ImGui::TextFormattedColored(ImColor(0xFFD69C56), "union");
ImGui::SameLine();
ImGui::TextUnformatted(PatternData::getTypeName().c_str());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TextFormatted("{}", this->formatDisplayValue("{ ... }", this)); ImGui::TextFormatted("{}", this->formatDisplayValue("{ ... }", this));
@ -1220,7 +1242,6 @@ namespace hex::pl {
if (!this->isInlined()) if (!this->isInlined())
ImGui::TreePop(); ImGui::TreePop();
} }
} }
void getHighlightedAddresses(std::map<u64, u32> &highlight) const override { void getHighlightedAddresses(std::map<u64, u32> &highlight) const override {
@ -1254,14 +1275,15 @@ namespace hex::pl {
} }
[[nodiscard]] std::string getFormattedName() const override { [[nodiscard]] std::string getFormattedName() const override {
return "union " + PatternData::getTypeName();; return "union " + PatternData::getTypeName();
;
} }
[[nodiscard]] const auto& getMembers() const { [[nodiscard]] const auto &getMembers() const {
return this->m_members; return this->m_members;
} }
void setMembers(const std::vector<PatternData*> & members) { void setMembers(const std::vector<PatternData *> &members) {
this->m_members.clear(); this->m_members.clear();
for (auto &member : members) { for (auto &member : members) {
if (member == nullptr) continue; if (member == nullptr) continue;
@ -1276,7 +1298,7 @@ namespace hex::pl {
if (!areCommonPropertiesEqual<decltype(*this)>(other)) if (!areCommonPropertiesEqual<decltype(*this)>(other))
return false; return false;
auto &otherUnion = *static_cast<const PatternDataUnion*>(&other); auto &otherUnion = *static_cast<const PatternDataUnion *>(&other);
if (this->m_members.size() != otherUnion.m_members.size()) if (this->m_members.size() != otherUnion.m_members.size())
return false; return false;
@ -1288,8 +1310,7 @@ namespace hex::pl {
return true; return true;
} }
[[nodiscard]] [[nodiscard]] const PatternData *getPattern(u64 offset) const override {
const PatternData* getPattern(u64 offset) const override {
if (this->isHidden()) return nullptr; if (this->isHidden()) return nullptr;
auto largestMember = std::find_if(this->m_members.begin(), this->m_members.end(), [this](PatternData *pattern) { auto largestMember = std::find_if(this->m_members.begin(), this->m_members.end(), [this](PatternData *pattern) {
@ -1299,26 +1320,26 @@ namespace hex::pl {
if (largestMember == this->m_members.end()) if (largestMember == this->m_members.end())
return nullptr; return nullptr;
else else
return (*largestMember)->getPattern(offset);; return (*largestMember)->getPattern(offset);
;
} }
private: private:
std::vector<PatternData*> m_members; std::vector<PatternData *> m_members;
std::vector<PatternData*> m_sortedMembers; std::vector<PatternData *> m_sortedMembers;
}; };
class PatternDataEnum : public PatternData { class PatternDataEnum : public PatternData {
public: public:
PatternDataEnum(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) PatternDataEnum(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0)
: PatternData(offset, size, evaluator, color) { : PatternData(offset, size, evaluator, color) {
} }
PatternData* clone() override { PatternData *clone() override {
return new PatternDataEnum(*this); return new PatternDataEnum(*this);
} }
void createEntry(prv::Provider* &provider) override { void createEntry(prv::Provider *&provider) override {
u64 value = 0; u64 value = 0;
provider->read(this->getOffset(), &value, this->getSize()); provider->read(this->getOffset(), &value, this->getSize());
value = hex::changeEndianess(value, this->getSize(), this->getEndian()); value = hex::changeEndianess(value, this->getSize(), this->getEndian());
@ -1338,8 +1359,8 @@ namespace hex::pl {
return false; return false;
}, },
[](std::string) { return false; }, [](std::string) { return false; },
[](PatternData*) { return false; } [](PatternData *) { return false; } },
}, entryValueLiteral); entryValueLiteral);
if (matches) if (matches)
break; break;
} }
@ -1363,7 +1384,9 @@ namespace hex::pl {
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TextFormatted("0x{0:04X}", this->getSize()); ImGui::TextFormatted("0x{0:04X}", this->getSize());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TextFormattedColored(ImColor(0xFFD69C56), "enum"); ImGui::SameLine(); ImGui::TextUnformatted(PatternData::getTypeName().c_str()); ImGui::TextFormattedColored(ImColor(0xFFD69C56), "enum");
ImGui::SameLine();
ImGui::TextUnformatted(PatternData::getTypeName().c_str());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TextFormatted("{}", this->formatDisplayValue(hex::format("{} (0x{:0{}X})", valueString.c_str(), value, this->getSize() * 2), this)); ImGui::TextFormatted("{}", this->formatDisplayValue(hex::format("{} (0x{:0{}X})", valueString.c_str(), value, this->getSize() * 2), this));
} }
@ -1372,7 +1395,7 @@ namespace hex::pl {
return "enum " + PatternData::getTypeName(); return "enum " + PatternData::getTypeName();
} }
[[nodiscard]] const auto& getEnumValues() const { [[nodiscard]] const auto &getEnumValues() const {
return this->m_enumValues; return this->m_enumValues;
} }
@ -1384,7 +1407,7 @@ namespace hex::pl {
if (!areCommonPropertiesEqual<decltype(*this)>(other)) if (!areCommonPropertiesEqual<decltype(*this)>(other))
return false; return false;
auto &otherEnum = *static_cast<const PatternDataEnum*>(&other); auto &otherEnum = *static_cast<const PatternDataEnum *>(&other);
if (this->m_enumValues.size() != otherEnum.m_enumValues.size()) if (this->m_enumValues.size() != otherEnum.m_enumValues.size())
return false; return false;
@ -1405,14 +1428,13 @@ namespace hex::pl {
public: public:
PatternDataBitfieldField(u64 offset, u8 bitOffset, u8 bitSize, PatternData *bitField, Evaluator *evaluator, u32 color = 0) PatternDataBitfieldField(u64 offset, u8 bitOffset, u8 bitSize, PatternData *bitField, Evaluator *evaluator, u32 color = 0)
: m_bitOffset(bitOffset), m_bitSize(bitSize), m_bitField(bitField), PatternData(offset, 0, evaluator, color) { : m_bitOffset(bitOffset), m_bitSize(bitSize), m_bitField(bitField), PatternData(offset, 0, evaluator, color) {
} }
PatternData* clone() override { PatternData *clone() override {
return new PatternDataBitfieldField(*this); return new PatternDataBitfieldField(*this);
} }
void createEntry(prv::Provider* &provider) override { void createEntry(prv::Provider *&provider) override {
std::vector<u8> value(this->m_bitField->getSize(), 0); std::vector<u8> value(this->m_bitField->getSize(), 0);
provider->read(this->m_bitField->getOffset(), &value[0], value.size()); provider->read(this->m_bitField->getOffset(), &value[0], value.size());
@ -1443,7 +1465,6 @@ namespace hex::pl {
u64 extractedValue = hex::extract(this->m_bitOffset + (this->m_bitSize - 1), this->m_bitOffset, value); u64 extractedValue = hex::extract(this->m_bitOffset + (this->m_bitSize - 1), this->m_bitOffset, value);
ImGui::TextFormatted("{}", this->formatDisplayValue(hex::format("{0} (0x{1:X})", extractedValue, extractedValue), this)); ImGui::TextFormatted("{}", this->formatDisplayValue(hex::format("{0} (0x{1:X})", extractedValue, extractedValue), this));
} }
} }
[[nodiscard]] std::string getFormattedName() const override { [[nodiscard]] std::string getFormattedName() const override {
@ -1462,7 +1483,7 @@ namespace hex::pl {
if (!areCommonPropertiesEqual<decltype(*this)>(other)) if (!areCommonPropertiesEqual<decltype(*this)>(other))
return false; return false;
auto &otherBitfieldField = *static_cast<const PatternDataBitfieldField*>(&other); auto &otherBitfieldField = *static_cast<const PatternDataBitfieldField *>(&other);
return this->m_bitOffset == otherBitfieldField.m_bitOffset && this->m_bitSize == otherBitfieldField.m_bitSize; return this->m_bitOffset == otherBitfieldField.m_bitOffset && this->m_bitSize == otherBitfieldField.m_bitSize;
} }
@ -1471,11 +1492,11 @@ namespace hex::pl {
PatternData *m_bitField; PatternData *m_bitField;
}; };
class PatternDataBitfield : public PatternData, public Inlinable { class PatternDataBitfield : public PatternData,
public Inlinable {
public: public:
PatternDataBitfield(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0) PatternDataBitfield(u64 offset, size_t size, Evaluator *evaluator, u32 color = 0)
: PatternData(offset, size, evaluator, color) { : PatternData(offset, size, evaluator, color) {
} }
PatternDataBitfield(const PatternDataBitfield &other) : PatternData(other) { PatternDataBitfield(const PatternDataBitfield &other) : PatternData(other) {
@ -1488,11 +1509,11 @@ namespace hex::pl {
delete field; delete field;
} }
PatternData* clone() override { PatternData *clone() override {
return new PatternDataBitfield(*this); return new PatternDataBitfield(*this);
} }
void createEntry(prv::Provider* &provider) override { void createEntry(prv::Provider *&provider) override {
std::vector<u8> value(this->getSize(), 0); std::vector<u8> value(this->getSize(), 0);
provider->read(this->getOffset(), &value[0], value.size()); provider->read(this->getOffset(), &value[0], value.size());
@ -1511,7 +1532,9 @@ namespace hex::pl {
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TextFormatted("0x{0:04X}", this->getSize()); ImGui::TextFormatted("0x{0:04X}", this->getSize());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui::TextFormattedColored(ImColor(0xFFD69C56), "bitfield"); ImGui::SameLine(); ImGui::TextUnformatted(PatternData::getTypeName().c_str()); ImGui::TextFormattedColored(ImColor(0xFFD69C56), "bitfield");
ImGui::SameLine();
ImGui::TextUnformatted(PatternData::getTypeName().c_str());
ImGui::TableNextColumn(); ImGui::TableNextColumn();
std::string valueString = "{ "; std::string valueString = "{ ";
@ -1530,7 +1553,6 @@ namespace hex::pl {
if (!this->isInlined()) if (!this->isInlined())
ImGui::TreePop(); ImGui::TreePop();
} }
} }
void setOffset(u64 offset) override { void setOffset(u64 offset) override {
@ -1544,11 +1566,11 @@ namespace hex::pl {
return "bitfield " + PatternData::getTypeName(); return "bitfield " + PatternData::getTypeName();
} }
[[nodiscard]] const auto& getFields() const { [[nodiscard]] const auto &getFields() const {
return this->m_fields; return this->m_fields;
} }
void setFields(const std::vector<PatternData*> &fields) { void setFields(const std::vector<PatternData *> &fields) {
this->m_fields = fields; this->m_fields = fields;
for (auto &field : this->m_fields) { for (auto &field : this->m_fields) {
@ -1567,7 +1589,7 @@ namespace hex::pl {
if (!areCommonPropertiesEqual<decltype(*this)>(other)) if (!areCommonPropertiesEqual<decltype(*this)>(other))
return false; return false;
auto &otherBitfield = *static_cast<const PatternDataBitfield*>(&other); auto &otherBitfield = *static_cast<const PatternDataBitfield *>(&other);
if (this->m_fields.size() != otherBitfield.m_fields.size()) if (this->m_fields.size() != otherBitfield.m_fields.size())
return false; return false;
@ -1580,7 +1602,7 @@ namespace hex::pl {
} }
private: private:
std::vector<PatternData*> m_fields; std::vector<PatternData *> m_fields;
}; };
} }

View File

@ -12,7 +12,9 @@
#include <hex/pattern_language/log_console.hpp> #include <hex/pattern_language/log_console.hpp>
#include <hex/pattern_language/token.hpp> #include <hex/pattern_language/token.hpp>
namespace hex::prv { class Provider; } namespace hex::prv {
class Provider;
}
namespace hex::pl { namespace hex::pl {
@ -30,31 +32,21 @@ namespace hex::pl {
PatternLanguage(); PatternLanguage();
~PatternLanguage(); ~PatternLanguage();
[[nodiscard]] [[nodiscard]] std::optional<std::vector<ASTNode *>> parseString(const std::string &code);
std::optional<std::vector<ASTNode*>> parseString(const std::string &code); [[nodiscard]] std::optional<std::vector<PatternData *>> executeString(prv::Provider *provider, const std::string &string, const std::map<std::string, Token::Literal> &envVars = {}, const std::map<std::string, Token::Literal> &inVariables = {});
[[nodiscard]] [[nodiscard]] std::optional<std::vector<PatternData *>> executeFile(prv::Provider *provider, const fs::path &path, const std::map<std::string, Token::Literal> &envVars = {}, const std::map<std::string, Token::Literal> &inVariables = {});
std::optional<std::vector<PatternData*>> executeString(prv::Provider *provider, const std::string &string, const std::map<std::string, Token::Literal> &envVars = { }, const std::map<std::string, Token::Literal> &inVariables = { }); [[nodiscard]] const std::vector<ASTNode *> &getCurrentAST() const;
[[nodiscard]]
std::optional<std::vector<PatternData*>> executeFile(prv::Provider *provider, const fs::path &path, const std::map<std::string, Token::Literal> &envVars = { }, const std::map<std::string, Token::Literal> &inVariables = { });
[[nodiscard]]
const std::vector<ASTNode*>& getCurrentAST() const;
void abort(); void abort();
[[nodiscard]] [[nodiscard]] const std::vector<std::pair<LogConsole::Level, std::string>> &getConsoleLog();
const std::vector<std::pair<LogConsole::Level, std::string>>& getConsoleLog(); [[nodiscard]] const std::optional<std::pair<u32, std::string>> &getError();
[[nodiscard]] [[nodiscard]] std::map<std::string, Token::Literal> getOutVariables() const;
const std::optional<std::pair<u32, std::string>>& getError();
[[nodiscard]]
std::map<std::string, Token::Literal> getOutVariables() const;
[[nodiscard]] [[nodiscard]] u32 getCreatedPatternCount();
u32 getCreatedPatternCount(); [[nodiscard]] u32 getMaximumPatternCount();
[[nodiscard]]
u32 getMaximumPatternCount();
[[nodiscard]] [[nodiscard]] bool hasDangerousFunctionBeenCalled() const;
bool hasDangerousFunctionBeenCalled() const;
void allowDangerousFunctions(bool allow); void allowDangerousFunctions(bool allow);
private: private:
@ -64,7 +56,7 @@ namespace hex::pl {
Validator *m_validator; Validator *m_validator;
Evaluator *m_evaluator; Evaluator *m_evaluator;
std::vector<ASTNode*> m_currAST; std::vector<ASTNode *> m_currAST;
std::optional<std::pair<u32, std::string>> m_currError; std::optional<std::pair<u32, std::string>> m_currError;
}; };

View File

@ -15,12 +15,12 @@ namespace hex::pl {
public: public:
Preprocessor(); Preprocessor();
std::optional<std::string> preprocess(const std::string& code, bool initialRun = true); std::optional<std::string> preprocess(const std::string &code, bool initialRun = true);
void addPragmaHandler(const std::string &pragmaType, const std::function<bool(const std::string&)> &function); void addPragmaHandler(const std::string &pragmaType, const std::function<bool(const std::string &)> &function);
void addDefaultPragmaHandlers(); void addDefaultPragmaHandlers();
const std::pair<u32, std::string>& getError() { return this->m_error; } const std::pair<u32, std::string> &getError() { return this->m_error; }
private: private:
using PreprocessorError = std::pair<u32, std::string>; using PreprocessorError = std::pair<u32, std::string>;

View File

@ -123,21 +123,19 @@ namespace hex::pl {
struct Identifier { struct Identifier {
explicit Identifier(std::string identifier) : m_identifier(std::move(identifier)) { } explicit Identifier(std::string identifier) : m_identifier(std::move(identifier)) { }
[[nodiscard]] [[nodiscard]] const std::string &get() const { return this->m_identifier; }
const std::string &get() const { return this->m_identifier; }
auto operator<=>(const Identifier&) const = default; auto operator<=>(const Identifier &) const = default;
bool operator==(const Identifier&) const = default; bool operator==(const Identifier &) const = default;
private: private:
std::string m_identifier; std::string m_identifier;
}; };
using Literal = std::variant<char, bool, u128, i128, double, std::string, PatternData*>; using Literal = std::variant<char, bool, u128, i128, double, std::string, PatternData *>;
using ValueTypes = std::variant<Keyword, Identifier, Operator, Literal, ValueType, Separator>; using ValueTypes = std::variant<Keyword, Identifier, Operator, Literal, ValueType, Separator>;
Token(Type type, auto value, u32 lineNumber) : type(type), value(value), lineNumber(lineNumber) { Token(Type type, auto value, u32 lineNumber) : type(type), value(value), lineNumber(lineNumber) {
} }
[[nodiscard]] constexpr static inline bool isUnsigned(const ValueType type) { [[nodiscard]] constexpr static inline bool isUnsigned(const ValueType type) {
@ -159,36 +157,32 @@ namespace hex::pl {
static u128 literalToUnsigned(const pl::Token::Literal &literal) { static u128 literalToUnsigned(const pl::Token::Literal &literal) {
return std::visit(overloaded { return std::visit(overloaded {
[](std::string) -> u128 { throw std::string("expected integral type, got string"); }, [](std::string) -> u128 { throw std::string("expected integral type, got string"); },
[](PatternData*) -> u128 { throw std::string("expected integral type, got custom type"); }, [](PatternData *) -> u128 { throw std::string("expected integral type, got custom type"); },
[](auto &&value) -> u128 { return value; } [](auto &&value) -> u128 { return value; } },
},
literal); literal);
} }
static i128 literalToSigned(const pl::Token::Literal &literal) { static i128 literalToSigned(const pl::Token::Literal &literal) {
return std::visit(overloaded { return std::visit(overloaded {
[](std::string) -> i128 { throw std::string("expected integral type, got string"); }, [](std::string) -> i128 { throw std::string("expected integral type, got string"); },
[](PatternData*) -> i128 { throw std::string("expected integral type, got custom type"); }, [](PatternData *) -> i128 { throw std::string("expected integral type, got custom type"); },
[](auto &&value) -> i128 { return value; } [](auto &&value) -> i128 { return value; } },
},
literal); literal);
} }
static double literalToFloatingPoint(const pl::Token::Literal &literal) { static double literalToFloatingPoint(const pl::Token::Literal &literal) {
return std::visit(overloaded { return std::visit(overloaded {
[](std::string) -> double { throw std::string("expected integral type, got string"); }, [](std::string) -> double { throw std::string("expected integral type, got string"); },
[](PatternData*) -> double { throw std::string("expected integral type, got custom type"); }, [](PatternData *) -> double { throw std::string("expected integral type, got custom type"); },
[](auto &&value) -> double { return value; } [](auto &&value) -> double { return value; } },
},
literal); literal);
} }
static bool literalToBoolean(const pl::Token::Literal &literal) { static bool literalToBoolean(const pl::Token::Literal &literal) {
return std::visit(overloaded { return std::visit(overloaded {
[](std::string) -> bool { throw std::string("expected integral type, got string"); }, [](std::string) -> bool { throw std::string("expected integral type, got string"); },
[](PatternData*) -> bool { throw std::string("expected integral type, got custom type"); }, [](PatternData *) -> bool { throw std::string("expected integral type, got custom type"); },
[](auto &&value) -> bool { return value != 0; } [](auto &&value) -> bool { return value != 0; } },
},
literal); literal);
} }
@ -202,31 +196,47 @@ namespace hex::pl {
[](i128 value) -> std::string { return std::to_string(i64(value)); }, [](i128 value) -> std::string { return std::to_string(i64(value)); },
[](bool value) -> std::string { return value ? "true" : "false"; }, [](bool value) -> std::string { return value ? "true" : "false"; },
[](char value) -> std::string { return std::string() + value; }, [](char value) -> std::string { return std::string() + value; },
[](PatternData*) -> std::string { throw std::string("expected integral type, got custom type"); }, [](PatternData *) -> std::string { throw std::string("expected integral type, got custom type"); },
[](auto &&value) -> std::string { return std::to_string(value); } [](auto &&value) -> std::string { return std::to_string(value); } },
},
literal); literal);
} }
[[nodiscard]] constexpr static auto getTypeName(const pl::Token::ValueType type) { [[nodiscard]] constexpr static auto getTypeName(const pl::Token::ValueType type) {
switch (type) { switch (type) {
case ValueType::Signed8Bit: return "s8"; case ValueType::Signed8Bit:
case ValueType::Signed16Bit: return "s16"; return "s8";
case ValueType::Signed32Bit: return "s32"; case ValueType::Signed16Bit:
case ValueType::Signed64Bit: return "s64"; return "s16";
case ValueType::Signed128Bit: return "s128"; case ValueType::Signed32Bit:
case ValueType::Unsigned8Bit: return "u8"; return "s32";
case ValueType::Unsigned16Bit: return "u16"; case ValueType::Signed64Bit:
case ValueType::Unsigned32Bit: return "u32"; return "s64";
case ValueType::Unsigned64Bit: return "u64"; case ValueType::Signed128Bit:
case ValueType::Unsigned128Bit: return "u128"; return "s128";
case ValueType::Float: return "float"; case ValueType::Unsigned8Bit:
case ValueType::Double: return "double"; return "u8";
case ValueType::Character: return "char"; case ValueType::Unsigned16Bit:
case ValueType::Character16: return "char16"; return "u16";
case ValueType::Padding: return "padding"; case ValueType::Unsigned32Bit:
case ValueType::String: return "str"; return "u32";
default: return "< ??? >"; case ValueType::Unsigned64Bit:
return "u64";
case ValueType::Unsigned128Bit:
return "u128";
case ValueType::Float:
return "float";
case ValueType::Double:
return "double";
case ValueType::Character:
return "char";
case ValueType::Character16:
return "char16";
case ValueType::Padding:
return "padding";
case ValueType::String:
return "str";
default:
return "< ??? >";
} }
} }
@ -252,8 +262,7 @@ namespace hex::pl {
return isFloatingPoint(*valueType); return isFloatingPoint(*valueType);
else if (*otherValueType == ValueType::Integer) else if (*otherValueType == ValueType::Integer)
return isUnsigned(*valueType) || isSigned(*valueType); return isUnsigned(*valueType) || isSigned(*valueType);
} } else
else
return other == this->value; return other == this->value;
return false; return false;
@ -266,7 +275,6 @@ namespace hex::pl {
Type type; Type type;
ValueTypes value; ValueTypes value;
u32 lineNumber; u32 lineNumber;
}; };
} }

View File

@ -13,9 +13,9 @@ namespace hex::pl {
public: public:
Validator(); Validator();
bool validate(const std::vector<ASTNode*>& ast); bool validate(const std::vector<ASTNode *> &ast);
const std::pair<u32, std::string>& getError() { return this->m_error; } const std::pair<u32, std::string> &getError() { return this->m_error; }
private: private:
std::pair<u32, std::string> m_error; std::pair<u32, std::string> m_error;
@ -25,7 +25,6 @@ namespace hex::pl {
[[noreturn]] void throwValidateError(std::string_view error, u32 lineNumber) const { [[noreturn]] void throwValidateError(std::string_view error, u32 lineNumber) const {
throw ValidatorError(lineNumber, error); throw ValidatorError(lineNumber, error);
} }
}; };
} }

View File

@ -9,9 +9,12 @@
#define IMHEX_PLUGIN_SETUP(name, author, description) IMHEX_PLUGIN_SETUP_IMPL(IMHEX_PLUGIN_NAME, name, author, description) #define IMHEX_PLUGIN_SETUP(name, author, description) IMHEX_PLUGIN_SETUP_IMPL(IMHEX_PLUGIN_NAME, name, author, description)
#define IMHEX_PLUGIN_SETUP_IMPL(namespaceName, name, author, description) \ #define IMHEX_PLUGIN_SETUP_IMPL(namespaceName, name, author, description) \
extern "C" [[gnu::visibility("default")]] const char* getPluginName() { return name; } \ extern "C" [[gnu::visibility("default")]] const char *getPluginName() { return name; } \
extern "C" [[gnu::visibility("default")]] const char* getPluginAuthor() { return author; } \ extern "C" [[gnu::visibility("default")]] const char *getPluginAuthor() { return author; } \
extern "C" [[gnu::visibility("default")]] const char* getPluginDescription() { return description; } \ extern "C" [[gnu::visibility("default")]] const char *getPluginDescription() { return description; } \
extern "C" [[gnu::visibility("default")]] const char* getCompatibleVersion() { return IMHEX_VERSION; } \ extern "C" [[gnu::visibility("default")]] const char *getCompatibleVersion() { return IMHEX_VERSION; } \
extern "C" [[gnu::visibility("default")]] void setImGuiContext(ImGuiContext *ctx) { ImGui::SetCurrentContext(ctx); GImGui = ctx; } \ extern "C" [[gnu::visibility("default")]] void setImGuiContext(ImGuiContext *ctx) { \
ImGui::SetCurrentContext(ctx); \
GImGui = ctx; \
} \
extern "C" [[gnu::visibility("default")]] void initializePlugin() extern "C" [[gnu::visibility("default")]] void initializePlugin()

View File

@ -14,7 +14,7 @@ namespace hex::prv {
[[nodiscard]] u64 getAddress() const { return this->m_address; } [[nodiscard]] u64 getAddress() const { return this->m_address; }
[[nodiscard]] u64 getSize() const { return this->m_data.size(); } [[nodiscard]] u64 getSize() const { return this->m_data.size(); }
[[nodiscard]] std::vector<u8>& getData() { return this->m_data; } [[nodiscard]] std::vector<u8> &getData() { return this->m_data; }
private: private:
u64 m_address = 0; u64 m_address = 0;

View File

@ -40,13 +40,13 @@ namespace hex::prv {
void applyOverlays(u64 offset, void *buffer, size_t size); void applyOverlays(u64 offset, void *buffer, size_t size);
[[nodiscard]] std::map<u64, u8>& getPatches(); [[nodiscard]] std::map<u64, u8> &getPatches();
[[nodiscard]] const std::map<u64, u8>& getPatches() const; [[nodiscard]] const std::map<u64, u8> &getPatches() const;
void applyPatches(); void applyPatches();
[[nodiscard]] Overlay* newOverlay(); [[nodiscard]] Overlay *newOverlay();
void deleteOverlay(Overlay *overlay); void deleteOverlay(Overlay *overlay);
[[nodiscard]] const std::list<Overlay*>& getOverlays(); [[nodiscard]] const std::list<Overlay *> &getOverlays();
[[nodiscard]] u32 getPageCount() const; [[nodiscard]] u32 getPageCount() const;
[[nodiscard]] u32 getCurrentPage() const; [[nodiscard]] u32 getCurrentPage() const;
@ -84,7 +84,7 @@ namespace hex::prv {
u32 m_patchTreeOffset = 0; u32 m_patchTreeOffset = 0;
std::list<std::map<u64, u8>> m_patches; std::list<std::map<u64, u8>> m_patches;
std::list<Overlay*> m_overlays; std::list<Overlay *> m_overlays;
}; };
} }

View File

@ -32,42 +32,39 @@ namespace ImGui {
ImTextureID textureId; ImTextureID textureId;
int width, height; int width, height;
[[nodiscard]] [[nodiscard]] constexpr bool valid() const noexcept {
constexpr bool valid() const noexcept {
return this->textureId != nullptr; return this->textureId != nullptr;
} }
[[nodiscard]] [[nodiscard]] constexpr operator ImTextureID() {
constexpr operator ImTextureID() {
return this->textureId; return this->textureId;
} }
[[nodiscard]] [[nodiscard]] auto size() const noexcept {
auto size() const noexcept {
return ImVec2(this->width, this->height); return ImVec2(this->width, this->height);
} }
}; };
int UpdateStringSizeCallback(ImGuiInputTextCallbackData *data); int UpdateStringSizeCallback(ImGuiInputTextCallbackData *data);
bool IconHyperlink(const char *icon, const char* label, const ImVec2& size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); bool IconHyperlink(const char *icon, const char *label, const ImVec2 &size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0);
bool Hyperlink(const char* label, const ImVec2& size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); bool Hyperlink(const char *label, const ImVec2 &size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0);
bool BulletHyperlink(const char* label, const ImVec2& size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); bool BulletHyperlink(const char *label, const ImVec2 &size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0);
bool DescriptionButton(const char* label, const char* description, const ImVec2& size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0); bool DescriptionButton(const char *label, const char *description, const ImVec2 &size_arg = ImVec2(0, 0), ImGuiButtonFlags flags = 0);
void UnderlinedText(const char* label, ImColor color = ImGui::GetStyleColorVec4(ImGuiCol_Text), const ImVec2& size_arg = ImVec2(0, 0)); void UnderlinedText(const char *label, ImColor color = ImGui::GetStyleColorVec4(ImGuiCol_Text), const ImVec2 &size_arg = ImVec2(0, 0));
void Disabled(const std::function<void()> &widgets, bool disabled); void Disabled(const std::function<void()> &widgets, bool disabled);
void TextSpinner(const char* label); void TextSpinner(const char *label);
void Header(const char *label, bool firstEntry = false); void Header(const char *label, bool firstEntry = false);
void HeaderColored(const char *label, ImColor color, bool firstEntry); void HeaderColored(const char *label, ImColor color, bool firstEntry);
void InfoTooltip(const char *text); void InfoTooltip(const char *text);
bool TitleBarButton(const char* label, ImVec2 size_arg); bool TitleBarButton(const char *label, ImVec2 size_arg);
bool ToolBarButton(const char* symbol, ImVec4 color); bool ToolBarButton(const char *symbol, ImVec4 color);
bool IconButton(const char* symbol, ImVec4 color, ImVec2 size_arg = ImVec2(0, 0)); bool IconButton(const char *symbol, ImVec4 color, ImVec2 size_arg = ImVec2(0, 0));
inline bool HasSecondPassed() { inline bool HasSecondPassed() {
return static_cast<ImU32>(ImGui::GetTime() * 100) % 100 <= static_cast<ImU32>(ImGui::GetIO().DeltaTime * 100); return static_cast<ImU32>(ImGui::GetTime() * 100) % 100 <= static_cast<ImU32>(ImGui::GetIO().DeltaTime * 100);
@ -92,23 +89,23 @@ namespace ImGui {
void SmallProgressBar(float fraction, float yOffset = 0.0F); void SmallProgressBar(float fraction, float yOffset = 0.0F);
void TextFormatted(const std::string &fmt, auto&& ... args) { void TextFormatted(const std::string &fmt, auto &&...args) {
ImGui::TextUnformatted(hex::format(fmt, std::forward<decltype(args)>(args)...).c_str()); ImGui::TextUnformatted(hex::format(fmt, std::forward<decltype(args)>(args)...).c_str());
} }
void TextFormattedColored(ImColor color, const std::string &fmt, auto&& ... args) { void TextFormattedColored(ImColor color, const std::string &fmt, auto &&...args) {
ImGui::TextColored(color, "%s", hex::format(fmt, std::forward<decltype(args)>(args)...).c_str()); ImGui::TextColored(color, "%s", hex::format(fmt, std::forward<decltype(args)>(args)...).c_str());
} }
void TextFormattedDisabled(const std::string &fmt, auto&& ... args) { void TextFormattedDisabled(const std::string &fmt, auto &&...args) {
ImGui::TextDisabled("%s", hex::format(fmt, std::forward<decltype(args)>(args)...).c_str()); ImGui::TextDisabled("%s", hex::format(fmt, std::forward<decltype(args)>(args)...).c_str());
} }
void TextFormattedWrapped(const std::string &fmt, auto&& ... args) { void TextFormattedWrapped(const std::string &fmt, auto &&...args) {
ImGui::TextWrapped("%s", hex::format(fmt, std::forward<decltype(args)>(args)...).c_str()); ImGui::TextWrapped("%s", hex::format(fmt, std::forward<decltype(args)>(args)...).c_str());
} }
void TextFormattedCentered(const std::string &fmt, auto&& ... args) { void TextFormattedCentered(const std::string &fmt, auto &&...args) {
auto text = hex::format(fmt); auto text = hex::format(fmt);
auto availableSpace = ImGui::GetContentRegionAvail(); auto availableSpace = ImGui::GetContentRegionAvail();
auto textSize = ImGui::CalcTextSize(text.c_str(), nullptr, false, availableSpace.x * 0.75F); auto textSize = ImGui::CalcTextSize(text.c_str(), nullptr, false, availableSpace.x * 0.75F);

View File

@ -36,7 +36,7 @@ namespace hex {
virtual bool shouldProcess() const { return this->isAvailable() && this->getWindowOpenState(); } virtual bool shouldProcess() const { return this->isAvailable() && this->getWindowOpenState(); }
static void doLater(std::function<void()> &&function); static void doLater(std::function<void()> &&function);
static std::vector<std::function<void()>>& getDeferedCalls(); static std::vector<std::function<void()>> &getDeferedCalls();
static void drawCommonInterfaces(); static void drawCommonInterfaces();
@ -50,10 +50,10 @@ namespace hex {
virtual ImVec2 getMinSize() const; virtual ImVec2 getMinSize() const;
virtual ImVec2 getMaxSize() const; virtual ImVec2 getMaxSize() const;
bool& getWindowOpenState(); bool &getWindowOpenState();
const bool& getWindowOpenState() const; const bool &getWindowOpenState() const;
[[nodiscard]] const std::string& getUnlocalizedName() const; [[nodiscard]] const std::string &getUnlocalizedName() const;
[[nodiscard]] std::string getName() const; [[nodiscard]] std::string getName() const;
static void confirmButtons(const std::string &textLeft, const std::string &textRight, const std::function<void()> &leftButtonFn, const std::function<void()> &rightButtonFn); static void confirmButtons(const std::string &textLeft, const std::string &textRight, const std::function<void()> &leftButtonFn, const std::function<void()> &rightButtonFn);

View File

@ -43,7 +43,7 @@ namespace hex {
void ContentRegistry::Settings::add(const std::string &unlocalizedCategory, const std::string &unlocalizedName, i64 defaultValue, const ContentRegistry::Settings::Callback &callback) { void ContentRegistry::Settings::add(const std::string &unlocalizedCategory, const std::string &unlocalizedName, i64 defaultValue, const ContentRegistry::Settings::Callback &callback) {
log::info("Registered new integer setting: [{}]: {}", unlocalizedCategory, unlocalizedName); log::info("Registered new integer setting: [{}]: {}", unlocalizedCategory, unlocalizedName);
ContentRegistry::Settings::getEntries()[unlocalizedCategory.c_str()].emplace_back(Entry{ unlocalizedName.c_str(), callback }); ContentRegistry::Settings::getEntries()[unlocalizedCategory.c_str()].emplace_back(Entry { unlocalizedName.c_str(), callback });
auto &json = getSettingsData(); auto &json = getSettingsData();
@ -56,7 +56,7 @@ namespace hex {
void ContentRegistry::Settings::add(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::string &defaultValue, const ContentRegistry::Settings::Callback &callback) { void ContentRegistry::Settings::add(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::string &defaultValue, const ContentRegistry::Settings::Callback &callback) {
log::info("Registered new string setting: [{}]: {}", unlocalizedCategory, unlocalizedName); log::info("Registered new string setting: [{}]: {}", unlocalizedCategory, unlocalizedName);
ContentRegistry::Settings::getEntries()[unlocalizedCategory].emplace_back(Entry{ unlocalizedName, callback }); ContentRegistry::Settings::getEntries()[unlocalizedCategory].emplace_back(Entry { unlocalizedName, callback });
auto &json = getSettingsData(); auto &json = getSettingsData();
@ -84,7 +84,7 @@ namespace hex {
json[unlocalizedCategory][unlocalizedName] = value; json[unlocalizedCategory][unlocalizedName] = value;
} }
void ContentRegistry::Settings::write(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector<std::string>& value) { void ContentRegistry::Settings::write(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector<std::string> &value) {
auto &json = getSettingsData(); auto &json = getSettingsData();
if (!json.contains(unlocalizedCategory)) if (!json.contains(unlocalizedCategory))
@ -122,7 +122,7 @@ namespace hex {
return json[unlocalizedCategory][unlocalizedName].get<std::string>(); return json[unlocalizedCategory][unlocalizedName].get<std::string>();
} }
std::vector<std::string> ContentRegistry::Settings::read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector<std::string>& defaultValue) { std::vector<std::string> ContentRegistry::Settings::read(const std::string &unlocalizedCategory, const std::string &unlocalizedName, const std::vector<std::string> &defaultValue) {
auto &json = getSettingsData(); auto &json = getSettingsData();
if (!json.contains(unlocalizedCategory)) if (!json.contains(unlocalizedCategory))
@ -140,20 +140,20 @@ namespace hex {
} }
std::map<std::string, std::vector<ContentRegistry::Settings::Entry>>& ContentRegistry::Settings::getEntries() { std::map<std::string, std::vector<ContentRegistry::Settings::Entry>> &ContentRegistry::Settings::getEntries() {
return SharedData::settingsEntries; return SharedData::settingsEntries;
} }
nlohmann::json ContentRegistry::Settings::getSetting(const std::string &unlocalizedCategory, const std::string &unlocalizedName) { nlohmann::json ContentRegistry::Settings::getSetting(const std::string &unlocalizedCategory, const std::string &unlocalizedName) {
auto &settings = getSettingsData(); auto &settings = getSettingsData();
if (!settings.contains(unlocalizedCategory)) return { }; if (!settings.contains(unlocalizedCategory)) return {};
if (!settings[unlocalizedCategory].contains(unlocalizedName)) return { }; if (!settings[unlocalizedCategory].contains(unlocalizedName)) return {};
return settings[unlocalizedCategory][unlocalizedName]; return settings[unlocalizedCategory][unlocalizedName];
} }
nlohmann::json& ContentRegistry::Settings::getSettingsData() { nlohmann::json &ContentRegistry::Settings::getSettingsData() {
return SharedData::settingsJson; return SharedData::settingsJson;
} }
@ -163,10 +163,10 @@ namespace hex {
void ContentRegistry::CommandPaletteCommands::add(ContentRegistry::CommandPaletteCommands::Type type, const std::string &command, const std::string &unlocalizedDescription, const std::function<std::string(std::string)> &displayCallback, const std::function<void(std::string)> &executeCallback) { void ContentRegistry::CommandPaletteCommands::add(ContentRegistry::CommandPaletteCommands::Type type, const std::string &command, const std::string &unlocalizedDescription, const std::function<std::string(std::string)> &displayCallback, const std::function<void(std::string)> &executeCallback) {
log::info("Registered new command palette command: {}", command); log::info("Registered new command palette command: {}", command);
getEntries().push_back(ContentRegistry::CommandPaletteCommands::Entry{ type, command, unlocalizedDescription, displayCallback, executeCallback }); getEntries().push_back(ContentRegistry::CommandPaletteCommands::Entry { type, command, unlocalizedDescription, displayCallback, executeCallback });
} }
std::vector<ContentRegistry::CommandPaletteCommands::Entry>& ContentRegistry::CommandPaletteCommands::getEntries() { std::vector<ContentRegistry::CommandPaletteCommands::Entry> &ContentRegistry::CommandPaletteCommands::getEntries() {
return SharedData::commandPaletteCommands; return SharedData::commandPaletteCommands;
} }
@ -196,7 +196,7 @@ namespace hex {
getFunctions()[getFunctionName(ns, name)] = Function { parameterCount, func, true }; getFunctions()[getFunctionName(ns, name)] = Function { parameterCount, func, true };
} }
std::map<std::string, ContentRegistry::PatternLanguage::Function>& ContentRegistry::PatternLanguage::getFunctions() { std::map<std::string, ContentRegistry::PatternLanguage::Function> &ContentRegistry::PatternLanguage::getFunctions() {
return SharedData::patternLanguageFunctions; return SharedData::patternLanguageFunctions;
} }
@ -209,7 +209,7 @@ namespace hex {
getEntries().insert({ view->getUnlocalizedName(), view }); getEntries().insert({ view->getUnlocalizedName(), view });
} }
std::map<std::string, View*>& ContentRegistry::Views::getEntries() { std::map<std::string, View *> &ContentRegistry::Views::getEntries() {
return SharedData::views; return SharedData::views;
} }
@ -225,13 +225,13 @@ namespace hex {
/* Tools */ /* Tools */
void ContentRegistry::Tools:: add(const std::string &unlocalizedName, const std::function<void()> &function) { void ContentRegistry::Tools::add(const std::string &unlocalizedName, const std::function<void()> &function) {
log::info("Registered new tool: {}", unlocalizedName); log::info("Registered new tool: {}", unlocalizedName);
getEntries().emplace_back(impl::Entry{ unlocalizedName, function }); getEntries().emplace_back(impl::Entry { unlocalizedName, function });
} }
std::vector<ContentRegistry::Tools::impl::Entry>& ContentRegistry::Tools::getEntries() { std::vector<ContentRegistry::Tools::impl::Entry> &ContentRegistry::Tools::getEntries() {
return SharedData::toolsEntries; return SharedData::toolsEntries;
} }
@ -244,7 +244,7 @@ namespace hex {
getEntries().push_back({ unlocalizedName, requiredSize, std::move(function) }); getEntries().push_back({ unlocalizedName, requiredSize, std::move(function) });
} }
std::vector<ContentRegistry::DataInspector::impl::Entry>& ContentRegistry::DataInspector::getEntries() { std::vector<ContentRegistry::DataInspector::impl::Entry> &ContentRegistry::DataInspector::getEntries() {
return SharedData::dataInspectorEntries; return SharedData::dataInspectorEntries;
} }
@ -257,10 +257,10 @@ namespace hex {
} }
void ContentRegistry::DataProcessorNode::addSeparator() { void ContentRegistry::DataProcessorNode::addSeparator() {
getEntries().push_back({ "", "", []{ return nullptr; } }); getEntries().push_back({ "", "", [] { return nullptr; } });
} }
std::vector<ContentRegistry::DataProcessorNode::impl::Entry>& ContentRegistry::DataProcessorNode::getEntries() { std::vector<ContentRegistry::DataProcessorNode::impl::Entry> &ContentRegistry::DataProcessorNode::getEntries() {
return SharedData::dataProcessorNodes; return SharedData::dataProcessorNodes;
} }
@ -278,16 +278,15 @@ namespace hex {
getLanguageDefinitions()[languageCode].push_back(definition); getLanguageDefinitions()[languageCode].push_back(definition);
} }
std::map<std::string, std::string>& ContentRegistry::Language::getLanguages() { std::map<std::string, std::string> &ContentRegistry::Language::getLanguages() {
return SharedData::languageNames; return SharedData::languageNames;
} }
std::map<std::string, std::vector<LanguageDefinition>>& ContentRegistry::Language::getLanguageDefinitions() { std::map<std::string, std::vector<LanguageDefinition>> &ContentRegistry::Language::getLanguageDefinitions() {
return SharedData::languageDefinitions; return SharedData::languageDefinitions;
} }
/* Interface */ /* Interface */
u32 ContentRegistry::Interface::getDockSpaceId() { u32 ContentRegistry::Interface::getDockSpaceId() {
@ -303,18 +302,20 @@ namespace hex {
void ContentRegistry::Interface::addMenuItem(const std::string &unlocalizedMainMenuName, u32 priority, const impl::DrawCallback &function) { void ContentRegistry::Interface::addMenuItem(const std::string &unlocalizedMainMenuName, u32 priority, const impl::DrawCallback &function) {
log::info("Added new menu item to menu {} with priority {}", unlocalizedMainMenuName, priority); log::info("Added new menu item to menu {} with priority {}", unlocalizedMainMenuName, priority);
getMenuItems().insert({ priority, { unlocalizedMainMenuName, function }}); getMenuItems().insert({
priority, {unlocalizedMainMenuName, function}
});
} }
void ContentRegistry::Interface::addWelcomeScreenEntry(const ContentRegistry::Interface::impl::DrawCallback &function) { void ContentRegistry::Interface::addWelcomeScreenEntry(const ContentRegistry::Interface::impl::DrawCallback &function) {
getWelcomeScreenEntries().push_back(function); getWelcomeScreenEntries().push_back(function);
} }
void ContentRegistry::Interface::addFooterItem(const ContentRegistry::Interface::impl::DrawCallback &function){ void ContentRegistry::Interface::addFooterItem(const ContentRegistry::Interface::impl::DrawCallback &function) {
getFooterItems().push_back(function); getFooterItems().push_back(function);
} }
void ContentRegistry::Interface::addToolbarItem(const ContentRegistry::Interface::impl::DrawCallback &function){ void ContentRegistry::Interface::addToolbarItem(const ContentRegistry::Interface::impl::DrawCallback &function) {
getToolbarItems().push_back(function); getToolbarItems().push_back(function);
} }
@ -329,27 +330,27 @@ namespace hex {
} }
std::multimap<u32, ContentRegistry::Interface::impl::MainMenuItem>& ContentRegistry::Interface::getMainMenuItems() { std::multimap<u32, ContentRegistry::Interface::impl::MainMenuItem> &ContentRegistry::Interface::getMainMenuItems() {
return SharedData::mainMenuItems; return SharedData::mainMenuItems;
} }
std::multimap<u32, ContentRegistry::Interface::impl::MenuItem>& ContentRegistry::Interface::getMenuItems() { std::multimap<u32, ContentRegistry::Interface::impl::MenuItem> &ContentRegistry::Interface::getMenuItems() {
return SharedData::menuItems; return SharedData::menuItems;
} }
std::vector<ContentRegistry::Interface::impl::DrawCallback>& ContentRegistry::Interface::getWelcomeScreenEntries() { std::vector<ContentRegistry::Interface::impl::DrawCallback> &ContentRegistry::Interface::getWelcomeScreenEntries() {
return SharedData::welcomeScreenEntries; return SharedData::welcomeScreenEntries;
} }
std::vector<ContentRegistry::Interface::impl::DrawCallback>& ContentRegistry::Interface::getFooterItems() { std::vector<ContentRegistry::Interface::impl::DrawCallback> &ContentRegistry::Interface::getFooterItems() {
return SharedData::footerItems; return SharedData::footerItems;
} }
std::vector<ContentRegistry::Interface::impl::DrawCallback>& ContentRegistry::Interface::getToolbarItems() { std::vector<ContentRegistry::Interface::impl::DrawCallback> &ContentRegistry::Interface::getToolbarItems() {
return SharedData::toolbarItems; return SharedData::toolbarItems;
} }
std::vector<ContentRegistry::Interface::impl::SidebarItem>& ContentRegistry::Interface::getSidebarItems() { std::vector<ContentRegistry::Interface::impl::SidebarItem> &ContentRegistry::Interface::getSidebarItems() {
return SharedData::sidebarItems; return SharedData::sidebarItems;
} }
std::vector<ContentRegistry::Interface::impl::Layout>& ContentRegistry::Interface::getLayouts() { std::vector<ContentRegistry::Interface::impl::Layout> &ContentRegistry::Interface::getLayouts() {
return SharedData::layouts; return SharedData::layouts;
} }
@ -367,7 +368,6 @@ namespace hex {
} }
/* Data Formatters */ /* Data Formatters */
void ContentRegistry::DataFormatter::add(const std::string &unlocalizedName, const impl::Callback &callback) { void ContentRegistry::DataFormatter::add(const std::string &unlocalizedName, const impl::Callback &callback) {
@ -381,7 +381,6 @@ namespace hex {
} }
/* File Handlers */ /* File Handlers */
void ContentRegistry::FileHandler::add(const std::vector<std::string> &extensions, const impl::Callback &callback) { void ContentRegistry::FileHandler::add(const std::vector<std::string> &extensions, const impl::Callback &callback) {

View File

@ -3,6 +3,6 @@
namespace hex { namespace hex {
EventManager::EventList EventManager::s_events; EventManager::EventList EventManager::s_events;
std::map<void*, EventManager::EventList::iterator> EventManager::s_tokenStore; std::map<void *, EventManager::EventList::iterator> EventManager::s_tokenStore;
} }

View File

@ -15,7 +15,7 @@ namespace hex {
void ImHexApi::Common::restartImHex() { void ImHexApi::Common::restartImHex() {
EventManager::post<RequestCloseImHex>(false); EventManager::post<RequestCloseImHex>(false);
std::atexit([]{ std::atexit([] {
execve(SharedData::mainArgv[0], SharedData::mainArgv, SharedData::mainEnvp); execve(SharedData::mainArgv[0], SharedData::mainArgv, SharedData::mainEnvp);
}); });
} }
@ -38,22 +38,22 @@ namespace hex {
} }
void ImHexApi::Bookmarks::add(u64 addr, size_t size, const std::string &name, const std::string &comment, u32 color) { void ImHexApi::Bookmarks::add(u64 addr, size_t size, const std::string &name, const std::string &comment, u32 color) {
Bookmarks::add(Region{addr, size}, name, comment, color); Bookmarks::add(Region { addr, size }, name, comment, color);
} }
std::list<ImHexApi::Bookmarks::Entry>& ImHexApi::Bookmarks::getEntries() { std::list<ImHexApi::Bookmarks::Entry> &ImHexApi::Bookmarks::getEntries() {
return SharedData::bookmarkEntries; return SharedData::bookmarkEntries;
} }
prv::Provider* ImHexApi::Provider::get() { prv::Provider *ImHexApi::Provider::get() {
if (!ImHexApi::Provider::isValid()) if (!ImHexApi::Provider::isValid())
return nullptr; return nullptr;
return SharedData::providers[SharedData::currentProvider]; return SharedData::providers[SharedData::currentProvider];
} }
const std::vector<prv::Provider*>& ImHexApi::Provider::getProviders() { const std::vector<prv::Provider *> &ImHexApi::Provider::getProviders() {
return SharedData::providers; return SharedData::providers;
} }

View File

@ -4,7 +4,7 @@
namespace hex { namespace hex {
Task::Task(const std::string& unlocalizedName, u64 maxValue) : m_name(LangEntry(unlocalizedName)), m_maxValue(maxValue), m_currValue(0) { Task::Task(const std::string &unlocalizedName, u64 maxValue) : m_name(LangEntry(unlocalizedName)), m_maxValue(maxValue), m_currValue(0) {
SharedData::runningTasks.push_back(this); SharedData::runningTasks.push_back(this);
} }
@ -36,7 +36,7 @@ namespace hex {
return this->m_maxValue == 0; return this->m_maxValue == 0;
} }
const std::string& Task::getName() const { const std::string &Task::getName() const {
return this->m_name; return this->m_name;
} }

View File

@ -5,7 +5,6 @@
namespace hex::dp { namespace hex::dp {
Attribute::Attribute(IOType ioType, Type type, std::string unlocalizedName) : m_id(SharedData::dataProcessorAttrIdCounter++), m_ioType(ioType), m_type(type), m_unlocalizedName(std::move(unlocalizedName)) { Attribute::Attribute(IOType ioType, Type type, std::string unlocalizedName) : m_id(SharedData::dataProcessorAttrIdCounter++), m_ioType(ioType), m_type(type), m_unlocalizedName(std::move(unlocalizedName)) {
} }
Attribute::~Attribute() { Attribute::~Attribute() {

View File

@ -51,7 +51,7 @@ namespace hex::dp {
if (outputData->size() < sizeof(u64)) if (outputData->size() < sizeof(u64))
throw std::runtime_error("Not enough data provided for integer"); throw std::runtime_error("Not enough data provided for integer");
return *reinterpret_cast<u64*>(outputData->data()); return *reinterpret_cast<u64 *>(outputData->data());
} }
float Node::getFloatOnInput(u32 index) { float Node::getFloatOnInput(u32 index) {
@ -74,7 +74,7 @@ namespace hex::dp {
if (outputData->size() < sizeof(float)) if (outputData->size() < sizeof(float))
throw std::runtime_error("Not enough data provided for float"); throw std::runtime_error("Not enough data provided for float");
return *reinterpret_cast<float*>(outputData->data()); return *reinterpret_cast<float *>(outputData->data());
} }
void Node::setBufferOnOutput(u32 index, std::vector<u8> data) { void Node::setBufferOnOutput(u32 index, std::vector<u8> data) {

View File

@ -23,30 +23,29 @@
#if MBEDTLS_VERSION_MAJOR <= 2 #if MBEDTLS_VERSION_MAJOR <= 2
#define mbedtls_md5_starts mbedtls_md5_starts_ret #define mbedtls_md5_starts mbedtls_md5_starts_ret
#define mbedtls_md5_update mbedtls_md5_update_ret #define mbedtls_md5_update mbedtls_md5_update_ret
#define mbedtls_md5_finish mbedtls_md5_finish_ret #define mbedtls_md5_finish mbedtls_md5_finish_ret
#define mbedtls_sha1_starts mbedtls_sha1_starts_ret #define mbedtls_sha1_starts mbedtls_sha1_starts_ret
#define mbedtls_sha1_update mbedtls_sha1_update_ret #define mbedtls_sha1_update mbedtls_sha1_update_ret
#define mbedtls_sha1_finish mbedtls_sha1_finish_ret #define mbedtls_sha1_finish mbedtls_sha1_finish_ret
#define mbedtls_sha256_starts mbedtls_sha256_starts_ret #define mbedtls_sha256_starts mbedtls_sha256_starts_ret
#define mbedtls_sha256_update mbedtls_sha256_update_ret #define mbedtls_sha256_update mbedtls_sha256_update_ret
#define mbedtls_sha256_finish mbedtls_sha256_finish_ret #define mbedtls_sha256_finish mbedtls_sha256_finish_ret
#define mbedtls_sha512_starts mbedtls_sha512_starts_ret #define mbedtls_sha512_starts mbedtls_sha512_starts_ret
#define mbedtls_sha512_update mbedtls_sha512_update_ret #define mbedtls_sha512_update mbedtls_sha512_update_ret
#define mbedtls_sha512_finish mbedtls_sha512_finish_ret #define mbedtls_sha512_finish mbedtls_sha512_finish_ret
#endif #endif
namespace hex::crypt { namespace hex::crypt {
using namespace std::placeholders; using namespace std::placeholders;
template<std::invocable<unsigned char*, size_t> Func> template<std::invocable<unsigned char *, size_t> Func>
void processDataByChunks(prv::Provider* data, u64 offset, size_t size, Func func) void processDataByChunks(prv::Provider *data, u64 offset, size_t size, Func func) {
{
std::array<u8, 512> buffer = { 0 }; std::array<u8, 512> buffer = { 0 };
for (size_t bufferOffset = 0; bufferOffset < size; bufferOffset += buffer.size()) { for (size_t bufferOffset = 0; bufferOffset < size; bufferOffset += buffer.size()) {
const auto readSize = std::min(buffer.size(), size - bufferOffset); const auto readSize = std::min(buffer.size(), size - bufferOffset);
@ -56,12 +55,10 @@ namespace hex::crypt {
} }
template<typename T> template<typename T>
T reflect(T in, std::size_t bits) T reflect(T in, std::size_t bits) {
{ T out {};
T out{};
for(std::size_t i = 0; i < bits; i++) for (std::size_t i = 0; i < bits; i++) {
{
out <<= 1; out <<= 1;
if (in & 0b1) if (in & 0b1)
out |= 1; out |= 1;
@ -71,21 +68,17 @@ namespace hex::crypt {
} }
template<typename T> template<typename T>
T reflect(T in) T reflect(T in) {
{ if constexpr (sizeof(T) == 1) {
if constexpr (sizeof(T) == 1) T out { in };
{
T out{in};
out = ((out & 0xf0u) >> 4) | ((out & 0x0fu) << 4); out = ((out & 0xf0u) >> 4) | ((out & 0x0fu) << 4);
out = ((out & 0xccu) >> 2) | ((out & 0x33u) << 2); out = ((out & 0xccu) >> 2) | ((out & 0x33u) << 2);
out = ((out & 0xaau) >> 1) | ((out & 0x55u) << 1); out = ((out & 0xaau) >> 1) | ((out & 0x55u) << 1);
return out; return out;
} } else {
else return reflect(in, sizeof(T) * 8);
{
return reflect(in, sizeof(T) *8 );
} }
} }
@ -96,15 +89,14 @@ namespace hex::crypt {
public: public:
using calc_type = uint64_t; using calc_type = uint64_t;
Crc(int bits, calc_type polynomial, calc_type init, calc_type xorout, bool refin, bool refout) : Crc(int bits, calc_type polynomial, calc_type init, calc_type xorout, bool refin, bool refout) : m_bits(bits),
m_bits(bits), m_init(init & ((0b10ull << (bits - 1)) - 1)),
m_init(init & ((0b10ull << (bits-1)) - 1)), m_xorout(xorout & ((0b10ull << (bits - 1)) - 1)),
m_xorout(xorout & ((0b10ull << (bits-1)) - 1)),
m_refin(refin), m_refin(refin),
m_refout(refout), m_refout(refout),
table([polynomial, bits](){ table([polynomial, bits]() {
auto reflectedpoly= reflect(polynomial & ((0b10ull << (bits-1)) - 1), bits); auto reflectedpoly = reflect(polynomial & ((0b10ull << (bits - 1)) - 1), bits);
std::array<uint64_t, 256> table = {0}; std::array<uint64_t, 256> table = { 0 };
for (uint32_t i = 0; i < 256; i++) { for (uint32_t i = 0; i < 256; i++) {
uint64_t c = i; uint64_t c = i;
@ -157,7 +149,7 @@ namespace hex::crypt {
}; };
template<int bits> template<int bits>
auto calcCrc(prv::Provider* data, u64 offset, std::size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut) { auto calcCrc(prv::Provider *data, u64 offset, std::size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut) {
Crc crc(bits, polynomial, init, xorout, reflectIn, reflectOut); Crc crc(bits, polynomial, init, xorout, reflectIn, reflectOut);
processDataByChunks(data, offset, size, std::bind(&Crc::processBytes, &crc, _1, _2)); processDataByChunks(data, offset, size, std::bind(&Crc::processBytes, &crc, _1, _2));
@ -165,20 +157,20 @@ namespace hex::crypt {
return crc.checksum(); return crc.checksum();
} }
u16 crc8(prv::Provider* &data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut) { u16 crc8(prv::Provider *&data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut) {
return calcCrc<8>(data, offset, size, polynomial, init, xorout, reflectIn, reflectOut); return calcCrc<8>(data, offset, size, polynomial, init, xorout, reflectIn, reflectOut);
} }
u16 crc16(prv::Provider* &data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut) { u16 crc16(prv::Provider *&data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut) {
return calcCrc<16>(data, offset, size, polynomial, init, xorout, reflectIn, reflectOut); return calcCrc<16>(data, offset, size, polynomial, init, xorout, reflectIn, reflectOut);
} }
u32 crc32(prv::Provider* &data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut) { u32 crc32(prv::Provider *&data, u64 offset, size_t size, u32 polynomial, u32 init, u32 xorout, bool reflectIn, bool reflectOut) {
return calcCrc<32>(data, offset, size, polynomial, init, xorout, reflectIn, reflectOut); return calcCrc<32>(data, offset, size, polynomial, init, xorout, reflectIn, reflectOut);
} }
std::array<u8, 16> md5(prv::Provider* &data, u64 offset, size_t size) { std::array<u8, 16> md5(prv::Provider *&data, u64 offset, size_t size) {
std::array<u8, 16> result = { 0 }; std::array<u8, 16> result = { 0 };
mbedtls_md5_context ctx; mbedtls_md5_context ctx;
@ -210,7 +202,7 @@ namespace hex::crypt {
return result; return result;
} }
std::array<u8, 20> sha1(prv::Provider* &data, u64 offset, size_t size) { std::array<u8, 20> sha1(prv::Provider *&data, u64 offset, size_t size) {
std::array<u8, 20> result = { 0 }; std::array<u8, 20> result = { 0 };
mbedtls_sha1_context ctx; mbedtls_sha1_context ctx;
@ -242,7 +234,7 @@ namespace hex::crypt {
return result; return result;
} }
std::array<u8, 28> sha224(prv::Provider* &data, u64 offset, size_t size) { std::array<u8, 28> sha224(prv::Provider *&data, u64 offset, size_t size) {
std::array<u8, 28> result = { 0 }; std::array<u8, 28> result = { 0 };
mbedtls_sha256_context ctx; mbedtls_sha256_context ctx;
@ -274,7 +266,7 @@ namespace hex::crypt {
return result; return result;
} }
std::array<u8, 32> sha256(prv::Provider* &data, u64 offset, size_t size) { std::array<u8, 32> sha256(prv::Provider *&data, u64 offset, size_t size) {
std::array<u8, 32> result = { 0 }; std::array<u8, 32> result = { 0 };
mbedtls_sha256_context ctx; mbedtls_sha256_context ctx;
@ -306,7 +298,7 @@ namespace hex::crypt {
return result; return result;
} }
std::array<u8, 48> sha384(prv::Provider* &data, u64 offset, size_t size) { std::array<u8, 48> sha384(prv::Provider *&data, u64 offset, size_t size) {
std::array<u8, 48> result = { 0 }; std::array<u8, 48> result = { 0 };
mbedtls_sha512_context ctx; mbedtls_sha512_context ctx;
@ -338,7 +330,7 @@ namespace hex::crypt {
return result; return result;
} }
std::array<u8, 64> sha512(prv::Provider* &data, u64 offset, size_t size) { std::array<u8, 64> sha512(prv::Provider *&data, u64 offset, size_t size) {
std::array<u8, 64> result = { 0 }; std::array<u8, 64> result = { 0 };
mbedtls_sha512_context ctx; mbedtls_sha512_context ctx;
@ -377,7 +369,7 @@ namespace hex::crypt {
mbedtls_base64_decode(nullptr, 0, &written, reinterpret_cast<const unsigned char *>(input.data()), input.size()); mbedtls_base64_decode(nullptr, 0, &written, reinterpret_cast<const unsigned char *>(input.data()), input.size());
std::vector<u8> output(written, 0x00); std::vector<u8> output(written, 0x00);
if (mbedtls_base64_decode(output.data(), output.size(), &written, reinterpret_cast<const unsigned char *>(input.data()), input.size())) if (mbedtls_base64_decode(output.data(), output.size(), &written, reinterpret_cast<const unsigned char *>(input.data()), input.size()))
return { }; return {};
output.resize(written); output.resize(written);
@ -391,7 +383,7 @@ namespace hex::crypt {
std::vector<u8> output(written, 0x00); std::vector<u8> output(written, 0x00);
if (mbedtls_base64_encode(output.data(), output.size(), &written, reinterpret_cast<const unsigned char *>(input.data()), input.size())) if (mbedtls_base64_encode(output.data(), output.size(), &written, reinterpret_cast<const unsigned char *>(input.data()), input.size()))
return { }; return {};
output.resize(written); output.resize(written);
@ -407,10 +399,10 @@ namespace hex::crypt {
ON_SCOPE_EXIT { mbedtls_mpi_free(&ctx); }; ON_SCOPE_EXIT { mbedtls_mpi_free(&ctx); };
if (mbedtls_mpi_read_string(&ctx, 16, input.c_str())) if (mbedtls_mpi_read_string(&ctx, 16, input.c_str()))
return { }; return {};
if (mbedtls_mpi_write_binary(&ctx, output.data(), output.size())) if (mbedtls_mpi_write_binary(&ctx, output.data(), output.size()))
return { }; return {};
return output; return output;
} }
@ -418,13 +410,13 @@ namespace hex::crypt {
std::string encode16(const std::vector<u8> &input) { std::string encode16(const std::vector<u8> &input) {
if (input.empty()) if (input.empty())
return { }; return {};
std::string output(input.size() * 2, '\0'); std::string output(input.size() * 2, '\0');
for(int i = 0; i < input.size(); i++) { for (int i = 0; i < input.size(); i++) {
output[2*i+0] = "0123456789ABCDEF"[input[i] / 16]; output[2 * i + 0] = "0123456789ABCDEF"[input[i] / 16];
output[2*i+1] = "0123456789ABCDEF"[input[i] % 16]; output[2 * i + 1] = "0123456789ABCDEF"[input[i] % 16];
} }
return output; return output;
@ -434,7 +426,7 @@ namespace hex::crypt {
std::vector<u8> output; std::vector<u8> output;
if (input.empty()) if (input.empty())
return { }; return {};
mbedtls_cipher_context_t ctx; mbedtls_cipher_context_t ctx;
auto cipherInfo = mbedtls_cipher_info_from_type(type); auto cipherInfo = mbedtls_cipher_info_from_type(type);
@ -460,23 +452,47 @@ namespace hex::crypt {
std::vector<u8> aesDecrypt(AESMode mode, KeyLength keyLength, const std::vector<u8> &key, std::array<u8, 8> nonce, std::array<u8, 8> iv, const std::vector<u8> &input) { std::vector<u8> aesDecrypt(AESMode mode, KeyLength keyLength, const std::vector<u8> &key, std::array<u8, 8> nonce, std::array<u8, 8> iv, const std::vector<u8> &input) {
switch (keyLength) { switch (keyLength) {
case KeyLength::Key128Bits: if (key.size() != 128 / 8) return { }; break; case KeyLength::Key128Bits:
case KeyLength::Key192Bits: if (key.size() != 192 / 8) return { }; break; if (key.size() != 128 / 8) return {};
case KeyLength::Key256Bits: if (key.size() != 256 / 8) return { }; break; break;
default: return { }; case KeyLength::Key192Bits:
if (key.size() != 192 / 8) return {};
break;
case KeyLength::Key256Bits:
if (key.size() != 256 / 8) return {};
break;
default:
return {};
} }
mbedtls_cipher_type_t type; mbedtls_cipher_type_t type;
switch (mode) { switch (mode) {
case AESMode::ECB: type = MBEDTLS_CIPHER_AES_128_ECB; break; case AESMode::ECB:
case AESMode::CBC: type = MBEDTLS_CIPHER_AES_128_CBC; break; type = MBEDTLS_CIPHER_AES_128_ECB;
case AESMode::CFB128: type = MBEDTLS_CIPHER_AES_128_CFB128; break; break;
case AESMode::CTR: type = MBEDTLS_CIPHER_AES_128_CTR; break; case AESMode::CBC:
case AESMode::GCM: type = MBEDTLS_CIPHER_AES_128_GCM; break; type = MBEDTLS_CIPHER_AES_128_CBC;
case AESMode::CCM: type = MBEDTLS_CIPHER_AES_128_CCM; break; break;
case AESMode::OFB: type = MBEDTLS_CIPHER_AES_128_OFB; break; case AESMode::CFB128:
case AESMode::XTS: type = MBEDTLS_CIPHER_AES_128_XTS; break; type = MBEDTLS_CIPHER_AES_128_CFB128;
default: return { }; break;
case AESMode::CTR:
type = MBEDTLS_CIPHER_AES_128_CTR;
break;
case AESMode::GCM:
type = MBEDTLS_CIPHER_AES_128_GCM;
break;
case AESMode::CCM:
type = MBEDTLS_CIPHER_AES_128_CCM;
break;
case AESMode::OFB:
type = MBEDTLS_CIPHER_AES_128_OFB;
break;
case AESMode::XTS:
type = MBEDTLS_CIPHER_AES_128_XTS;
break;
default:
return {};
} }
type = mbedtls_cipher_type_t(type + u8(keyLength)); type = mbedtls_cipher_type_t(type + u8(keyLength));

View File

@ -10,8 +10,11 @@ namespace hex {
std::ifstream encodingFile(path.c_str()); std::ifstream encodingFile(path.c_str());
switch (type) { switch (type) {
case Type::Thingy: parseThingyFile(encodingFile); break; case Type::Thingy:
default: return; parseThingyFile(encodingFile);
break;
default:
return;
} }
this->m_valid = true; this->m_valid = true;
@ -55,7 +58,7 @@ namespace hex {
if (fromBytes.empty()) continue; if (fromBytes.empty()) continue;
if (!this->m_mapping.contains(fromBytes.size())) if (!this->m_mapping.contains(fromBytes.size()))
this->m_mapping.insert({ fromBytes.size(), { } }); this->m_mapping.insert({ fromBytes.size(), {} });
this->m_mapping[fromBytes.size()].insert({ fromBytes, to }); this->m_mapping[fromBytes.size()].insert({ fromBytes, to });
this->m_longestSequence = std::max(this->m_longestSequence, fromBytes.size()); this->m_longestSequence = std::max(this->m_longestSequence, fromBytes.size());

View File

@ -26,7 +26,7 @@ namespace hex {
this->close(); this->close();
} }
File& File::operator=(File &&other) noexcept { File &File::operator=(File &&other) noexcept {
this->m_file = other.m_file; this->m_file = other.m_file;
other.m_file = nullptr; other.m_file = nullptr;
@ -54,7 +54,7 @@ namespace hex {
} }
std::vector<u8> File::readBytes(size_t numBytes) { std::vector<u8> File::readBytes(size_t numBytes) {
if (!isValid()) return { }; if (!isValid()) return {};
std::vector<u8> bytes(numBytes ?: getSize()); std::vector<u8> bytes(numBytes ?: getSize());
auto bytesRead = fread(bytes.data(), 1, bytes.size(), this->m_file); auto bytesRead = fread(bytes.data(), 1, bytes.size(), this->m_file);
@ -65,13 +65,13 @@ namespace hex {
} }
std::string File::readString(size_t numBytes) { std::string File::readString(size_t numBytes) {
if (!isValid()) return { }; if (!isValid()) return {};
if (getSize() == 0) return { }; if (getSize() == 0) return {};
auto bytes = readBytes(numBytes); auto bytes = readBytes(numBytes);
return { reinterpret_cast<char*>(bytes.data()), bytes.size() }; return { reinterpret_cast<char *>(bytes.data()), bytes.size() };
} }
void File::write(const u8 *buffer, size_t size) { void File::write(const u8 *buffer, size_t size) {

View File

@ -11,7 +11,7 @@ namespace hex {
this->m_entries.insert(pair); this->m_entries.insert(pair);
} }
const std::map<std::string, std::string>& LanguageDefinition::getEntries() const { const std::map<std::string, std::string> &LanguageDefinition::getEntries() const {
return this->m_entries; return this->m_entries;
} }
@ -27,7 +27,7 @@ namespace hex {
return get(); return get();
} }
LangEntry::operator const char*() const { LangEntry::operator const char *() const {
return get().c_str(); return get().c_str();
} }
@ -59,7 +59,7 @@ namespace hex {
return static_cast<std::string>(left) + right; return static_cast<std::string>(left) + right;
} }
const std::string& LangEntry::get() const { const std::string &LangEntry::get() const {
auto &lang = SharedData::loadedLanguageStrings; auto &lang = SharedData::loadedLanguageStrings;
if (lang.contains(this->m_unlocalizedString)) if (lang.contains(this->m_unlocalizedString))
return lang[this->m_unlocalizedString]; return lang[this->m_unlocalizedString];
@ -85,7 +85,7 @@ namespace hex {
} }
} }
const std::map<std::string, std::string>& LangEntry::getSupportedLanguages() { const std::map<std::string, std::string> &LangEntry::getSupportedLanguages() {
return ContentRegistry::Language::getLanguages(); return ContentRegistry::Language::getLanguages();
} }
@ -93,7 +93,7 @@ namespace hex {
LangEntry::s_fallbackLanguage = language; LangEntry::s_fallbackLanguage = language;
} }
const std::string& LangEntry::getFallbackLanguage() { const std::string &LangEntry::getFallbackLanguage() {
return LangEntry::s_fallbackLanguage; return LangEntry::s_fallbackLanguage;
} }

View File

@ -17,11 +17,11 @@ using namespace std::literals::string_literals;
namespace hex { namespace hex {
PyObject* LoaderScript::Py_getFilePath(PyObject *self, PyObject *args) { PyObject *LoaderScript::Py_getFilePath(PyObject *self, PyObject *args) {
return PyUnicode_FromString(LoaderScript::s_filePath.string().c_str()); return PyUnicode_FromString(LoaderScript::s_filePath.string().c_str());
} }
PyObject* LoaderScript::Py_addPatch(PyObject *self, PyObject *args) { PyObject *LoaderScript::Py_addPatch(PyObject *self, PyObject *args) {
u64 address; u64 address;
u8 *patches; u8 *patches;
Py_ssize_t count; Py_ssize_t count;
@ -46,7 +46,7 @@ namespace hex {
Py_RETURN_NONE; Py_RETURN_NONE;
} }
PyObject* LoaderScript::Py_addBookmark(PyObject *self, PyObject *args) { PyObject *LoaderScript::Py_addBookmark(PyObject *self, PyObject *args) {
u64 address; u64 address;
size_t size; size_t size;
@ -68,7 +68,7 @@ namespace hex {
Py_RETURN_NONE; Py_RETURN_NONE;
} }
static PyObject* createStructureType(std::string keyword, PyObject *args) { static PyObject *createStructureType(std::string keyword, PyObject *args) {
auto type = PyTuple_GetItem(args, 0); auto type = PyTuple_GetItem(args, 0);
if (type == nullptr) { if (type == nullptr) {
PyErr_BadArgument(); PyErr_BadArgument();
@ -170,11 +170,11 @@ namespace hex {
Py_RETURN_NONE; Py_RETURN_NONE;
} }
PyObject* LoaderScript::Py_addStruct(PyObject *self, PyObject *args) { PyObject *LoaderScript::Py_addStruct(PyObject *self, PyObject *args) {
return createStructureType("struct", args); return createStructureType("struct", args);
} }
PyObject* LoaderScript::Py_addUnion(PyObject *self, PyObject *args) { PyObject *LoaderScript::Py_addUnion(PyObject *self, PyObject *args) {
return createStructureType("union", args); return createStructureType("union", args);
} }
@ -188,10 +188,9 @@ namespace hex {
} }
} }
PyImport_AppendInittab("_imhex", []() -> PyObject* { PyImport_AppendInittab("_imhex", []() -> PyObject * {
static PyMethodDef ImHexMethods[] = { static PyMethodDef ImHexMethods[] = {
{ "get_file_path", &LoaderScript::Py_getFilePath, METH_NOARGS, "Returns the path of the file being loaded." }, {"get_file_path", &LoaderScript::Py_getFilePath, METH_NOARGS, "Returns the path of the file being loaded."},
{ "patch", &LoaderScript::Py_addPatch, METH_VARARGS, "Patches a region of memory" }, { "patch", &LoaderScript::Py_addPatch, METH_VARARGS, "Patches a region of memory" },
{ "add_bookmark", &LoaderScript::Py_addBookmark, METH_VARARGS, "Adds a bookmark" }, { "add_bookmark", &LoaderScript::Py_addBookmark, METH_VARARGS, "Adds a bookmark" },
{ "add_struct", &LoaderScript::Py_addStruct, METH_VARARGS, "Adds a struct" }, { "add_struct", &LoaderScript::Py_addStruct, METH_VARARGS, "Adds a struct" },

View File

@ -9,7 +9,7 @@ namespace hex::log {
static File g_loggerFile; static File g_loggerFile;
FILE* getDestination() { FILE *getDestination() {
if (g_loggerFile.isValid()) if (g_loggerFile.isValid())
return g_loggerFile.getHandle(); return g_loggerFile.getHandle();
else else

View File

@ -32,7 +32,7 @@ namespace hex::magic {
} }
if (error) if (error)
return { }; return {};
else else
return magicFiles; return magicFiles;
} }
@ -70,7 +70,7 @@ namespace hex::magic {
return getDescription(buffer); return getDescription(buffer);
} }
std::string getMIMEType(const std::vector<u8> &data){ std::string getMIMEType(const std::vector<u8> &data) {
auto magicFiles = getMagicFiles(); auto magicFiles = getMagicFiles();
if (magicFiles.has_value()) { if (magicFiles.has_value()) {

View File

@ -33,31 +33,31 @@ namespace hex {
curl_easy_cleanup(this->m_ctx); curl_easy_cleanup(this->m_ctx);
} }
static size_t writeToString(void *contents, size_t size, size_t nmemb, void *userdata){ static size_t writeToString(void *contents, size_t size, size_t nmemb, void *userdata) {
static_cast<std::string*>(userdata)->append((char*)contents, size * nmemb); static_cast<std::string *>(userdata)->append((char *)contents, size * nmemb);
return size * nmemb; return size * nmemb;
} }
static size_t readFromFile(void *contents, size_t size, size_t nmemb, void *userdata) { static size_t readFromFile(void *contents, size_t size, size_t nmemb, void *userdata) {
FILE *file = static_cast<FILE*>(userdata); FILE *file = static_cast<FILE *>(userdata);
return fread(contents, size, nmemb, file); return fread(contents, size, nmemb, file);
} }
static size_t writeToFile(void *contents, size_t size, size_t nmemb, void *userdata) { static size_t writeToFile(void *contents, size_t size, size_t nmemb, void *userdata) {
FILE *file = static_cast<FILE*>(userdata); FILE *file = static_cast<FILE *>(userdata);
return fwrite(contents, size, nmemb, file); return fwrite(contents, size, nmemb, file);
} }
static CURLcode sslCtxFunction(CURL *ctx, void *sslctx, void *userdata) { static CURLcode sslCtxFunction(CURL *ctx, void *sslctx, void *userdata) {
auto* cfg = static_cast<mbedtls_ssl_config*>(sslctx); auto *cfg = static_cast<mbedtls_ssl_config *>(sslctx);
static mbedtls_x509_crt crt; static mbedtls_x509_crt crt;
mbedtls_x509_crt_init(&crt); mbedtls_x509_crt_init(&crt);
auto cacert = romfs::get("cacert.pem").string(); auto cacert = romfs::get("cacert.pem").string();
mbedtls_x509_crt_parse(&crt, reinterpret_cast<const u8*>(cacert.data()), cacert.size()); mbedtls_x509_crt_parse(&crt, reinterpret_cast<const u8 *>(cacert.data()), cacert.size());
mbedtls_ssl_conf_ca_chain(cfg, &crt, nullptr); mbedtls_ssl_conf_ca_chain(cfg, &crt, nullptr);
@ -65,7 +65,7 @@ namespace hex {
} }
int progressCallback(void *contents, curl_off_t dlTotal, curl_off_t dlNow, curl_off_t ulTotal, curl_off_t ulNow) { int progressCallback(void *contents, curl_off_t dlTotal, curl_off_t dlNow, curl_off_t ulTotal, curl_off_t ulNow) {
auto &net = *static_cast<Net*>(contents); auto &net = *static_cast<Net *>(contents);
if (dlTotal > 0) if (dlTotal > 0)
net.m_progress = float(dlNow) / dlTotal; net.m_progress = float(dlNow) / dlTotal;
@ -129,7 +129,7 @@ namespace hex {
this->m_shouldCancel = false; this->m_shouldCancel = false;
if (result != CURLE_OK) if (result != CURLE_OK)
return { }; return {};
else else
return responseCode; return responseCode;
} }
@ -137,7 +137,7 @@ namespace hex {
std::future<Response<std::string>> Net::getString(const std::string &url, u32 timeout) { std::future<Response<std::string>> Net::getString(const std::string &url, u32 timeout) {
this->m_transmissionActive.lock(); this->m_transmissionActive.lock();
return std::async(std::launch::async, [=, this]{ return std::async(std::launch::async, [=, this] {
std::string response; std::string response;
ON_SCOPE_EXIT { this->m_transmissionActive.unlock(); }; ON_SCOPE_EXIT { this->m_transmissionActive.unlock(); };
@ -154,7 +154,7 @@ namespace hex {
std::future<Response<nlohmann::json>> Net::getJson(const std::string &url, u32 timeout) { std::future<Response<nlohmann::json>> Net::getJson(const std::string &url, u32 timeout) {
this->m_transmissionActive.lock(); this->m_transmissionActive.lock();
return std::async(std::launch::async, [=, this]{ return std::async(std::launch::async, [=, this] {
std::string response; std::string response;
ON_SCOPE_EXIT { this->m_transmissionActive.unlock(); }; ON_SCOPE_EXIT { this->m_transmissionActive.unlock(); };
@ -178,26 +178,21 @@ namespace hex {
File file(filePath.string(), File::Mode::Read); File file(filePath.string(), File::Mode::Read);
if (!file.isValid()) if (!file.isValid())
return Response<std::string> { 400, { } }; return Response<std::string> { 400, {} };
curl_mime *mime = curl_mime_init(this->m_ctx); curl_mime *mime = curl_mime_init(this->m_ctx);
curl_mimepart *part = curl_mime_addpart(mime); curl_mimepart *part = curl_mime_addpart(mime);
auto fileName = filePath.filename().string(); auto fileName = filePath.filename().string();
curl_mime_data_cb(part, file.getSize(), curl_mime_data_cb(
[](char *buffer, size_t size, size_t nitems, void *arg) -> size_t { part, file.getSize(), [](char *buffer, size_t size, size_t nitems, void *arg) -> size_t {
auto file = static_cast<FILE*>(arg); auto file = static_cast<FILE*>(arg);
return fread(buffer, size, nitems, file); return fread(buffer, size, nitems, file); }, [](void *arg, curl_off_t offset, int origin) -> int {
},
[](void *arg, curl_off_t offset, int origin) -> int {
auto file = static_cast<FILE*>(arg); auto file = static_cast<FILE*>(arg);
fseek(file, offset, origin); fseek(file, offset, origin);
return CURL_SEEKFUNC_OK; return CURL_SEEKFUNC_OK; }, [](void *arg) {
},
[](void *arg) {
auto file = static_cast<FILE*>(arg); auto file = static_cast<FILE*>(arg);
fclose(file); fclose(file); }, file.getHandle());
}, file.getHandle());
curl_mime_filename(part, fileName.c_str()); curl_mime_filename(part, fileName.c_str());
curl_mime_name(part, "file"); curl_mime_name(part, "file");
@ -214,7 +209,7 @@ namespace hex {
std::future<Response<void>> Net::downloadFile(const std::string &url, const fs::path &filePath, u32 timeout) { std::future<Response<void>> Net::downloadFile(const std::string &url, const fs::path &filePath, u32 timeout) {
this->m_transmissionActive.lock(); this->m_transmissionActive.lock();
return std::async(std::launch::async, [=, this]{ return std::async(std::launch::async, [=, this] {
std::string response; std::string response;
ON_SCOPE_EXIT { this->m_transmissionActive.unlock(); }; ON_SCOPE_EXIT { this->m_transmissionActive.unlock(); };
@ -243,7 +238,7 @@ namespace hex {
return output; return output;
} }
return { }; return {};
} }
} }

View File

@ -43,19 +43,21 @@ namespace hex {
bytes.push_back(values[i]); bytes.push_back(values[i]);
if (bytes.size() > 0xFFFF || startAddress > 0xFF'FFFF) if (bytes.size() > 0xFFFF || startAddress > 0xFF'FFFF)
return { }; return {};
u32 address = startAddress.value(); u32 address = startAddress.value();
auto addressBytes = reinterpret_cast<u8*>(&address); auto addressBytes = reinterpret_cast<u8 *>(&address);
result.push_back(addressBytes[2]); result.push_back(addressBytes[1]); result.push_back(addressBytes[0]); result.push_back(addressBytes[2]);
result.push_back(addressBytes[1]);
result.push_back(addressBytes[0]);
pushBytesBack<u16>(result, changeEndianess<u16>(bytes.size(), std::endian::big)); pushBytesBack<u16>(result, changeEndianess<u16>(bytes.size(), std::endian::big));
for (auto byte : bytes) for (auto byte : bytes)
result.push_back(byte); result.push_back(byte);
bytes.clear(); bytes.clear();
startAddress = { }; startAddress = {};
} }
} }
@ -89,19 +91,22 @@ namespace hex {
bytes.push_back(values[i]); bytes.push_back(values[i]);
if (bytes.size() > 0xFFFF || startAddress > 0xFFFF'FFFF) if (bytes.size() > 0xFFFF || startAddress > 0xFFFF'FFFF)
return { }; return {};
u32 address = startAddress.value(); u32 address = startAddress.value();
auto addressBytes = reinterpret_cast<u8*>(&address); auto addressBytes = reinterpret_cast<u8 *>(&address);
result.push_back(addressBytes[3]); result.push_back(addressBytes[2]); result.push_back(addressBytes[1]); result.push_back(addressBytes[0]); result.push_back(addressBytes[3]);
result.push_back(addressBytes[2]);
result.push_back(addressBytes[1]);
result.push_back(addressBytes[0]);
pushBytesBack<u16>(result, changeEndianess<u16>(bytes.size(), std::endian::big)); pushBytesBack<u16>(result, changeEndianess<u16>(bytes.size(), std::endian::big));
for (auto byte : bytes) for (auto byte : bytes)
result.push_back(byte); result.push_back(byte);
bytes.clear(); bytes.clear();
startAddress = { }; startAddress = {};
} }
} }
@ -112,10 +117,10 @@ namespace hex {
Patches loadIPSPatch(const std::vector<u8> &ipsPatch) { Patches loadIPSPatch(const std::vector<u8> &ipsPatch) {
if (ipsPatch.size() < (5 + 3)) if (ipsPatch.size() < (5 + 3))
return { }; return {};
if (std::memcmp(ipsPatch.data(), "PATCH", 5) != 0) if (std::memcmp(ipsPatch.data(), "PATCH", 5) != 0)
return { }; return {};
Patches result; Patches result;
bool foundEOF = false; bool foundEOF = false;
@ -130,7 +135,7 @@ namespace hex {
// Handle normal record // Handle normal record
if (size > 0x0000) { if (size > 0x0000) {
if (ipsOffset + size > ipsPatch.size() - 3) if (ipsOffset + size > ipsPatch.size() - 3)
return { }; return {};
for (u16 i = 0; i < size; i++) for (u16 i = 0; i < size; i++)
result[offset + i] = ipsPatch[ipsOffset + i]; result[offset + i] = ipsPatch[ipsOffset + i];
@ -139,7 +144,7 @@ namespace hex {
// Handle RLE record // Handle RLE record
else { else {
if (ipsOffset + 3 > ipsPatch.size() - 3) if (ipsOffset + 3 > ipsPatch.size() - 3)
return { }; return {};
u16 rleSize = ipsPatch[ipsOffset + 0] | (ipsPatch[ipsOffset + 1] << 8); u16 rleSize = ipsPatch[ipsOffset + 0] | (ipsPatch[ipsOffset + 1] << 8);
@ -158,15 +163,15 @@ namespace hex {
if (foundEOF) if (foundEOF)
return result; return result;
else else
return { }; return {};
} }
Patches loadIPS32Patch(const std::vector<u8> &ipsPatch) { Patches loadIPS32Patch(const std::vector<u8> &ipsPatch) {
if (ipsPatch.size() < (5 + 4)) if (ipsPatch.size() < (5 + 4))
return { }; return {};
if (std::memcmp(ipsPatch.data(), "IPS32", 5) != 0) if (std::memcmp(ipsPatch.data(), "IPS32", 5) != 0)
return { }; return {};
Patches result; Patches result;
bool foundEEOF = false; bool foundEEOF = false;
@ -181,7 +186,7 @@ namespace hex {
// Handle normal record // Handle normal record
if (size > 0x0000) { if (size > 0x0000) {
if (ipsOffset + size > ipsPatch.size() - 3) if (ipsOffset + size > ipsPatch.size() - 3)
return { }; return {};
for (u16 i = 0; i < size; i++) for (u16 i = 0; i < size; i++)
result[offset + i] = ipsPatch[ipsOffset + i]; result[offset + i] = ipsPatch[ipsOffset + i];
@ -190,7 +195,7 @@ namespace hex {
// Handle RLE record // Handle RLE record
else { else {
if (ipsOffset + 3 > ipsPatch.size() - 3) if (ipsOffset + 3 > ipsPatch.size() - 3)
return { }; return {};
u16 rleSize = ipsPatch[ipsOffset + 0] | (ipsPatch[ipsOffset + 1] << 8); u16 rleSize = ipsPatch[ipsOffset + 0] | (ipsPatch[ipsOffset + 1] << 8);
@ -209,7 +214,7 @@ namespace hex {
if (foundEEOF) if (foundEEOF)
return result; return result;
else else
return { }; return {};
} }
} }

View File

@ -19,27 +19,27 @@
namespace hex { namespace hex {
std::string getExecutablePath() { std::string getExecutablePath() {
#if defined(OS_WINDOWS) #if defined(OS_WINDOWS)
std::string exePath(MAX_PATH, '\0'); std::string exePath(MAX_PATH, '\0');
GetModuleFileName(nullptr, exePath.data(), exePath.length()); GetModuleFileName(nullptr, exePath.data(), exePath.length());
return exePath; return exePath;
#elif defined(OS_LINUX) #elif defined(OS_LINUX)
std::string exePath(PATH_MAX, '\0'); std::string exePath(PATH_MAX, '\0');
readlink("/proc/self/exe", exePath.data(), PATH_MAX); readlink("/proc/self/exe", exePath.data(), PATH_MAX);
return exePath; return exePath;
#elif defined(OS_MACOS) #elif defined(OS_MACOS)
return getMacExecutableDirectoryPath(); return getMacExecutableDirectoryPath();
#else #else
return ""; return "";
#endif #endif
} }
std::vector<fs::path> getPath(ImHexPath path, bool listNonExisting) { std::vector<fs::path> getPath(ImHexPath path, bool listNonExisting) {
std::vector<fs::path> result; std::vector<fs::path> result;
#if defined(OS_WINDOWS) #if defined(OS_WINDOWS)
const auto exePath = getExecutablePath(); const auto exePath = getExecutablePath();
const auto parentDir = fs::path(exePath).parent_path(); const auto parentDir = fs::path(exePath).parent_path();
@ -57,60 +57,61 @@ namespace hex {
switch (path) { switch (path) {
case ImHexPath::Patterns: case ImHexPath::Patterns:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "patterns").string(); return (path / "patterns").string();
}); });
break; break;
case ImHexPath::PatternsInclude: case ImHexPath::PatternsInclude:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "includes").string(); return (path / "includes").string();
}); });
break; break;
case ImHexPath::Magic: case ImHexPath::Magic:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "magic").string(); return (path / "magic").string();
}); });
break; break;
case ImHexPath::Python: case ImHexPath::Python:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "python").string(); return (path / "python").string();
}); });
break; break;
case ImHexPath::Plugins: case ImHexPath::Plugins:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "plugins").string(); return (path / "plugins").string();
}); });
break; break;
case ImHexPath::Yara: case ImHexPath::Yara:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "yara").string(); return (path / "yara").string();
}); });
break; break;
case ImHexPath::Config: case ImHexPath::Config:
return { (appDataDir / "imhex" / "config").string() }; return { (appDataDir / "imhex" / "config").string() };
case ImHexPath::Resources: case ImHexPath::Resources:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "resources").string(); return (path / "resources").string();
}); });
break; break;
case ImHexPath::Constants: case ImHexPath::Constants:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "constants").string(); return (path / "constants").string();
}); });
break; break;
case ImHexPath::Encodings: case ImHexPath::Encodings:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "encodings").string(); return (path / "encodings").string();
}); });
break; break;
case ImHexPath::Logs: case ImHexPath::Logs:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "logs").string(); return (path / "logs").string();
}); });
break; break;
default: __builtin_unreachable(); default:
__builtin_unreachable();
} }
#elif defined(OS_MACOS) #elif defined(OS_MACOS)
// Get path to special directories // Get path to special directories
const auto exePath = getExecutablePath(); const auto exePath = getExecutablePath();
const fs::path applicationSupportDir(getMacApplicationSupportDirectoryPath()); const fs::path applicationSupportDir(getMacApplicationSupportDirectoryPath());
@ -131,7 +132,7 @@ namespace hex {
result.push_back((applicationSupportDir / "python").string()); result.push_back((applicationSupportDir / "python").string());
break; break;
case ImHexPath::Plugins: case ImHexPath::Plugins:
std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path){ std::transform(paths.begin(), paths.end(), std::back_inserter(result), [](auto &path) {
return (path / "plugins").string(); return (path / "plugins").string();
}); });
break; break;
@ -153,9 +154,10 @@ namespace hex {
case ImHexPath::Logs: case ImHexPath::Logs:
result.push_back((applicationSupportDir / "logs").string()); result.push_back((applicationSupportDir / "logs").string());
break; break;
default: __builtin_unreachable(); default:
__builtin_unreachable();
} }
#else #else
std::vector<fs::path> configDirs = xdg::ConfigDirs(); std::vector<fs::path> configDirs = xdg::ConfigDirs();
std::vector<fs::path> dataDirs = xdg::DataDirs(); std::vector<fs::path> dataDirs = xdg::DataDirs();
@ -172,57 +174,48 @@ namespace hex {
switch (path) { switch (path) {
case ImHexPath::Patterns: case ImHexPath::Patterns:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "patterns").string(); });
[](auto p) { return (p / "patterns").string(); });
break; break;
case ImHexPath::PatternsInclude: case ImHexPath::PatternsInclude:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "includes").string(); });
[](auto p) { return (p / "includes").string(); });
break; break;
case ImHexPath::Magic: case ImHexPath::Magic:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "magic").string(); });
[](auto p) { return (p / "magic").string(); });
break; break;
case ImHexPath::Python: case ImHexPath::Python:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p).string(); });
[](auto p) { return (p).string(); });
break; break;
case ImHexPath::Plugins: case ImHexPath::Plugins:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "plugins").string(); });
[](auto p) { return (p / "plugins").string(); });
break; break;
case ImHexPath::Yara: case ImHexPath::Yara:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "yara").string(); });
[](auto p) { return (p / "yara").string(); });
break; break;
case ImHexPath::Config: case ImHexPath::Config:
std::transform(configDirs.begin(), configDirs.end(), std::back_inserter(result), std::transform(configDirs.begin(), configDirs.end(), std::back_inserter(result), [](auto p) { return (p / "imhex").string(); });
[](auto p) { return (p / "imhex").string(); });
break; break;
case ImHexPath::Resources: case ImHexPath::Resources:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "resources").string(); });
[](auto p) { return (p / "resources").string(); });
break; break;
case ImHexPath::Constants: case ImHexPath::Constants:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "constants").string(); });
[](auto p) { return (p / "constants").string(); });
break; break;
case ImHexPath::Encodings: case ImHexPath::Encodings:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "encodings").string(); });
[](auto p) { return (p / "encodings").string(); });
break; break;
case ImHexPath::Logs: case ImHexPath::Logs:
std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), std::transform(dataDirs.begin(), dataDirs.end(), std::back_inserter(result), [](auto p) { return (p / "logs").string(); });
[](auto p) { return (p / "logs").string(); });
break; break;
default: __builtin_unreachable(); default:
__builtin_unreachable();
} }
#endif #endif
if (!listNonExisting) { if (!listNonExisting) {
result.erase(std::remove_if(result.begin(), result.end(), [](const auto& path){ result.erase(std::remove_if(result.begin(), result.end(), [](const auto &path) {
return !fs::is_directory(path); return !fs::is_directory(path);
}), result.end()); }),
result.end());
} }
return result; return result;

View File

@ -18,11 +18,18 @@ namespace hex {
std::list<ImHexApi::Bookmarks::Entry> ProjectFile::s_bookmarks; std::list<ImHexApi::Bookmarks::Entry> ProjectFile::s_bookmarks;
std::string ProjectFile::s_dataProcessorContent; std::string ProjectFile::s_dataProcessorContent;
void to_json(json& j, const ImHexApi::Bookmarks::Entry& b) { void to_json(json &j, const ImHexApi::Bookmarks::Entry &b) {
j = json{ { "address", b.region.address }, { "size", b.region.size }, { "name", b.name.data() }, { "comment", b.comment.data() }, { "locked", b.locked }, { "color", b.color } }; j = json {
{"address", b.region.address},
{ "size", b.region.size },
{ "name", b.name.data() },
{ "comment", b.comment.data()},
{ "locked", b.locked },
{ "color", b.color }
};
} }
void from_json(const json& j, ImHexApi::Bookmarks::Entry& b) { void from_json(const json &j, ImHexApi::Bookmarks::Entry &b) {
std::string name, comment; std::string name, comment;
if (j.contains("address")) j.at("address").get_to(b.region.address); if (j.contains("address")) j.at("address").get_to(b.region.address);

View File

@ -6,20 +6,20 @@ namespace hex {
std::vector<std::function<void()>> SharedData::deferredCalls; std::vector<std::function<void()>> SharedData::deferredCalls;
std::vector<prv::Provider*> SharedData::providers; std::vector<prv::Provider *> SharedData::providers;
u32 SharedData::currentProvider; u32 SharedData::currentProvider;
std::map<std::string, std::vector<ContentRegistry::Settings::Entry>> SharedData::settingsEntries; std::map<std::string, std::vector<ContentRegistry::Settings::Entry>> SharedData::settingsEntries;
nlohmann::json SharedData::settingsJson; nlohmann::json SharedData::settingsJson;
std::vector<ContentRegistry::CommandPaletteCommands::Entry> SharedData::commandPaletteCommands; std::vector<ContentRegistry::CommandPaletteCommands::Entry> SharedData::commandPaletteCommands;
std::map<std::string, ContentRegistry::PatternLanguage::Function> SharedData::patternLanguageFunctions; std::map<std::string, ContentRegistry::PatternLanguage::Function> SharedData::patternLanguageFunctions;
std::map<std::string, View*> SharedData::views; std::map<std::string, View *> SharedData::views;
std::vector<ContentRegistry::Tools::impl::Entry> SharedData::toolsEntries; std::vector<ContentRegistry::Tools::impl::Entry> SharedData::toolsEntries;
std::vector<ContentRegistry::DataInspector::impl::Entry> SharedData::dataInspectorEntries; std::vector<ContentRegistry::DataInspector::impl::Entry> SharedData::dataInspectorEntries;
u32 SharedData::patternPaletteOffset; u32 SharedData::patternPaletteOffset;
std::string SharedData::popupMessage; std::string SharedData::popupMessage;
std::list<ImHexApi::Bookmarks::Entry> SharedData::bookmarkEntries; std::list<ImHexApi::Bookmarks::Entry> SharedData::bookmarkEntries;
std::vector<pl::PatternData*> SharedData::patternData; std::vector<pl::PatternData *> SharedData::patternData;
u32 SharedData::selectableFileIndex; u32 SharedData::selectableFileIndex;
std::vector<fs::path> SharedData::selectableFiles; std::vector<fs::path> SharedData::selectableFiles;
@ -44,7 +44,7 @@ namespace hex {
std::map<Shortcut, std::function<void()>> SharedData::globalShortcuts; std::map<Shortcut, std::function<void()>> SharedData::globalShortcuts;
std::mutex SharedData::tasksMutex; std::mutex SharedData::tasksMutex;
std::list<Task*> SharedData::runningTasks; std::list<Task *> SharedData::runningTasks;
std::vector<std::string> SharedData::providerNames; std::vector<std::string> SharedData::providerNames;

View File

@ -6,7 +6,7 @@
namespace hex { namespace hex {
Socket::Socket(const std::string &address, u16 port) { Socket::Socket(const std::string &address, u16 port) {
#if defined(OS_WINDOWS) #if defined(OS_WINDOWS)
FIRST_TIME { FIRST_TIME {
WSAData wsa; WSAData wsa;
WSAStartup(MAKEWORD(2, 2), &wsa); WSAStartup(MAKEWORD(2, 2), &wsa);
@ -15,7 +15,7 @@ namespace hex {
FINAL_CLEANUP { FINAL_CLEANUP {
WSACleanup(); WSACleanup();
}; };
#endif #endif
this->connect(address, port); this->connect(address, port);
} }
@ -34,7 +34,7 @@ namespace hex {
void Socket::writeBytes(const std::vector<u8> &bytes) const { void Socket::writeBytes(const std::vector<u8> &bytes) const {
if (!this->isConnected()) return; if (!this->isConnected()) return;
::send(this->m_socket, reinterpret_cast<const char*>(bytes.data()), bytes.size(), 0); ::send(this->m_socket, reinterpret_cast<const char *>(bytes.data()), bytes.size(), 0);
} }
void Socket::writeString(const std::string &string) const { void Socket::writeString(const std::string &string) const {
@ -50,7 +50,7 @@ namespace hex {
auto receivedSize = ::recv(this->m_socket, reinterpret_cast<char *>(data.data()), size, 0); auto receivedSize = ::recv(this->m_socket, reinterpret_cast<char *>(data.data()), size, 0);
if (receivedSize < 0) if (receivedSize < 0)
return { }; return {};
data.resize(receivedSize); data.resize(receivedSize);
@ -80,22 +80,22 @@ namespace hex {
client.sin_family = AF_INET; client.sin_family = AF_INET;
client.sin_port = htons(port); client.sin_port = htons(port);
#if defined(OS_WINDOWS) #if defined(OS_WINDOWS)
client.sin_addr.S_un.S_addr = ::inet_addr(address.c_str()); client.sin_addr.S_un.S_addr = ::inet_addr(address.c_str());
#else #else
client.sin_addr.s_addr = ::inet_addr(address.c_str()); client.sin_addr.s_addr = ::inet_addr(address.c_str());
#endif #endif
this->m_connected = ::connect(this->m_socket, reinterpret_cast<sockaddr*>(&client), sizeof(client)) == 0; this->m_connected = ::connect(this->m_socket, reinterpret_cast<sockaddr *>(&client), sizeof(client)) == 0;
} }
void Socket::disconnect() { void Socket::disconnect() {
if (this->m_socket != SOCKET_NONE) { if (this->m_socket != SOCKET_NONE) {
#if defined(OS_WINDOWS) #if defined(OS_WINDOWS)
closesocket(this->m_socket); closesocket(this->m_socket);
#else #else
close(this->m_socket); close(this->m_socket);
#endif #endif
} }
this->m_connected = false; this->m_connected = false;

View File

@ -8,11 +8,11 @@
#include <hex/helpers/fmt.hpp> #include <hex/helpers/fmt.hpp>
#include <hex/helpers/shared_data.hpp> #include <hex/helpers/shared_data.hpp>
#if defined (OS_WINDOWS) #if defined(OS_WINDOWS)
#include <windows.h> #include <windows.h>
#elif defined (OS_LINUX) #elif defined(OS_LINUX)
#include <unistd.h> #include <unistd.h>
#elif defined (OS_MACOS) #elif defined(OS_MACOS)
#include <CoreFoundation/CFBundle.h> #include <CoreFoundation/CFBundle.h>
#include <ApplicationServices/ApplicationServices.h> #include <ApplicationServices/ApplicationServices.h>
#endif #endif
@ -78,14 +78,29 @@ namespace hex {
std::string result = hex::format("{0:.2f}", value); std::string result = hex::format("{0:.2f}", value);
switch (unitIndex) { switch (unitIndex) {
case 0: result += " Bytes"; break; case 0:
case 1: result += " kB"; break; result += " Bytes";
case 2: result += " MB"; break; break;
case 3: result += " GB"; break; case 1:
case 4: result += " TB"; break; result += " kB";
case 5: result += " PB"; break; break;
case 6: result += " EB"; break; case 2:
default: result = "A lot!"; result += " MB";
break;
case 3:
result += " GB";
break;
case 4:
result += " TB";
break;
case 5:
result += " PB";
break;
case 6:
result += " EB";
break;
default:
result = "A lot!";
} }
return result; return result;
@ -93,42 +108,78 @@ namespace hex {
std::string makePrintable(u8 c) { std::string makePrintable(u8 c) {
switch (c) { switch (c) {
case 0: return "NUL"; case 0:
case 1: return "SOH"; return "NUL";
case 2: return "STX"; case 1:
case 3: return "ETX"; return "SOH";
case 4: return "EOT"; case 2:
case 5: return "ENQ"; return "STX";
case 6: return "ACK"; case 3:
case 7: return "BEL"; return "ETX";
case 8: return "BS"; case 4:
case 9: return "TAB"; return "EOT";
case 10: return "LF"; case 5:
case 11: return "VT"; return "ENQ";
case 12: return "FF"; case 6:
case 13: return "CR"; return "ACK";
case 14: return "SO"; case 7:
case 15: return "SI"; return "BEL";
case 16: return "DLE"; case 8:
case 17: return "DC1"; return "BS";
case 18: return "DC2"; case 9:
case 19: return "DC3"; return "TAB";
case 20: return "DC4"; case 10:
case 21: return "NAK"; return "LF";
case 22: return "SYN"; case 11:
case 23: return "ETB"; return "VT";
case 24: return "CAN"; case 12:
case 25: return "EM"; return "FF";
case 26: return "SUB"; case 13:
case 27: return "ESC"; return "CR";
case 28: return "FS"; case 14:
case 29: return "GS"; return "SO";
case 30: return "RS"; case 15:
case 31: return "US"; return "SI";
case 32: return "Space"; case 16:
case 127: return "DEL"; return "DLE";
case 128 ... 255: return " "; case 17:
default: return std::string() + static_cast<char>(c); return "DC1";
case 18:
return "DC2";
case 19:
return "DC3";
case 20:
return "DC4";
case 21:
return "NAK";
case 22:
return "SYN";
case 23:
return "ETB";
case 24:
return "CAN";
case 25:
return "EM";
case 26:
return "SUB";
case 27:
return "ESC";
case 28:
return "FS";
case 29:
return "GS";
case 30:
return "RS";
case 31:
return "US";
case 32:
return "Space";
case 127:
return "DEL";
case 128 ... 255:
return " ";
default:
return std::string() + static_cast<char>(c);
} }
} }
@ -177,16 +228,15 @@ namespace hex {
void runCommand(const std::string &command) { void runCommand(const std::string &command) {
#if defined(OS_WINDOWS) #if defined(OS_WINDOWS)
system(hex::format("start {0}", command).c_str()); system(hex::format("start {0}", command).c_str());
#elif defined(OS_MACOS) #elif defined(OS_MACOS)
system(hex::format("open {0}", command).c_str()); system(hex::format("open {0}", command).c_str());
#elif defined(OS_LINUX) #elif defined(OS_LINUX)
system(hex::format("xdg-open {0}", command).c_str()); system(hex::format("xdg-open {0}", command).c_str());
#else #else
#warning "Unknown OS, can't open webpages" #warning "Unknown OS, can't open webpages"
#endif #endif
} }
void openWebpage(std::string url) { void openWebpage(std::string url) {
@ -194,18 +244,17 @@ namespace hex {
if (url.find("://") == std::string::npos) if (url.find("://") == std::string::npos)
url = "https://" + url; url = "https://" + url;
#if defined(OS_WINDOWS) #if defined(OS_WINDOWS)
ShellExecute(nullptr, "open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL); ShellExecute(nullptr, "open", url.c_str(), nullptr, nullptr, SW_SHOWNORMAL);
#elif defined(OS_MACOS) #elif defined(OS_MACOS)
CFURLRef urlRef = CFURLCreateWithBytes(nullptr, reinterpret_cast<u8*>(url.data()), url.length(), kCFStringEncodingASCII, nullptr); CFURLRef urlRef = CFURLCreateWithBytes(nullptr, reinterpret_cast<u8 *>(url.data()), url.length(), kCFStringEncodingASCII, nullptr);
LSOpenCFURLRef(urlRef, nullptr); LSOpenCFURLRef(urlRef, nullptr);
CFRelease(urlRef); CFRelease(urlRef);
#elif defined(OS_LINUX) #elif defined(OS_LINUX)
system(hex::format("xdg-open {0}", url).c_str()); system(hex::format("xdg-open {0}", url).c_str());
#else #else
#warning "Unknown OS, can't open webpages" #warning "Unknown OS, can't open webpages"
#endif #endif
} }
void openFileBrowser(const std::string &title, DialogMode mode, const std::vector<nfdfilteritem_t> &validExtensions, const std::function<void(fs::path)> &callback, const std::string &defaultPath) { void openFileBrowser(const std::string &title, DialogMode mode, const std::vector<nfdfilteritem_t> &validExtensions, const std::function<void(fs::path)> &callback, const std::string &defaultPath) {
@ -223,7 +272,8 @@ namespace hex {
case DialogMode::Folder: case DialogMode::Folder:
result = NFD::PickFolder(outPath, defaultPath.c_str()); result = NFD::PickFolder(outPath, defaultPath.c_str());
break; break;
default: __builtin_unreachable(); default:
__builtin_unreachable();
} }
if (result == NFD_OKAY) { if (result == NFD_OKAY) {
@ -265,11 +315,11 @@ namespace hex {
result = (sign << 31) | ((exponent + (0x7F - 15)) << 23) | (mantissa << 13); result = (sign << 31) | ((exponent + (0x7F - 15)) << 23) | (mantissa << 13);
} }
return reinterpret_cast<float&>(result); return reinterpret_cast<float &>(result);
} }
bool isProcessElevated() { bool isProcessElevated() {
#if defined (OS_WINDOWS) #if defined(OS_WINDOWS)
bool elevated = false; bool elevated = false;
HANDLE token = INVALID_HANDLE_VALUE; HANDLE token = INVALID_HANDLE_VALUE;
@ -286,9 +336,9 @@ namespace hex {
return elevated; return elevated;
#elif defined(OS_LINUX) || defined (OS_MACOS) #elif defined(OS_LINUX) || defined(OS_MACOS)
return getuid() < 0 || getuid() != geteuid(); return getuid() < 0 || getuid() != geteuid();
#endif #endif
} }
} }

View File

@ -30,8 +30,8 @@ namespace hex::pl {
pattern = new PatternDataBoolean(0, this); pattern = new PatternDataBoolean(0, this);
else if (std::get_if<char>(&value.value()) != nullptr) else if (std::get_if<char>(&value.value()) != nullptr)
pattern = new PatternDataCharacter(0, this); pattern = new PatternDataCharacter(0, this);
else if (std::get_if<PatternData*>(&value.value()) != nullptr) else if (std::get_if<PatternData *>(&value.value()) != nullptr)
pattern = std::get<PatternData*>(value.value())->clone(); pattern = std::get<PatternData *>(value.value())->clone();
else if (std::get_if<std::string>(&value.value()) != nullptr) else if (std::get_if<std::string>(&value.value()) != nullptr)
pattern = new PatternDataString(0, 1, this); pattern = new PatternDataString(0, 1, this);
else else
@ -49,7 +49,7 @@ namespace hex::pl {
this->m_outVariables[name] = pattern->getOffset(); this->m_outVariables[name] = pattern->getOffset();
} }
void Evaluator::setVariable(const std::string &name, const Token::Literal& value) { void Evaluator::setVariable(const std::string &name, const Token::Literal &value) {
PatternData *pattern = nullptr; PatternData *pattern = nullptr;
{ {
@ -80,48 +80,47 @@ namespace hex::pl {
Token::Literal castedLiteral = std::visit(overloaded { Token::Literal castedLiteral = std::visit(overloaded {
[&](double &value) -> Token::Literal { [&](double &value) -> Token::Literal {
if (dynamic_cast<PatternDataUnsigned*>(pattern)) if (dynamic_cast<PatternDataUnsigned *>(pattern))
return u128(value) & bitmask(pattern->getSize() * 8); return u128(value) & bitmask(pattern->getSize() * 8);
else if (dynamic_cast<PatternDataSigned*>(pattern)) else if (dynamic_cast<PatternDataSigned *>(pattern))
return i128(value) & bitmask(pattern->getSize() * 8); return i128(value) & bitmask(pattern->getSize() * 8);
else if (dynamic_cast<PatternDataFloat*>(pattern)) else if (dynamic_cast<PatternDataFloat *>(pattern))
return pattern->getSize() == sizeof(float) ? double(float(value)) : value; return pattern->getSize() == sizeof(float) ? double(float(value)) : value;
else else
LogConsole::abortEvaluation(hex::format("cannot cast type 'double' to type '{}'", pattern->getTypeName())); LogConsole::abortEvaluation(hex::format("cannot cast type 'double' to type '{}'", pattern->getTypeName()));
}, },
[&](const std::string &value) -> Token::Literal { [&](const std::string &value) -> Token::Literal {
if (dynamic_cast<PatternDataString*>(pattern)) if (dynamic_cast<PatternDataString *>(pattern))
return value; return value;
else else
LogConsole::abortEvaluation(hex::format("cannot cast type 'string' to type '{}'", pattern->getTypeName())); LogConsole::abortEvaluation(hex::format("cannot cast type 'string' to type '{}'", pattern->getTypeName()));
}, },
[&](PatternData * const &value) -> Token::Literal { [&](PatternData *const &value) -> Token::Literal {
if (value->getTypeName() == pattern->getTypeName()) if (value->getTypeName() == pattern->getTypeName())
return value; return value;
else else
LogConsole::abortEvaluation(hex::format("cannot cast type '{}' to type '{}'", value->getTypeName(), pattern->getTypeName())); LogConsole::abortEvaluation(hex::format("cannot cast type '{}' to type '{}'", value->getTypeName(), pattern->getTypeName()));
}, },
[&](auto &&value) -> Token::Literal { [&](auto &&value) -> Token::Literal {
if (dynamic_cast<PatternDataUnsigned*>(pattern) || dynamic_cast<PatternDataEnum*>(pattern)) if (dynamic_cast<PatternDataUnsigned *>(pattern) || dynamic_cast<PatternDataEnum *>(pattern))
return u128(value) & bitmask(pattern->getSize() * 8); return u128(value) & bitmask(pattern->getSize() * 8);
else if (dynamic_cast<PatternDataSigned*>(pattern)) else if (dynamic_cast<PatternDataSigned *>(pattern))
return i128(value) & bitmask(pattern->getSize() * 8); return i128(value) & bitmask(pattern->getSize() * 8);
else if (dynamic_cast<PatternDataCharacter*>(pattern)) else if (dynamic_cast<PatternDataCharacter *>(pattern))
return char(value); return char(value);
else if (dynamic_cast<PatternDataBoolean*>(pattern)) else if (dynamic_cast<PatternDataBoolean *>(pattern))
return bool(value); return bool(value);
else if (dynamic_cast<PatternDataFloat*>(pattern)) else if (dynamic_cast<PatternDataFloat *>(pattern))
return pattern->getSize() == sizeof(float) ? double(float(value)) : value; return pattern->getSize() == sizeof(float) ? double(float(value)) : value;
else else
LogConsole::abortEvaluation(hex::format("cannot cast integer literal to type '{}'", pattern->getTypeName())); LogConsole::abortEvaluation(hex::format("cannot cast integer literal to type '{}'", pattern->getTypeName()));
} } },
}, value); value);
this->getStack()[pattern->getOffset()] = castedLiteral; this->getStack()[pattern->getOffset()] = castedLiteral;
} }
std::optional<std::vector<PatternData*>> Evaluator::evaluate(const std::vector<ASTNode*> &ast) { std::optional<std::vector<PatternData *>> Evaluator::evaluate(const std::vector<ASTNode *> &ast) {
this->m_stack.clear(); this->m_stack.clear();
this->m_customFunctions.clear(); this->m_customFunctions.clear();
this->m_scopes.clear(); this->m_scopes.clear();
@ -143,20 +142,20 @@ namespace hex::pl {
delete func; delete func;
this->m_customFunctionDefinitions.clear(); this->m_customFunctionDefinitions.clear();
std::vector<PatternData*> patterns; std::vector<PatternData *> patterns;
try { try {
this->setCurrentControlFlowStatement(ControlFlowStatement::None); this->setCurrentControlFlowStatement(ControlFlowStatement::None);
pushScope(nullptr, patterns); pushScope(nullptr, patterns);
for (auto node : ast) { for (auto node : ast) {
if (dynamic_cast<ASTNodeTypeDecl*>(node)) { if (dynamic_cast<ASTNodeTypeDecl *>(node)) {
;// Don't create patterns from type declarations ; // Don't create patterns from type declarations
} else if (dynamic_cast<ASTNodeFunctionCall*>(node)) { } else if (dynamic_cast<ASTNodeFunctionCall *>(node)) {
delete node->evaluate(this); delete node->evaluate(this);
} else if (dynamic_cast<ASTNodeFunctionDefinition*>(node)) { } else if (dynamic_cast<ASTNodeFunctionDefinition *>(node)) {
this->m_customFunctionDefinitions.push_back(node->evaluate(this)); this->m_customFunctionDefinitions.push_back(node->evaluate(this));
} else if (auto varDeclNode = dynamic_cast<ASTNodeVariableDecl*>(node)) { } else if (auto varDeclNode = dynamic_cast<ASTNodeVariableDecl *>(node)) {
auto pattern = node->createPatterns(this).front(); auto pattern = node->createPatterns(this).front();
if (varDeclNode->getPlacementOffset() == nullptr) { if (varDeclNode->getPlacementOffset() == nullptr) {
@ -185,7 +184,7 @@ namespace hex::pl {
if (mainFunction.parameterCount > 0) if (mainFunction.parameterCount > 0)
LogConsole::abortEvaluation("main function may not accept any arguments"); LogConsole::abortEvaluation("main function may not accept any arguments");
auto result = mainFunction.func(this, { }); auto result = mainFunction.func(this, {});
if (result) { if (result) {
auto returnCode = Token::literalToSigned(*result); auto returnCode = Token::literalToSigned(*result);

View File

@ -10,7 +10,7 @@ namespace hex::pl {
#define TOKEN(type, value) Token::Type::type, Token::type::value, lineNumber #define TOKEN(type, value) Token::Type::type, Token::type::value, lineNumber
#define VALUE_TOKEN(type, value) Token::Type::type, value, lineNumber #define VALUE_TOKEN(type, value) Token::Type::type, value, lineNumber
std::string matchTillInvalid(const char* characters, std::function<bool(char)> predicate) { std::string matchTillInvalid(const char *characters, std::function<bool(char)> predicate) {
std::string ret; std::string ret;
while (*characters != 0x00) { while (*characters != 0x00) {
@ -55,46 +55,46 @@ namespace hex::pl {
base = 16; base = 16;
if (Token::isFloatingPoint(type)) if (Token::isFloatingPoint(type))
return { }; return {};
if (numberData.find_first_not_of("0123456789ABCDEFabcdef") != std::string_view::npos) if (numberData.find_first_not_of("0123456789ABCDEFabcdef") != std::string_view::npos)
return { }; return {};
} else if (numberData.starts_with("0b")) { } else if (numberData.starts_with("0b")) {
numberData = numberData.substr(2); numberData = numberData.substr(2);
base = 2; base = 2;
if (Token::isFloatingPoint(type)) if (Token::isFloatingPoint(type))
return { }; return {};
if (numberData.find_first_not_of("01") != std::string_view::npos) if (numberData.find_first_not_of("01") != std::string_view::npos)
return { }; return {};
} else if (numberData.find('.') != std::string_view::npos || Token::isFloatingPoint(type)) { } else if (numberData.find('.') != std::string_view::npos || Token::isFloatingPoint(type)) {
base = 10; base = 10;
if (type == Token::ValueType::Any) if (type == Token::ValueType::Any)
type = Token::ValueType::Double; type = Token::ValueType::Double;
if (std::count(numberData.begin(), numberData.end(), '.') > 1 || numberData.find_first_not_of("0123456789.") != std::string_view::npos) if (std::count(numberData.begin(), numberData.end(), '.') > 1 || numberData.find_first_not_of("0123456789.") != std::string_view::npos)
return { }; return {};
if (numberData.ends_with('.')) if (numberData.ends_with('.'))
return { }; return {};
} else if (isdigit(numberData[0])) { } else if (isdigit(numberData[0])) {
base = 10; base = 10;
if (numberData.find_first_not_of("0123456789") != std::string_view::npos) if (numberData.find_first_not_of("0123456789") != std::string_view::npos)
return { }; return {};
} else return { }; } else return {};
if (type == Token::ValueType::Any) if (type == Token::ValueType::Any)
type = Token::ValueType::Signed128Bit; type = Token::ValueType::Signed128Bit;
if (numberData.length() == 0) if (numberData.length() == 0)
return { }; return {};
if (Token::isUnsigned(type) || Token::isSigned(type)) { if (Token::isUnsigned(type) || Token::isSigned(type)) {
u128 integer = 0; u128 integer = 0;
for (const char& c : numberData) { for (const char &c : numberData) {
integer *= base; integer *= base;
if (isdigit(c)) if (isdigit(c))
@ -103,82 +103,124 @@ namespace hex::pl {
integer += 10 + (c - 'A'); integer += 10 + (c - 'A');
else if (c >= 'a' && c <= 'f') else if (c >= 'a' && c <= 'f')
integer += 10 + (c - 'a'); integer += 10 + (c - 'a');
else return { }; else return {};
} }
switch (type) { switch (type) {
case Token::ValueType::Unsigned128Bit: return { u128(integer) }; case Token::ValueType::Unsigned128Bit:
case Token::ValueType::Signed128Bit: return { i128(integer) }; return { u128(integer) };
default: return { }; case Token::ValueType::Signed128Bit:
return { i128(integer) };
default:
return {};
} }
} else if (Token::isFloatingPoint(type)) { } else if (Token::isFloatingPoint(type)) {
double floatingPoint = strtod(numberData.data(), nullptr); double floatingPoint = strtod(numberData.data(), nullptr);
switch (type) { switch (type) {
case Token::ValueType::Float: return { float(floatingPoint) }; case Token::ValueType::Float:
case Token::ValueType::Double: return { double(floatingPoint) }; return { float(floatingPoint) };
default: return { }; case Token::ValueType::Double:
return { double(floatingPoint) };
default:
return {};
} }
} }
return { }; return {};
} }
std::optional<std::pair<char, size_t>> getCharacter(const std::string &string) { std::optional<std::pair<char, size_t>> getCharacter(const std::string &string) {
if (string.length() < 1) if (string.length() < 1)
return { }; return {};
// Escape sequences // Escape sequences
if (string[0] == '\\') { if (string[0] == '\\') {
if (string.length() < 2) if (string.length() < 2)
return { }; return {};
// Handle simple escape sequences // Handle simple escape sequences
switch (string[1]) { switch (string[1]) {
case 'a': return {{ '\a', 2 }}; case 'a':
case 'b': return {{ '\b', 2 }}; return {
case 'f': return {{ '\f', 2 }}; {'\a', 2}
case 'n': return {{ '\n', 2 }}; };
case 'r': return {{ '\r', 2 }}; case 'b':
case 't': return {{ '\t', 2 }}; return {
case 'v': return {{ '\v', 2 }}; {'\b', 2}
case '\\': return {{ '\\', 2 }}; };
case '\'': return {{ '\'', 2 }}; case 'f':
case '\"': return {{ '\"', 2 }}; return {
{'\f', 2}
};
case 'n':
return {
{'\n', 2}
};
case 'r':
return {
{'\r', 2}
};
case 't':
return {
{'\t', 2}
};
case 'v':
return {
{'\v', 2}
};
case '\\':
return {
{'\\', 2}
};
case '\'':
return {
{'\'', 2}
};
case '\"':
return {
{'\"', 2}
};
} }
// Hexadecimal number // Hexadecimal number
if (string[1] == 'x') { if (string[1] == 'x') {
if (string.length() != 4) if (string.length() != 4)
return { }; return {};
if (!isxdigit(string[2]) || !isxdigit(string[3])) if (!isxdigit(string[2]) || !isxdigit(string[3]))
return { }; return {};
return {{ std::strtoul(&string[2], nullptr, 16), 4 }}; return {
{std::strtoul(&string[2], nullptr, 16), 4}
};
} }
// Octal number // Octal number
if (string[1] == 'o') { if (string[1] == 'o') {
if (string.length() != 5) if (string.length() != 5)
return { }; return {};
if (string[2] < '0' || string[2] > '7' || string[3] < '0' || string[3] > '7' || string[4] < '0' || string[4] > '7') if (string[2] < '0' || string[2] > '7' || string[3] < '0' || string[3] > '7' || string[4] < '0' || string[4] > '7')
return { }; return {};
return {{ std::strtoul(&string[2], nullptr, 8), 5 }}; return {
{std::strtoul(&string[2], nullptr, 8), 5}
};
} }
return { }; return {};
} else return {{ string[0], 1 }}; } else return {
{string[0], 1}
};
} }
std::optional<std::pair<std::string, size_t>> getStringLiteral(const std::string &string) { std::optional<std::pair<std::string, size_t>> getStringLiteral(const std::string &string) {
if (!string.starts_with('\"')) if (!string.starts_with('\"'))
return { }; return {};
size_t size = 1; size_t size = 1;
@ -187,7 +229,7 @@ namespace hex::pl {
auto character = getCharacter(string.substr(size)); auto character = getCharacter(string.substr(size));
if (!character.has_value()) if (!character.has_value())
return { }; return {};
auto &[c, charSize] = character.value(); auto &[c, charSize] = character.value();
@ -195,34 +237,38 @@ namespace hex::pl {
size += charSize; size += charSize;
if (size >= string.length()) if (size >= string.length())
return { }; return {};
} }
return {{ result, size + 1 }}; return {
{result, size + 1}
};
} }
std::optional<std::pair<char, size_t>> getCharacterLiteral(const std::string &string) { std::optional<std::pair<char, size_t>> getCharacterLiteral(const std::string &string) {
if (string.empty()) if (string.empty())
return { }; return {};
if (string[0] != '\'') if (string[0] != '\'')
return { }; return {};
auto character = getCharacter(string.substr(1)); auto character = getCharacter(string.substr(1));
if (!character.has_value()) if (!character.has_value())
return { }; return {};
auto &[c, charSize] = character.value(); auto &[c, charSize] = character.value();
if (string.length() >= charSize + 2 && string[charSize + 1] != '\'') if (string.length() >= charSize + 2 && string[charSize + 1] != '\'')
return { }; return {};
return {{ c, charSize + 2 }}; return {
{c, charSize + 2}
};
} }
std::optional<std::vector<Token>> Lexer::lex(const std::string& code) { std::optional<std::vector<Token>> Lexer::lex(const std::string &code) {
std::vector<Token> tokens; std::vector<Token> tokens;
u32 offset = 0; u32 offset = 0;
@ -231,7 +277,7 @@ namespace hex::pl {
try { try {
while (offset < code.length()) { while (offset < code.length()) {
const char& c = code[offset]; const char &c = code[offset];
if (c == 0x00) if (c == 0x00)
break; break;
@ -350,12 +396,10 @@ namespace hex::pl {
} else if (code.substr(offset, 9) == "addressof") { } else if (code.substr(offset, 9) == "addressof") {
tokens.emplace_back(TOKEN(Operator, AddressOf)); tokens.emplace_back(TOKEN(Operator, AddressOf));
offset += 9; offset += 9;
} } else if (code.substr(offset, 6) == "sizeof") {
else if (code.substr(offset, 6) == "sizeof") {
tokens.emplace_back(TOKEN(Operator, SizeOf)); tokens.emplace_back(TOKEN(Operator, SizeOf));
offset += 6; offset += 6;
} } else if (c == '\'') {
else if (c == '\'') {
auto character = getCharacterLiteral(code.substr(offset)); auto character = getCharacterLiteral(code.substr(offset));
if (!character.has_value()) if (!character.has_value())
@ -480,13 +524,12 @@ namespace hex::pl {
offset += getIntegerLiteralLength(&code[offset]); offset += getIntegerLiteralLength(&code[offset]);
} else } else
throwLexerError("unknown token", lineNumber); throwLexerError("unknown token", lineNumber);
} }
tokens.emplace_back(TOKEN(Separator, EndOfProgram)); tokens.emplace_back(TOKEN(Separator, EndOfProgram));
} catch (LexerError &e) { } catch (LexerError &e) {
this->m_error = e; this->m_error = e;
return { }; return {};
} }

View File

@ -8,19 +8,17 @@ namespace hex::pl {
this->m_consoleLog.emplace_back(level, message); this->m_consoleLog.emplace_back(level, message);
} }
[[noreturn]] [[noreturn]] void LogConsole::abortEvaluation(const std::string &message) {
void LogConsole::abortEvaluation(const std::string &message) {
throw EvaluateError(0, message); throw EvaluateError(0, message);
} }
[[noreturn]] [[noreturn]] void LogConsole::abortEvaluation(const std::string &message, const ASTNode *node) {
void LogConsole::abortEvaluation(const std::string &message, const ASTNode *node) { throw EvaluateError(static_cast<const ASTNode *>(node)->getLineNumber(), message);
throw EvaluateError(static_cast<const ASTNode*>(node)->getLineNumber(), message);
} }
void LogConsole::clear() { void LogConsole::clear() {
this->m_consoleLog.clear(); this->m_consoleLog.clear();
this->m_lastHardError = { }; this->m_lastHardError = {};
} }
} }

View File

@ -16,13 +16,13 @@ namespace hex::pl {
/* Mathematical expressions */ /* Mathematical expressions */
// Identifier([(parseMathematicalExpression)|<(parseMathematicalExpression),...>(parseMathematicalExpression)] // Identifier([(parseMathematicalExpression)|<(parseMathematicalExpression),...>(parseMathematicalExpression)]
ASTNode* Parser::parseFunctionCall() { ASTNode *Parser::parseFunctionCall() {
std::string functionName = parseNamespaceResolution(); std::string functionName = parseNamespaceResolution();
if (!MATCHES(sequence(SEPARATOR_ROUNDBRACKETOPEN))) if (!MATCHES(sequence(SEPARATOR_ROUNDBRACKETOPEN)))
throwParseError("expected '(' after function name"); throwParseError("expected '(' after function name");
std::vector<ASTNode*> params; std::vector<ASTNode *> params;
auto paramCleanup = SCOPE_GUARD { auto paramCleanup = SCOPE_GUARD {
for (auto &param : params) for (auto &param : params)
delete param; delete param;
@ -37,7 +37,6 @@ namespace hex::pl {
break; break;
else if (!MATCHES(sequence(SEPARATOR_COMMA))) else if (!MATCHES(sequence(SEPARATOR_COMMA)))
throwParseError("missing ',' between parameters", -1); throwParseError("missing ',' between parameters", -1);
} }
paramCleanup.release(); paramCleanup.release();
@ -45,7 +44,7 @@ namespace hex::pl {
return create(new ASTNodeFunctionCall(functionName, params)); return create(new ASTNodeFunctionCall(functionName, params));
} }
ASTNode* Parser::parseStringLiteral() { ASTNode *Parser::parseStringLiteral() {
return create(new ASTNodeLiteral(getValue<Token::Literal>(-1))); return create(new ASTNodeLiteral(getValue<Token::Literal>(-1)));
} }
@ -58,15 +57,14 @@ namespace hex::pl {
if (MATCHES(sequence(OPERATOR_SCOPERESOLUTION, IDENTIFIER))) { if (MATCHES(sequence(OPERATOR_SCOPERESOLUTION, IDENTIFIER))) {
name += "::"; name += "::";
continue; continue;
} } else
else
break; break;
} }
return name; return name;
} }
ASTNode* Parser::parseScopeResolution() { ASTNode *Parser::parseScopeResolution() {
std::string typeName; std::string typeName;
while (true) { while (true) {
@ -82,8 +80,7 @@ namespace hex::pl {
return create(new ASTNodeScopeResolution(this->m_types[typeName]->clone(), getValue<Token::Identifier>(-1).get())); return create(new ASTNodeScopeResolution(this->m_types[typeName]->clone(), getValue<Token::Identifier>(-1).get()));
} }
} } else
else
break; break;
} }
@ -91,7 +88,7 @@ namespace hex::pl {
} }
// <Identifier[.]...> // <Identifier[.]...>
ASTNode* Parser::parseRValue(ASTNodeRValue::Path &path) { ASTNode *Parser::parseRValue(ASTNodeRValue::Path &path) {
if (peek(IDENTIFIER, -1)) if (peek(IDENTIFIER, -1))
path.push_back(getValue<Token::Identifier>(-1).get()); path.push_back(getValue<Token::Identifier>(-1).get());
else if (peek(KEYWORD_PARENT, -1)) else if (peek(KEYWORD_PARENT, -1))
@ -115,7 +112,7 @@ namespace hex::pl {
} }
// <Integer|((parseMathematicalExpression))> // <Integer|((parseMathematicalExpression))>
ASTNode* Parser::parseFactor() { ASTNode *Parser::parseFactor() {
if (MATCHES(sequence(INTEGER))) if (MATCHES(sequence(INTEGER)))
return new ASTNodeLiteral(getValue<Token::Literal>(-1)); return new ASTNodeLiteral(getValue<Token::Literal>(-1));
else if (peek(OPERATOR_PLUS) || peek(OPERATOR_MINUS) || peek(OPERATOR_BITNOT) || peek(OPERATOR_BOOLNOT)) else if (peek(OPERATOR_PLUS) || peek(OPERATOR_MINUS) || peek(OPERATOR_BITNOT) || peek(OPERATOR_BOOLNOT))
@ -165,10 +162,10 @@ namespace hex::pl {
throwParseError("expected value or parenthesis"); throwParseError("expected value or parenthesis");
} }
ASTNode* Parser::parseCastExpression() { ASTNode *Parser::parseCastExpression() {
if (peek(KEYWORD_BE) || peek(KEYWORD_LE) || peek(VALUETYPE_ANY)) { if (peek(KEYWORD_BE) || peek(KEYWORD_LE) || peek(VALUETYPE_ANY)) {
auto type = parseType(true); auto type = parseType(true);
auto builtinType = dynamic_cast<ASTNodeBuiltinType*>(type->getType()); auto builtinType = dynamic_cast<ASTNodeBuiltinType *>(type->getType());
if (builtinType == nullptr) if (builtinType == nullptr)
throwParseError("invalid type used for pointer size", -1); throwParseError("invalid type used for pointer size", -1);
@ -183,7 +180,7 @@ namespace hex::pl {
} }
// <+|-|!|~> (parseFactor) // <+|-|!|~> (parseFactor)
ASTNode* Parser::parseUnaryExpression() { ASTNode *Parser::parseUnaryExpression() {
if (MATCHES(oneOf(OPERATOR_PLUS, OPERATOR_MINUS, OPERATOR_BOOLNOT, OPERATOR_BITNOT))) { if (MATCHES(oneOf(OPERATOR_PLUS, OPERATOR_MINUS, OPERATOR_BOOLNOT, OPERATOR_BITNOT))) {
auto op = getValue<Token::Operator>(-1); auto op = getValue<Token::Operator>(-1);
@ -196,7 +193,7 @@ namespace hex::pl {
} }
// (parseUnaryExpression) <*|/|%> (parseUnaryExpression) // (parseUnaryExpression) <*|/|%> (parseUnaryExpression)
ASTNode* Parser::parseMultiplicativeExpression() { ASTNode *Parser::parseMultiplicativeExpression() {
auto node = this->parseUnaryExpression(); auto node = this->parseUnaryExpression();
auto nodeCleanup = SCOPE_GUARD { delete node; }; auto nodeCleanup = SCOPE_GUARD { delete node; };
@ -212,7 +209,7 @@ namespace hex::pl {
} }
// (parseMultiplicativeExpression) <+|-> (parseMultiplicativeExpression) // (parseMultiplicativeExpression) <+|-> (parseMultiplicativeExpression)
ASTNode* Parser::parseAdditiveExpression() { ASTNode *Parser::parseAdditiveExpression() {
auto node = this->parseMultiplicativeExpression(); auto node = this->parseMultiplicativeExpression();
auto nodeCleanup = SCOPE_GUARD { delete node; }; auto nodeCleanup = SCOPE_GUARD { delete node; };
@ -228,7 +225,7 @@ namespace hex::pl {
} }
// (parseAdditiveExpression) < >>|<< > (parseAdditiveExpression) // (parseAdditiveExpression) < >>|<< > (parseAdditiveExpression)
ASTNode* Parser::parseShiftExpression() { ASTNode *Parser::parseShiftExpression() {
auto node = this->parseAdditiveExpression(); auto node = this->parseAdditiveExpression();
auto nodeCleanup = SCOPE_GUARD { delete node; }; auto nodeCleanup = SCOPE_GUARD { delete node; };
@ -244,10 +241,10 @@ namespace hex::pl {
} }
// (parseAdditiveExpression) < >=|<=|>|< > (parseAdditiveExpression) // (parseAdditiveExpression) < >=|<=|>|< > (parseAdditiveExpression)
ASTNode* Parser::parseRelationExpression() { ASTNode *Parser::parseRelationExpression() {
auto node = this->parseShiftExpression(); auto node = this->parseShiftExpression();
auto nodeCleanup = SCOPE_GUARD{ delete node; }; auto nodeCleanup = SCOPE_GUARD { delete node; };
while (MATCHES(sequence(OPERATOR_BOOLGREATERTHAN) || sequence(OPERATOR_BOOLLESSTHAN) || sequence(OPERATOR_BOOLGREATERTHANOREQUALS) || sequence(OPERATOR_BOOLLESSTHANOREQUALS))) { while (MATCHES(sequence(OPERATOR_BOOLGREATERTHAN) || sequence(OPERATOR_BOOLLESSTHAN) || sequence(OPERATOR_BOOLGREATERTHANOREQUALS) || sequence(OPERATOR_BOOLLESSTHANOREQUALS))) {
auto op = getValue<Token::Operator>(-1); auto op = getValue<Token::Operator>(-1);
@ -260,7 +257,7 @@ namespace hex::pl {
} }
// (parseRelationExpression) <==|!=> (parseRelationExpression) // (parseRelationExpression) <==|!=> (parseRelationExpression)
ASTNode* Parser::parseEqualityExpression() { ASTNode *Parser::parseEqualityExpression() {
auto node = this->parseRelationExpression(); auto node = this->parseRelationExpression();
auto nodeCleanup = SCOPE_GUARD { delete node; }; auto nodeCleanup = SCOPE_GUARD { delete node; };
@ -276,7 +273,7 @@ namespace hex::pl {
} }
// (parseEqualityExpression) & (parseEqualityExpression) // (parseEqualityExpression) & (parseEqualityExpression)
ASTNode* Parser::parseBinaryAndExpression() { ASTNode *Parser::parseBinaryAndExpression() {
auto node = this->parseEqualityExpression(); auto node = this->parseEqualityExpression();
auto nodeCleanup = SCOPE_GUARD { delete node; }; auto nodeCleanup = SCOPE_GUARD { delete node; };
@ -291,7 +288,7 @@ namespace hex::pl {
} }
// (parseBinaryAndExpression) ^ (parseBinaryAndExpression) // (parseBinaryAndExpression) ^ (parseBinaryAndExpression)
ASTNode* Parser::parseBinaryXorExpression() { ASTNode *Parser::parseBinaryXorExpression() {
auto node = this->parseBinaryAndExpression(); auto node = this->parseBinaryAndExpression();
auto nodeCleanup = SCOPE_GUARD { delete node; }; auto nodeCleanup = SCOPE_GUARD { delete node; };
@ -306,7 +303,7 @@ namespace hex::pl {
} }
// (parseBinaryXorExpression) | (parseBinaryXorExpression) // (parseBinaryXorExpression) | (parseBinaryXorExpression)
ASTNode* Parser::parseBinaryOrExpression() { ASTNode *Parser::parseBinaryOrExpression() {
auto node = this->parseBinaryXorExpression(); auto node = this->parseBinaryXorExpression();
auto nodeCleanup = SCOPE_GUARD { delete node; }; auto nodeCleanup = SCOPE_GUARD { delete node; };
@ -321,7 +318,7 @@ namespace hex::pl {
} }
// (parseBinaryOrExpression) && (parseBinaryOrExpression) // (parseBinaryOrExpression) && (parseBinaryOrExpression)
ASTNode* Parser::parseBooleanAnd() { ASTNode *Parser::parseBooleanAnd() {
auto node = this->parseBinaryOrExpression(); auto node = this->parseBinaryOrExpression();
auto nodeCleanup = SCOPE_GUARD { delete node; }; auto nodeCleanup = SCOPE_GUARD { delete node; };
@ -336,7 +333,7 @@ namespace hex::pl {
} }
// (parseBooleanAnd) ^^ (parseBooleanAnd) // (parseBooleanAnd) ^^ (parseBooleanAnd)
ASTNode* Parser::parseBooleanXor() { ASTNode *Parser::parseBooleanXor() {
auto node = this->parseBooleanAnd(); auto node = this->parseBooleanAnd();
auto nodeCleanup = SCOPE_GUARD { delete node; }; auto nodeCleanup = SCOPE_GUARD { delete node; };
@ -351,7 +348,7 @@ namespace hex::pl {
} }
// (parseBooleanXor) || (parseBooleanXor) // (parseBooleanXor) || (parseBooleanXor)
ASTNode* Parser::parseBooleanOr() { ASTNode *Parser::parseBooleanOr() {
auto node = this->parseBooleanXor(); auto node = this->parseBooleanXor();
auto nodeCleanup = SCOPE_GUARD { delete node; }; auto nodeCleanup = SCOPE_GUARD { delete node; };
@ -366,7 +363,7 @@ namespace hex::pl {
} }
// (parseBooleanOr) ? (parseBooleanOr) : (parseBooleanOr) // (parseBooleanOr) ? (parseBooleanOr) : (parseBooleanOr)
ASTNode* Parser::parseTernaryConditional() { ASTNode *Parser::parseTernaryConditional() {
auto node = this->parseBooleanOr(); auto node = this->parseBooleanOr();
auto nodeCleanup = SCOPE_GUARD { delete node; }; auto nodeCleanup = SCOPE_GUARD { delete node; };
@ -387,7 +384,7 @@ namespace hex::pl {
} }
// (parseTernaryConditional) // (parseTernaryConditional)
ASTNode* Parser::parseMathematicalExpression() { ASTNode *Parser::parseMathematicalExpression() {
return this->parseTernaryConditional(); return this->parseTernaryConditional();
} }
@ -410,8 +407,7 @@ namespace hex::pl {
throwParseError("expected string attribute argument"); throwParseError("expected string attribute argument");
currNode->addAttribute(create(new ASTNodeAttribute(attribute, *string))); currNode->addAttribute(create(new ASTNodeAttribute(attribute, *string)));
} } else
else
currNode->addAttribute(create(new ASTNodeAttribute(attribute))); currNode->addAttribute(create(new ASTNodeAttribute(attribute)));
} while (MATCHES(sequence(SEPARATOR_COMMA))); } while (MATCHES(sequence(SEPARATOR_COMMA)));
@ -422,9 +418,9 @@ namespace hex::pl {
/* Functions */ /* Functions */
ASTNode* Parser::parseFunctionDefinition() { ASTNode *Parser::parseFunctionDefinition() {
const auto &functionName = getValue<Token::Identifier>(-2).get(); const auto &functionName = getValue<Token::Identifier>(-2).get();
std::vector<std::pair<std::string, ASTNode*>> params; std::vector<std::pair<std::string, ASTNode *>> params;
// Parse parameter list // Parse parameter list
bool hasParams = !peek(SEPARATOR_ROUNDBRACKETCLOSE); bool hasParams = !peek(SEPARATOR_ROUNDBRACKETCLOSE);
@ -456,7 +452,7 @@ namespace hex::pl {
// Parse function body // Parse function body
std::vector<ASTNode*> body; std::vector<ASTNode *> body;
auto bodyCleanup = SCOPE_GUARD { auto bodyCleanup = SCOPE_GUARD {
for (auto &node : body) for (auto &node : body)
delete node; delete node;
@ -470,7 +466,7 @@ namespace hex::pl {
return create(new ASTNodeFunctionDefinition(getNamespacePrefixedName(functionName), params, body)); return create(new ASTNodeFunctionDefinition(getNamespacePrefixedName(functionName), params, body));
} }
ASTNode* Parser::parseFunctionVariableDecl() { ASTNode *Parser::parseFunctionVariableDecl() {
ASTNode *statement; ASTNode *statement;
auto type = parseType(true); auto type = parseType(true);
@ -483,14 +479,13 @@ namespace hex::pl {
statement = create(new ASTNodeCompoundStatement({ statement, create(new ASTNodeAssignment(identifier, expression)) })); statement = create(new ASTNodeCompoundStatement({ statement, create(new ASTNodeAssignment(identifier, expression)) }));
} }
} } else
else
throwParseError("invalid variable declaration"); throwParseError("invalid variable declaration");
return statement; return statement;
} }
ASTNode* Parser::parseFunctionStatement() { ASTNode *Parser::parseFunctionStatement() {
bool needsSemicolon = true; bool needsSemicolon = true;
ASTNode *statement; ASTNode *statement;
@ -515,16 +510,13 @@ namespace hex::pl {
if (isFunction) { if (isFunction) {
this->m_curr = originalPos; this->m_curr = originalPos;
statement = parseFunctionCall(); statement = parseFunctionCall();
} } else {
else {
this->m_curr = originalPos - 1; this->m_curr = originalPos - 1;
statement = parseFunctionVariableDecl(); statement = parseFunctionVariableDecl();
} }
} } else if (peek(KEYWORD_BE) || peek(KEYWORD_LE) || peek(VALUETYPE_ANY)) {
else if (peek(KEYWORD_BE) || peek(KEYWORD_LE) || peek(VALUETYPE_ANY)) {
statement = parseFunctionVariableDecl(); statement = parseFunctionVariableDecl();
} } else
else
throwParseError("invalid sequence", 0); throwParseError("invalid sequence", 0);
if (needsSemicolon && !MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION))) { if (needsSemicolon && !MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION))) {
@ -533,12 +525,13 @@ namespace hex::pl {
} }
// Consume superfluous semicolons // Consume superfluous semicolons
while (needsSemicolon && MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION))); while (needsSemicolon && MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION)))
;
return statement; return statement;
} }
ASTNode* Parser::parseFunctionVariableAssignment() { ASTNode *Parser::parseFunctionVariableAssignment() {
const auto &lvalue = getValue<Token::Identifier>(-2).get(); const auto &lvalue = getValue<Token::Identifier>(-2).get();
auto rvalue = this->parseMathematicalExpression(); auto rvalue = this->parseMathematicalExpression();
@ -546,7 +539,7 @@ namespace hex::pl {
return create(new ASTNodeAssignment(lvalue, rvalue)); return create(new ASTNodeAssignment(lvalue, rvalue));
} }
ASTNode* Parser::parseFunctionControlFlowStatement() { ASTNode *Parser::parseFunctionControlFlowStatement() {
ControlFlowStatement type; ControlFlowStatement type;
if (peek(KEYWORD_RETURN, -1)) if (peek(KEYWORD_RETURN, -1))
type = ControlFlowStatement::Return; type = ControlFlowStatement::Return;
@ -563,8 +556,8 @@ namespace hex::pl {
return create(new ASTNodeControlFlowStatement(type, this->parseMathematicalExpression())); return create(new ASTNodeControlFlowStatement(type, this->parseMathematicalExpression()));
} }
std::vector<ASTNode*> Parser::parseStatementBody() { std::vector<ASTNode *> Parser::parseStatementBody() {
std::vector<ASTNode*> body; std::vector<ASTNode *> body;
auto bodyCleanup = SCOPE_GUARD { auto bodyCleanup = SCOPE_GUARD {
for (auto &node : body) for (auto &node : body)
@ -584,9 +577,9 @@ namespace hex::pl {
return body; return body;
} }
ASTNode* Parser::parseFunctionConditional() { ASTNode *Parser::parseFunctionConditional() {
auto condition = parseMathematicalExpression(); auto condition = parseMathematicalExpression();
std::vector<ASTNode*> trueBody, falseBody; std::vector<ASTNode *> trueBody, falseBody;
auto cleanup = SCOPE_GUARD { auto cleanup = SCOPE_GUARD {
delete condition; delete condition;
@ -609,9 +602,9 @@ namespace hex::pl {
return create(new ASTNodeConditionalStatement(condition, trueBody, falseBody)); return create(new ASTNodeConditionalStatement(condition, trueBody, falseBody));
} }
ASTNode* Parser::parseFunctionWhileLoop() { ASTNode *Parser::parseFunctionWhileLoop() {
auto condition = parseMathematicalExpression(); auto condition = parseMathematicalExpression();
std::vector<ASTNode*> body; std::vector<ASTNode *> body;
auto cleanup = SCOPE_GUARD { auto cleanup = SCOPE_GUARD {
delete condition; delete condition;
@ -629,7 +622,7 @@ namespace hex::pl {
return create(new ASTNodeWhileStatement(condition, body)); return create(new ASTNodeWhileStatement(condition, body));
} }
ASTNode* Parser::parseFunctionForLoop() { ASTNode *Parser::parseFunctionForLoop() {
auto variable = parseFunctionVariableDecl(); auto variable = parseFunctionVariableDecl();
auto variableCleanup = SCOPE_GUARD { delete variable; }; auto variableCleanup = SCOPE_GUARD { delete variable; };
@ -648,7 +641,7 @@ namespace hex::pl {
auto postExpression = parseFunctionVariableAssignment(); auto postExpression = parseFunctionVariableAssignment();
auto postExpressionCleanup = SCOPE_GUARD { delete postExpression; }; auto postExpressionCleanup = SCOPE_GUARD { delete postExpression; };
std::vector<ASTNode*> body; std::vector<ASTNode *> body;
auto bodyCleanup = SCOPE_GUARD { auto bodyCleanup = SCOPE_GUARD {
for (auto &statement : body) for (auto &statement : body)
@ -671,9 +664,9 @@ namespace hex::pl {
/* Control flow */ /* Control flow */
// if ((parseMathematicalExpression)) { (parseMember) } // if ((parseMathematicalExpression)) { (parseMember) }
ASTNode* Parser::parseConditional() { ASTNode *Parser::parseConditional() {
auto condition = parseMathematicalExpression(); auto condition = parseMathematicalExpression();
std::vector<ASTNode*> trueBody, falseBody; std::vector<ASTNode *> trueBody, falseBody;
auto cleanup = SCOPE_GUARD { auto cleanup = SCOPE_GUARD {
delete condition; delete condition;
@ -706,7 +699,7 @@ namespace hex::pl {
} }
// while ((parseMathematicalExpression)) // while ((parseMathematicalExpression))
ASTNode* Parser::parseWhileStatement() { ASTNode *Parser::parseWhileStatement() {
auto condition = parseMathematicalExpression(); auto condition = parseMathematicalExpression();
auto cleanup = SCOPE_GUARD { auto cleanup = SCOPE_GUARD {
@ -718,13 +711,13 @@ namespace hex::pl {
cleanup.release(); cleanup.release();
return create(new ASTNodeWhileStatement(condition, { })); return create(new ASTNodeWhileStatement(condition, {}));
} }
/* Type declarations */ /* Type declarations */
// [be|le] <Identifier|u8|u16|u32|u64|u128|s8|s16|s32|s64|s128|float|double|str> // [be|le] <Identifier|u8|u16|u32|u64|u128|s8|s16|s32|s64|s128|float|double|str>
ASTNodeTypeDecl* Parser::parseType(bool allowFunctionTypes) { ASTNodeTypeDecl *Parser::parseType(bool allowFunctionTypes) {
std::optional<std::endian> endian; std::optional<std::endian> endian;
if (MATCHES(sequence(KEYWORD_LE))) if (MATCHES(sequence(KEYWORD_LE)))
@ -736,13 +729,12 @@ namespace hex::pl {
std::string typeName = parseNamespaceResolution(); std::string typeName = parseNamespaceResolution();
if (this->m_types.contains(typeName)) if (this->m_types.contains(typeName))
return create(new ASTNodeTypeDecl({ }, this->m_types[typeName]->clone(), endian)); return create(new ASTNodeTypeDecl({}, this->m_types[typeName]->clone(), endian));
else if (this->m_types.contains(getNamespacePrefixedName(typeName))) else if (this->m_types.contains(getNamespacePrefixedName(typeName)))
return create(new ASTNodeTypeDecl({ }, this->m_types[getNamespacePrefixedName(typeName)]->clone(), endian)); return create(new ASTNodeTypeDecl({}, this->m_types[getNamespacePrefixedName(typeName)]->clone(), endian));
else else
throwParseError(hex::format("unknown type '{}'", typeName)); throwParseError(hex::format("unknown type '{}'", typeName));
} } else if (MATCHES(sequence(VALUETYPE_ANY))) { // Builtin type
else if (MATCHES(sequence(VALUETYPE_ANY))) { // Builtin type
auto type = getValue<Token::ValueType>(-1); auto type = getValue<Token::ValueType>(-1);
if (!allowFunctionTypes) { if (!allowFunctionTypes) {
if (type == Token::ValueType::String) if (type == Token::ValueType::String)
@ -751,12 +743,12 @@ namespace hex::pl {
throwParseError("cannot use 'auto' in this context"); throwParseError("cannot use 'auto' in this context");
} }
return create(new ASTNodeTypeDecl({ }, new ASTNodeBuiltinType(type), endian)); return create(new ASTNodeTypeDecl({}, new ASTNodeBuiltinType(type), endian));
} else throwParseError("failed to parse type. Expected identifier or builtin type"); } else throwParseError("failed to parse type. Expected identifier or builtin type");
} }
// using Identifier = (parseType) // using Identifier = (parseType)
ASTNode* Parser::parseUsingDeclaration() { ASTNode *Parser::parseUsingDeclaration() {
auto name = parseNamespaceResolution(); auto name = parseNamespaceResolution();
if (!MATCHES(sequence(OPERATOR_ASSIGNMENT))) if (!MATCHES(sequence(OPERATOR_ASSIGNMENT)))
@ -769,7 +761,7 @@ namespace hex::pl {
} }
// padding[(parseMathematicalExpression)] // padding[(parseMathematicalExpression)]
ASTNode* Parser::parsePadding() { ASTNode *Parser::parsePadding() {
auto size = parseMathematicalExpression(); auto size = parseMathematicalExpression();
if (!MATCHES(sequence(SEPARATOR_SQUAREBRACKETCLOSE))) { if (!MATCHES(sequence(SEPARATOR_SQUAREBRACKETCLOSE))) {
@ -777,15 +769,17 @@ namespace hex::pl {
throwParseError("expected closing ']' at end of array declaration", -1); throwParseError("expected closing ']' at end of array declaration", -1);
} }
return create(new ASTNodeArrayVariableDecl({ }, new ASTNodeTypeDecl({ }, new ASTNodeBuiltinType(Token::ValueType::Padding)), size)); return create(new ASTNodeArrayVariableDecl({}, new ASTNodeTypeDecl({}, new ASTNodeBuiltinType(Token::ValueType::Padding)), size));
} }
// (parseType) Identifier // (parseType) Identifier
ASTNode* Parser::parseMemberVariable(ASTNodeTypeDecl *type) { ASTNode *Parser::parseMemberVariable(ASTNodeTypeDecl *type) {
if (peek(SEPARATOR_COMMA)) { if (peek(SEPARATOR_COMMA)) {
std::vector<ASTNode*> variables; std::vector<ASTNode *> variables;
auto variableCleanup = SCOPE_GUARD { for (auto var : variables) delete var; }; auto variableCleanup = SCOPE_GUARD {
for (auto var : variables) delete var;
};
do { do {
variables.push_back(create(new ASTNodeVariableDecl(getValue<Token::Identifier>(-1).get(), type->clone()))); variables.push_back(create(new ASTNodeVariableDecl(getValue<Token::Identifier>(-1).get(), type->clone())));
@ -800,7 +794,7 @@ namespace hex::pl {
} }
// (parseType) Identifier[(parseMathematicalExpression)] // (parseType) Identifier[(parseMathematicalExpression)]
ASTNode* Parser::parseMemberArrayVariable(ASTNodeTypeDecl *type) { ASTNode *Parser::parseMemberArrayVariable(ASTNodeTypeDecl *type) {
auto name = getValue<Token::Identifier>(-2).get(); auto name = getValue<Token::Identifier>(-2).get();
ASTNode *size = nullptr; ASTNode *size = nullptr;
@ -822,13 +816,13 @@ namespace hex::pl {
} }
// (parseType) *Identifier : (parseType) // (parseType) *Identifier : (parseType)
ASTNode* Parser::parseMemberPointerVariable(ASTNodeTypeDecl *type) { ASTNode *Parser::parseMemberPointerVariable(ASTNodeTypeDecl *type) {
auto name = getValue<Token::Identifier>(-2).get(); auto name = getValue<Token::Identifier>(-2).get();
auto sizeType = parseType(); auto sizeType = parseType();
{ {
auto builtinType = dynamic_cast<ASTNodeBuiltinType*>(sizeType->getType()); auto builtinType = dynamic_cast<ASTNodeBuiltinType *>(sizeType->getType());
if (builtinType == nullptr || !Token::isUnsigned(builtinType->getType())) if (builtinType == nullptr || !Token::isUnsigned(builtinType->getType()))
throwParseError("invalid type used for pointer size", -1); throwParseError("invalid type used for pointer size", -1);
@ -838,7 +832,7 @@ namespace hex::pl {
} }
// [(parsePadding)|(parseMemberVariable)|(parseMemberArrayVariable)|(parseMemberPointerVariable)] // [(parsePadding)|(parseMemberVariable)|(parseMemberArrayVariable)|(parseMemberPointerVariable)]
ASTNode* Parser::parseMember() { ASTNode *Parser::parseMember() {
ASTNode *member; ASTNode *member;
@ -873,8 +867,7 @@ namespace hex::pl {
else else
throwParseError("invalid variable declaration"); throwParseError("invalid variable declaration");
} }
} } else if (MATCHES(sequence(VALUETYPE_PADDING, SEPARATOR_SQUAREBRACKETOPEN)))
else if (MATCHES(sequence(VALUETYPE_PADDING, SEPARATOR_SQUAREBRACKETOPEN)))
member = parsePadding(); member = parsePadding();
else if (MATCHES(sequence(KEYWORD_IF, SEPARATOR_ROUNDBRACKETOPEN))) else if (MATCHES(sequence(KEYWORD_IF, SEPARATOR_ROUNDBRACKETOPEN)))
return parseConditional(); return parseConditional();
@ -894,18 +887,22 @@ namespace hex::pl {
throwParseError("missing ';' at end of expression", -1); throwParseError("missing ';' at end of expression", -1);
// Consume superfluous semicolons // Consume superfluous semicolons
while (MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION))); while (MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION)))
;
return member; return member;
} }
// struct Identifier { <(parseMember)...> } // struct Identifier { <(parseMember)...> }
ASTNode* Parser::parseStruct() { ASTNode *Parser::parseStruct() {
const auto &typeName = getValue<Token::Identifier>(-1).get(); const auto &typeName = getValue<Token::Identifier>(-1).get();
const auto structNode = create(new ASTNodeStruct()); const auto structNode = create(new ASTNodeStruct());
const auto typeDecl = addType(typeName, structNode); const auto typeDecl = addType(typeName, structNode);
auto structGuard = SCOPE_GUARD { delete structNode; delete typeDecl; }; auto structGuard = SCOPE_GUARD {
delete structNode;
delete typeDecl;
};
if (MATCHES(sequence(OPERATOR_INHERIT, IDENTIFIER))) { if (MATCHES(sequence(OPERATOR_INHERIT, IDENTIFIER))) {
// Inheritance // Inheritance
@ -935,12 +932,15 @@ namespace hex::pl {
} }
// union Identifier { <(parseMember)...> } // union Identifier { <(parseMember)...> }
ASTNode* Parser::parseUnion() { ASTNode *Parser::parseUnion() {
const auto &typeName = getValue<Token::Identifier>(-2).get(); const auto &typeName = getValue<Token::Identifier>(-2).get();
const auto unionNode = create(new ASTNodeUnion()); const auto unionNode = create(new ASTNodeUnion());
const auto typeDecl = addType(typeName, unionNode); const auto typeDecl = addType(typeName, unionNode);
auto unionGuard = SCOPE_GUARD { delete unionNode; delete typeDecl; }; auto unionGuard = SCOPE_GUARD {
delete unionNode;
delete typeDecl;
};
while (!MATCHES(sequence(SEPARATOR_CURLYBRACKETCLOSE))) { while (!MATCHES(sequence(SEPARATOR_CURLYBRACKETCLOSE))) {
unionNode->addMember(parseMember()); unionNode->addMember(parseMember());
@ -952,7 +952,7 @@ namespace hex::pl {
} }
// enum Identifier : (parseType) { <<Identifier|Identifier = (parseMathematicalExpression)[,]>...> } // enum Identifier : (parseType) { <<Identifier|Identifier = (parseMathematicalExpression)[,]>...> }
ASTNode* Parser::parseEnum() { ASTNode *Parser::parseEnum() {
auto typeName = getValue<Token::Identifier>(-2).get(); auto typeName = getValue<Token::Identifier>(-2).get();
auto underlyingType = parseType(); auto underlyingType = parseType();
@ -960,7 +960,10 @@ namespace hex::pl {
const auto enumNode = create(new ASTNodeEnum(underlyingType)); const auto enumNode = create(new ASTNodeEnum(underlyingType));
const auto typeDecl = addType(typeName, enumNode); const auto typeDecl = addType(typeName, enumNode);
auto enumGuard = SCOPE_GUARD { delete enumNode; delete typeDecl; }; auto enumGuard = SCOPE_GUARD {
delete enumNode;
delete typeDecl;
};
if (!MATCHES(sequence(SEPARATOR_CURLYBRACKETOPEN))) if (!MATCHES(sequence(SEPARATOR_CURLYBRACKETOPEN)))
throwParseError("expected '{' after enum definition", -1); throwParseError("expected '{' after enum definition", -1);
@ -973,8 +976,7 @@ namespace hex::pl {
enumNode->addEntry(name, value); enumNode->addEntry(name, value);
lastEntry = value; lastEntry = value;
} } else if (MATCHES(sequence(IDENTIFIER))) {
else if (MATCHES(sequence(IDENTIFIER))) {
ASTNode *valueExpr; ASTNode *valueExpr;
auto name = getValue<Token::Identifier>(-1).get(); auto name = getValue<Token::Identifier>(-1).get();
if (enumNode->getEntries().empty()) if (enumNode->getEntries().empty())
@ -983,8 +985,7 @@ namespace hex::pl {
valueExpr = lastEntry = create(new ASTNodeMathematicalExpression(lastEntry->clone(), new ASTNodeLiteral(u128(1)), Token::Operator::Plus)); valueExpr = lastEntry = create(new ASTNodeMathematicalExpression(lastEntry->clone(), new ASTNodeLiteral(u128(1)), Token::Operator::Plus));
enumNode->addEntry(name, valueExpr); enumNode->addEntry(name, valueExpr);
} } else if (MATCHES(sequence(SEPARATOR_ENDOFPROGRAM)))
else if (MATCHES(sequence(SEPARATOR_ENDOFPROGRAM)))
throwParseError("unexpected end of program", -2); throwParseError("unexpected end of program", -2);
else else
throwParseError("invalid enum entry", -1); throwParseError("invalid enum entry", -1);
@ -1003,13 +1004,16 @@ namespace hex::pl {
} }
// bitfield Identifier { <Identifier : (parseMathematicalExpression)[;]...> } // bitfield Identifier { <Identifier : (parseMathematicalExpression)[;]...> }
ASTNode* Parser::parseBitfield() { ASTNode *Parser::parseBitfield() {
std::string typeName = getValue<Token::Identifier>(-2).get(); std::string typeName = getValue<Token::Identifier>(-2).get();
const auto bitfieldNode = create(new ASTNodeBitfield()); const auto bitfieldNode = create(new ASTNodeBitfield());
const auto typeDecl = addType(typeName, bitfieldNode); const auto typeDecl = addType(typeName, bitfieldNode);
auto enumGuard = SCOPE_GUARD { delete bitfieldNode; delete typeDecl; }; auto enumGuard = SCOPE_GUARD {
delete bitfieldNode;
delete typeDecl;
};
while (!MATCHES(sequence(SEPARATOR_CURLYBRACKETCLOSE))) { while (!MATCHES(sequence(SEPARATOR_CURLYBRACKETCLOSE))) {
if (MATCHES(sequence(IDENTIFIER, OPERATOR_INHERIT))) { if (MATCHES(sequence(IDENTIFIER, OPERATOR_INHERIT))) {
@ -1026,7 +1030,8 @@ namespace hex::pl {
throwParseError("missing ';' at end of expression", -1); throwParseError("missing ';' at end of expression", -1);
// Consume superfluous semicolons // Consume superfluous semicolons
while (MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION))); while (MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION)))
;
} }
enumGuard.release(); enumGuard.release();
@ -1035,7 +1040,7 @@ namespace hex::pl {
} }
// (parseType) Identifier @ Integer // (parseType) Identifier @ Integer
ASTNode* Parser::parseVariablePlacement(ASTNodeTypeDecl *type) { ASTNode *Parser::parseVariablePlacement(ASTNodeTypeDecl *type) {
bool inVariable = false; bool inVariable = false;
bool outVariable = false; bool outVariable = false;
@ -1046,8 +1051,7 @@ namespace hex::pl {
placementOffset = parseMathematicalExpression(); placementOffset = parseMathematicalExpression();
} else if (MATCHES(sequence(KEYWORD_IN))) { } else if (MATCHES(sequence(KEYWORD_IN))) {
inVariable = true; inVariable = true;
} } else if (MATCHES(sequence(KEYWORD_OUT))) {
else if (MATCHES(sequence(KEYWORD_OUT))) {
outVariable = true; outVariable = true;
} }
@ -1055,7 +1059,7 @@ namespace hex::pl {
} }
// (parseType) Identifier[[(parseMathematicalExpression)]] @ Integer // (parseType) Identifier[[(parseMathematicalExpression)]] @ Integer
ASTNode* Parser::parseArrayVariablePlacement(ASTNodeTypeDecl *type) { ASTNode *Parser::parseArrayVariablePlacement(ASTNodeTypeDecl *type) {
auto name = getValue<Token::Identifier>(-2).get(); auto name = getValue<Token::Identifier>(-2).get();
ASTNode *size = nullptr; ASTNode *size = nullptr;
@ -1082,14 +1086,14 @@ namespace hex::pl {
} }
// (parseType) *Identifier : (parseType) @ Integer // (parseType) *Identifier : (parseType) @ Integer
ASTNode* Parser::parsePointerVariablePlacement(ASTNodeTypeDecl *type) { ASTNode *Parser::parsePointerVariablePlacement(ASTNodeTypeDecl *type) {
auto name = getValue<Token::Identifier>(-2).get(); auto name = getValue<Token::Identifier>(-2).get();
auto sizeType = parseType(); auto sizeType = parseType();
auto sizeCleanup = SCOPE_GUARD { delete sizeType; }; auto sizeCleanup = SCOPE_GUARD { delete sizeType; };
{ {
auto builtinType = dynamic_cast<ASTNodeBuiltinType*>(sizeType->getType()); auto builtinType = dynamic_cast<ASTNodeBuiltinType *>(sizeType->getType());
if (builtinType == nullptr || !Token::isUnsigned(builtinType->getType())) if (builtinType == nullptr || !Token::isUnsigned(builtinType->getType()))
throwParseError("invalid type used for pointer size", -1); throwParseError("invalid type used for pointer size", -1);
@ -1105,8 +1109,8 @@ namespace hex::pl {
return create(new ASTNodePointerVariableDecl(name, type->clone(), sizeType, placementOffset)); return create(new ASTNodePointerVariableDecl(name, type->clone(), sizeType, placementOffset));
} }
std::vector<ASTNode*> Parser::parseNamespace() { std::vector<ASTNode *> Parser::parseNamespace() {
std::vector<ASTNode*> statements; std::vector<ASTNode *> statements;
if (!MATCHES(sequence(IDENTIFIER))) if (!MATCHES(sequence(IDENTIFIER)))
throwParseError("expected namespace identifier"); throwParseError("expected namespace identifier");
@ -1135,7 +1139,7 @@ namespace hex::pl {
return statements; return statements;
} }
ASTNode* Parser::parsePlacement() { ASTNode *Parser::parsePlacement() {
auto type = parseType(); auto type = parseType();
ON_SCOPE_EXIT { delete type; }; ON_SCOPE_EXIT { delete type; };
@ -1151,7 +1155,7 @@ namespace hex::pl {
/* Program */ /* Program */
// <(parseUsingDeclaration)|(parseVariablePlacement)|(parseStruct)> // <(parseUsingDeclaration)|(parseVariablePlacement)|(parseStruct)>
std::vector<ASTNode*> Parser::parseStatements() { std::vector<ASTNode *> Parser::parseStatements() {
ASTNode *statement = nullptr; ASTNode *statement = nullptr;
auto statementGuard = SCOPE_GUARD { auto statementGuard = SCOPE_GUARD {
delete statement; delete statement;
@ -1169,11 +1173,9 @@ namespace hex::pl {
if (isFunction) { if (isFunction) {
this->m_curr++; this->m_curr++;
statement = parseFunctionCall(); statement = parseFunctionCall();
} } else
else
statement = parsePlacement(); statement = parsePlacement();
} } else if (peek(KEYWORD_BE) || peek(KEYWORD_LE) || peek(VALUETYPE_ANY))
else if (peek(KEYWORD_BE) || peek(KEYWORD_LE) || peek(VALUETYPE_ANY))
statement = parsePlacement(); statement = parsePlacement();
else if (MATCHES(sequence(KEYWORD_STRUCT, IDENTIFIER))) else if (MATCHES(sequence(KEYWORD_STRUCT, IDENTIFIER)))
statement = parseStruct(); statement = parseStruct();
@ -1196,14 +1198,15 @@ namespace hex::pl {
throwParseError("missing ';' at end of expression", -1); throwParseError("missing ';' at end of expression", -1);
// Consume superfluous semicolons // Consume superfluous semicolons
while (MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION))); while (MATCHES(sequence(SEPARATOR_ENDOFEXPRESSION)))
;
statementGuard.release(); statementGuard.release();
return { statement }; return { statement };
} }
ASTNodeTypeDecl* Parser::addType(const std::string &name, ASTNode *node, std::optional<std::endian> endian) { ASTNodeTypeDecl *Parser::addType(const std::string &name, ASTNode *node, std::optional<std::endian> endian) {
auto typeName = getNamespacePrefixedName(name); auto typeName = getNamespacePrefixedName(name);
if (this->m_types.contains(typeName)) if (this->m_types.contains(typeName))
@ -1216,7 +1219,7 @@ namespace hex::pl {
} }
// <(parseNamespace)...> EndOfProgram // <(parseNamespace)...> EndOfProgram
std::optional<std::vector<ASTNode*>> Parser::parse(const std::vector<Token> &tokens) { std::optional<std::vector<ASTNode *>> Parser::parse(const std::vector<Token> &tokens) {
this->m_curr = tokens.begin(); this->m_curr = tokens.begin();
this->m_types.clear(); this->m_types.clear();
@ -1235,7 +1238,7 @@ namespace hex::pl {
this->m_error = e; this->m_error = e;
} }
return { }; return {};
} }
} }

View File

@ -94,29 +94,29 @@ namespace hex::pl {
delete this->m_validator; delete this->m_validator;
} }
std::optional<std::vector<ASTNode*>> PatternLanguage::parseString(const std::string &code) { std::optional<std::vector<ASTNode *>> PatternLanguage::parseString(const std::string &code) {
auto preprocessedCode = this->m_preprocessor->preprocess(code); auto preprocessedCode = this->m_preprocessor->preprocess(code);
if (!preprocessedCode.has_value()) { if (!preprocessedCode.has_value()) {
this->m_currError = this->m_preprocessor->getError(); this->m_currError = this->m_preprocessor->getError();
return { }; return {};
} }
auto tokens = this->m_lexer->lex(preprocessedCode.value()); auto tokens = this->m_lexer->lex(preprocessedCode.value());
if (!tokens.has_value()) { if (!tokens.has_value()) {
this->m_currError = this->m_lexer->getError(); this->m_currError = this->m_lexer->getError();
return { }; return {};
} }
auto ast = this->m_parser->parse(tokens.value()); auto ast = this->m_parser->parse(tokens.value());
if (!ast.has_value()) { if (!ast.has_value()) {
this->m_currError = this->m_parser->getError(); this->m_currError = this->m_parser->getError();
return { }; return {};
} }
return ast; return ast;
} }
std::optional<std::vector<PatternData*>> PatternLanguage::executeString(prv::Provider *provider, const std::string &code, const std::map<std::string, Token::Literal> &envVars, const std::map<std::string, Token::Literal> &inVariables) { std::optional<std::vector<PatternData *>> PatternLanguage::executeString(prv::Provider *provider, const std::string &code, const std::map<std::string, Token::Literal> &envVars, const std::map<std::string, Token::Literal> &inVariables) {
this->m_currError.reset(); this->m_currError.reset();
this->m_evaluator->getConsole().clear(); this->m_evaluator->getConsole().clear();
this->m_evaluator->setProvider(provider); this->m_evaluator->setProvider(provider);
@ -136,20 +136,20 @@ namespace hex::pl {
auto ast = this->parseString(code); auto ast = this->parseString(code);
if (!ast) if (!ast)
return { }; return {};
this->m_currAST = ast.value(); this->m_currAST = ast.value();
auto patterns = this->m_evaluator->evaluate(ast.value()); auto patterns = this->m_evaluator->evaluate(ast.value());
if (!patterns.has_value()) { if (!patterns.has_value()) {
this->m_currError = this->m_evaluator->getConsole().getLastHardError(); this->m_currError = this->m_evaluator->getConsole().getLastHardError();
return { }; return {};
} }
return patterns; return patterns;
} }
std::optional<std::vector<PatternData*>> PatternLanguage::executeFile(prv::Provider *provider, const fs::path &path, const std::map<std::string, Token::Literal> &envVars, const std::map<std::string, Token::Literal> &inVariables) { std::optional<std::vector<PatternData *>> PatternLanguage::executeFile(prv::Provider *provider, const fs::path &path, const std::map<std::string, Token::Literal> &envVars, const std::map<std::string, Token::Literal> &inVariables) {
File file(path, File::Mode::Read); File file(path, File::Mode::Read);
return this->executeString(provider, file.readString(), envVars, inVariables); return this->executeString(provider, file.readString(), envVars, inVariables);
@ -159,21 +159,20 @@ namespace hex::pl {
this->m_evaluator->abort(); this->m_evaluator->abort();
} }
const std::vector<ASTNode*> &PatternLanguage::getCurrentAST() const { const std::vector<ASTNode *> &PatternLanguage::getCurrentAST() const {
return this->m_currAST; return this->m_currAST;
} }
[[nodiscard]] [[nodiscard]] std::map<std::string, Token::Literal> PatternLanguage::getOutVariables() const {
std::map<std::string, Token::Literal> PatternLanguage::getOutVariables() const {
return this->m_evaluator->getOutVariables(); return this->m_evaluator->getOutVariables();
} }
const std::vector<std::pair<LogConsole::Level, std::string>>& PatternLanguage::getConsoleLog() { const std::vector<std::pair<LogConsole::Level, std::string>> &PatternLanguage::getConsoleLog() {
return this->m_evaluator->getConsole().getLog(); return this->m_evaluator->getConsole().getLog();
} }
const std::optional<std::pair<u32, std::string>>& PatternLanguage::getError() { const std::optional<std::pair<u32, std::string>> &PatternLanguage::getError() {
return this->m_currError; return this->m_currError;
} }

View File

@ -9,10 +9,9 @@
namespace hex::pl { namespace hex::pl {
Preprocessor::Preprocessor() { Preprocessor::Preprocessor() {
} }
std::optional<std::string> Preprocessor::preprocess(const std::string& code, bool initialRun) { std::optional<std::string> Preprocessor::preprocess(const std::string &code, bool initialRun) {
u32 offset = 0; u32 offset = 0;
u32 lineNumber = 1; u32 lineNumber = 1;
bool isInString = false; bool isInString = false;
@ -196,7 +195,7 @@ namespace hex::pl {
for (const auto &[define, value, defineLine] : sortedDefines) { for (const auto &[define, value, defineLine] : sortedDefines) {
i32 index = 0; i32 index = 0;
while((index = output.find(define, index)) != std::string::npos) { while ((index = output.find(define, index)) != std::string::npos) {
output.replace(index, define.length(), value); output.replace(index, define.length(), value);
index += value.length(); index += value.length();
} }
@ -213,13 +212,13 @@ namespace hex::pl {
} }
} catch (PreprocessorError &e) { } catch (PreprocessorError &e) {
this->m_error = e; this->m_error = e;
return { }; return {};
} }
return output; return output;
} }
void Preprocessor::addPragmaHandler(const std::string &pragmaType, const std::function<bool(const std::string&)> &function) { void Preprocessor::addPragmaHandler(const std::string &pragmaType, const std::function<bool(const std::string &)> &function) {
if (!this->m_pragmaHandlers.contains(pragmaType)) if (!this->m_pragmaHandlers.contains(pragmaType))
this->m_pragmaHandlers.emplace(pragmaType, function); this->m_pragmaHandlers.emplace(pragmaType, function);
} }

View File

@ -10,10 +10,9 @@
namespace hex::pl { namespace hex::pl {
Validator::Validator() { Validator::Validator() {
} }
bool Validator::validate(const std::vector<ASTNode*>& ast) { bool Validator::validate(const std::vector<ASTNode *> &ast) {
std::unordered_set<std::string> identifiers; std::unordered_set<std::string> identifiers;
try { try {
@ -22,21 +21,21 @@ namespace hex::pl {
if (node == nullptr) if (node == nullptr)
throwValidateError("nullptr in AST. This is a bug!", 1); throwValidateError("nullptr in AST. This is a bug!", 1);
if (auto variableDeclNode = dynamic_cast<ASTNodeVariableDecl*>(node); variableDeclNode != nullptr) { if (auto variableDeclNode = dynamic_cast<ASTNodeVariableDecl *>(node); variableDeclNode != nullptr) {
if (!identifiers.insert(variableDeclNode->getName().data()).second) if (!identifiers.insert(variableDeclNode->getName().data()).second)
throwValidateError(hex::format("redefinition of identifier '{0}'", variableDeclNode->getName().data()), variableDeclNode->getLineNumber()); throwValidateError(hex::format("redefinition of identifier '{0}'", variableDeclNode->getName().data()), variableDeclNode->getLineNumber());
this->validate({ variableDeclNode->getType() }); this->validate({ variableDeclNode->getType() });
} else if (auto typeDeclNode = dynamic_cast<ASTNodeTypeDecl*>(node); typeDeclNode != nullptr) { } else if (auto typeDeclNode = dynamic_cast<ASTNodeTypeDecl *>(node); typeDeclNode != nullptr) {
if (!identifiers.insert(typeDeclNode->getName().data()).second) if (!identifiers.insert(typeDeclNode->getName().data()).second)
throwValidateError(hex::format("redefinition of identifier '{0}'", typeDeclNode->getName().data()), typeDeclNode->getLineNumber()); throwValidateError(hex::format("redefinition of identifier '{0}'", typeDeclNode->getName().data()), typeDeclNode->getLineNumber());
this->validate({ typeDeclNode->getType() }); this->validate({ typeDeclNode->getType() });
} else if (auto structNode = dynamic_cast<ASTNodeStruct*>(node); structNode != nullptr) { } else if (auto structNode = dynamic_cast<ASTNodeStruct *>(node); structNode != nullptr) {
this->validate(structNode->getMembers()); this->validate(structNode->getMembers());
} else if (auto unionNode = dynamic_cast<ASTNodeUnion*>(node); unionNode != nullptr) { } else if (auto unionNode = dynamic_cast<ASTNodeUnion *>(node); unionNode != nullptr) {
this->validate(unionNode->getMembers()); this->validate(unionNode->getMembers());
} else if (auto enumNode = dynamic_cast<ASTNodeEnum*>(node); enumNode != nullptr) { } else if (auto enumNode = dynamic_cast<ASTNodeEnum *>(node); enumNode != nullptr) {
std::unordered_set<std::string> enumIdentifiers; std::unordered_set<std::string> enumIdentifiers;
for (auto &[name, value] : enumNode->getEntries()) { for (auto &[name, value] : enumNode->getEntries()) {
if (!enumIdentifiers.insert(name).second) if (!enumIdentifiers.insert(name).second)

View File

@ -60,12 +60,12 @@ namespace hex::prv {
i128 overlapMin = std::max(offset, overlayOffset); i128 overlapMin = std::max(offset, overlayOffset);
i128 overlapMax = std::min(offset + size, overlayOffset + overlaySize); i128 overlapMax = std::min(offset + size, overlayOffset + overlaySize);
if (overlapMax > overlapMin) if (overlapMax > overlapMin)
std::memcpy(static_cast<u8*>(buffer) + std::max<i128>(0, overlapMin - offset), overlay->getData().data() + std::max<i128>(0, overlapMin - overlayOffset), overlapMax - overlapMin); std::memcpy(static_cast<u8 *>(buffer) + std::max<i128>(0, overlapMin - offset), overlay->getData().data() + std::max<i128>(0, overlapMin - overlayOffset), overlapMax - overlapMin);
} }
} }
std::map<u64, u8>& Provider::getPatches() { std::map<u64, u8> &Provider::getPatches() {
auto iter = this->m_patches.end(); auto iter = this->m_patches.end();
for (auto i = 0; i < this->m_patchTreeOffset + 1; i++) for (auto i = 0; i < this->m_patchTreeOffset + 1; i++)
iter--; iter--;
@ -73,7 +73,7 @@ namespace hex::prv {
return *(iter); return *(iter);
} }
const std::map<u64, u8>& Provider::getPatches() const { const std::map<u64, u8> &Provider::getPatches() const {
auto iter = this->m_patches.end(); auto iter = this->m_patches.end();
for (auto i = 0; i < this->m_patchTreeOffset + 1; i++) for (auto i = 0; i < this->m_patchTreeOffset + 1; i++)
iter--; iter--;
@ -88,7 +88,7 @@ namespace hex::prv {
} }
Overlay* Provider::newOverlay() { Overlay *Provider::newOverlay() {
return this->m_overlays.emplace_back(new Overlay()); return this->m_overlays.emplace_back(new Overlay());
} }
@ -97,7 +97,7 @@ namespace hex::prv {
delete overlay; delete overlay;
} }
const std::list<Overlay*>& Provider::getOverlays() { const std::list<Overlay *> &Provider::getOverlays() {
return this->m_overlays; return this->m_overlays;
} }
@ -136,7 +136,7 @@ namespace hex::prv {
u32 page = std::floor((address - this->getBaseAddress()) / double(PageSize)); u32 page = std::floor((address - this->getBaseAddress()) / double(PageSize));
if (page >= this->getPageCount()) if (page >= this->getPageCount())
return { }; return {};
return page; return page;
} }
@ -155,7 +155,7 @@ namespace hex::prv {
createUndoPoint(); createUndoPoint();
for (u64 i = 0; i < size; i++) for (u64 i = 0; i < size; i++)
getPatches()[offset + i] = reinterpret_cast<const u8*>(buffer)[i]; getPatches()[offset + i] = reinterpret_cast<const u8 *>(buffer)[i];
} }
void Provider::createUndoPoint() { void Provider::createUndoPoint() {
@ -190,11 +190,9 @@ namespace hex::prv {
} }
void Provider::drawLoadInterface() { void Provider::drawLoadInterface() {
} }
void Provider::drawInterface() { void Provider::drawInterface() {
} }
} }

View File

@ -16,19 +16,19 @@
namespace ImGui { namespace ImGui {
int UpdateStringSizeCallback(ImGuiInputTextCallbackData *data) { int UpdateStringSizeCallback(ImGuiInputTextCallbackData *data) {
auto &mathInput = *static_cast<std::string*>(data->UserData); auto &mathInput = *static_cast<std::string *>(data->UserData);
mathInput.resize(data->BufTextLen); mathInput.resize(data->BufTextLen);
return 0; return 0;
} }
bool IconHyperlink(const char *icon, const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags) { bool IconHyperlink(const char *icon, const char *label, const ImVec2 &size_arg, ImGuiButtonFlags flags) {
ImGuiWindow* window = GetCurrentWindow(); ImGuiWindow *window = GetCurrentWindow();
if (window->SkipItems) if (window->SkipItems)
return false; return false;
ImGuiContext& g = *GImGui; ImGuiContext &g = *GImGui;
const ImGuiStyle& style = g.Style; const ImGuiStyle &style = g.Style;
const ImGuiID id = window->GetID(label); const ImGuiID id = window->GetID(label);
ImVec2 label_size = CalcTextSize(icon, NULL, false); ImVec2 label_size = CalcTextSize(icon, NULL, false);
label_size.x += CalcTextSize(" ", NULL, false).x + CalcTextSize(label, NULL, false).x; label_size.x += CalcTextSize(" ", NULL, false).x + CalcTextSize(label, NULL, false).x;
@ -57,13 +57,13 @@ namespace ImGui {
return pressed; return pressed;
} }
bool Hyperlink(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags) { bool Hyperlink(const char *label, const ImVec2 &size_arg, ImGuiButtonFlags flags) {
ImGuiWindow* window = GetCurrentWindow(); ImGuiWindow *window = GetCurrentWindow();
if (window->SkipItems) if (window->SkipItems)
return false; return false;
ImGuiContext& g = *GImGui; ImGuiContext &g = *GImGui;
const ImGuiStyle& style = g.Style; const ImGuiStyle &style = g.Style;
const ImGuiID id = window->GetID(label); const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImVec2 label_size = CalcTextSize(label, NULL, true);
@ -90,13 +90,13 @@ namespace ImGui {
return pressed; return pressed;
} }
bool BulletHyperlink(const char* label, const ImVec2& size_arg, ImGuiButtonFlags flags) { bool BulletHyperlink(const char *label, const ImVec2 &size_arg, ImGuiButtonFlags flags) {
ImGuiWindow* window = GetCurrentWindow(); ImGuiWindow *window = GetCurrentWindow();
if (window->SkipItems) if (window->SkipItems)
return false; return false;
ImGuiContext& g = *GImGui; ImGuiContext &g = *GImGui;
const ImGuiStyle& style = g.Style; const ImGuiStyle &style = g.Style;
const ImGuiID id = window->GetID(label); const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImVec2 label_size = CalcTextSize(label, NULL, true);
@ -125,13 +125,13 @@ namespace ImGui {
return pressed; return pressed;
} }
bool DescriptionButton(const char* label, const char* description, const ImVec2& size_arg, ImGuiButtonFlags flags) { bool DescriptionButton(const char *label, const char *description, const ImVec2 &size_arg, ImGuiButtonFlags flags) {
ImGuiWindow* window = GetCurrentWindow(); ImGuiWindow *window = GetCurrentWindow();
if (window->SkipItems) if (window->SkipItems)
return false; return false;
ImGuiContext& g = *GImGui; ImGuiContext &g = *GImGui;
const ImGuiStyle& style = g.Style; const ImGuiStyle &style = g.Style;
const ImGuiID id = window->GetID(label); const ImGuiID id = window->GetID(label);
const ImVec2 text_size = CalcTextSize((std::string(label) + "\n " + std::string(description)).c_str(), NULL, true); const ImVec2 text_size = CalcTextSize((std::string(label) + "\n " + std::string(description)).c_str(), NULL, true);
const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImVec2 label_size = CalcTextSize(label, NULL, true);
@ -154,7 +154,8 @@ namespace ImGui {
ImGui::PushStyleVar(ImGuiStyleVar_ButtonTextAlign, ImVec2(0.0, 0.5)); ImGui::PushStyleVar(ImGuiStyleVar_ButtonTextAlign, ImVec2(0.0, 0.5));
// Render // Render
const ImU32 col = GetCustomColorU32((held && hovered) ? ImGuiCustomCol_DescButtonActive : hovered ? ImGuiCustomCol_DescButtonHovered : ImGuiCustomCol_DescButton); const ImU32 col = GetCustomColorU32((held && hovered) ? ImGuiCustomCol_DescButtonActive : hovered ? ImGuiCustomCol_DescButtonHovered
: ImGuiCustomCol_DescButton);
RenderNavHighlight(bb, id); RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_ButtonActive)); PushStyleColor(ImGuiCol_Text, GetColorU32(ImGuiCol_ButtonActive));
@ -167,15 +168,15 @@ namespace ImGui {
ImGui::PopStyleVar(); ImGui::PopStyleVar();
// Automatically close popups // Automatically close popups
//if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) // if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
// CloseCurrentPopup(); // CloseCurrentPopup();
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
return pressed; return pressed;
} }
void UnderlinedText(const char* label, ImColor color, const ImVec2& size_arg) { void UnderlinedText(const char *label, ImColor color, const ImVec2 &size_arg) {
ImGuiWindow* window = GetCurrentWindow(); ImGuiWindow *window = GetCurrentWindow();
const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImVec2 label_size = CalcTextSize(label, NULL, true);
@ -196,10 +197,9 @@ namespace ImGui {
} else { } else {
widgets(); widgets();
} }
} }
void TextSpinner(const char* label) { void TextSpinner(const char *label) {
ImGui::Text("[%c] %s", "|/-\\"[ImU32(ImGui::GetTime() * 20) % 4], label); ImGui::Text("[%c] %s", "|/-\\"[ImU32(ImGui::GetTime() * 20) % 4], label);
} }
@ -237,21 +237,21 @@ namespace ImGui {
} }
ImU32 GetCustomColorU32(ImGuiCustomCol idx, float alpha_mul) { ImU32 GetCustomColorU32(ImGuiCustomCol idx, float alpha_mul) {
auto& customData = *static_cast<ImHexCustomData*>(GImGui->IO.UserData); auto &customData = *static_cast<ImHexCustomData *>(GImGui->IO.UserData);
ImVec4 c = customData.Colors[idx]; ImVec4 c = customData.Colors[idx];
c.w *= GImGui->Style.Alpha * alpha_mul; c.w *= GImGui->Style.Alpha * alpha_mul;
return ColorConvertFloat4ToU32(c); return ColorConvertFloat4ToU32(c);
} }
ImVec4 GetCustomColorVec4(ImGuiCustomCol idx, float alpha_mul) { ImVec4 GetCustomColorVec4(ImGuiCustomCol idx, float alpha_mul) {
auto& customData = *static_cast<ImHexCustomData*>(GImGui->IO.UserData); auto &customData = *static_cast<ImHexCustomData *>(GImGui->IO.UserData);
ImVec4 c = customData.Colors[idx]; ImVec4 c = customData.Colors[idx];
c.w *= GImGui->Style.Alpha * alpha_mul; c.w *= GImGui->Style.Alpha * alpha_mul;
return c; return c;
} }
void StyleCustomColorsDark() { void StyleCustomColorsDark() {
auto &colors = static_cast<ImHexCustomData*>(GImGui->IO.UserData)->Colors; auto &colors = static_cast<ImHexCustomData *>(GImGui->IO.UserData)->Colors;
colors[ImGuiCustomCol_DescButton] = ImColor(20, 20, 20); colors[ImGuiCustomCol_DescButton] = ImColor(20, 20, 20);
colors[ImGuiCustomCol_DescButtonHovered] = ImColor(40, 40, 40); colors[ImGuiCustomCol_DescButtonHovered] = ImColor(40, 40, 40);
@ -269,7 +269,7 @@ namespace ImGui {
} }
void StyleCustomColorsLight() { void StyleCustomColorsLight() {
auto &colors = static_cast<ImHexCustomData*>(GImGui->IO.UserData)->Colors; auto &colors = static_cast<ImHexCustomData *>(GImGui->IO.UserData)->Colors;
colors[ImGuiCustomCol_DescButton] = ImColor(230, 230, 230); colors[ImGuiCustomCol_DescButton] = ImColor(230, 230, 230);
colors[ImGuiCustomCol_DescButtonHovered] = ImColor(210, 210, 210); colors[ImGuiCustomCol_DescButtonHovered] = ImColor(210, 210, 210);
@ -287,7 +287,7 @@ namespace ImGui {
} }
void StyleCustomColorsClassic() { void StyleCustomColorsClassic() {
auto &colors = static_cast<ImHexCustomData*>(GImGui->IO.UserData)->Colors; auto &colors = static_cast<ImHexCustomData *>(GImGui->IO.UserData)->Colors;
colors[ImGuiCustomCol_DescButton] = ImColor(40, 40, 80); colors[ImGuiCustomCol_DescButton] = ImColor(40, 40, 80);
colors[ImGuiCustomCol_DescButtonHovered] = ImColor(60, 60, 100); colors[ImGuiCustomCol_DescButtonHovered] = ImColor(60, 60, 100);
@ -308,7 +308,7 @@ namespace ImGui {
int imageWidth = 0; int imageWidth = 0;
int imageHeight = 0; int imageHeight = 0;
unsigned char* imageData = stbi_load(path, &imageWidth, &imageHeight, nullptr, 4); unsigned char *imageData = stbi_load(path, &imageWidth, &imageHeight, nullptr, 4);
if (imageData == nullptr) if (imageData == nullptr)
return { nullptr, -1, -1 }; return { nullptr, -1, -1 };
@ -320,9 +320,9 @@ namespace ImGui {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
#if defined(GL_UNPACK_ROW_LENGTH) #if defined(GL_UNPACK_ROW_LENGTH)
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
#endif #endif
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imageWidth, imageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imageWidth, imageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);
stbi_image_free(imageData); stbi_image_free(imageData);
@ -334,7 +334,7 @@ namespace ImGui {
int imageHeight = 0; int imageHeight = 0;
unsigned char* imageData = stbi_load_from_memory(buffer, size, &imageWidth, &imageHeight, nullptr, 4); unsigned char *imageData = stbi_load_from_memory(buffer, size, &imageWidth, &imageHeight, nullptr, 4);
if (imageData == nullptr) if (imageData == nullptr)
return { nullptr, -1, -1 }; return { nullptr, -1, -1 };
@ -345,9 +345,9 @@ namespace ImGui {
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
#if defined(GL_UNPACK_ROW_LENGTH) #if defined(GL_UNPACK_ROW_LENGTH)
glPixelStorei(GL_UNPACK_ROW_LENGTH, 0); glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
#endif #endif
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imageWidth, imageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, imageWidth, imageHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, imageData);
stbi_image_free(imageData); stbi_image_free(imageData);
@ -372,13 +372,13 @@ namespace ImGui {
} }
bool TitleBarButton(const char* label, ImVec2 size_arg) { bool TitleBarButton(const char *label, ImVec2 size_arg) {
ImGuiWindow* window = GetCurrentWindow(); ImGuiWindow *window = GetCurrentWindow();
if (window->SkipItems) if (window->SkipItems)
return false; return false;
ImGuiContext& g = *GImGui; ImGuiContext &g = *GImGui;
const ImGuiStyle& style = g.Style; const ImGuiStyle &style = g.Style;
const ImGuiID id = window->GetID(label); const ImGuiID id = window->GetID(label);
const ImVec2 label_size = CalcTextSize(label, NULL, true); const ImVec2 label_size = CalcTextSize(label, NULL, true);
@ -395,28 +395,29 @@ namespace ImGui {
bool pressed = ButtonBehavior(bb, id, &hovered, &held); bool pressed = ButtonBehavior(bb, id, &hovered, &held);
// Render // Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered
: ImGuiCol_Button);
RenderNavHighlight(bb, id); RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding); RenderFrame(bb.Min, bb.Max, col, true, style.FrameRounding);
RenderTextClipped(bb.Min + style.FramePadding * ImVec2(1, 2), bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb); RenderTextClipped(bb.Min + style.FramePadding * ImVec2(1, 2), bb.Max - style.FramePadding, label, NULL, &label_size, style.ButtonTextAlign, &bb);
// Automatically close popups // Automatically close popups
//if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) // if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
// CloseCurrentPopup(); // CloseCurrentPopup();
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
return pressed; return pressed;
} }
bool ToolBarButton(const char* symbol, ImVec4 color) { bool ToolBarButton(const char *symbol, ImVec4 color) {
ImGuiWindow* window = GetCurrentWindow(); ImGuiWindow *window = GetCurrentWindow();
if (window->SkipItems) if (window->SkipItems)
return false; return false;
color.w = 1.0F; color.w = 1.0F;
ImGuiContext& g = *GImGui; ImGuiContext &g = *GImGui;
const ImGuiStyle& style = g.Style; const ImGuiStyle &style = g.Style;
const ImGuiID id = window->GetID(symbol); const ImGuiID id = window->GetID(symbol);
const ImVec2 label_size = CalcTextSize(symbol, NULL, true); const ImVec2 label_size = CalcTextSize(symbol, NULL, true);
@ -435,7 +436,8 @@ namespace ImGui {
PushStyleColor(ImGuiCol_Text, color); PushStyleColor(ImGuiCol_Text, color);
// Render // Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered : ImGuiCol_MenuBarBg); const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ScrollbarGrabActive : hovered ? ImGuiCol_ScrollbarGrabHovered
: ImGuiCol_MenuBarBg);
RenderNavHighlight(bb, id); RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, false, style.FrameRounding); RenderFrame(bb.Min, bb.Max, col, false, style.FrameRounding);
RenderTextClipped(bb.Min + style.FramePadding * ImVec2(1, 2), bb.Max - style.FramePadding, symbol, NULL, &label_size, style.ButtonTextAlign, &bb); RenderTextClipped(bb.Min + style.FramePadding * ImVec2(1, 2), bb.Max - style.FramePadding, symbol, NULL, &label_size, style.ButtonTextAlign, &bb);
@ -443,22 +445,22 @@ namespace ImGui {
PopStyleColor(); PopStyleColor();
// Automatically close popups // Automatically close popups
//if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) // if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
// CloseCurrentPopup(); // CloseCurrentPopup();
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
return pressed; return pressed;
} }
bool IconButton(const char* symbol, ImVec4 color, ImVec2 size_arg) { bool IconButton(const char *symbol, ImVec4 color, ImVec2 size_arg) {
ImGuiWindow* window = GetCurrentWindow(); ImGuiWindow *window = GetCurrentWindow();
if (window->SkipItems) if (window->SkipItems)
return false; return false;
color.w = 1.0F; color.w = 1.0F;
ImGuiContext& g = *GImGui; ImGuiContext &g = *GImGui;
const ImGuiStyle& style = g.Style; const ImGuiStyle &style = g.Style;
const ImGuiID id = window->GetID(symbol); const ImGuiID id = window->GetID(symbol);
const ImVec2 label_size = CalcTextSize(symbol, NULL, true); const ImVec2 label_size = CalcTextSize(symbol, NULL, true);
@ -477,7 +479,8 @@ namespace ImGui {
PushStyleColor(ImGuiCol_Text, color); PushStyleColor(ImGuiCol_Text, color);
// Render // Render
const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered : ImGuiCol_Button); const ImU32 col = GetColorU32((held && hovered) ? ImGuiCol_ButtonActive : hovered ? ImGuiCol_ButtonHovered
: ImGuiCol_Button);
RenderNavHighlight(bb, id); RenderNavHighlight(bb, id);
RenderFrame(bb.Min, bb.Max, col, false, style.FrameRounding); RenderFrame(bb.Min, bb.Max, col, false, style.FrameRounding);
RenderTextClipped(bb.Min + style.FramePadding * ImVec2(1, 2), bb.Max - style.FramePadding, symbol, NULL, &label_size, style.ButtonTextAlign, &bb); RenderTextClipped(bb.Min + style.FramePadding * ImVec2(1, 2), bb.Max - style.FramePadding, symbol, NULL, &label_size, style.ButtonTextAlign, &bb);
@ -485,7 +488,7 @@ namespace ImGui {
PopStyleColor(); PopStyleColor();
// Automatically close popups // Automatically close popups
//if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup)) // if (pressed && !(flags & ImGuiButtonFlags_DontClosePopups) && (window->Flags & ImGuiWindowFlags_Popup))
// CloseCurrentPopup(); // CloseCurrentPopup();
IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags); IMGUI_TEST_ENGINE_ITEM_INFO(id, label, window->DC.LastItemStatusFlags);
@ -493,12 +496,12 @@ namespace ImGui {
} }
void SmallProgressBar(float fraction, float yOffset) { void SmallProgressBar(float fraction, float yOffset) {
ImGuiWindow* window = GetCurrentWindow(); ImGuiWindow *window = GetCurrentWindow();
if (window->SkipItems) if (window->SkipItems)
return; return;
ImGuiContext& g = *GImGui; ImGuiContext &g = *GImGui;
const ImGuiStyle& style = g.Style; const ImGuiStyle &style = g.Style;
ImVec2 pos = window->DC.CursorPos + ImVec2(0, yOffset); ImVec2 pos = window->DC.CursorPos + ImVec2(0, yOffset);
ImVec2 size = CalcItemSize(ImVec2(100, 5), 100, g.FontSize + style.FramePadding.y * 2.0f); ImVec2 size = CalcItemSize(ImVec2(100, 5), 100, g.FontSize + style.FramePadding.y * 2.0f);

View File

@ -16,7 +16,7 @@ namespace hex {
return ImHexApi::Provider::isValid() && ImHexApi::Provider::get()->isAvailable(); return ImHexApi::Provider::isValid() && ImHexApi::Provider::get()->isAvailable();
} }
std::vector<std::function<void()>>& View::getDeferedCalls() { std::vector<std::function<void()>> &View::getDeferedCalls() {
return SharedData::deferredCalls; return SharedData::deferredCalls;
} }
@ -133,15 +133,15 @@ namespace hex {
} }
bool& View::getWindowOpenState() { bool &View::getWindowOpenState() {
return this->m_windowOpen; return this->m_windowOpen;
} }
const bool& View::getWindowOpenState() const { const bool &View::getWindowOpenState() const {
return this->m_windowOpen; return this->m_windowOpen;
} }
const std::string& View::getUnlocalizedName() const { const std::string &View::getUnlocalizedName() const {
return this->m_unlocalizedViewName; return this->m_unlocalizedViewName;
} }

View File

@ -14,7 +14,7 @@ namespace hex {
class Plugin { class Plugin {
public: public:
explicit Plugin(const fs::path &path); explicit Plugin(const fs::path &path);
Plugin(const Plugin&) = delete; Plugin(const Plugin &) = delete;
Plugin(Plugin &&other) noexcept; Plugin(Plugin &&other) noexcept;
~Plugin(); ~Plugin();
@ -25,16 +25,17 @@ namespace hex {
[[nodiscard]] std::string getCompatibleVersion() const; [[nodiscard]] std::string getCompatibleVersion() const;
void setImGuiContext(ImGuiContext *ctx) const; void setImGuiContext(ImGuiContext *ctx) const;
[[nodiscard]] const fs::path& getPath() const; [[nodiscard]] const fs::path &getPath() const;
[[nodiscard]] bool isLoaded() const; [[nodiscard]] bool isLoaded() const;
private: private:
using InitializePluginFunc = void(*)(); using InitializePluginFunc = void (*)();
using GetPluginNameFunc = const char*(*)(); using GetPluginNameFunc = const char *(*)();
using GetPluginAuthorFunc = const char*(*)(); using GetPluginAuthorFunc = const char *(*)();
using GetPluginDescriptionFunc = const char*(*)(); using GetPluginDescriptionFunc = const char *(*)();
using GetCompatibleVersionFunc = const char*(*)(); using GetCompatibleVersionFunc = const char *(*)();
using SetImGuiContextFunc = void(*)(ImGuiContext*); using SetImGuiContextFunc = void (*)(ImGuiContext *);
void *m_handle = nullptr; void *m_handle = nullptr;
fs::path m_path; fs::path m_path;
@ -54,7 +55,7 @@ namespace hex {
} }
private: private:
[[nodiscard]] void* getPluginFunction(const std::string &symbol); [[nodiscard]] void *getPluginFunction(const std::string &symbol);
}; };
class PluginManager { class PluginManager {
@ -65,7 +66,7 @@ namespace hex {
static void unload(); static void unload();
static void reload(); static void reload();
static const auto& getPlugins() { static const auto &getPlugins() {
return PluginManager::s_plugins; return PluginManager::s_plugins;
} }

View File

@ -18,5 +18,5 @@ namespace hex::init {
std::vector<Task> getInitTasks(); std::vector<Task> getInitTasks();
std::vector<Task> getExitTasks(); std::vector<Task> getExitTasks();
std::vector<Argument>& getInitArguments(); std::vector<Argument> &getInitArguments();
} }

View File

@ -42,10 +42,10 @@ namespace hex {
void exitImGui(); void exitImGui();
friend void *ImHexSettingsHandler_ReadOpenFn(ImGuiContext *ctx, ImGuiSettingsHandler *, const char *); friend void *ImHexSettingsHandler_ReadOpenFn(ImGuiContext *ctx, ImGuiSettingsHandler *, const char *);
friend void ImHexSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler *handler, void *, const char* line); friend void ImHexSettingsHandler_ReadLine(ImGuiContext *, ImGuiSettingsHandler *handler, void *, const char *line);
friend void ImHexSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler *handler, ImGuiTextBuffer *buf); friend void ImHexSettingsHandler_WriteAll(ImGuiContext *ctx, ImGuiSettingsHandler *handler, ImGuiTextBuffer *buf);
GLFWwindow* m_window = nullptr; GLFWwindow *m_window = nullptr;
double m_targetFps = 60.0; double m_targetFps = 60.0;
bool m_layoutConfigured = false; bool m_layoutConfigured = false;

View File

@ -100,7 +100,7 @@ namespace hex {
this->m_setImGuiContextFunction(ctx); this->m_setImGuiContextFunction(ctx);
} }
const fs::path& Plugin::getPath() const { const fs::path &Plugin::getPath() const {
return this->m_path; return this->m_path;
} }
@ -109,7 +109,7 @@ namespace hex {
} }
void* Plugin::getPluginFunction(const std::string &symbol) { void *Plugin::getPluginFunction(const std::string &symbol) {
return dlsym(this->m_handle, symbol.c_str()); return dlsym(this->m_handle, symbol.c_str());
} }
@ -120,7 +120,7 @@ namespace hex {
PluginManager::s_pluginFolder = pluginFolder; PluginManager::s_pluginFolder = pluginFolder;
for (auto& pluginPath : fs::directory_iterator(pluginFolder)) { for (auto &pluginPath : fs::directory_iterator(pluginFolder)) {
if (pluginPath.is_regular_file() && pluginPath.path().extension() == ".hexplug") if (pluginPath.is_regular_file() && pluginPath.path().extension() == ".hexplug")
PluginManager::s_plugins.emplace_back(pluginPath.path().string()); PluginManager::s_plugins.emplace_back(pluginPath.path().string());
} }

View File

@ -69,7 +69,7 @@ namespace hex::init {
bool WindowSplash::loop() { bool WindowSplash::loop() {
auto splash = romfs::get("splash.png"); auto splash = romfs::get("splash.png");
ImGui::Texture splashTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8*>(splash.data()), splash.size()); ImGui::Texture splashTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(splash.data()), splash.size());
if (splashTexture == nullptr) { if (splashTexture == nullptr) {
log::fatal("Could not load splash screen image!"); log::fatal("Could not load splash screen image!");
@ -98,15 +98,14 @@ namespace hex::init {
drawList->AddText(ImVec2(15, 120) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("WerWolv 2020 - {0}", &__DATE__[7]).c_str()); drawList->AddText(ImVec2(15, 120) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("WerWolv 2020 - {0}", &__DATE__[7]).c_str());
#if defined(DEBUG) #if defined(DEBUG)
drawList->AddText(ImVec2(15, 140) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("{0} : {1} {2}@{3}", IMHEX_VERSION, ICON_FA_CODE_BRANCH, GIT_BRANCH, GIT_COMMIT_HASH).c_str()); drawList->AddText(ImVec2(15, 140) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("{0} : {1} {2}@{3}", IMHEX_VERSION, ICON_FA_CODE_BRANCH, GIT_BRANCH, GIT_COMMIT_HASH).c_str());
#else #else
drawList->AddText(ImVec2(15, 140) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("{0}", IMHEX_VERSION).c_str()); drawList->AddText(ImVec2(15, 140) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("{0}", IMHEX_VERSION).c_str());
#endif #endif
drawList->AddRectFilled(ImVec2(0, splashTexture.size().y - 5) * scale, ImVec2(splashTexture.size().x * this->m_progress, splashTexture.size().y) * scale, 0xFFFFFFFF); drawList->AddRectFilled(ImVec2(0, splashTexture.size().y - 5) * scale, ImVec2(splashTexture.size().x * this->m_progress, splashTexture.size().y) * scale, 0xFFFFFFFF);
drawList->AddText(ImVec2(15, splashTexture.size().y - 25) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), drawList->AddText(ImVec2(15, splashTexture.size().y - 25) * scale, ImColor(0xFF, 0xFF, 0xFF, 0xFF), hex::format("[{}] {}", "|/-\\"[ImU32(ImGui::GetTime() * 15) % 4], this->m_currTaskName).c_str());
hex::format("[{}] {}", "|/-\\"[ImU32(ImGui::GetTime() * 15) % 4], this->m_currTaskName).c_str());
} }
ImGui::Render(); ImGui::Render();
@ -171,12 +170,12 @@ namespace hex::init {
SharedData::globalScale = SharedData::fontScale = std::midpoint(xScale, yScale); SharedData::globalScale = SharedData::fontScale = std::midpoint(xScale, yScale);
// On Macs with a retina display (basically all modern ones we care about), the OS reports twice // On Macs with a retina display (basically all modern ones we care about), the OS reports twice
// the actual monitor scale for some obscure reason. Get rid of this here so ImHex doesn't look // the actual monitor scale for some obscure reason. Get rid of this here so ImHex doesn't look
// extremely huge with native scaling on MacOS. // extremely huge with native scaling on MacOS.
#if defined(OS_MACOS) #if defined(OS_MACOS)
SharedData::globalScale /= 2; SharedData::globalScale /= 2;
#endif #endif
if (SharedData::globalScale <= 0) { if (SharedData::globalScale <= 0) {
SharedData::globalScale = 1.0; SharedData::globalScale = 1.0;
@ -217,8 +216,7 @@ namespace hex::init {
cfg.MergeMode = true; cfg.MergeMode = true;
ImWchar fontAwesomeRange[] = { ImWchar fontAwesomeRange[] = {
ICON_MIN_FA, ICON_MAX_FA, ICON_MIN_FA, ICON_MAX_FA, 0
0
}; };
std::uint8_t *px; std::uint8_t *px;
int w, h; int w, h;

View File

@ -83,7 +83,7 @@ namespace hex::init {
} }
if (!result) if (!result)
getInitArguments().push_back({ "folder-creation-error", { } }); getInitArguments().push_back({ "folder-creation-error", {} });
return result; return result;
} }
@ -93,7 +93,7 @@ namespace hex::init {
auto &cfg = SharedData::fontConfig; auto &cfg = SharedData::fontConfig;
fonts = IM_NEW(ImFontAtlas)(); fonts = IM_NEW(ImFontAtlas)();
cfg = { }; cfg = {};
fs::path fontFile; fs::path fontFile;
for (const auto &dir : hex::getPath(ImHexPath::Resources)) { for (const auto &dir : hex::getPath(ImHexPath::Resources)) {
@ -120,18 +120,15 @@ namespace hex::init {
} }
ImWchar fontAwesomeRange[] = { ImWchar fontAwesomeRange[] = {
ICON_MIN_FA, ICON_MAX_FA, ICON_MIN_FA, ICON_MAX_FA, 0
0
}; };
ImWchar codiconsRange[] = { ImWchar codiconsRange[] = {
ICON_MIN_VS, ICON_MAX_VS, ICON_MIN_VS, ICON_MAX_VS, 0
0
}; };
ImWchar unifontRange[] = { ImWchar unifontRange[] = {
0x0020, 0xFFF0, 0x0020, 0xFFF0, 0
0
}; };
@ -224,7 +221,7 @@ namespace hex::init {
if (PluginManager::getPlugins().empty()) { if (PluginManager::getPlugins().empty()) {
log::error("No plugins found!"); log::error("No plugins found!");
getInitArguments().push_back({ "no-plugins", { } }); getInitArguments().push_back({ "no-plugins", {} });
return false; return false;
} }
@ -284,8 +281,8 @@ namespace hex::init {
std::vector<Task> getInitTasks() { std::vector<Task> getInitTasks() {
return { return {
{ "Checking for updates...", checkForUpdates }, {"Checking for updates...", checkForUpdates },
{ "Downloading information...", downloadInformation }, { "Downloading information...", downloadInformation},
{ "Creating directories...", createDirectories }, { "Creating directories...", createDirectories },
{ "Loading settings...", loadSettings }, { "Loading settings...", loadSettings },
{ "Loading plugins...", loadPlugins }, { "Loading plugins...", loadPlugins },
@ -295,13 +292,13 @@ namespace hex::init {
std::vector<Task> getExitTasks() { std::vector<Task> getExitTasks() {
return { return {
{ "Saving settings...", storeSettings }, {"Saving settings...", storeSettings },
{ "Cleaning up shared data...", deleteSharedData }, { "Cleaning up shared data...", deleteSharedData},
{ "Unloading plugins...", unloadPlugins }, { "Unloading plugins...", unloadPlugins },
}; };
} }
std::vector<Argument>& getInitArguments() { std::vector<Argument> &getInitArguments() {
static std::vector<Argument> initArguments; static std::vector<Argument> initArguments;
return initArguments; return initArguments;

View File

@ -30,7 +30,7 @@ int main(int argc, char **argv, char **envp) {
splashWindow.addStartupTask(name, task); splashWindow.addStartupTask(name, task);
if (!splashWindow.loop()) if (!splashWindow.loop())
init::getInitArguments().push_back({ "tasks-failed", { } }); init::getInitArguments().push_back({ "tasks-failed", {} });
} }
// Clean up // Clean up

View File

@ -9,7 +9,7 @@
#include <sys/wait.h> #include <sys/wait.h>
#include <unistd.h> #include <unistd.h>
namespace hex { namespace hex {
void Window::initNative() { void Window::initNative() {
if (!isatty(STDOUT_FILENO)) { if (!isatty(STDOUT_FILENO)) {
@ -19,14 +19,14 @@
void Window::setupNativeWindow() { void Window::setupNativeWindow() {
bool themeFollowSystem = ContentRegistry::Settings::getSetting("hex.builtin.setting.interface", "hex.builtin.setting.interface.color") == 0; bool themeFollowSystem = ContentRegistry::Settings::getSetting("hex.builtin.setting.interface", "hex.builtin.setting.interface.color") == 0;
EventManager::subscribe<EventOSThemeChanged>(this, [themeFollowSystem]{ EventManager::subscribe<EventOSThemeChanged>(this, [themeFollowSystem] {
if (!themeFollowSystem) return; if (!themeFollowSystem) return;
std::array<char, 128> buffer = { 0 }; std::array<char, 128> buffer = { 0 };
std::string result; std::string result;
// TODO: In the future maybe support more DEs instead of just GNOME // TODO: In the future maybe support more DEs instead of just GNOME
FILE* pipe = popen("gsettings get org.gnome.desktop.interface gtk-theme 2>&1", "r"); FILE *pipe = popen("gsettings get org.gnome.desktop.interface gtk-theme 2>&1", "r");
if (pipe == nullptr) return; if (pipe == nullptr) return;
while (fgets(buffer.data(), buffer.size(), pipe) != nullptr) while (fgets(buffer.data(), buffer.size(), pipe) != nullptr)
@ -43,17 +43,14 @@
} }
void Window::beginNativeWindowFrame() { void Window::beginNativeWindowFrame() {
} }
void Window::endNativeWindowFrame() { void Window::endNativeWindowFrame() {
} }
void Window::drawTitleBar() { void Window::drawTitleBar() {
} }
} }
#endif #endif

View File

@ -7,7 +7,7 @@
#include <nlohmann/json.hpp> #include <nlohmann/json.hpp>
#include <unistd.h> #include <unistd.h>
namespace hex { namespace hex {
void Window::initNative() { void Window::initNative() {
if (!isatty(STDOUT_FILENO)) { if (!isatty(STDOUT_FILENO)) {
@ -17,7 +17,7 @@
void Window::setupNativeWindow() { void Window::setupNativeWindow() {
bool themeFollowSystem = ContentRegistry::Settings::getSetting("hex.builtin.setting.interface", "hex.builtin.setting.interface.color") == 0; bool themeFollowSystem = ContentRegistry::Settings::getSetting("hex.builtin.setting.interface", "hex.builtin.setting.interface.color") == 0;
EventManager::subscribe<EventOSThemeChanged>(this, [themeFollowSystem]{ EventManager::subscribe<EventOSThemeChanged>(this, [themeFollowSystem] {
if (!themeFollowSystem) return; if (!themeFollowSystem) return;
// TODO: Implement this when MacOS build is working again // TODO: Implement this when MacOS build is working again
@ -29,17 +29,14 @@
} }
void Window::beginNativeWindowFrame() { void Window::beginNativeWindowFrame() {
} }
void Window::endNativeWindowFrame() { void Window::endNativeWindowFrame() {
} }
void Window::drawTitleBar() { void Window::drawTitleBar() {
} }
} }
#endif #endif

View File

@ -21,7 +21,7 @@
#include <dwmapi.h> #include <dwmapi.h>
#include <windowsx.h> #include <windowsx.h>
namespace hex { namespace hex {
static LONG_PTR g_oldWndProc; static LONG_PTR g_oldWndProc;
static float g_titleBarHeight; static float g_titleBarHeight;
@ -33,8 +33,9 @@
case WM_NCACTIVATE: case WM_NCACTIVATE:
case WM_NCPAINT: case WM_NCPAINT:
return DefWindowProcW(hwnd, uMsg, wParam, lParam); return DefWindowProcW(hwnd, uMsg, wParam, lParam);
case WM_NCCALCSIZE: { case WM_NCCALCSIZE:
RECT &rect = *reinterpret_cast<RECT*>(lParam); {
RECT &rect = *reinterpret_cast<RECT *>(lParam);
RECT client = rect; RECT client = rect;
CallWindowProc((WNDPROC)g_oldWndProc, hwnd, uMsg, wParam, lParam); CallWindowProc((WNDPROC)g_oldWndProc, hwnd, uMsg, wParam, lParam);
@ -54,7 +55,8 @@
return 0; return 0;
} }
case WM_SETCURSOR: { case WM_SETCURSOR:
{
auto cursorPos = LOWORD(lParam); auto cursorPos = LOWORD(lParam);
switch (cursorPos) { switch (cursorPos) {
@ -82,10 +84,11 @@
return TRUE; return TRUE;
} }
case WM_NCHITTEST: { case WM_NCHITTEST:
{
POINT cursor = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) }; POINT cursor = { GET_X_LPARAM(lParam), GET_Y_LPARAM(lParam) };
const POINT border{ const POINT border {
static_cast<LONG>((::GetSystemMetrics(SM_CXFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER)) * SharedData::globalScale / 1.5F), static_cast<LONG>((::GetSystemMetrics(SM_CXFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER)) * SharedData::globalScale / 1.5F),
static_cast<LONG>((::GetSystemMetrics(SM_CYFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER)) * SharedData::globalScale / 1.5F) static_cast<LONG>((::GetSystemMetrics(SM_CYFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER)) * SharedData::globalScale / 1.5F)
}; };
@ -147,10 +150,10 @@
} }
case WM_COPYDATA: case WM_COPYDATA:
{ {
auto message = reinterpret_cast<COPYDATASTRUCT*>(lParam); auto message = reinterpret_cast<COPYDATASTRUCT *>(lParam);
if (message == nullptr) break; if (message == nullptr) break;
auto path = reinterpret_cast<const char*>(message->lpData); auto path = reinterpret_cast<const char *>(message->lpData);
if (path == nullptr) break; if (path == nullptr) break;
log::info("Opening file in existing instance: {}", path); log::info("Opening file in existing instance: {}", path);
@ -158,7 +161,8 @@
break; break;
} }
default: break; default:
break;
} }
return CallWindowProc((WNDPROC)g_oldWndProc, hwnd, uMsg, wParam, lParam); return CallWindowProc((WNDPROC)g_oldWndProc, hwnd, uMsg, wParam, lParam);
@ -222,7 +226,8 @@
} }
return TRUE; return TRUE;
}, 0); },
0);
std::exit(0); std::exit(0);
} }
@ -246,7 +251,7 @@
// Setup system theme change detector // Setup system theme change detector
bool themeFollowSystem = ContentRegistry::Settings::getSetting("hex.builtin.setting.interface", "hex.builtin.setting.interface.color") == 0; bool themeFollowSystem = ContentRegistry::Settings::getSetting("hex.builtin.setting.interface", "hex.builtin.setting.interface.color") == 0;
EventManager::subscribe<EventOSThemeChanged>(this, [themeFollowSystem]{ EventManager::subscribe<EventOSThemeChanged>(this, [themeFollowSystem] {
if (!themeFollowSystem) return; if (!themeFollowSystem) return;
HKEY hkey; HKEY hkey;
@ -323,7 +328,7 @@
if (ImGui::GetIO().KeyCtrl) { if (ImGui::GetIO().KeyCtrl) {
// Explicitly trigger a segfault by writing to an invalid memory location // Explicitly trigger a segfault by writing to an invalid memory location
// Used for debugging crashes // Used for debugging crashes
*reinterpret_cast<u8*>(0x10) = 0x10; *reinterpret_cast<u8 *>(0x10) = 0x10;
} else if (ImGui::GetIO().KeyShift) { } else if (ImGui::GetIO().KeyShift) {
// Explicitly trigger an abort by throwing an uncaught exception // Explicitly trigger an abort by throwing an uncaught exception
// Used for debugging exception errors // Used for debugging exception errors
@ -364,6 +369,6 @@
ImGui::TextUnformatted(this->m_windowTitle.c_str()); ImGui::TextUnformatted(this->m_windowTitle.c_str());
} }
} }
#endif #endif

View File

@ -49,14 +49,14 @@ namespace hex {
return ctx; // Unused, but the return value has to be non-null return ctx; // Unused, but the return value has to be non-null
} }
void ImHexSettingsHandler_ReadLine(ImGuiContext*, ImGuiSettingsHandler *handler, void *, const char* line) { void ImHexSettingsHandler_ReadLine(ImGuiContext *, ImGuiSettingsHandler *handler, void *, const char *line) {
for (auto &[name, view] : ContentRegistry::Views::getEntries()) { for (auto &[name, view] : ContentRegistry::Views::getEntries()) {
std::string format = std::string(view->getUnlocalizedName()) + "=%d"; std::string format = std::string(view->getUnlocalizedName()) + "=%d";
sscanf(line, format.c_str(), &view->getWindowOpenState()); sscanf(line, format.c_str(), &view->getWindowOpenState());
} }
} }
void ImHexSettingsHandler_WriteAll(ImGuiContext* ctx, ImGuiSettingsHandler *handler, ImGuiTextBuffer *buf) { void ImHexSettingsHandler_WriteAll(ImGuiContext *ctx, ImGuiSettingsHandler *handler, ImGuiTextBuffer *buf) {
buf->reserve(buf->size() + 0x20); // Ballpark reserve buf->reserve(buf->size() + 0x20); // Ballpark reserve
buf->appendf("[%s][General]\n", handler->TypeName); buf->appendf("[%s][General]\n", handler->TypeName);
@ -74,13 +74,13 @@ namespace hex {
if (argument == "update-available") { if (argument == "update-available") {
this->m_availableUpdate = value; this->m_availableUpdate = value;
} else if (argument == "no-plugins") { } else if (argument == "no-plugins") {
View::doLater([]{ ImGui::OpenPopup("No Plugins"); }); View::doLater([] { ImGui::OpenPopup("No Plugins"); });
} else if (argument == "tip-of-the-day") { } else if (argument == "tip-of-the-day") {
this->m_tipOfTheDay = value; this->m_tipOfTheDay = value;
this->m_showTipOfTheDay = ContentRegistry::Settings::read("hex.builtin.setting.general", "hex.builtin.setting.general.show_tips", 1); this->m_showTipOfTheDay = ContentRegistry::Settings::read("hex.builtin.setting.general", "hex.builtin.setting.general.show_tips", 1);
if (this->m_showTipOfTheDay) if (this->m_showTipOfTheDay)
View::doLater([]{ ImGui::OpenPopup("hex.welcome.tip_of_the_day"_lang); }); View::doLater([] { ImGui::OpenPopup("hex.welcome.tip_of_the_day"_lang); });
} }
} }
} }
@ -136,7 +136,7 @@ namespace hex {
ImPlot::StyleColorsDark(); ImPlot::StyleColorsDark();
auto banner = romfs::get("banner_dark.png"); auto banner = romfs::get("banner_dark.png");
this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8*>(banner.data()), banner.size()); this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(banner.data()), banner.size());
break; break;
} }
@ -147,7 +147,7 @@ namespace hex {
ImPlot::StyleColorsLight(); ImPlot::StyleColorsLight();
auto banner = romfs::get("banner_light.png"); auto banner = romfs::get("banner_light.png");
this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8*>(banner.data()), banner.size()); this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(banner.data()), banner.size());
break; break;
} }
@ -158,7 +158,7 @@ namespace hex {
ImPlot::StyleColorsClassic(); ImPlot::StyleColorsClassic();
auto banner = romfs::get("banner_dark.png"); auto banner = romfs::get("banner_dark.png");
this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8*>(banner.data()), banner.size()); this->m_bannerTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(banner.data()), banner.size());
break; break;
} }
@ -175,7 +175,7 @@ namespace hex {
} }
}); });
EventManager::subscribe<EventFileLoaded>(this, [](const auto &path){ EventManager::subscribe<EventFileLoaded>(this, [](const auto &path) {
SharedData::recentFilePaths.push_front(path); SharedData::recentFilePaths.push_front(path);
{ {
@ -206,7 +206,7 @@ namespace hex {
} }
}); });
EventManager::subscribe<EventFileUnloaded>(this, []{ EventManager::subscribe<EventFileUnloaded>(this, [] {
EventManager::post<RequestChangeWindowTitle>(""); EventManager::post<RequestChangeWindowTitle>("");
}); });
@ -244,14 +244,14 @@ namespace hex {
} }
}); });
EventManager::subscribe<RequestOpenPopup>(this, [this](auto name){ EventManager::subscribe<RequestOpenPopup>(this, [this](auto name) {
this->m_popupsToOpen.push_back(name); this->m_popupsToOpen.push_back(name);
}); });
for (const auto &path : hex::getPath(ImHexPath::Config)) { for (const auto &path : hex::getPath(ImHexPath::Config)) {
if (auto filePath = fs::path(path) / CrashBackupFileName; fs::exists(filePath)) { if (auto filePath = fs::path(path) / CrashBackupFileName; fs::exists(filePath)) {
this->m_safetyBackupPath = filePath; this->m_safetyBackupPath = filePath;
View::doLater([]{ ImGui::OpenPopup("hex.safety_backup.title"_lang); }); View::doLater([] { ImGui::OpenPopup("hex.safety_backup.title"_lang); });
} }
} }
@ -269,12 +269,11 @@ namespace hex {
// Let's not loop on this... // Let's not loop on this...
std::signal(signalNumber, nullptr); std::signal(signalNumber, nullptr);
#if defined(DEBUG) #if defined(DEBUG)
assert(false); assert(false);
#else #else
std::raise(signalNumber); std::raise(signalNumber);
#endif #endif
}; };
std::signal(SIGTERM, signalHandler); std::signal(SIGTERM, signalHandler);
@ -285,7 +284,7 @@ namespace hex {
std::signal(SIGFPE, signalHandler); std::signal(SIGFPE, signalHandler);
auto imhexLogo = romfs::get("logo.png"); auto imhexLogo = romfs::get("logo.png");
this->m_logoTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8*>(imhexLogo.data()), imhexLogo.size()); this->m_logoTexture = ImGui::LoadImageFromMemory(reinterpret_cast<const ImU8 *>(imhexLogo.data()), imhexLogo.size());
ContentRegistry::Settings::store(); ContentRegistry::Settings::store();
EventManager::post<EventSettingsChanged>(); EventManager::post<EventSettingsChanged>();
@ -333,7 +332,7 @@ namespace hex {
ImGui_ImplGlfw_NewFrame(); ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame(); ImGui::NewFrame();
ImGuiViewport* viewport = ImGui::GetMainViewport(); ImGuiViewport *viewport = ImGui::GetMainViewport();
ImGui::SetNextWindowPos(viewport->WorkPos); ImGui::SetNextWindowPos(viewport->WorkPos);
ImGui::SetNextWindowSize(viewport->WorkSize); ImGui::SetNextWindowSize(viewport->WorkSize);
ImGui::SetNextWindowViewport(viewport->ID); ImGui::SetNextWindowViewport(viewport->ID);
@ -341,11 +340,7 @@ namespace hex {
ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f); ImGui::PushStyleVar(ImGuiStyleVar_WindowBorderSize, 0.0f);
ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0)); ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2(0, 0));
ImGuiWindowFlags windowFlags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking ImGuiWindowFlags windowFlags = ImGuiWindowFlags_MenuBar | ImGuiWindowFlags_NoDocking | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoBringToFrontOnFocus | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
| ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_NoCollapse
| ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize
| ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoBringToFrontOnFocus
| ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard;
@ -617,7 +612,7 @@ namespace hex {
glClear(GL_COLOR_BUFFER_BIT); glClear(GL_COLOR_BUFFER_BIT);
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData()); ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
GLFWwindow* backup_current_context = glfwGetCurrentContext(); GLFWwindow *backup_current_context = glfwGetCurrentContext();
ImGui::UpdatePlatformWindows(); ImGui::UpdatePlatformWindows();
ImGui::RenderPlatformWindowsDefault(); ImGui::RenderPlatformWindowsDefault();
glfwMakeContextCurrent(backup_current_context); glfwMakeContextCurrent(backup_current_context);
@ -700,7 +695,7 @@ namespace hex {
ImGui::TableNextRow(ImGuiTableRowFlags_None, ImGui::GetTextLineHeightWithSpacing() * 6); ImGui::TableNextRow(ImGuiTableRowFlags_None, ImGui::GetTextLineHeightWithSpacing() * 6);
ImGui::TableNextColumn(); ImGui::TableNextColumn();
ImGui:: UnderlinedText("hex.welcome.header.help"_lang); ImGui::UnderlinedText("hex.welcome.header.help"_lang);
ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 5_scaled); ImGui::SetCursorPosY(ImGui::GetCursorPosY() + 5_scaled);
{ {
if (ImGui::IconHyperlink(ICON_VS_GITHUB, "hex.welcome.help.repo"_lang)) hex::openWebpage("hex.welcome.help.repo.link"_lang); if (ImGui::IconHyperlink(ICON_VS_GITHUB, "hex.welcome.help.repo"_lang)) hex::openWebpage("hex.welcome.help.repo.link"_lang);
@ -796,11 +791,10 @@ namespace hex {
function(ContentRegistry::Interface::getDockSpaceId()); function(ContentRegistry::Interface::getDockSpaceId());
} }
} }
void Window::initGLFW() { void Window::initGLFW() {
glfwSetErrorCallback([](int error, const char* desc) { glfwSetErrorCallback([](int error, const char *desc) {
log::error("GLFW Error [{}] : {}", error, desc); log::error("GLFW Error [{}] : {}", error, desc);
}); });
@ -809,11 +803,11 @@ namespace hex {
std::abort(); std::abort();
} }
#if defined(OS_WINDOWS) #if defined(OS_WINDOWS)
glfwWindowHint(GLFW_DECORATED, GLFW_FALSE); glfwWindowHint(GLFW_DECORATED, GLFW_FALSE);
#elif defined(OS_MACOS) #elif defined(OS_MACOS)
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif #endif
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
@ -866,7 +860,7 @@ namespace hex {
if (auto g = ImGui::GetCurrentContext(); g == nullptr || g->WithinFrameScope) return; if (auto g = ImGui::GetCurrentContext(); g == nullptr || g->WithinFrameScope) return;
auto win = static_cast<Window*>(glfwGetWindowUserPointer(window)); auto win = static_cast<Window *>(glfwGetWindowUserPointer(window));
win->frameBegin(); win->frameBegin();
win->frame(); win->frame();
win->frameEnd(); win->frameEnd();
@ -877,19 +871,18 @@ namespace hex {
if (auto g = ImGui::GetCurrentContext(); g == nullptr || g->WithinFrameScope) return; if (auto g = ImGui::GetCurrentContext(); g == nullptr || g->WithinFrameScope) return;
auto win = static_cast<Window*>(glfwGetWindowUserPointer(window)); auto win = static_cast<Window *>(glfwGetWindowUserPointer(window));
win->frameBegin(); win->frameBegin();
win->frame(); win->frame();
win->frameEnd(); win->frameEnd();
}); });
glfwSetKeyCallback(this->m_window, [](GLFWwindow *window, int key, int scancode, int action, int mods) { glfwSetKeyCallback(this->m_window, [](GLFWwindow *window, int key, int scancode, int action, int mods) {
auto keyName = glfwGetKeyName(key, scancode); auto keyName = glfwGetKeyName(key, scancode);
if (keyName != nullptr) if (keyName != nullptr)
key = std::toupper(keyName[0]); key = std::toupper(keyName[0]);
auto win = static_cast<Window*>(glfwGetWindowUserPointer(window)); auto win = static_cast<Window *>(glfwGetWindowUserPointer(window));
if (action == GLFW_PRESS) { if (action == GLFW_PRESS) {
auto &io = ImGui::GetIO(); auto &io = ImGui::GetIO();
@ -899,8 +892,7 @@ namespace hex {
io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0; io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0; io.KeyShift = (mods & GLFW_MOD_SHIFT) != 0;
io.KeyAlt = (mods & GLFW_MOD_ALT) != 0; io.KeyAlt = (mods & GLFW_MOD_ALT) != 0;
} } else if (action == GLFW_RELEASE) {
else if (action == GLFW_RELEASE) {
auto &io = ImGui::GetIO(); auto &io = ImGui::GetIO();
io.KeysDown[key] = false; io.KeysDown[key] = false;
io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0; io.KeyCtrl = (mods & GLFW_MOD_CONTROL) != 0;
@ -950,16 +942,16 @@ namespace hex {
GImPlot = ImPlot::CreateContext(); GImPlot = ImPlot::CreateContext();
GImNodes = ImNodes::CreateContext(); GImNodes = ImNodes::CreateContext();
ImGuiIO& io = ImGui::GetIO(); ImGuiIO &io = ImGui::GetIO();
ImGuiStyle& style = ImGui::GetStyle(); ImGuiStyle &style = ImGui::GetStyle();
style.Alpha = 1.0F; style.Alpha = 1.0F;
style.WindowRounding = 0.0F; style.WindowRounding = 0.0F;
io.ConfigFlags |= ImGuiConfigFlags_DockingEnable | ImGuiConfigFlags_NavEnableKeyboard; io.ConfigFlags |= ImGuiConfigFlags_DockingEnable | ImGuiConfigFlags_NavEnableKeyboard;
#if !defined(OS_LINUX) #if !defined(OS_LINUX)
io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; io.ConfigFlags |= ImGuiConfigFlags_ViewportsEnable;
#endif #endif
for (auto &entry : SharedData::fontAtlas->ConfigData) for (auto &entry : SharedData::fontAtlas->ConfigData)
io.Fonts->ConfigData.push_back(entry); io.Fonts->ConfigData.push_back(entry);
@ -1052,7 +1044,7 @@ namespace hex {
} }
void Window::exitImGui() { void Window::exitImGui() {
delete static_cast<ImGui::ImHexCustomData*>(ImGui::GetIO().UserData); delete static_cast<ImGui::ImHexCustomData *>(ImGui::GetIO().UserData);
ImNodes::PopAttributeFlag(); ImNodes::PopAttributeFlag();
ImNodes::PopAttributeFlag(); ImNodes::PopAttributeFlag();

View File

@ -44,12 +44,12 @@ namespace hex::plugin::builtin::prv {
std::set<std::string> m_availableDrives; std::set<std::string> m_availableDrives;
fs::path m_path; fs::path m_path;
#if defined(OS_WINDOWS) #if defined(OS_WINDOWS)
HANDLE m_diskHandle = INVALID_HANDLE_VALUE; HANDLE m_diskHandle = INVALID_HANDLE_VALUE;
#else #else
std::string m_pathBuffer; std::string m_pathBuffer;
int m_diskHandle = -1; int m_diskHandle = -1;
#endif #endif
size_t m_diskSize; size_t m_diskSize;
size_t m_sectorSize; size_t m_sectorSize;

View File

@ -7,11 +7,11 @@
#include <sys/stat.h> #include <sys/stat.h>
#if defined(OS_WINDOWS) #if defined(OS_WINDOWS)
#include <windows.h> #include <windows.h>
#else #else
#include <sys/mman.h> #include <sys/mman.h>
#include <unistd.h> #include <unistd.h>
#include <sys/fcntl.h> #include <sys/fcntl.h>
#endif #endif
namespace hex::plugin::builtin::prv { namespace hex::plugin::builtin::prv {
@ -49,12 +49,12 @@ namespace hex::plugin::builtin::prv {
void close() override; void close() override;
protected: protected:
#if defined(OS_WINDOWS) #if defined(OS_WINDOWS)
HANDLE m_file = INVALID_HANDLE_VALUE; HANDLE m_file = INVALID_HANDLE_VALUE;
HANDLE m_mapping = INVALID_HANDLE_VALUE; HANDLE m_mapping = INVALID_HANDLE_VALUE;
#else #else
int m_file = -1; int m_file = -1;
#endif #endif
fs::path m_path; fs::path m_path;
void *m_mappedFile = nullptr; void *m_mappedFile = nullptr;

View File

@ -9,7 +9,7 @@
namespace hex::plugin::builtin::prv { namespace hex::plugin::builtin::prv {
class GDBProvider : public hex::prv::Provider { class GDBProvider : public hex::prv::Provider {
public: public:
explicit GDBProvider(); explicit GDBProvider();
~GDBProvider() override; ~GDBProvider() override;

View File

@ -7,7 +7,9 @@
namespace hex::plugin::builtin { namespace hex::plugin::builtin {
namespace prv { class Provider; } namespace prv {
class Provider;
}
class ViewBookmarks : public View { class ViewBookmarks : public View {
public: public:

View File

@ -10,7 +10,9 @@
namespace hex::plugin::builtin { namespace hex::plugin::builtin {
namespace prv { class Provider; } namespace prv {
class Provider;
}
class ViewDataInspector : public View { class ViewDataInspector : public View {
public: public:
@ -28,7 +30,7 @@ namespace hex::plugin::builtin {
bool m_shouldInvalidate = true; bool m_shouldInvalidate = true;
std::endian m_endian = std::endian::native; std::endian m_endian = std::endian::native;
ContentRegistry::DataInspector::NumberDisplayStyle m_numberDisplayStyle =ContentRegistry::DataInspector::NumberDisplayStyle::Decimal; ContentRegistry::DataInspector::NumberDisplayStyle m_numberDisplayStyle = ContentRegistry::DataInspector::NumberDisplayStyle::Decimal;
u64 m_startAddress = 0; u64 m_startAddress = 0;
size_t m_validBytes = 0; size_t m_validBytes = 0;

View File

@ -12,7 +12,9 @@
namespace hex::plugin::builtin { namespace hex::plugin::builtin {
namespace prv { class Provider; } namespace prv {
class Provider;
}
class ViewDataProcessor : public View { class ViewDataProcessor : public View {
public: public:
@ -22,11 +24,11 @@ namespace hex::plugin::builtin {
void drawContent() override; void drawContent() override;
private: private:
std::list<dp::Node*> m_endNodes; std::list<dp::Node *> m_endNodes;
std::list<dp::Node*> m_nodes; std::list<dp::Node *> m_nodes;
std::list<dp::Link> m_links; std::list<dp::Link> m_links;
std::vector<hex::prv::Overlay*> m_dataOverlays; std::vector<hex::prv::Overlay *> m_dataOverlays;
int m_rightClickedId = -1; int m_rightClickedId = -1;
ImVec2 m_rightClickedCoords; ImVec2 m_rightClickedCoords;

View File

@ -11,7 +11,9 @@
namespace hex::plugin::builtin { namespace hex::plugin::builtin {
namespace prv { class Provider; } namespace prv {
class Provider;
}
class ViewDiff : public View { class ViewDiff : public View {
public: public:

View File

@ -10,7 +10,9 @@
namespace hex::plugin::builtin { namespace hex::plugin::builtin {
namespace prv { class Provider; } namespace prv {
class Provider;
}
struct Disassembly { struct Disassembly {
u64 address; u64 address;

View File

@ -8,7 +8,9 @@
namespace hex::plugin::builtin { namespace hex::plugin::builtin {
namespace prv { class Provider; } namespace prv {
class Provider;
}
class ViewHashes : public View { class ViewHashes : public View {
public: public:
@ -18,7 +20,17 @@ namespace hex::plugin::builtin {
void drawContent() override; void drawContent() override;
private: private:
enum class HashFunctions { Crc8, Crc16, Crc32, Md5, Sha1, Sha224, Sha256, Sha384, Sha512 }; enum class HashFunctions {
Crc8,
Crc16,
Crc32,
Md5,
Sha1,
Sha224,
Sha256,
Sha384,
Sha512
};
bool m_shouldInvalidate = true; bool m_shouldInvalidate = true;
int m_currHashFunction = 0; int m_currHashFunction = 0;
@ -26,15 +38,15 @@ namespace hex::plugin::builtin {
bool m_shouldMatchSelection = false; bool m_shouldMatchSelection = false;
static constexpr std::array hashFunctionNames { static constexpr std::array hashFunctionNames {
std::pair{HashFunctions::Crc8, "CRC8"}, std::pair {HashFunctions::Crc8, "CRC8" },
std::pair{HashFunctions::Crc16, "CRC16"}, std::pair { HashFunctions::Crc16, "CRC16" },
std::pair{HashFunctions::Crc32, "CRC32"}, std::pair { HashFunctions::Crc32, "CRC32" },
std::pair{HashFunctions::Md5, "MD5"}, std::pair { HashFunctions::Md5, "MD5" },
std::pair{HashFunctions::Sha1, "SHA-1"}, std::pair { HashFunctions::Sha1, "SHA-1" },
std::pair{HashFunctions::Sha224, "SHA-224"}, std::pair { HashFunctions::Sha224, "SHA-224"},
std::pair{HashFunctions::Sha256, "SHA-256"}, std::pair { HashFunctions::Sha256, "SHA-256"},
std::pair{HashFunctions::Sha384, "SHA-384"}, std::pair { HashFunctions::Sha384, "SHA-384"},
std::pair{HashFunctions::Sha512, "SHA-512"}, std::pair { HashFunctions::Sha512, "SHA-512"},
}; };
}; };

View File

@ -11,7 +11,9 @@
namespace hex::plugin::builtin { namespace hex::plugin::builtin {
namespace prv { class Provider; } namespace prv {
class Provider;
}
class ViewHelp : public View { class ViewHelp : public View {
public: public:

View File

@ -10,13 +10,15 @@
#include <random> #include <random>
#include <vector> #include <vector>
namespace hex::prv { class Provider; } namespace hex::prv {
class Provider;
}
namespace hex::plugin::builtin { namespace hex::plugin::builtin {
using SearchFunction = std::vector<std::pair<u64, u64>> (*)(prv::Provider* &provider, std::string string); using SearchFunction = std::vector<std::pair<u64, u64>> (*)(prv::Provider *&provider, std::string string);
class ViewHexEditor : public View { class ViewHexEditor : public View {
public: public:
@ -44,7 +46,7 @@ namespace hex::plugin::builtin {
u64 m_resizeSize = 0; u64 m_resizeSize = 0;
std::vector<u8> m_dataToSave; std::vector<u8> m_dataToSave;
std::set<pl::PatternData*> m_highlightedPatterns; std::set<pl::PatternData *> m_highlightedPatterns;
std::string m_loaderScriptScriptPath; std::string m_loaderScriptScriptPath;
std::string m_loaderScriptFilePath; std::string m_loaderScriptFilePath;

View File

@ -10,7 +10,9 @@
namespace hex::plugin::builtin { namespace hex::plugin::builtin {
namespace prv { class Provider; } namespace prv {
class Provider;
}
class ViewInformation : public View { class ViewInformation : public View {
public: public:

View File

@ -9,7 +9,9 @@
namespace hex::plugin::builtin { namespace hex::plugin::builtin {
namespace prv { class Provider; } namespace prv {
class Provider;
}
class ViewPatches : public View { class ViewPatches : public View {
public: public:

View File

@ -11,8 +11,12 @@
namespace hex { namespace hex {
namespace prv { class Provider; } namespace prv {
namespace lang { class PatternData; } class Provider;
}
namespace lang {
class PatternData;
}
} }
@ -27,7 +31,7 @@ namespace hex::plugin::builtin {
void drawContent() override; void drawContent() override;
private: private:
std::vector<pl::PatternData*> m_sortedPatternData; std::vector<pl::PatternData *> m_sortedPatternData;
}; };
} }

View File

@ -7,7 +7,9 @@
namespace hex::plugin::builtin { namespace hex::plugin::builtin {
namespace prv { class Provider; } namespace prv {
class Provider;
}
struct FoundString { struct FoundString {
u64 offset; u64 offset;

View File

@ -10,7 +10,9 @@
namespace hex::plugin::builtin { namespace hex::plugin::builtin {
namespace prv { class Provider; } namespace prv {
class Provider;
}
class ViewTools : public View { class ViewTools : public View {
public: public:
@ -18,7 +20,6 @@ namespace hex::plugin::builtin {
~ViewTools() override; ~ViewTools() override;
void drawContent() override; void drawContent() override;
}; };
} }

View File

@ -74,7 +74,7 @@ namespace hex {
void setVariable(std::string name, long double value); void setVariable(std::string name, long double value);
void setFunction(std::string name, std::function<std::optional<long double>(std::vector<long double>)> function, size_t minNumArgs, size_t maxNumArgs); void setFunction(std::string name, std::function<std::optional<long double>(std::vector<long double>)> function, size_t minNumArgs, size_t maxNumArgs);
std::unordered_map<std::string, long double>& getVariables() { return this->m_variables; } std::unordered_map<std::string, long double> &getVariables() { return this->m_variables; }
private: private:
std::queue<Token> parseInput(const char *input); std::queue<Token> parseInput(const char *input);

View File

@ -14,7 +14,8 @@ namespace hex::plugin::builtin {
ContentRegistry::CommandPaletteCommands::add( ContentRegistry::CommandPaletteCommands::add(
ContentRegistry::CommandPaletteCommands::Type::SymbolCommand, ContentRegistry::CommandPaletteCommands::Type::SymbolCommand,
"#", "hex.builtin.command.calc.desc", "#",
"hex.builtin.command.calc.desc",
[](auto input) { [](auto input) {
hex::MathEvaluator evaluator; hex::MathEvaluator evaluator;
evaluator.registerStandardVariables(); evaluator.registerStandardVariables();
@ -24,7 +25,7 @@ namespace hex::plugin::builtin {
try { try {
result = evaluator.evaluate(input); result = evaluator.evaluate(input);
} catch (std::exception &e) {} } catch (std::exception &e) { }
if (result.has_value()) if (result.has_value())
@ -35,7 +36,8 @@ namespace hex::plugin::builtin {
ContentRegistry::CommandPaletteCommands::add( ContentRegistry::CommandPaletteCommands::add(
ContentRegistry::CommandPaletteCommands::Type::KeywordCommand, ContentRegistry::CommandPaletteCommands::Type::KeywordCommand,
"/web", "hex.builtin.command.web.desc", "/web",
"hex.builtin.command.web.desc",
[](auto input) { [](auto input) {
return hex::format("hex.builtin.command.web.result"_lang, input.data()); return hex::format("hex.builtin.command.web.result"_lang, input.data());
}, },
@ -45,14 +47,14 @@ namespace hex::plugin::builtin {
ContentRegistry::CommandPaletteCommands::add( ContentRegistry::CommandPaletteCommands::add(
ContentRegistry::CommandPaletteCommands::Type::SymbolCommand, ContentRegistry::CommandPaletteCommands::Type::SymbolCommand,
"$", "hex.builtin.command.cmd.desc", "$",
"hex.builtin.command.cmd.desc",
[](auto input) { [](auto input) {
return hex::format("hex.builtin.command.cmd.result"_lang, input.data()); return hex::format("hex.builtin.command.cmd.result"_lang, input.data());
}, },
[](auto input) { [](auto input) {
hex::runCommand(input); hex::runCommand(input);
}); });
} }
} }

View File

@ -23,7 +23,8 @@ namespace hex::plugin::builtin {
} }
// Remove trailing comma // Remove trailing comma
result.pop_back(); result.pop_back(); result.pop_back();
result.pop_back();
} }
result += "\n"; result += "\n";
@ -35,52 +36,31 @@ namespace hex::plugin::builtin {
void registerDataFormatters() { void registerDataFormatters() {
ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.c", [](prv::Provider *provider, u64 offset, size_t size) { ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.c", [](prv::Provider *provider, u64 offset, size_t size) {
return formatLanguageArray(provider, offset, size, return formatLanguageArray(provider, offset, size, hex::format("const uint8_t data[{0}] = {{", size), "0x{0:02X}, ", "};");
hex::format("const uint8_t data[{0}] = {{", size),
"0x{0:02X}, ",
"};");
}); });
ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.cpp", [](prv::Provider *provider, u64 offset, size_t size) { ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.cpp", [](prv::Provider *provider, u64 offset, size_t size) {
return formatLanguageArray(provider, offset, size, return formatLanguageArray(provider, offset, size, hex::format("constexpr std::array<uint8_t, {0}> data = {{", size), "0x{0:02X}, ", "};");
hex::format("constexpr std::array<uint8_t, {0}> data = {{", size),
"0x{0:02X}, ",
"};");
}); });
ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.java", [](prv::Provider *provider, u64 offset, size_t size) { ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.java", [](prv::Provider *provider, u64 offset, size_t size) {
return formatLanguageArray(provider, offset, size, return formatLanguageArray(provider, offset, size, "final byte[] data = {", "0x{0:02X}, ", "};");
"final byte[] data = {",
"0x{0:02X}, ",
"};");
}); });
ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.csharp", [](prv::Provider *provider, u64 offset, size_t size) { ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.csharp", [](prv::Provider *provider, u64 offset, size_t size) {
return formatLanguageArray(provider, offset, size, return formatLanguageArray(provider, offset, size, "const byte[] data = {", "0x{0:02X}, ", "};");
"const byte[] data = {",
"0x{0:02X}, ",
"};");
}); });
ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.rust", [](prv::Provider *provider, u64 offset, size_t size) { ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.rust", [](prv::Provider *provider, u64 offset, size_t size) {
return formatLanguageArray(provider, offset, size, return formatLanguageArray(provider, offset, size, hex::format("let data: [u8; 0x{0:02X}] = [", size), "0x{0:02X}, ", "];");
hex::format("let data: [u8; 0x{0:02X}] = [", size),
"0x{0:02X}, ",
"];");
}); });
ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.python", [](prv::Provider *provider, u64 offset, size_t size) { ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.python", [](prv::Provider *provider, u64 offset, size_t size) {
return formatLanguageArray(provider, offset, size, return formatLanguageArray(provider, offset, size, "data = bytes([", "0x{0:02X}, ", "]);");
"data = bytes([",
"0x{0:02X}, ",
"]);");
}); });
ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.js", [](prv::Provider *provider, u64 offset, size_t size) { ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.js", [](prv::Provider *provider, u64 offset, size_t size) {
return formatLanguageArray(provider, offset, size, return formatLanguageArray(provider, offset, size, "const data = new Uint8Array([", "0x{0:02X}, ", "]);");
"const data = new Uint8Array([",
"0x{0:02X}, ",
"]);");
}); });
ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.ascii", [](prv::Provider *provider, u64 offset, size_t size) { ContentRegistry::DataFormatter::add("hex.builtin.view.hexeditor.copy.ascii", [](prv::Provider *provider, u64 offset, size_t size) {
@ -95,7 +75,7 @@ namespace hex::plugin::builtin {
for (u32 col = offset >> 4; col <= (end >> 4); col++) { for (u32 col = offset >> 4; col <= (end >> 4); col++) {
result += hex::format("{0:08X} ", col << 4); result += hex::format("{0:08X} ", col << 4);
for (u64 i = 0 ; i < 16; i++) { for (u64 i = 0; i < 16; i++) {
if (col == (offset >> 4) && i < (offset & 0xF) || col == (end >> 4) && i > (end & 0xF)) if (col == (offset >> 4) && i < (offset & 0xF) || col == (end >> 4) && i > (end & 0xF))
result += " "; result += " ";
@ -108,7 +88,7 @@ namespace hex::plugin::builtin {
result += " "; result += " ";
for (u64 i = 0 ; i < 16; i++) { for (u64 i = 0; i < 16; i++) {
if (col == (offset >> 4) && i < (offset & 0xF) || col == (end >> 4) && i > (end & 0xF)) if (col == (offset >> 4) && i < (offset & 0xF) || col == (end >> 4) && i > (end & 0xF))
result += " "; result += " ";
@ -121,7 +101,6 @@ namespace hex::plugin::builtin {
result += "\n"; result += "\n";
} }
} }
return result; return result;
}); });
@ -148,7 +127,7 @@ namespace hex::plugin::builtin {
for (u32 col = offset >> 4; col <= (end >> 4); col++) { for (u32 col = offset >> 4; col <= (end >> 4); col++) {
result += hex::format(" <span class=\"offsetcolumn\">{0:08X}</span>&nbsp&nbsp<span class=\"hexcolumn\">", col << 4); result += hex::format(" <span class=\"offsetcolumn\">{0:08X}</span>&nbsp&nbsp<span class=\"hexcolumn\">", col << 4);
for (u64 i = 0 ; i < 16; i++) { for (u64 i = 0; i < 16; i++) {
if (col == (offset >> 4) && i < (offset & 0xF) || col == (end >> 4) && i > (end & 0xF)) if (col == (offset >> 4) && i < (offset & 0xF) || col == (end >> 4) && i > (end & 0xF))
result += "&nbsp&nbsp "; result += "&nbsp&nbsp ";
@ -161,7 +140,7 @@ namespace hex::plugin::builtin {
result += "</span>&nbsp&nbsp<span class=\"textcolumn\">"; result += "</span>&nbsp&nbsp<span class=\"textcolumn\">";
for (u64 i = 0 ; i < 16; i++) { for (u64 i = 0; i < 16; i++) {
if (col == (offset >> 4) && i < (offset & 0xF) || col == (end >> 4) && i > (end & 0xF)) if (col == (offset >> 4) && i < (offset & 0xF) || col == (end >> 4) && i > (end & 0xF))
result += "&nbsp"; result += "&nbsp";
@ -174,7 +153,6 @@ namespace hex::plugin::builtin {
result += "</span><br>\n"; result += "</span><br>\n";
} }
} }
result += result +=
@ -183,7 +161,6 @@ namespace hex::plugin::builtin {
return result; return result;
}); });
} }
} }

Some files were not shown because too many files have changed in this diff Show More