commit 20437fac8f4a253be01d541ca4775c1334ea6352 Author: Kirill Zhumarin Date: Sat Jun 29 18:25:15 2024 +0000 some test code diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9785597 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +build +.cache diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..bd58ce0 --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,16 @@ +cmake_minimum_required(VERSION 3.9) + +project(ptr89) +set(CMAKE_CXX_STANDARD 20) +set(CMAKE_CXX_FLAGS " -static -O3 ") +# set(CMAKE_INTERPROCEDURAL_OPTIMIZATION TRUE) +set(CMAKE_EXPORT_COMPILE_COMMANDS TRUE) + +include_directories("lib") + +add_executable(ptr89 src/main.cpp lib/src/Pattern.cpp lib/src/Tokenizer.cpp lib/src/Parser.cpp lib/src/utils.cpp) +install(TARGETS ptr89 DESTINATION /usr/bin) + +# enable_testing() +# add_executable(ptr89-tests src/tests.cpp src/Pattern.cpp src/Tokenizer.cpp src/Parser.cpp src/utils.cpp) +# add_test(NAME test COMMAND ptr89-tests) diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..eb2d074 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Kirill Zhumarin + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/build.sh b/build.sh new file mode 100755 index 0000000..d61656b --- /dev/null +++ b/build.sh @@ -0,0 +1,7 @@ +#!/bin/bash +set -e +set -x +[[ -d build ]] || mkdir build +cd build +cmake .. +make "$@" diff --git a/lib/ptr89.h b/lib/ptr89.h new file mode 100644 index 0000000..3095ef8 --- /dev/null +++ b/lib/ptr89.h @@ -0,0 +1,3 @@ +#pragma once + +#include "src/Pattern.h" diff --git a/lib/src/Parser.cpp b/lib/src/Parser.cpp new file mode 100644 index 0000000..f3c39f7 --- /dev/null +++ b/lib/src/Parser.cpp @@ -0,0 +1,268 @@ +#include "Parser.h" +#include "Pattern.h" +#include "Tokenizer.h" +#include "src/utils.h" +#include +#include + +namespace Ptr89 { + +std::shared_ptr Parser::parse(const std::string &input) { + m_input = input; + m_pattern = {}; + m_tok.reset(m_input); + + skipWhitespaces(); + + switch (m_tok.peek().type) { + case Tokenizer::TOK_POINTER: // *( ... ) + case Tokenizer::TOK_REFERENCE: // &( ... ) + parseReferenceOrPointer(); + break; + + default: + parseOffsetPattern(); + break; + + case Tokenizer::TOK_EOF: + throw PatternError(this, "Unexpected EOF"); + break; + + case Tokenizer::TOK_INVALID: + throw PatternError(this, "Syntax error"); + break; + } + + skipWhitespaces(); + + if (m_tok.peek().type != Tokenizer::TOK_EOF) + throw PatternError(this, "Unexpected tokens after end of pattern"); + + return std::make_shared(m_pattern); +} + +void Parser::parseReferenceOrPointer() { + if (m_tok.peek().type == Tokenizer::TOK_POINTER) { + m_pattern.type = PATTERN_TYPE_POINTER; + } else { + m_pattern.type = PATTERN_TYPE_REFERENCE; + } + + m_tok.next(); + + expectToken(Tokenizer::TOK_PAREN_OPEN); + m_tok.next(); + + parsePatternBody(); + + expectToken(Tokenizer::TOK_PAREN_CLOSE); + m_tok.next(); + + m_pattern.outputOffset = parseOffset(); +} + +void Parser::parseOffsetPattern() { + m_pattern.type = PATTERN_TYPE_OFFSET; + parsePatternBody(); +} + +void Parser::parsePatternBody() { + skipWhitespaces(); + while (parsePatternData()); + m_pattern.inputOffset = parseOffset(); +} + +int Parser::parseOffset() { + skipWhitespaces(); + if (m_tok.peek().type != Tokenizer::TOK_MINUS && m_tok.peek().type != Tokenizer::TOK_PLUS) + return 0; + + bool isNegative = (m_tok.peek().type == Tokenizer::TOK_MINUS); + m_tok.next(); + + skipWhitespaces(); + expectToken(Tokenizer::TOK_HEX); + return getTokenInt(m_tok.next()) * (isNegative ? -1 : 1); +} + +void Parser::parseHexMask() { + auto value = getTokenStr(m_tok.peek()); + if (value.size() % 2 != 0) + throw PatternError(this, "The hex number length must be even"); + + for (int i = 0; i < value.size(); i += 2) { + uint16_t mask = 0; + uint16_t byte = 0; + + if (value[i] != '?') { + mask |= 0xF0; + byte |= hex2byte(value[i]) << 4; + } + + if (value[i + 1] != '?') { + mask |= 0x0F; + byte |= hex2byte(value[i + 1]); + } + + m_pattern.bytes.push_back(byte); + m_pattern.masks.push_back(mask); + } + + m_tok.next(); +} + +void Parser::parseBinMask() { + auto value = getTokenStr(m_tok.peek()); + uint16_t mask = 0; + uint16_t byte = 0; + for (int i = 1; i <= 8; i++) { + int16_t bit = 1 << (8 - i); + if (value[i] == '1') { + mask |= bit; + byte |= bit; + } else if (value[i] == '0') { + mask |= bit; + } + } + m_pattern.bytes.push_back(byte); + m_pattern.masks.push_back(mask); + m_tok.next(); +} + +void Parser::parseSubPattern(SubPatternType type, Tokenizer::TokenType openTag, Tokenizer::TokenType closeTag) { + PtrExp mainPattern = m_pattern; + + expectToken(openTag); + m_tok.next(); + + m_pattern = {}; + m_pattern.source = m_input; + while (parsePatternData()); + + PtrExp subPattern = m_pattern; + m_pattern = mainPattern; + + int offset = m_pattern.bytes.size(); + m_pattern.subPatterns[offset] = { + .type = type, + .pattern = std::make_shared(subPattern), + .offset = offset, + .size = 0 + }; + + if (type == SUB_PATTERN_TYPE_BRANCH_2B) { + for (int i = 0; i < 2; i++) { + m_pattern.bytes.push_back(0); + m_pattern.masks.push_back(0); + } + m_pattern.subPatterns[offset].size = 2; + } else if (type == SUB_PATTERN_TYPE_BRANCH_4B) { + for (int i = 0; i < 4; i++) { + m_pattern.bytes.push_back(0); + m_pattern.masks.push_back(0); + } + m_pattern.subPatterns[offset].size = 4; + } + + expectToken(closeTag); + m_tok.next(); +} + +bool Parser::parsePatternData() { + switch (m_tok.peek().type) { + case Tokenizer::TOK_HEX: + case Tokenizer::TOK_MASK: + parseHexMask(); + break; + + case Tokenizer::TOK_BIN: + parseBinMask(); + break; + + case Tokenizer::TOK_2B_BRANCH_OPEN: // [ ... ] + parseSubPattern(SUB_PATTERN_TYPE_BRANCH_2B, Tokenizer::TOK_2B_BRANCH_OPEN, Tokenizer::TOK_2B_BRANCH_CLOSE); + break; + + case Tokenizer::TOK_4B_BRANCH_OPEN: // { ... } + parseSubPattern(SUB_PATTERN_TYPE_BRANCH_4B, Tokenizer::TOK_4B_BRANCH_OPEN, Tokenizer::TOK_4B_BRANCH_CLOSE); + break; + + case Tokenizer::TOK_BLF: // _BLF(...) + m_tok.next(); + parseSubPattern(SUB_PATTERN_TYPE_BRANCH_4B, Tokenizer::TOK_PAREN_OPEN, Tokenizer::TOK_PAREN_CLOSE); + break; + + case Tokenizer::TOK_SEPARATOR: + case Tokenizer::TOK_WHITESPACE: + m_tok.next(); + break; + + case Tokenizer::TOK_INVALID: + throw PatternError(this, "Syntax error"); + break; + + default: + // Data is end + return false; + break; + } + return true; +} + +Tokenizer::TokenType Parser::getClosingToken(Tokenizer::TokenType tokenType) { + switch (tokenType) { + case Tokenizer::TOK_2B_BRANCH_OPEN: return Tokenizer::TOK_2B_BRANCH_CLOSE; + case Tokenizer::TOK_4B_BRANCH_OPEN: return Tokenizer::TOK_4B_BRANCH_CLOSE; + case Tokenizer::TOK_PAREN_OPEN: return Tokenizer::TOK_PAREN_CLOSE; + default: return Tokenizer::TOK_INVALID; + } +} + +void Parser::expectTokens(const std::vector tokenTypes) { + for (const auto tokenType: tokenTypes) { + if (m_tok.peek().type == tokenType) + return; + } + if (m_tok.peek().type == Tokenizer::TOK_EOF) { + throw PatternError(this, "Unexpected EOF"); + } else if (m_tok.peek().type == Tokenizer::TOK_INVALID) { + throw PatternError(this, "Syntax error"); + } else { + throw PatternError(this, "Unexpected token " + Tokenizer::getTokenName(m_tok.peek().type)); + } +} + +void Parser::expectToken(Tokenizer::TokenType tokenType) { + if (m_tok.peek().type == tokenType) + return; + if (m_tok.peek().type == Tokenizer::TOK_EOF) { + throw PatternError(this, "Unexpected EOF"); + } else if (m_tok.peek().type == Tokenizer::TOK_INVALID) { + throw PatternError(this, "Syntax error"); + } else { + throw PatternError(this, "Unexpected token " + Tokenizer::getTokenName(m_tok.peek().type)); + } +} + +void Parser::skipWhitespaces() { + while (m_tok.peek().type == Tokenizer::TOK_WHITESPACE) + m_tok.next(); +} + +int Parser::getTokenInt(const Tokenizer::Token &token) { + return stoi(getTokenStr(token), nullptr, 16); +} + +std::string Parser::getTokenStr(const Tokenizer::Token &token) { + return m_input.substr(token.start, token.end - token.start); +} + +std::pair Parser::getLocation() const { + return getLocByOffset(m_input, m_tok.offset()); +} + +std::string Parser::getCodeFrame(const std::pair &loc) const { + return codeFrame(m_input, loc.first, loc.second); +} + +}; // namespace Ptr89 diff --git a/lib/src/Parser.h b/lib/src/Parser.h new file mode 100644 index 0000000..6b9581d --- /dev/null +++ b/lib/src/Parser.h @@ -0,0 +1,48 @@ +#pragma once + +#include +#include +#include +#include "Pattern.h" +#include "Tokenizer.h" + +namespace Ptr89 { + +class Parser { + protected: + PtrExp m_pattern; + std::string m_input; + Tokenizer m_tok; + void parseReferenceOrPointer(); + void parseOffsetPattern(); + void parseSubPattern(SubPatternType type, Tokenizer::TokenType openTag, Tokenizer::TokenType closeTag); + void parseHexMask(); + void parseBinMask(); + bool parsePatternData(); + void parsePatternBody(); + int parseOffset(); + void skipWhitespaces(); + void expectToken(Tokenizer::TokenType tokenType); + void expectTokens(const std::vector tokenTypes); + + Tokenizer::TokenType getClosingToken(Tokenizer::TokenType tokenType); + int getTokenInt(const Tokenizer::Token &token); + std::string getTokenStr(const Tokenizer::Token &token); + + static inline int hex2byte(char c) { + if (c >= '0' && c <= '9') + return c - '0'; + if (c >= 'A' && c <= 'F') + return (c - 'A') + 10; + if (c >= 'a' && c <= 'f') + return (c - 'a') + 10; + return -1; + } + public: + std::shared_ptr parse(const std::string &value); + + std::pair getLocation() const; + std::string getCodeFrame(const std::pair &loc) const; +}; + +}; // namespace Ptr89 diff --git a/lib/src/Pattern.cpp b/lib/src/Pattern.cpp new file mode 100644 index 0000000..8ecf86e --- /dev/null +++ b/lib/src/Pattern.cpp @@ -0,0 +1,560 @@ +#include "Pattern.h" +#include "Parser.h" +#include +#include +#include +#include +#include +#include +#include + +#include "utils.h" + +namespace Ptr89 { + +Pattern::DebugHandlerFunc Pattern::m_debugHandler = nullptr; +int Pattern::m_debugLevel = 0; + +PatternError::PatternError(const Parser *parser, const std::string &msg): std::runtime_error(getErrorMsg(parser, msg)) { + +} + +std::string PatternError::getErrorMsg(const Parser *parser, const std::string &msg) { + auto loc = parser->getLocation(); + return msg + " at line " + std::to_string(loc.first) + " column " + std::to_string(loc.second) + ".\n" + parser->getCodeFrame(loc); +} + +std::shared_ptr Pattern::parse(const std::string &pattern) { + Parser parser; + return parser.parse(pattern); +} + +bool Pattern::fuzzyMatch(const uint8_t *bytes, const uint8_t *masks, int patternSize, const uint8_t *memory) { + bool found = true; + for (int j = 0; j < patternSize; j++) { + uint8_t mask = masks[j]; + + if (mask != 0x00) { + uint8_t byte = bytes[j]; + uint8_t memoryByte = memory[j]; + + if (mask == 0xFF) { + if (byte != memoryByte) { + found = false; + break; + } + } else { + if ((byte & mask) != (memoryByte & mask)) { + found = false; + break; + } + } + } + } + return found; +} + +bool Pattern::checkPattern(const std::shared_ptr &pattern, size_t offset, const Memory &memory) { + debugSectionBegin(); + if (m_debugHandler) { + debug("Checking pattern: '%s' at %08lX\n", stringify(pattern).c_str(), offset); + if (m_debugLevel == 0) + debug("Memory: %08X %08lX\n", memory.base, memory.size); + } + + int patternSize = pattern->bytes.size(); + if (offset + patternSize >= memory.size) { + if (m_debugHandler) + debug("FAIL: Address %08lX is out of range.\n", memory.base + offset); + debugSectionEnd(); + return false; + } + if (!fuzzyMatch(&pattern->bytes[0], &pattern->masks[0], patternSize, memory.data + offset)) { + if (m_debugHandler) + debug("FAIL: bytes not matched.\n"); + debugSectionEnd(); + return false; + } + if (!checkSubpatterns(pattern, offset, memory)) { + if (m_debugHandler) + debug("FAIL: sub patterns not matched.\n"); + debugSectionEnd(); + return false; + } + if (m_debugHandler) + debug("Pattern matched!\n"); + debugSectionEnd(); + return true; +} + +bool Pattern::checkSubpatterns(const std::shared_ptr &pattern, size_t offset, const Memory &memory) { + if (!pattern->subPatterns.size()) + return true; + + if (m_debugHandler) + debug("Checking sub patterns...\n"); + + debugSectionBegin(); + + for (auto it: pattern->subPatterns) { + const SubPtrExp &p = it.second; + + switch (p.type) { + case SUB_PATTERN_TYPE_BRANCH_2B: + { + if (m_debugHandler) + debug("Decoding THUMB B at %08lX\n", offset + p.offset); + + auto [isThumb, thumbAddr] = decodeThumbB(memory.base + offset + p.offset, memory.data + offset + p.offset); + if (isThumb && thumbAddr >= memory.base && thumbAddr < memory.base + memory.size) { + uint32_t fileOffset = thumbAddr - memory.base; + if (checkPattern(p.pattern, fileOffset, memory)) { + debugSectionEnd(); + return true; + } + } else { + if (m_debugHandler) + debug("FAIL: not instruction!\n"); + } + } + break; + + case SUB_PATTERN_TYPE_BRANCH_4B: + { + if (m_debugHandler) + debug("Decoding THUMB BL/BLX at %08lX\n", offset + p.offset); + + auto [isThumb, thumbAddr] = decodeThumbBL(memory.base + offset + p.offset, memory.data + offset + p.offset); + if (isThumb && thumbAddr >= memory.base && thumbAddr < memory.base + memory.size) { + uint32_t fileOffset = thumbAddr - memory.base; + if (checkPattern(p.pattern, fileOffset, memory)) { + debugSectionEnd(); + return true; + } + } else { + if (m_debugHandler) + debug("FAIL: not instruction!\n"); + } + + if (m_debugHandler) + debug("Decoding ARM B/BL/BLX at %08lX\n", offset + p.offset); + + auto [isArm, armAddr] = decodeArmBL(memory.base + offset + p.offset, memory.data + offset + p.offset); + if (isArm && armAddr >= memory.base && armAddr < memory.base + memory.size) { + uint32_t fileOffset = armAddr - memory.base; + if (checkPattern(p.pattern, fileOffset, memory)) { + debugSectionEnd(); + return true; + } + } else { + if (m_debugHandler) + debug("FAIL: not instruction!\n"); + } + } + break; + + case SUB_PATTERN_TYPE_STRING: + + break; + } + } + + debugSectionEnd(); + + return false; +} + +std::pair Pattern::decodeReference(uint32_t offset, const Memory &memory) { + offset &= ~1; + + debug("Decoding ARM LDR at %08X\n", offset); + auto [isARM, armLDR] = decodeArmLDR(memory.base + offset, memory.data + offset); + if (isARM) { + auto [success, addr] = decodePointer(armLDR, memory); + if (success) + return { true, addr }; + } + debug("FAIL: not instruction!\n"); + + debug("Decoding THUMB LDR at %08X\n", offset); + auto [isThumb, thumbLDR] = decodeThumbLDR(memory.base + offset, memory.data + offset); + if (isThumb) { + auto [success, addr] = decodePointer(thumbLDR, memory); + if (success) + return { true, addr }; + } + debug("FAIL: not instruction!\n"); + + return { false, 0 }; +} + +std::pair Pattern::decodePointer(uint32_t addr, const Memory &memory) { + debug("Decoding pointer at %08X\n", addr - memory.base); + if (addr >= memory.base && addr + 4 <= memory.base + memory.size) { + uint32_t value = *reinterpret_cast(memory.data + (addr - memory.base)); + debug("Pointer address: %08X\n", value); + return { true, value }; + } else { + debug("FAIL: address is out of memory range!\n"); + } + return { false, 0 }; +} + +std::pair Pattern::decodeResult(const std::shared_ptr &pattern, uint32_t offset, const Memory &memory) { + uint32_t address = memory.base + offset; + + switch (pattern->type) { + case PATTERN_TYPE_OFFSET: + return { true, { address, offset, address } }; + break; + + case PATTERN_TYPE_REFERENCE: + { + auto [success, value] = decodeReference(offset, memory); + if (success) + return { true, { address, offset, value + pattern->outputOffset } }; + } + break; + + case PATTERN_TYPE_POINTER: + { + auto [success, value] = decodePointer(offset + memory.base, memory); + if (success) + return { true, { address, offset, value + pattern->outputOffset } }; + } + break; + } + return { false, { } }; +} + +std::vector Pattern::find(const std::shared_ptr &pattern, const Memory &memory, int maxResults) { + int firstNonWildcardByte = -1; + int patternSize = pattern->bytes.size(); + + for (int i = 0; i < patternSize; i++) { + if (pattern->masks[i] != 0x00) { + firstNonWildcardByte = i; + break; + } + } + + if (m_debugHandler) { + debug("Searching pattern: %s\n", stringify(pattern).c_str()); + debug("Memory: %08X %08lX\n", memory.base, memory.size); + debug("firstNonWildcardByte=%d\n", firstNonWildcardByte); + debug("\n"); + } + + if (firstNonWildcardByte == -1) + throw std::runtime_error("Internal error!"); + + /* + * Optimized variant of checkPattern(). + */ + auto *masks = &pattern->masks[firstNonWildcardByte]; + auto *bytes = &pattern->bytes[firstNonWildcardByte]; + int size = patternSize - firstNonWildcardByte; + std::vector searchResults; + + if (size >= 4) { // faster + debug("Using fast pattern matching algorithm.\n"); + + uint32_t mask = *reinterpret_cast(masks); + uint32_t searchValue = *reinterpret_cast(bytes) & mask; + + debug("Search prefix: mask=%08X, searchValue=%08X\n", mask, searchValue); + debug("\n"); + + for (size_t i = firstNonWildcardByte; i < memory.size - patternSize + 1; i++) { + uint32_t memoryValue = *reinterpret_cast(memory.data + i); + if ((memoryValue & mask) == searchValue) { + if (size == 4 || fuzzyMatch(bytes + 4, masks + 4, size - 4, memory.data + i + 4)) { + size_t foundOffset = i - firstNonWildcardByte; + + if (m_debugHandler) + debug("Possible result at %08lX\n", foundOffset); + + if (checkSubpatterns(pattern, foundOffset, memory)) { + auto [isDecoded, result] = decodeResult(pattern, foundOffset + pattern->inputOffset, memory); + if (isDecoded) { + searchResults.push_back(result); + + if (m_debugHandler) { + debug("FOUND: address=%08X, offset=%08X, value=%08X\n", result.address, result.offset, result.value); + debug("\n"); + } + + if (maxResults && searchResults.size() >= maxResults) { + debug("Maximum search results are reached.\n"); + break; + } + + i += size - 1; + } else { + debug("FAIL: can't decode result!\n"); + debug("\n"); + } + } else { + if (m_debugHandler) { + debug("FAIL: sub patterns not matched.\n"); + debug("\n"); + } + } + } + } + } + } else { + debug("Using slow pattern matching algorithm.\n"); + debug("\n"); + + for (size_t i = firstNonWildcardByte; i < memory.size - patternSize + 1; i++) { + if (fuzzyMatch(bytes, masks, size, memory.data + i)) { + size_t foundOffset = i - firstNonWildcardByte; + if (m_debugHandler) + debug("Possible result at %08lX\n", foundOffset); + if (checkSubpatterns(pattern, foundOffset, memory)) { + auto [isDecoded, result] = decodeResult(pattern, foundOffset + pattern->inputOffset, memory); + if (isDecoded) { + searchResults.push_back(result); + + if (m_debugHandler) { + debug("FOUND: address=%08X, offset=%08X, value=%08X\n", result.address, result.offset, result.value); + debug("\n"); + } + + if (maxResults && searchResults.size() >= maxResults) { + debug("Maximum search results are reached.\n"); + break; + } + + i += size - 1; + } else { + debug("FAIL: can't decode result!\n"); + debug("\n"); + } + } else { + if (m_debugHandler) { + debug("FAIL: sub patterns not matched.\n"); + debug("\n"); + } + } + } + } + } + + if (m_debugHandler) { + debug("Search results (%ld):\n", searchResults.size()); + debug("Off | Addr | Value\n"); + for (auto result: searchResults) { + debug("%08X | %08X | %08X\n", result.offset, result.address, result.value); + } + } + + return searchResults; +} + +std::string Pattern::stringify(const std::shared_ptr &pattern) { + std::string patternText; + + if (pattern->type == PATTERN_TYPE_REFERENCE) { + patternText += "&("; + } else if (pattern->type == PATTERN_TYPE_POINTER) { + patternText += "*("; + } + + int patternSize = pattern->bytes.size(); + std::vector tmp; + + for (int i = 0; i < patternSize; i++) { + uint8_t mask = pattern->masks[i]; + uint8_t byte = pattern->bytes[i]; + + if (pattern->subPatterns.find(i) != pattern->subPatterns.end()) { + auto &p = pattern->subPatterns[i]; + if (p.type == SUB_PATTERN_TYPE_BRANCH_2B) { + tmp.push_back("[ " + stringify(p.pattern) + " ]"); + } else if (p.type == SUB_PATTERN_TYPE_BRANCH_4B) { + tmp.push_back("{ " + stringify(p.pattern) + " }"); + } + i += p.size; + } else { + if (mask == 0x00) { + tmp.push_back("??"); + } else if (mask == 0x0F) { + tmp.push_back(strprintf("?%X", byte & 0x0F)); + } else if (mask == 0xF0) { + tmp.push_back(strprintf("%X?", (byte & 0xF0) >> 4)); + } else if (mask == 0xFF) { + tmp.push_back(strprintf("%02X", byte)); + } else { + char bin[9] = {}; + for (int i = 0; i < 8; i++) { + int bit = 1 << (7 - i); + if ((mask & bit) == 0) { + bin[i] = '.'; + } else if ((byte & bit)) { + bin[i] = '1'; + } else { + bin[i] = '0'; + } + } + tmp.push_back(strprintf("[%s]", bin)); + } + } + } + + if (pattern->inputOffset != 0) + tmp.push_back(strprintf("%c %X", pattern->inputOffset < 0 ? '-' : '+', abs(pattern->inputOffset))); + + patternText += strJoin(" ", tmp); + + if (pattern->type == PATTERN_TYPE_REFERENCE || pattern->type == PATTERN_TYPE_POINTER) { + patternText += ")"; + } + + if (pattern->outputOffset != 0) + patternText += strprintf(" %c %X", pattern->inputOffset < 0 ? '-' : '+', abs(pattern->outputOffset)); + + return patternText; +} + +std::pair Pattern::decodeThumbBL(uint32_t offset, const uint8_t *bytes) { + uint16_t thumb_instr1 = (bytes[1] << 8) | bytes[0]; + uint16_t thumb_instr2 = (bytes[3] << 8) | bytes[2]; + + if ((offset % 2) != 0) + return { false, 0 }; + + if ((thumb_instr1 & 0xF800) == 0xF000 && (thumb_instr2 & 0xF800) == 0xE800) { + int32_t offset11_a = (int32_t) (signExtend(thumb_instr1 & 0x7FF, 11, 32) << 12); + uint32_t offset11_b = (thumb_instr2 & 0x7FF) << 1; + uint32_t addr = (offset + 4 + offset11_a + offset11_b) & 0xFFFFFFFC; + debug("%08X: %02X %02X %02X %02X BLX #0x%08X\n", offset, bytes[0], bytes[1], bytes[2], bytes[3], addr); + return { true, addr }; + } else if ((thumb_instr1 & 0xF800) == 0xF000 && (thumb_instr2 & 0xF800) == 0xF800) { + int32_t offset11_a = (int32_t) (signExtend(thumb_instr1 & 0x7FF, 11, 32) << 12); + uint32_t offset11_b = (thumb_instr2 & 0x7FF) << 1; + uint32_t addr = (offset + 4 + offset11_a + offset11_b); + debug("%08X: %02X %02X %02X %02X BL #0x%08X\n", offset, bytes[0], bytes[1], bytes[2], bytes[3], addr); + return { true, addr }; + } + + return { false, 0 }; +} + +std::pair Pattern::decodeArmBL(uint32_t offset, const uint8_t *bytes) { + uint32_t instr = (bytes[3] << 24) | (bytes[2] << 16) | (bytes[1] << 8) | bytes[0]; + + if ((offset % 4) != 0) + return { false, 0 }; + + if (((instr & 0xFE000000) == 0xFA000000)) { + int32_t offset24 = (int32_t) (signExtend(instr & 0xFFFFFF, 24, 30) << 2U); + uint32_t H = (instr & 0x01000000) != 0 ? 1 : 0; + uint32_t addr = (offset + 8 + offset24) + (H << 1); + debug("%08X: %02X %02X %02X %02X BLX #0x%08X\n", offset, bytes[0], bytes[1], bytes[2], bytes[3], addr); + return { true, addr }; + } else if (((instr & 0x0F000000) == 0x0B000000) || ((instr & 0x0F000000) == 0x0A000000)) { + int32_t offset24 = (int32_t) (signExtend(instr & 0xFFFFFF, 24, 30) << 2U); + uint32_t addr = (offset + 8 + offset24); + if (m_debugHandler) { + uint32_t cond = (instr & 0xF0000000) >> 28; + uint32_t L = (instr & 0x0F000000) == 0x0B000000; + const char *MNEMONICS[] = { "EQ", "NE", "CS", "CC", "MI", "PL", "VS", "VC", "HI", "LS", "GE", "LT", "GT", "LE", "", "??" }; + debug("%08X: %02X %02X %02X %02X B%s%s #0x%08X\n", offset, bytes[0], bytes[1], bytes[2], bytes[3], L ? "L" : "", MNEMONICS[cond], addr); + } + return { true, addr }; + } + + return { false, 0 }; +} + +std::pair Pattern::decodeThumbB(uint32_t offset, const uint8_t *bytes) { + uint16_t instr = (bytes[1] << 8) | bytes[0]; + + if ((offset % 2) != 0) + return { false, 0 }; + + if ((instr & 0xF800) == 0xE000) { + int32_t offset11 = (int32_t) (signExtend(instr & 0x7FF, 11, 32) << 1); + uint32_t addr = offset + 4 + offset11; + debug("%08X: %02X %02X B #0x%08X\n", offset, bytes[0], bytes[1], addr); + return { true, addr }; + } else if ((instr & 0xF000) == 0xD000) { + int32_t offset8 = (int32_t) (signExtend(instr & 0xFF, 8, 32) << 1); + uint32_t addr = offset + 4 + offset8; + if (m_debugHandler) { + uint32_t cond = (instr & 0x0F00) >> 8; + const char *MNEMONICS[] = { "EQ", "NE", "CS", "CC", "MI", "PL", "VS", "VC", "HI", "LS", "GE", "LT", "GT", "LE", "", "??" }; + debug("%08X: %02X %02X B%s #0x%08X\n", offset, bytes[0], bytes[1], MNEMONICS[cond], addr); + } + return { true, addr }; + } + + return { false, 0 }; +} + +std::pair Pattern::decodeThumbLDR(uint32_t offset, const uint8_t *bytes) { + uint16_t instr1 = (bytes[1] << 8) | bytes[0]; + uint16_t instr2 = (bytes[3] << 8) | bytes[2]; + + if ((offset % 2) != 0) + return { false, 0 }; + + if ((instr1 & 0xF800) == 0x4800) { + uint32_t instr1_offset8 = (instr1 & 0xFF) << 2; + uint32_t instr1_Rd = (instr1 & 0x700) >> 8; + uint32_t addr = offset + 4 + instr1_offset8; + debug("%08X: %02X %02X LDR R%d, [PC, #0x%X] ; 0x%08X\n", offset, bytes[0], bytes[1], instr1_Rd, instr1_offset8, addr); + return { true, addr }; + } + + return { false, 0 }; +} + +std::pair Pattern::decodeArmLDR(uint32_t offset, const uint8_t *bytes) { + uint32_t instr = (bytes[3] << 24) | (bytes[2] << 16) | (bytes[1] << 8) | bytes[0]; + + if ((offset % 4) != 0) + return { false, 0 }; + + if ((instr & 0xE0F0000) == 0x40F0000) { // Immediate offset/index + int32_t U = (instr & (1 << 23)) != 0; + int32_t offset_12 = U ? (instr & 0xFFFU) : -(instr & 0xFFFU); + uint32_t addr = offset + 8 + offset_12; + uint32_t Rd = (instr & 0xF000) >> 12; + + if (m_debugHandler) { + uint32_t cond = (instr & 0xF0000000) >> 28; + const char *MNEMONICS[] = { "EQ", "NE", "CS", "CC", "MI", "PL", "VS", "VC", "HI", "LS", "GE", "LT", "GT", "LE", "", "??" }; + debug("%08X: %02X %02X %02X %02X LDR%s R%d, [PC, #%c0x%X] ; 0x%08X\n", offset, bytes[0], bytes[1], bytes[2], bytes[3], + MNEMONICS[cond], Rd, U ? '+' : '-', abs(offset_12), addr); + } + + return { true, addr }; + } + + return { false, 0 }; +} + +void Pattern::debug(const char *format, ...) { + if (!m_debugHandler) + return; + + for (int i = 0; i < m_debugLevel; i++) + _debug(" "); + + va_list v; + va_start(v, format); + m_debugHandler(format, v); + va_end(v); +} + +void Pattern::_debug(const char *format, ...) { + va_list v; + va_start(v, format); + m_debugHandler(format, v); + va_end(v); +} + +}; // namespace Ptr89 diff --git a/lib/src/Pattern.h b/lib/src/Pattern.h new file mode 100644 index 0000000..3e705d6 --- /dev/null +++ b/lib/src/Pattern.h @@ -0,0 +1,123 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Ptr89 { + +enum PatternType { + PATTERN_TYPE_OFFSET, // AB ?? CD ??, return offset of the finded bytes + PATTERN_TYPE_POINTER, // *(AB ?? CD ??), use bytes as pointer + PATTERN_TYPE_REFERENCE, // &(AB ?? CD ??), decode LDR +}; + +enum SubPatternType { + SUB_PATTERN_TYPE_BRANCH_4B, // _blf(AB ?? CD ??) or { AB ?? CD ?? } + SUB_PATTERN_TYPE_BRANCH_2B, // [ AB ?? CD ?? ] + SUB_PATTERN_TYPE_STRING, // %string% +}; + +struct PtrExp; + +struct PtrExpPart { + SubPatternType type; + std::vector bytes; // for SUB_PATTERN_TYPE_BYTES or SUB_PATTERN_TYPE_STRING + std::shared_ptr pattern; // for SUB_PATTERN_TYPE_BRANCH_4B or SUB_PATTERN_TYPE_BRANCH_2B +}; + +struct SubPtrExp { + SubPatternType type; + std::shared_ptr pattern; + int offset; + int size; +}; + +struct PtrExp { + PatternType type = PATTERN_TYPE_OFFSET; + std::string source; + int inputOffset = 0; // &( AB ?? CD ?? + 1 ) + int outputOffset = 0; // &( AB ?? CD ?? ) + 1 or AB ?? AB ?? + 1 + std::vector masks; + std::vector bytes; + std::map subPatterns; + std::string error; +}; + +class Parser; + +class PatternError: public std::runtime_error { + public: + PatternError(const Parser *parser, const std::string &msg); + private: + std::string getErrorMsg(const Parser *parser, const std::string &msg); +}; + +class Pattern { + public: + typedef typeof(vprintf) * DebugHandlerFunc; + + struct Memory { + uint32_t base; + uint8_t *data; + size_t size; + }; + + struct SearchResult { + uint32_t address; + uint32_t offset; + uint32_t value; + }; + + static std::shared_ptr parse(const std::string &pattern); + static std::string stringify(const std::shared_ptr &pattern); + static std::vector find(const std::shared_ptr &pattern, const Memory &memory, int maxResults = 0); + static bool checkPattern(const std::shared_ptr &pattern, size_t offset, const Memory &memory); + static std::pair decodeThumbBL(uint32_t offset, const uint8_t *bytes); + static std::pair decodeArmBL(uint32_t offset, const uint8_t *bytes); + static std::pair decodeThumbB(uint32_t offset, const uint8_t *bytes); + static std::pair decodeThumbLDR(uint32_t offset, const uint8_t *bytes); + static std::pair decodeArmLDR(uint32_t offset, const uint8_t *bytes); + static std::pair decodeReference(uint32_t offset, const Memory &memory); + static std::pair decodePointer(uint32_t offset, const Memory &memory); + + static void setDebugHandler(DebugHandlerFunc debugHandler) { + m_debugHandler = debugHandler; + } + + static void debugSectionBegin() { + m_debugLevel++; + } + + static void debugSectionEnd() { + m_debugLevel--; + } + + static void debug(const char *format, ...) __attribute__((format(printf, 1, 2))); + static void _debug(const char *format, ...) __attribute__((format(printf, 1, 2))); + private: + static DebugHandlerFunc m_debugHandler; + static int m_debugLevel; + static bool checkSubpatterns(const std::shared_ptr &pattern, size_t offset, const Memory &memory); + static bool fuzzyMatch(const uint8_t *bytes, const uint8_t *masks, int patternSize, const uint8_t *memory); + static std::pair decodeResult(const std::shared_ptr &pattern, uint32_t offset, const Memory &memory); + + static inline uint32_t signExtend(uint32_t value, int from, int to) { + if ((value & (1 << (from - 1))) != 0) { + uint32_t mask = 0; + for (int i = from; i < to; i++) + mask |= 1 << i; + return mask | value; + } else { + return value; + } + } +}; + +}; // namespace Ptr89 diff --git a/lib/src/Tokenizer.cpp b/lib/src/Tokenizer.cpp new file mode 100644 index 0000000..c428335 --- /dev/null +++ b/lib/src/Tokenizer.cpp @@ -0,0 +1,165 @@ +#include "Tokenizer.h" +#include + +namespace Ptr89 { + +const Tokenizer::Token &Tokenizer::next() { + if (m_nextToken.type == TOK_NULL) + m_nextToken = parseToken(); + m_currentToken = m_nextToken; + m_savedOffset = m_offset; + m_nextToken = parseToken(); + return m_currentToken; +} + +const Tokenizer::Token &Tokenizer::peek() { + if (m_nextToken.type == TOK_NULL) + m_nextToken = parseToken(); + return m_nextToken; +} + +bool Tokenizer::isHexPattern(char c) { + return (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F') || (c >= '0' && c <= '9') || c == '?'; +} + +bool Tokenizer::isBinPattern(char c) { + return c == '1' || c == '0' || c == '.'; +} + +Tokenizer::Token Tokenizer::parseToken() { + auto start = m_offset; + + if (m_offset == m_input.size()) { + return { TOK_EOF, m_offset, m_offset }; + } + + while (isspace(m_input[m_offset])) { + m_offset++; + while (avail() > 0 && isspace(m_input[m_offset])) + m_offset++; + return { TOK_WHITESPACE, start, m_offset }; + } + + if (m_input[m_offset] == '[' && avail() >= 10 && m_input[m_offset + 9] == ']') { + bool isBinaryPtr = false; + for (int i = 1; i <= 8; i++) { + if (!isBinPattern(m_input[m_offset + i])) { + isBinaryPtr = false; + break; + } + if (m_input[m_offset + i] == '.') + isBinaryPtr = true; + } + if (isBinaryPtr) { + m_offset += 10; + return { TOK_BIN, start, start + 10 }; + } + } + + switch (m_input[m_offset]) { + case '&': + m_offset++; + return { TOK_REFERENCE, start, m_offset }; + break; + case '*': + m_offset++; + return { TOK_POINTER, start, m_offset }; + break; + case '(': + m_offset++; + return { TOK_PAREN_OPEN, start, m_offset }; + break; + case ')': + m_offset++; + return { TOK_PAREN_CLOSE, start, m_offset }; + break; + case '[': + m_offset++; + return { TOK_2B_BRANCH_OPEN, start, m_offset }; + break; + case ']': + m_offset++; + return { TOK_2B_BRANCH_CLOSE, start, m_offset }; + break; + case '{': + m_offset++; + return { TOK_4B_BRANCH_OPEN, start, m_offset }; + break; + case '}': + m_offset++; + return { TOK_4B_BRANCH_CLOSE, start, m_offset }; + break; + case '+': + m_offset++; + return { TOK_PLUS, start, m_offset }; + break; + case '-': + m_offset++; + return { TOK_MINUS, start, m_offset }; + break; + case ',': + m_offset++; + return { TOK_SEPARATOR, start, m_offset }; + break; + } + + if (isHexPattern(m_input[m_offset])) { + bool isMask = false; + m_offset++; + + if (m_input[m_offset] == '?') + isMask = true; + + while (avail() > 0 && isHexPattern(m_input[m_offset])) { + if (m_input[m_offset] == '?') + isMask = true; + m_offset++; + } + + return { (isMask ? TOK_MASK : TOK_HEX), start, m_offset }; + } + + if (m_input[m_offset] == '_' && strcasecmp(m_input.substr(m_offset, 4).c_str(), "_blf") == 0) { + m_offset += 4; + return { TOK_BLF, start, m_offset }; + } + + if (m_input[m_offset] == '%') { + m_offset++; + while (avail() > 0 && m_input[m_offset] != '%') { + m_offset++; + if (m_input[m_offset] == '%') + return { TOK_ASCII_STRING, start, m_offset }; + } + } + + return { TOK_INVALID, start, m_offset }; +} + +std::string Tokenizer::getTokenName(TokenType type) { + switch (type) { + case TOK_EOF: return "EOF"; + case TOK_NULL: return "NULL"; + case TOK_INVALID: return "INVALID"; + case TOK_REFERENCE: return "REFERENCE"; + case TOK_POINTER: return "POINTER"; + case TOK_BLF: return "BLF"; + case TOK_4B_BRANCH_OPEN: return "4B_BRANCH_OPEN"; + case TOK_4B_BRANCH_CLOSE: return "4B_BRANCH_CLOSE"; + case TOK_2B_BRANCH_OPEN: return "2B_BRANCH_OPEN"; + case TOK_2B_BRANCH_CLOSE: return "2B_BRANCH_CLOSE"; + case TOK_PAREN_OPEN: return "PAREN_OPEN"; + case TOK_PAREN_CLOSE: return "PAREN_CLOSE"; + case TOK_SEPARATOR: return "SEPARATOR"; + case TOK_WHITESPACE: return "WHITESPACE"; + case TOK_PLUS: return "PLUS"; + case TOK_MINUS: return "MINUS"; + case TOK_HEX: return "HEX"; + case TOK_MASK: return "MASK"; + case TOK_BIN: return "BIN"; + case TOK_ASCII_STRING: return "ASCII_STRING"; + } + return "UNKNOWN"; +} + +}; // namespace Ptr89 diff --git a/lib/src/Tokenizer.h b/lib/src/Tokenizer.h new file mode 100644 index 0000000..03af008 --- /dev/null +++ b/lib/src/Tokenizer.h @@ -0,0 +1,68 @@ +#pragma once + +#include + +namespace Ptr89 { + +class Tokenizer { + public: + enum TokenType { + TOK_EOF = -1, + TOK_NULL, + TOK_INVALID, + TOK_REFERENCE, + TOK_POINTER, + TOK_BLF, + TOK_4B_BRANCH_OPEN, + TOK_4B_BRANCH_CLOSE, + TOK_2B_BRANCH_OPEN, + TOK_2B_BRANCH_CLOSE, + TOK_PAREN_OPEN, + TOK_PAREN_CLOSE, + TOK_SEPARATOR, + TOK_WHITESPACE, + TOK_PLUS, + TOK_MINUS, + TOK_HEX, + TOK_MASK, + TOK_BIN, + TOK_ASCII_STRING, + }; + + struct Token { + TokenType type; + int start; + int end; + }; + + protected: + Token m_nextToken = { TOK_NULL }; + Token m_currentToken = { TOK_NULL }; + int m_offset = 0; + int m_savedOffset = 0; + std::string m_input; + Token parseToken(); + static bool isHexPattern(char c); + static bool isBinPattern(char c); + inline int avail() { + return m_input.size() - m_offset; + } + + public: + const Token &next(); + const Token &peek(); + inline void reset(const std::string &value) { + m_input = value; + m_offset = 0; + m_savedOffset = 0; + m_nextToken = { TOK_NULL }; + } + + inline int offset() const { + return m_savedOffset; + } + + static std::string getTokenName(TokenType type); +}; + +}; // namespace Ptr89 diff --git a/lib/src/utils.cpp b/lib/src/utils.cpp new file mode 100644 index 0000000..5614451 --- /dev/null +++ b/lib/src/utils.cpp @@ -0,0 +1,140 @@ +#include "utils.h" + +#include +#include +#include + +namespace Ptr89 { + +std::pair getLocByOffset(const std::string &text, int offset) { + int line = 1; + int col = 1; + for (int i = 0; i < text.size(); i++) { + if (text[i] == '\n') { + line++; + col = 1; + } + if (i == offset) + return { line, col }; + col++; + } + return { line, 1 }; +} + +std::string codeFrame(const std::string &text, int lineNum, int colNum) { + auto lines = strSplit("\n", text); + int maxLineNumLen = std::to_string(lines.size()).size() + 1; + std::string out = ""; + int n = 1; + for (auto &line: lines) { + if (abs(n - lineNum) > 3) { + n++; + continue; + } + out += (n == lineNum ? '>' : ' ') + + padStart(std::to_string(n), maxLineNumLen, ' ') + + " | " + tab2spaces(line) + "\n"; + if (n == lineNum) { + for (int j = 0; j < maxLineNumLen + 1; j++) + out += " "; + out += " | " + str2spaces(line.substr(0, colNum - 1)) + "^"; + } + n++; + } + return out; +} + +std::string padStart(const std::string &line, int maxLength, char c) { + std::string newStr = line; + while (newStr.size() < maxLength) + newStr = c + newStr; + return newStr; +} + +std::string str2spaces(const std::string &line) { + std::string newStr = ""; + for (int i = 0; i < line.size(); i++) { + newStr += ' '; + } + return newStr; +} + +std::string tab2spaces(const std::string &line) { + std::string newStr = ""; + int virtualSymbols = 0; + for (int i = 0; i < line.size(); i++) { + char c = line[i]; + if (c == '\t') { + int spacesCnt = 4 - virtualSymbols % 4; + for (int j = 0; j < spacesCnt; j++) + newStr += " "; + virtualSymbols += spacesCnt; + } else { + virtualSymbols++; + newStr += c; + } + } + return newStr; +} + +std::string strJoin(const std::string &sep, const std::vector &lines) { + std::string out; + size_t length = lines.size() > 1 ? sep.size() * (lines.size() - 1) : 0; + for (auto &line: lines) + length += line.size(); + + out.reserve(length); + + bool first = true; + for (auto &line: lines) { + if (first) { + first = false; + out += line; + } else { + out += sep + line; + } + } + + return out; +} + +std::vector strSplit(const std::string &sep, const std::string &str) { + std::vector result; + size_t last_pos = 0; + + while (true) { + size_t pos = str.find(sep, last_pos); + if (pos == std::string::npos) { + result.push_back(str.substr(last_pos)); + break; + } else { + result.push_back(str.substr(last_pos, pos - last_pos)); + last_pos = pos + 1; + } + } + + return result; +} + +std::string strprintf(const char *format, ...) { + va_list v; + + std::string out; + + va_start(v, format); + int n = vsnprintf(nullptr, 0, format, v); + va_end(v); + + if (n <= 0) + throw std::runtime_error("vsnprintf error..."); + + out.resize(n); + + va_start(v, format); + vsnprintf(&out[0], out.size() + 1, format, v); + va_end(v); + + return out; +} + +}; // namespace Ptr89 diff --git a/lib/src/utils.h b/lib/src/utils.h new file mode 100644 index 0000000..f5acf73 --- /dev/null +++ b/lib/src/utils.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include +#include + +namespace Ptr89 { + +std::pair getLocByOffset(const std::string &text, int offset); +std::string codeFrame(const std::string &text, int lineNum, int colNum); +std::string padStart(const std::string &line, int maxLength, char c); +std::string str2spaces(const std::string &line); +std::string tab2spaces(const std::string &line); + +std::string strJoin(const std::string &sep, const std::vector &lines); +std::vector strSplit(const std::string &sep, const std::string &str); +std::string strprintf(const char *format, ...) __attribute__((format(printf, 1, 2))); + +}; // namespace Ptr89 diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..c9f1580 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,83 @@ +#include +#include +#include +#include +#include +/* + +# HEX +ABCD + +# HEX MASK +AB?? +A?C? + +# Binary MASK +[1111.11.] + +# Reference +&( ... ) + +# Pointer +*( ... ) + +# Sub-pattern: BL +{ } +_BLF( ) + +# Sub-pattern: B +[ ] + +# Force value +< A0000000 > + +# String (decode LDR and check string by addr) +%ascii% + +*/ + +using namespace Ptr89; + +int main() { + Pattern::setDebugHandler(vprintf); + + // parser.parse("&(??4840687047,??4800687047,??B5 + 1) - 4"); + // auto pattern = parser.parse("??,1C,??,48,??,B5,??,68, {??,1C,??,68,??,68,??,2B,??,D0,??,68, [??,23, [??B5??1C??6E] ] ,??,47} ,??,BD + 1"); +/// auto pattern = parser.parse("??,1C,??,48,??,B5,??,68, { ??,1C,??,68,??,68,??,2B,??,D0,??,68, [??,23, [??B5??1C??6E] ] ,??,47 },??,BD + 1"); + +// auto pattern = parser.parse("&(??4840687047,??4800687047,??B5 + 1) - 4"); // THUMB LDR+LDR + +// auto pattern = parser.parse("&(70402DE9??669FE50050A0E10140A0E1+4)"); // ARM + +// auto pattern = parser.parse("&( 98 02 9f e5 00 00 90 e5 08 80 bd e8 )"); // ARM + +// auto pattern = parser.parse("&(04D000220021??48 + 6)"); // THUMB LDR + +// auto pattern = parser.parse("&(??,48,??,B5,??,68, {??,63,??,47}, ??,BD + 1)"); // THUMB LDR + auto pattern = Pattern::parse("*(010080E2020051E15C008415AC008405????????0400A0E11040BDE8+20)"); // THUMB LDR + + + //auto pattern = parser.parse("70 40 [0010....] e9 [0000....] [....0000] a0 e1 [0000....] [....0000] a0 e1 [........] [........] [0100....] e2 [........] [........] [1000....] e2 [........] [........] a0 e3 [........] [........] a0 e3 [........] [........] [........] eb [........] [0000....] [0101....] e3 [........] [........] [........] 0a [........] [........] a0 e3 [........] [........] [1000....] e2 [........] [........] [........] [1111101.] [0000....] [....0000] a0 e1 [........] [........] [1000....] e2 [........] [........] a0 e3 [........] [........] [........] [1111101.] [........] [0000....] [0101....] e3 [........] [0000....] [0101....] 13 [........] [........] [........] 0a [0000....] [....0000] [0100....] e0 [........] [0000....] [0101....] e3 [........] [........] [........] ba [........] [........] a0 e3 [........] [........] [1100....] e5 [........] [........] [1000....] e2 [0000....] [....0000] a0 e1 [........] [........] [........] [1111101.] [.000....] [........] a0 e1 [.010....] [........] a0 e1 [........] [........] [1000....] e2 "); + + //auto pattern = parser.parse("{ AA } [........] [........] [1001....] e5 [........] [0000....] [0101....] e3 [........] [0000....] [0101....] 13 [........] [........] [1001....] 15 [........] [0000....] [0101....] 13 [........] [........] [1001....] 15 [........] [0000....] [0101....] 13 [........] [0000....] [0101....] 13 [........] [0000....] [0101....] 13 [........] [0000....] [0101....] 13 [........] [0000....] [0101....] 13 [........] [0000....] [0101....] 13 [........] [........] e0 03 [........] [........] [........] 0a e0 0d [1000....] e8 [........] [........] [1000....] e2 0f 00 [1001....] e8 [........] [........] [........] eb [0000....] [....0000] a0 e1 "); + +// auto [memory, memorySize] = readBinaryFile("/home/azq2/dev/sie/elfloader3/ff/EL71sw45.bin"); + + // Pattern::Memory memoryRegion = { 0xA0000000, memory, memorySize }; + // Pattern::find(pattern, memoryRegion); + + printf("parsed pattern: '%s'\n", Pattern::stringify(pattern).c_str()); + + /* + while (true) { + auto token = m_tok.next(); + + printf("TOK_%d %.*s\n", token.type, token.end - token.start, &input[token.start]); + + if (token.type == Tokenizer::TOK_INVALID || token.type == Tokenizer::TOK_EOF) + break; + } + */ + + return 0; +} diff --git a/src/tests.cpp b/src/tests.cpp new file mode 100644 index 0000000..560b0d3 --- /dev/null +++ b/src/tests.cpp @@ -0,0 +1,82 @@ +#include +#include +#include + +using namespace Ptr89; + +void testArmDecoder() { + // ARM BL #-offset + uint8_t instr1[] = { 0xFE, 0xFB, 0xFF, 0x0B }; + assert(Pattern::decodeArmBL(0xA0001000, instr1) == std::make_pair(true, 0xA0000000)); + + // ARM BLX #-offset + uint8_t instr2[] = { 0xFE, 0xFB, 0xFF, 0xFA }; + assert(Pattern::decodeArmBL(0xA0001000, instr2) == std::make_pair(true, 0xA0000000)); + + // ARM BL #+offset + uint8_t instr3[] = { 0xFE, 0x03, 0x00, 0x0B }; + assert(Pattern::decodeArmBL(0xA0000000, instr3) == std::make_pair(true, 0xA0001000)); + + // ARM BLX #+offset + uint8_t instr4[] = { 0xFE, 0x03, 0x00, 0xFA }; + assert(Pattern::decodeArmBL(0xA0000000, instr4) == std::make_pair(true, 0xA0001000)); + + // ARM BLX #-offset with H=1 + uint8_t instr5[] = { 0xFE, 0xFB, 0xFF, 0xFB }; + assert(Pattern::decodeArmBL(0xA0001000, instr5) == std::make_pair(true, 0xA0000002)); + + // ARM BLX #+offset with H=1 + uint8_t instr6[] = { 0xFE, 0x03, 0x00, 0xFB }; + assert(Pattern::decodeArmBL(0xA0000000, instr6) == std::make_pair(true, 0xA0001002)); + + // THUMB BL #-offset + uint8_t instr7[] = { 0xFE, 0xF7, 0xFE, 0xFF }; + assert(Pattern::decodeThumbBL(0xA0001000, instr7) == std::make_pair(true, 0xA0000000)); + + // THUMB BLX #-offset + uint8_t instr8[] = { 0xFE, 0xF7, 0xFE, 0xEF }; + assert(Pattern::decodeThumbBL(0xA0001000, instr8) == std::make_pair(true, 0xA0000000)); + + // THUMB BL #+offset + uint8_t instr9[] = { 0x00, 0xF0, 0xFE, 0xFF }; + assert(Pattern::decodeThumbBL(0xA0000000, instr9) == std::make_pair(true, 0xA0001000)); + + // THUMB BLX #+offset + uint8_t instr10[] = { 0x00, 0xF0, 0xFE, 0xEF }; + assert(Pattern::decodeThumbBL(0xA0000000, instr10) == std::make_pair(true, 0xA0001000)); + + // THUMB B #-offset + uint8_t instr11[] = { 0x7E, 0xE7 }; + assert(Pattern::decodeThumbB(0xA0000100, instr11) == std::make_pair(true, 0xA0000000)); + + // THUMB B #+offset + uint8_t instr12[] = { 0x7E, 0xE0 }; + assert(Pattern::decodeThumbB(0xA0000000, instr12) == std::make_pair(true, 0xA0000100)); + + // THUMB BEQ #-offset + uint8_t instr13[] = { 0xF6, 0xD0 }; + assert(Pattern::decodeThumbB(0xA0000010, instr13) == std::make_pair(true, 0xA0000000)); + + // THUMB BEQ #+offset + uint8_t instr14[] = { 0x06, 0xD0 }; + assert(Pattern::decodeThumbB(0xA0000000, instr14) == std::make_pair(true, 0xA0000010)); + + // THUMB LDR Rd, [PC, #offset] + uint8_t instr15[] = { 0x16, 0x48 }; + assert(Pattern::decodeThumbLDR(0xA0000000, instr15) == std::make_pair(true, 0xA000005C)); + + // ARM LDR Rd, [PC, #+offset] + uint8_t instr16[] = { 0x00, 0x01, 0x9F, 0xE5 }; + assert(Pattern::decodeArmLDR(0xA0000000, instr16) == std::make_pair(true, 0xA0000108)); + + // ARM LDR Rd, [PC, #-offset] + uint8_t instr17[] = { 0x00, 0x01, 0x1F, 0xE5 }; + assert(Pattern::decodeArmLDR(0xA0000100, instr17) == std::make_pair(true, 0xA0000008)); +} + +int main() { + Pattern::setDebugHandler(vprintf); + testArmDecoder(); + printf("All tests passed.\n"); + return 0; +}