1
0
mirror of synced 2025-01-18 09:04:52 +01:00

Fixed duplicated utils.hpp

This commit is contained in:
WerWolv 2020-12-27 15:54:12 +01:00
parent f74eff8934
commit 144e30775f
9 changed files with 174 additions and 248 deletions

View File

@ -1,168 +0,0 @@
#pragma once
#include <hex.hpp>
#include <array>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <vector>
#ifdef __MINGW32__
#include <winsock.h>
#else
#include <arpa/inet.h>
#endif
#include "lang/token.hpp"
#ifdef __APPLE__
#define off64_t off_t
#define fopen64 fopen
#define fseeko64 fseek
#define ftello64 ftell
#endif
#if defined(_LIBCPP_VERSION) && _LIBCPP_VERSION <= 12000
#if __has_include(<concepts>)
// Make sure we break when derived_from is implemented in libc++. Then we can fix a compatibility version above
#include <concepts>
#endif
// libcxx 12 still doesn't have derived_from implemented, as a result we need to define it ourself using clang built-ins.
// [concept.derived] (patch from https://reviews.llvm.org/D74292)
namespace hex {
template<class _Dp, class _Bp>
concept derived_from =
__is_base_of(_Bp, _Dp) && __is_convertible_to(const volatile _Dp*, const volatile _Bp*);
}
#else
// Assume supported
#include <concepts>
namespace hex {
using std::derived_from;
}
#endif
namespace hex {
template<typename ... Args>
inline std::string format(const char *format, Args ... args) {
ssize_t size = snprintf( nullptr, 0, format, args ... );
if (size <= 0)
return "";
std::vector<char> buffer(size + 1, 0x00);
snprintf(buffer.data(), size + 1, format, args ...);
return std::string(buffer.data(), buffer.data() + size);
}
[[nodiscard]] constexpr inline u64 extract(u8 from, u8 to, const u64 &value) {
u64 mask = (std::numeric_limits<u64>::max() >> (63 - (from - to))) << to;
return (value & mask) >> to;
}
[[nodiscard]] constexpr inline u64 signExtend(u64 value, u8 currWidth, u8 targetWidth) {
u64 mask = 1LLU << (currWidth - 1);
return (((value ^ mask) - mask) << (64 - targetWidth)) >> (64 - targetWidth);
}
[[nodiscard]] constexpr inline bool isUnsigned(const lang::Token::TypeToken::Type type) {
return (static_cast<u32>(type) & 0x0F) == 0x00;
}
[[nodiscard]] constexpr inline bool isSigned(const lang::Token::TypeToken::Type type) {
return (static_cast<u32>(type) & 0x0F) == 0x01;
}
[[nodiscard]] constexpr inline bool isFloatingPoint(const lang::Token::TypeToken::Type type) {
return (static_cast<u32>(type) & 0x0F) == 0x02;
}
[[nodiscard]] constexpr inline u32 getTypeSize(const lang::Token::TypeToken::Type type) {
return static_cast<u32>(type) >> 4;
}
std::string toByteString(u64 bytes);
std::string makePrintable(char c);
template<typename T>
struct always_false : std::false_type {};
template<typename T>
constexpr T changeEndianess(T value, std::endian endian) {
if (endian == std::endian::native)
return value;
if constexpr (sizeof(T) == 1)
return value;
else if constexpr (sizeof(T) == 2)
return __builtin_bswap16(value);
else if constexpr (sizeof(T) == 4)
return __builtin_bswap32(value);
else if constexpr (sizeof(T) == 8)
return __builtin_bswap64(value);
else
static_assert(always_false<T>::value, "Invalid type provided!");
}
template<typename T>
constexpr T changeEndianess(T value, size_t size, std::endian endian) {
if (endian == std::endian::native)
return value;
if (size == 1)
return value;
else if (size == 2)
return __builtin_bswap16(value);
else if (size == 4)
return __builtin_bswap32(value);
else if (size == 8)
return __builtin_bswap64(value);
else
throw std::invalid_argument("Invalid value size!");
}
template< class T >
constexpr T bit_width(T x) noexcept {
return std::numeric_limits<T>::digits - std::countl_zero(x);
}
template<typename T>
constexpr T bit_ceil(T x) noexcept {
if (x <= 1u)
return T(1);
return T(1) << bit_width(T(x - 1));
}
std::vector<u8> readFile(std::string_view path);
class ScopeExit {
public:
ScopeExit(std::function<void()> func) : m_func(func) {}
~ScopeExit() { if (this->m_func != nullptr) this->m_func(); }
void release() {
this->m_func = nullptr;
}
private:
std::function<void()> m_func;
};
struct Region {
u64 address;
size_t size;
};
struct Bookmark {
Region region;
std::vector<char> name;
std::vector<char> comment;
};
}

View File

@ -67,5 +67,21 @@ namespace hex::lang {
} typeToken;
u32 lineNumber;
[[nodiscard]] constexpr static inline bool isUnsigned(const TypeToken::Type type) {
return (static_cast<u32>(type) & 0x0F) == 0x00;
}
[[nodiscard]] constexpr static inline bool isSigned(const TypeToken::Type type) {
return (static_cast<u32>(type) & 0x0F) == 0x01;
}
[[nodiscard]] constexpr static inline bool isFloatingPoint(const TypeToken::Type type) {
return (static_cast<u32>(type) & 0x0F) == 0x02;
}
[[nodiscard]] constexpr static inline u32 getTypeSize(const TypeToken::Type type) {
return static_cast<u32>(type) >> 4;
}
};
}

View File

@ -2,8 +2,19 @@
#include <hex.hpp>
#define TOKEN_CONCAT_IMPL(x, y) x ## y
#define TOKEN_CONCAT(x, y) TOKEN_CONCAT_IMPL(x, y)
#include <array>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <vector>
#ifdef __MINGW32__
#include <winsock.h>
#else
#include <arpa/inet.h>
#endif
#ifdef __APPLE__
#define off64_t off_t
@ -12,20 +23,24 @@
#define ftello64 ftell
#endif
#include <array>
#include <functional>
#include <memory>
#include <optional>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#ifdef __MINGW32__
#include <winsock.h>
#if defined(_LIBCPP_VERSION) && _LIBCPP_VERSION <= 12000
#if __has_include(<concepts>)
// Make sure we break when derived_from is implemented in libc++. Then we can fix a compatibility version above
#include <concepts>
#endif
// libcxx 12 still doesn't have derived_from implemented, as a result we need to define it ourself using clang built-ins.
// [concept.derived] (patch from https://reviews.llvm.org/D74292)
namespace hex {
template<class _Dp, class _Bp>
concept derived_from =
__is_base_of(_Bp, _Dp) && __is_convertible_to(const volatile _Dp*, const volatile _Bp*);
}
#else
#include <arpa/inet.h>
// Assume supported
#include <concepts>
namespace hex {
using std::derived_from;
}
#endif
namespace hex {
@ -43,8 +58,8 @@ namespace hex {
return std::string(buffer.data(), buffer.data() + size);
}
[[nodiscard]] constexpr inline u64 extract(u8 from, u8 to, const hex::unsigned_integral auto &value) {
std::remove_cvref_t<decltype(value)> mask = (std::numeric_limits<std::remove_cvref_t<decltype(value)>>::max() >> (((sizeof(value) * 8) - 1) - (from - to))) << to;
[[nodiscard]] constexpr inline u64 extract(u8 from, u8 to, const u64 &value) {
u64 mask = (std::numeric_limits<u64>::max() >> (63 - (from - to))) << to;
return (value & mask) >> to;
}
@ -108,18 +123,16 @@ namespace hex {
std::vector<u8> readFile(std::string_view path);
#define SCOPE_EXIT(func) ScopeExit TOKEN_CONCAT(scopeGuard, __COUNTER__)([&] { func })
class ScopeExit {
public:
ScopeExit(std::function<void()> func) : m_func(std::move(func)) {}
~ScopeExit() { if (!this->m_released) this->m_func(); }
ScopeExit(std::function<void()> func) : m_func(func) {}
~ScopeExit() { if (this->m_func != nullptr) this->m_func(); }
void release() {
this->m_released = true;
this->m_func = nullptr;
}
private:
bool m_released = false;
std::function<void()> m_func;
};

View File

@ -24,51 +24,3 @@ extern char **mainArgv;
#else
#define MAGIC_PATH_SEPARATOR ":"
#endif
template<>
struct std::is_integral<u128> : public std::true_type { };
template<>
struct std::is_integral<s128> : public std::true_type { };
template<>
struct std::is_signed<s128> : public std::true_type { };
#if defined(_LIBCPP_VERSION) && _LIBCPP_VERSION <= 12000
#if __has_include(<concepts>)
// Make sure we break when derived_from is implemented in libc++. Then we can fix a compatibility version above
#include <concepts>
#endif
// 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)
namespace hex {
template<class _Dp, class _Bp>
concept derived_from =
__is_base_of(_Bp, _Dp) && __is_convertible_to(const volatile _Dp*, const volatile _Bp*);
}
// [concepts.arithmetic] (patch from https://reviews.llvm.org/D88131)
namespace hex {
template<class _Tp>
concept integral = __is_integral(_Tp);
template<class _Tp>
concept signed_integral = integral<_Tp> && __is_signed(_Tp);
template<class _Tp>
concept unsigned_integral = integral<_Tp> && !signed_integral<_Tp>;
template<class _Tp>
concept floating_point = __is_floating_point(_Tp);
}
#else
// Assume supported
#include <concepts>
namespace hex {
using std::derived_from;
using std::integral;
using std::signed_integral;
using std::unsigned_integral;
using std::floating_point;
}
#endif

4
plugins/wintools/.idea/misc.xml generated Normal file
View File

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CMakeWorkspace" PROJECT_DIR="$PROJECT_DIR$" />
</project>

6
plugins/wintools/.idea/vcs.xml generated Normal file
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/../.." vcs="Git" />
</component>
</project>

100
plugins/wintools/.idea/workspace.xml generated Normal file
View File

@ -0,0 +1,100 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CMakeRunConfigurationManager" shouldGenerate="true" shouldDeleteObsolete="true">
<generated>
<config projectName="wintools" targetName="wintools" />
<config projectName="wintools" targetName="glad" />
<config projectName="wintools" targetName="imgui" />
<config projectName="wintools" targetName="libimhex" />
</generated>
</component>
<component name="CMakeSettings">
<configurations>
<configuration PROFILE_NAME="Debug" CONFIG_NAME="Debug" ENABLED="true" />
</configurations>
</component>
<component name="ChangeListManager">
<list default="true" id="c454de66-8fe4-4e5f-acc9-f16bc0889fb6" name="Default Changelist" comment="">
<change beforePath="$PROJECT_DIR$/../../CMakeLists.txt" beforeDir="false" afterPath="$PROJECT_DIR$/../../CMakeLists.txt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/../../external/ImGui/CMakeLists.txt" beforeDir="false" afterPath="$PROJECT_DIR$/../../external/ImGui/CMakeLists.txt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/../../external/ImGui/include/imgui_memory_editor.h" beforeDir="false" afterPath="$PROJECT_DIR$/../../external/ImGui/include/imgui_memory_editor.h" afterDir="false" />
<change beforePath="$PROJECT_DIR$/../../include/helpers/project_file_handler.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/../../include/helpers/project_file_handler.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/../../include/helpers/utils.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/../libimhex/include/helpers/utils.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/../../include/lang/ast_node.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/../../include/lang/ast_node.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/../example/CMakeLists.txt" beforeDir="false" afterPath="$PROJECT_DIR$/../example/CMakeLists.txt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/../libimhex/CMakeLists.txt" beforeDir="false" afterPath="$PROJECT_DIR$/../libimhex/CMakeLists.txt" afterDir="false" />
<change beforePath="$PROJECT_DIR$/../libimhex/include/hex.hpp" beforeDir="false" afterPath="$PROJECT_DIR$/../libimhex/include/hex.hpp" afterDir="false" />
<change beforePath="$PROJECT_DIR$/../../source/helpers/utils.cpp" beforeDir="false" afterPath="$PROJECT_DIR$/../libimhex/source/helpers/utils.cpp" afterDir="false" />
</list>
<option name="SHOW_DIALOG" value="false" />
<option name="HIGHLIGHT_CONFLICTS" value="true" />
<option name="HIGHLIGHT_NON_ACTIVE_CHANGELIST" value="false" />
<option name="LAST_RESOLUTION" value="IGNORE" />
</component>
<component name="ClangdSettings">
<option name="formatViaClangd" value="false" />
</component>
<component name="ExecutionTargetManager" SELECTED_TARGET="CMakeBuildProfile:Debug" />
<component name="Git.Settings">
<option name="RECENT_GIT_ROOT_PATH" value="$PROJECT_DIR$/../.." />
</component>
<component name="ProjectId" id="1m42axiGvEOkDElQLOQVaunq0yZ" />
<component name="ProjectLevelVcsManager" settingsEditedManually="true" />
<component name="ProjectViewState">
<option name="hideEmptyMiddlePackages" value="true" />
<option name="showLibraryContents" value="true" />
</component>
<component name="PropertiesComponent">
<property name="RunOnceActivity.OpenProjectViewOnStart" value="true" />
<property name="RunOnceActivity.ShowReadmeOnStart" value="true" />
<property name="WebServerToolWindowFactoryState" value="false" />
<property name="cf.first.check.clang-format" value="false" />
<property name="last_opened_file_path" value="$PROJECT_DIR$" />
</component>
<component name="RunManager" selected="CMake Application.wintools">
<configuration name="glad" type="CMakeRunConfiguration" factoryName="Application" REDIRECT_INPUT="false" ELEVATE="false" PASS_PARENT_ENVS_2="true" PROJECT_NAME="wintools" TARGET_NAME="glad" CONFIG_NAME="Debug">
<method v="2">
<option name="com.jetbrains.cidr.execution.CidrBuildBeforeRunTaskProvider$BuildBeforeRunTask" enabled="true" />
</method>
</configuration>
<configuration name="imgui" type="CMakeRunConfiguration" factoryName="Application" REDIRECT_INPUT="false" ELEVATE="false" PASS_PARENT_ENVS_2="true" PROJECT_NAME="wintools" TARGET_NAME="imgui" CONFIG_NAME="Debug">
<method v="2">
<option name="com.jetbrains.cidr.execution.CidrBuildBeforeRunTaskProvider$BuildBeforeRunTask" enabled="true" />
</method>
</configuration>
<configuration name="libimhex" type="CMakeRunConfiguration" factoryName="Application" REDIRECT_INPUT="false" ELEVATE="false" PASS_PARENT_ENVS_2="true" PROJECT_NAME="wintools" TARGET_NAME="libimhex" CONFIG_NAME="Debug">
<method v="2">
<option name="com.jetbrains.cidr.execution.CidrBuildBeforeRunTaskProvider$BuildBeforeRunTask" enabled="true" />
</method>
</configuration>
<configuration name="wintools" type="CMakeRunConfiguration" factoryName="Application" REDIRECT_INPUT="false" ELEVATE="false" PASS_PARENT_ENVS_2="true" PROJECT_NAME="wintools" TARGET_NAME="wintools" CONFIG_NAME="Debug">
<method v="2">
<option name="com.jetbrains.cidr.execution.CidrBuildBeforeRunTaskProvider$BuildBeforeRunTask" enabled="true" />
</method>
</configuration>
<list>
<item itemvalue="CMake Application.wintools" />
<item itemvalue="CMake Application.glad" />
<item itemvalue="CMake Application.imgui" />
<item itemvalue="CMake Application.libimhex" />
</list>
</component>
<component name="SpellCheckerSettings" RuntimeDictionaries="0" Folders="0" CustomDictionaries="0" DefaultDictionary="application-level" UseSingleDictionary="true" transferred="true" />
<component name="TaskManager">
<task active="true" id="Default" summary="Default task">
<changelist id="c454de66-8fe4-4e5f-acc9-f16bc0889fb6" name="Default Changelist" comment="" />
<created>1608738610011</created>
<option name="number" value="Default" />
<option name="presentableId" value="Default" />
<updated>1608738610011</updated>
<workItem from="1608738611380" duration="619000" />
<workItem from="1608800289164" duration="13000" />
<workItem from="1608983229676" duration="7070000" />
<workItem from="1609067748804" duration="11000" />
</task>
<servers />
</component>
<component name="TypeScriptGeneratedFilesManager">
<option name="version" value="3" />
</component>
</project>

View File

@ -1,5 +1,7 @@
#include "lang/evaluator.hpp"
#include "lang/token.hpp"
#include <bit>
#include <unordered_map>
@ -204,7 +206,7 @@ namespace hex::lang {
return { nullptr, 0 };
}
size_t size = getTypeSize(enumType->getUnderlyingType());
size_t size = Token::getTypeSize(enumType->getUnderlyingType());
return { new PatternDataEnum(offset, size, varDeclNode->getVariableName(), enumType->getName(), enumType->getValues(), varDeclNode->getEndianess().value_or(this->m_defaultDataEndianess)), size };
}
@ -322,22 +324,22 @@ namespace hex::lang {
type = currType->getAssignedType();
}
size_t typeSize = getTypeSize(type);
size_t typeSize = Token::getTypeSize(type);
size_t arraySize = varDeclNode->getArraySize();
if (isSigned(type)) {
if (Token::isSigned(type)) {
if (typeSize == 1 && arraySize == 1)
return { new PatternDataCharacter(offset, typeSize, varDeclNode->getVariableName(), varDeclNode->getEndianess().value_or(this->m_defaultDataEndianess)), 1 };
else if (arraySize > 1)
return createArrayPattern(varDeclNode, offset);
else
return { new PatternDataSigned(offset, typeSize, varDeclNode->getVariableName(), varDeclNode->getEndianess().value_or(this->m_defaultDataEndianess)), typeSize * arraySize };
} else if (isUnsigned(varDeclNode->getVariableType())) {
} else if (Token::isUnsigned(varDeclNode->getVariableType())) {
if (arraySize > 1)
return createArrayPattern(varDeclNode, offset);
else
return { new PatternDataUnsigned(offset, typeSize, varDeclNode->getVariableName(), varDeclNode->getEndianess().value_or(this->m_defaultDataEndianess)), typeSize * arraySize };
} else if (isFloatingPoint(varDeclNode->getVariableType())) {
} else if (Token::isFloatingPoint(varDeclNode->getVariableType())) {
if (arraySize > 1)
return createArrayPattern(varDeclNode, offset);
else

View File

@ -1,6 +1,7 @@
#include "lang/parser.hpp"
#include "helpers/utils.hpp"
#include "lang/token.hpp"
#include <optional>
@ -63,7 +64,7 @@ namespace hex::lang {
ASTNode* Parser::parseBuiltinPointerVariableDecl(TokenIter &curr, bool hasEndianDef) {
auto pointerType = curr[-2].typeToken.type;
if (!isUnsigned(pointerType)) {
if (!Token::isUnsigned(pointerType)) {
this->m_error = { curr->lineNumber, "Pointer size needs to be a unsigned type" };
return nullptr;
}
@ -88,16 +89,16 @@ namespace hex::lang {
endianess = std::endian::big;
else return nullptr;
return new ASTNodeVariableDecl(curr[-7].lineNumber, curr[-6].typeToken.type, curr[-4].identifierToken.identifier, "", { }, 1, { }, getTypeSize(pointerType), endianess);
return new ASTNodeVariableDecl(curr[-7].lineNumber, curr[-6].typeToken.type, curr[-4].identifierToken.identifier, "", { }, 1, { }, Token::getTypeSize(pointerType), endianess);
}
else
return new ASTNodeVariableDecl(curr[-6].lineNumber, curr[-6].typeToken.type, curr[-4].identifierToken.identifier, "", { }, 1, { }, getTypeSize(pointerType));
return new ASTNodeVariableDecl(curr[-6].lineNumber, curr[-6].typeToken.type, curr[-4].identifierToken.identifier, "", { }, 1, { }, Token::getTypeSize(pointerType));
}
ASTNode* Parser::parseCustomTypePointerVariableDecl(TokenIter &curr, bool hasEndianDef) {
auto pointerType = curr[-2].typeToken.type;
if (!isUnsigned(pointerType)) {
if (!Token::isUnsigned(pointerType)) {
this->m_error = { curr->lineNumber, "Pointer size needs to be a unsigned type" };
return nullptr;
}
@ -124,10 +125,10 @@ namespace hex::lang {
return nullptr;
}
return new ASTNodeVariableDecl(curr[-7].lineNumber,Token::TypeToken::Type::CustomType, curr[-4].identifierToken.identifier, curr[-6].identifierToken.identifier, { }, 1, { }, getTypeSize(pointerType), endianess);
return new ASTNodeVariableDecl(curr[-7].lineNumber,Token::TypeToken::Type::CustomType, curr[-4].identifierToken.identifier, curr[-6].identifierToken.identifier, { }, 1, { }, Token::getTypeSize(pointerType), endianess);
}
else
return new ASTNodeVariableDecl(curr[-6].lineNumber, Token::TypeToken::Type::CustomType, curr[-4].identifierToken.identifier, curr[-6].identifierToken.identifier, { }, 1, { }, getTypeSize(pointerType));
return new ASTNodeVariableDecl(curr[-6].lineNumber, Token::TypeToken::Type::CustomType, curr[-4].identifierToken.identifier, curr[-6].identifierToken.identifier, { }, 1, { }, Token::getTypeSize(pointerType));
}
ASTNode* Parser::parseBuiltinArrayDecl(TokenIter &curr, bool hasEndianDef) {
@ -369,7 +370,7 @@ namespace hex::lang {
return nullptr;
}
if (!isUnsigned(underlyingType)) {
if (!Token::isUnsigned(underlyingType)) {
this->m_error = { curr[-3].lineNumber, "Underlying type needs to be an unsigned type" };
return nullptr;
}