capstone/Mapping.c

526 lines
14 KiB
C
Raw Normal View History

/* Capstone Disassembly Engine */
/* By Nguyen Anh Quynh <aquynh@gmail.com>, 2013-2019 */
/* Rot127 <unisono@quyllur.org>, 2022-2023 */
#include "Mapping.h"
#include "capstone/capstone.h"
PPC LLVM 18 (#2540) * Update PPC module to LLVM 18. **New** (According to LLVM changelog) - Added DFP instruction. - Added the SCV instruction. **Changes** - Memory decoder were simplified by decoding disponent and base reg separately. - `DFORM` -> `DFORM_BASE` - Use inverted `MCInstDesc` table. - Replace the many declared printer in PPCInstPrinter with `static inlines`. - Renamed groups to upper case. - Switched to `ARCH_add_cs_detail_X()` function names. - Remove `PPCInstPrinter.h` because it is no longer used. * Fix: Use correct directory name. * Fix segfaults and add asserts for these NULL cases. * Allow to map a single LLVM option to multiple CS options * Add default endian option to the MCUpdater * Fix setter for Little endian * Add SPE option to cstool * Fix QPX instructions. Due to https://github.com/llvm/llvm-project/commit/4b43ef3e5c37459996ce0f53615881f436cb0e65 the names of the operands were matched. Because FRT dosn't exist in the XForm_1 class, the generated tables didn't decoded them. * Fix: AbsAddr should be printed as unsigned. * Fix S12 immediate printing for PC memory operands * Fix MCUpdater tests * Update PPCRegisterInfo_stripRegisterPrefix * Add support for selection of Power versions * Run clang-format * Fix feature check * Allow to overwrite in multi-mode * Add some more flags * Fix order and map name * Add new test files. * Fix checks for features. Only enables PowerX feature checks of a Power architecture is enabled and the feature is in the list of it. * Print byte sequence with space between comma. This helps with copy and search of the byte string in the test files. * Fix tests broken due to feature toggles * Shorten generated names. * Update bindings
2024-12-05 11:26:33 +00:00
#include "cs_priv.h"
2023-12-02 07:18:58 +00:00
#include "utils.h"
// Create a cache to map LLVM instruction IDs to capstone instruction IDs, if
// the architecture needs this.
cs_err populate_insn_map_cache(cs_struct *handle)
{
2024-05-18 06:32:01 +00:00
unsigned int i;
// If this architecture doesn't use instruction mapping, do nothing
if (!handle->insn_map || handle->insn_map_size <= 0)
return CS_ERR_OK;
// Since the instruction map is assumed to be stored in ascending
// order, we can get the maximum LLVM instruction id just by looking at
// the last element.
unsigned int cache_elements =
handle->insn_map[handle->insn_map_size - 1].id + 1;
// This should not be initialized yet.
CS_ASSERT(!handle->insn_cache);
unsigned short *cache = cs_mem_calloc(cache_elements, sizeof(*cache));
if (!cache) {
handle->errnum = CS_ERR_MEM;
return CS_ERR_MEM;
}
handle->insn_cache = cache;
for (i = 1; i < handle->insn_map_size; ++i)
handle->insn_cache[handle->insn_map[i].id] = i;
return CS_ERR_OK;
}
const insn_map *lookup_insn_map(cs_struct *handle, unsigned short id)
{
// If this is getting called, we need the cache to already be populated
// (this should be done when populate_insn_map_cache() gets called).
CS_ASSERT(handle->insn_cache);
CS_ASSERT(handle->insn_map_size);
unsigned short highest_id =
handle->insn_map[handle->insn_map_size - 1].id;
if (id > highest_id)
return NULL;
unsigned short i = handle->insn_cache[id];
return &handle->insn_map[i];
}
// Gives the id for the given @name if it is saved in @map.
// Returns the id or -1 if not found.
int name2id(const name_map *map, int max, const char *name)
{
PPC LLVM 18 (#2540) * Update PPC module to LLVM 18. **New** (According to LLVM changelog) - Added DFP instruction. - Added the SCV instruction. **Changes** - Memory decoder were simplified by decoding disponent and base reg separately. - `DFORM` -> `DFORM_BASE` - Use inverted `MCInstDesc` table. - Replace the many declared printer in PPCInstPrinter with `static inlines`. - Renamed groups to upper case. - Switched to `ARCH_add_cs_detail_X()` function names. - Remove `PPCInstPrinter.h` because it is no longer used. * Fix: Use correct directory name. * Fix segfaults and add asserts for these NULL cases. * Allow to map a single LLVM option to multiple CS options * Add default endian option to the MCUpdater * Fix setter for Little endian * Add SPE option to cstool * Fix QPX instructions. Due to https://github.com/llvm/llvm-project/commit/4b43ef3e5c37459996ce0f53615881f436cb0e65 the names of the operands were matched. Because FRT dosn't exist in the XForm_1 class, the generated tables didn't decoded them. * Fix: AbsAddr should be printed as unsigned. * Fix S12 immediate printing for PC memory operands * Fix MCUpdater tests * Update PPCRegisterInfo_stripRegisterPrefix * Add support for selection of Power versions * Run clang-format * Fix feature check * Allow to overwrite in multi-mode * Add some more flags * Fix order and map name * Add new test files. * Fix checks for features. Only enables PowerX feature checks of a Power architecture is enabled and the feature is in the list of it. * Print byte sequence with space between comma. This helps with copy and search of the byte string in the test files. * Fix tests broken due to feature toggles * Shorten generated names. * Update bindings
2024-12-05 11:26:33 +00:00
CS_ASSERT_RET_VAL(map && name, -1);
int i;
for (i = 0; i < max; i++) {
PPC LLVM 18 (#2540) * Update PPC module to LLVM 18. **New** (According to LLVM changelog) - Added DFP instruction. - Added the SCV instruction. **Changes** - Memory decoder were simplified by decoding disponent and base reg separately. - `DFORM` -> `DFORM_BASE` - Use inverted `MCInstDesc` table. - Replace the many declared printer in PPCInstPrinter with `static inlines`. - Renamed groups to upper case. - Switched to `ARCH_add_cs_detail_X()` function names. - Remove `PPCInstPrinter.h` because it is no longer used. * Fix: Use correct directory name. * Fix segfaults and add asserts for these NULL cases. * Allow to map a single LLVM option to multiple CS options * Add default endian option to the MCUpdater * Fix setter for Little endian * Add SPE option to cstool * Fix QPX instructions. Due to https://github.com/llvm/llvm-project/commit/4b43ef3e5c37459996ce0f53615881f436cb0e65 the names of the operands were matched. Because FRT dosn't exist in the XForm_1 class, the generated tables didn't decoded them. * Fix: AbsAddr should be printed as unsigned. * Fix S12 immediate printing for PC memory operands * Fix MCUpdater tests * Update PPCRegisterInfo_stripRegisterPrefix * Add support for selection of Power versions * Run clang-format * Fix feature check * Allow to overwrite in multi-mode * Add some more flags * Fix order and map name * Add new test files. * Fix checks for features. Only enables PowerX feature checks of a Power architecture is enabled and the feature is in the list of it. * Print byte sequence with space between comma. This helps with copy and search of the byte string in the test files. * Fix tests broken due to feature toggles * Shorten generated names. * Update bindings
2024-12-05 11:26:33 +00:00
if (!map[i].name) {
return -1;
}
if (!strcmp(map[i].name, name)) {
return map[i].id;
}
}
// nothing match
return -1;
}
// Gives the name for the given @id if it is saved in @map.
// Returns the name or NULL if not found.
const char *id2name(const name_map *map, int max, const unsigned int id)
{
int i;
for (i = 0; i < max; i++) {
if (map[i].id == id) {
return map[i].name;
}
}
// nothing match
return NULL;
}
/// Adds a register to the implicit write register list.
/// It will not add the same register twice.
void map_add_implicit_write(MCInst *MI, uint32_t Reg)
{
if (!MI->flat_insn->detail)
return;
uint16_t *regs_write = MI->flat_insn->detail->regs_write;
for (int i = 0; i < MAX_IMPL_W_REGS; ++i) {
if (i == MI->flat_insn->detail->regs_write_count) {
regs_write[i] = Reg;
MI->flat_insn->detail->regs_write_count++;
return;
}
if (regs_write[i] == Reg)
return;
}
}
/// Adds a register to the implicit read register list.
/// It will not add the same register twice.
void map_add_implicit_read(MCInst *MI, uint32_t Reg)
{
if (!MI->flat_insn->detail)
return;
uint16_t *regs_read = MI->flat_insn->detail->regs_read;
for (int i = 0; i < MAX_IMPL_R_REGS; ++i) {
if (i == MI->flat_insn->detail->regs_read_count) {
regs_read[i] = Reg;
MI->flat_insn->detail->regs_read_count++;
return;
}
if (regs_read[i] == Reg)
return;
}
}
Architecture updater (auto-sync) - Updating ARM (#1949) * Add auto-sync updater. * Update Capstone core with auto-sync changes. * Update ARM via auto-sync. * Make changes to arch modules which are introduced by auto-sync. * Update tests for ARM. * Fix build warnings for make * Remove meson.build * Print shift amount in decimal * Patch non LLVM register alias. * Change type of immediate operand to unsiged (due to: #771) * Replace all occurances of a register with its alias. * Fix printing of signed imms * Print rotate amount in decimal * CHange imm type to int64_t to match LLVM imm type. * Fix search for register names, by completing string first. * Print ModImm operands always in decimal * Use number format of previous capstone version. * Correct implicit writes and update_flags according to SBit. * Add missing test for RegImmShift * Reverse incorrect comparision. * Set shift information for move instructions. * Set mem access for all memory operands * Set subtracted flag if offset is negative. * Add flag for post-index memory operands. * Add detail op for BX_RET and MOVPCLR * Use instruction post_index operand. * Add VPOP and VPUSH as unique CS IDs. * Add shifting info for MOVsr. * Add TODOs. * Add in LLVM hardcoded operands to detail. * Move detail editing from InstPrinter to Mapping * Formatting * Add removed check. * Add writeback register and constraints to RFEI instructions. * Translate shift immediate * Print negative immediates * Remove duplicate invalid entry * Add CS groups to instructions * Fix write attriutes of stores. * Add missing names of added instructions * Fix LLVM bug * Add more post_index flags * http -> https * Make generated functions static * Remove tab prefix for alias instructions. * Set ValidateMCOperand to NULL. * Fix AddrMode3Operand operands * Allow getting system and banked register name via API * Add writeback to STC/LDC instructions. * Fix (hopefully) last case where disp is negative and subtracted = true * Remove accidentially introduced regressions
2023-07-19 09:56:27 +00:00
/// Removes a register from the implicit write register list.
void map_remove_implicit_write(MCInst *MI, uint32_t Reg)
{
if (!MI->flat_insn->detail)
return;
uint16_t *regs_write = MI->flat_insn->detail->regs_write;
bool shorten_list = false;
for (int i = 0; i < MAX_IMPL_W_REGS; ++i) {
if (shorten_list) {
regs_write[i - 1] = regs_write[i];
}
if (i >= MI->flat_insn->detail->regs_write_count)
return;
if (regs_write[i] == Reg) {
MI->flat_insn->detail->regs_write_count--;
// The register should exist only once in the list.
CS_ASSERT_RET(!shorten_list);
Architecture updater (auto-sync) - Updating ARM (#1949) * Add auto-sync updater. * Update Capstone core with auto-sync changes. * Update ARM via auto-sync. * Make changes to arch modules which are introduced by auto-sync. * Update tests for ARM. * Fix build warnings for make * Remove meson.build * Print shift amount in decimal * Patch non LLVM register alias. * Change type of immediate operand to unsiged (due to: #771) * Replace all occurances of a register with its alias. * Fix printing of signed imms * Print rotate amount in decimal * CHange imm type to int64_t to match LLVM imm type. * Fix search for register names, by completing string first. * Print ModImm operands always in decimal * Use number format of previous capstone version. * Correct implicit writes and update_flags according to SBit. * Add missing test for RegImmShift * Reverse incorrect comparision. * Set shift information for move instructions. * Set mem access for all memory operands * Set subtracted flag if offset is negative. * Add flag for post-index memory operands. * Add detail op for BX_RET and MOVPCLR * Use instruction post_index operand. * Add VPOP and VPUSH as unique CS IDs. * Add shifting info for MOVsr. * Add TODOs. * Add in LLVM hardcoded operands to detail. * Move detail editing from InstPrinter to Mapping * Formatting * Add removed check. * Add writeback register and constraints to RFEI instructions. * Translate shift immediate * Print negative immediates * Remove duplicate invalid entry * Add CS groups to instructions * Fix write attriutes of stores. * Add missing names of added instructions * Fix LLVM bug * Add more post_index flags * http -> https * Make generated functions static * Remove tab prefix for alias instructions. * Set ValidateMCOperand to NULL. * Fix AddrMode3Operand operands * Allow getting system and banked register name via API * Add writeback to STC/LDC instructions. * Fix (hopefully) last case where disp is negative and subtracted = true * Remove accidentially introduced regressions
2023-07-19 09:56:27 +00:00
shorten_list = true;
}
}
}
/// Copies the implicit read registers of @imap to @MI->flat_insn.
/// Already present registers will be preserved.
void map_implicit_reads(MCInst *MI, const insn_map *imap)
{
#ifndef CAPSTONE_DIET
if (!MI->flat_insn->detail)
return;
cs_detail *detail = MI->flat_insn->detail;
unsigned Opcode = MCInst_getOpcode(MI);
unsigned i = 0;
uint16_t reg = imap[Opcode].regs_use[i];
while (reg != 0) {
if (i >= MAX_IMPL_R_REGS ||
2023-05-30 11:09:37 +08:00
detail->regs_read_count >= MAX_IMPL_R_REGS) {
printf("ERROR: Too many implicit read register defined in "
2023-05-30 11:09:37 +08:00
"instruction mapping.\n");
return;
}
detail->regs_read[detail->regs_read_count++] = reg;
Coverity defects (#2469) * Fix CID 508418 - Uninitialized struct * Fix CID 509089 - Fix OOB read and write * Fix CID 509088 - OOB. Also adds tests and to ensure no OOB access. * Fix CID 509085 - Resource leak. * Fix CID 508414 and companions - Using undefined values. * Fix CID 508405 - Use of uninitialized value * Remove unnecessary and badly implemented dev fuzz code. * Fix CID 508396 - Uninitialzied variable. * Fix CID 508393, 508365 -- OOB read. * Fix CID 432207 - OVerlapping memory access. * Remove unused functions * Fix CID 432170 - Overlapping memory access. * Fix CID 166022 - Check for negative index * Let strncat not depend n src operand. * Fix 509083 and 509084 - NULL dereference * Remove duplicated code. * Initialize sysop * Fix resource leak * Remove unreachable code. * Remove duplicate code. * Add assert to check return value of cmoack * Fixed: d should be a signed value, since it is checked against < 0 * Add missing break. * Add NULL check * Fix signs of binary search comparisons. * Add explicit cast of or result * Fix correct scope of case. * Handle invalid integer type. * Return UINT_MAX instead of implicitly casted -1 * Remove dead code * Fix type of im * Fix type of d * Remove duplicated code. * Add returns after CS_ASSERTS * Check for len == 0 case. * Ensure shift operates on uint64 * Replace strcpy with strncpy. * Handle edge cases for 32bit rotate * Fix some out of enum warnings * Replace a strcpy with strncpy. * Fix increment of address * Skip some linting * Fix: set instruction id * Remove unused enum * Replace the last usages of strcpy with SStream functions. * Increase number of allowed AArch64 operands. * Check safety of incrementing t the next operand. * Fix naming of operand * Update python constants * Fix option setup of CS_OPT_DETAIL_REAL * Document DETAIL_REAL has to be used with CS_OPT_ON. * Run Coverity scan every Monday. * Remove dead code * Fix OOB read * Rename macro to reflect it is only used with sstreams * Fix rebase issues
2024-09-18 13:19:42 +00:00
if (i + 1 < MAX_IMPL_R_REGS) {
// Select next one
reg = imap[Opcode].regs_use[++i];
}
}
#endif // CAPSTONE_DIET
}
/// Copies the implicit write registers of @imap to @MI->flat_insn.
/// Already present registers will be preserved.
void map_implicit_writes(MCInst *MI, const insn_map *imap)
{
#ifndef CAPSTONE_DIET
if (!MI->flat_insn->detail)
return;
cs_detail *detail = MI->flat_insn->detail;
unsigned Opcode = MCInst_getOpcode(MI);
unsigned i = 0;
uint16_t reg = imap[Opcode].regs_mod[i];
while (reg != 0) {
if (i >= MAX_IMPL_W_REGS ||
2023-05-30 11:09:37 +08:00
detail->regs_write_count >= MAX_IMPL_W_REGS) {
printf("ERROR: Too many implicit write register defined in "
2023-05-30 11:09:37 +08:00
"instruction mapping.\n");
return;
}
detail->regs_write[detail->regs_write_count++] = reg;
Coverity defects (#2469) * Fix CID 508418 - Uninitialized struct * Fix CID 509089 - Fix OOB read and write * Fix CID 509088 - OOB. Also adds tests and to ensure no OOB access. * Fix CID 509085 - Resource leak. * Fix CID 508414 and companions - Using undefined values. * Fix CID 508405 - Use of uninitialized value * Remove unnecessary and badly implemented dev fuzz code. * Fix CID 508396 - Uninitialzied variable. * Fix CID 508393, 508365 -- OOB read. * Fix CID 432207 - OVerlapping memory access. * Remove unused functions * Fix CID 432170 - Overlapping memory access. * Fix CID 166022 - Check for negative index * Let strncat not depend n src operand. * Fix 509083 and 509084 - NULL dereference * Remove duplicated code. * Initialize sysop * Fix resource leak * Remove unreachable code. * Remove duplicate code. * Add assert to check return value of cmoack * Fixed: d should be a signed value, since it is checked against < 0 * Add missing break. * Add NULL check * Fix signs of binary search comparisons. * Add explicit cast of or result * Fix correct scope of case. * Handle invalid integer type. * Return UINT_MAX instead of implicitly casted -1 * Remove dead code * Fix type of im * Fix type of d * Remove duplicated code. * Add returns after CS_ASSERTS * Check for len == 0 case. * Ensure shift operates on uint64 * Replace strcpy with strncpy. * Handle edge cases for 32bit rotate * Fix some out of enum warnings * Replace a strcpy with strncpy. * Fix increment of address * Skip some linting * Fix: set instruction id * Remove unused enum * Replace the last usages of strcpy with SStream functions. * Increase number of allowed AArch64 operands. * Check safety of incrementing t the next operand. * Fix naming of operand * Update python constants * Fix option setup of CS_OPT_DETAIL_REAL * Document DETAIL_REAL has to be used with CS_OPT_ON. * Run Coverity scan every Monday. * Remove dead code * Fix OOB read * Rename macro to reflect it is only used with sstreams * Fix rebase issues
2024-09-18 13:19:42 +00:00
if (i + 1 < MAX_IMPL_W_REGS) {
// Select next one
reg = imap[Opcode].regs_mod[++i];
}
}
#endif // CAPSTONE_DIET
}
Architecture updater (auto-sync) - Updating ARM (#1949) * Add auto-sync updater. * Update Capstone core with auto-sync changes. * Update ARM via auto-sync. * Make changes to arch modules which are introduced by auto-sync. * Update tests for ARM. * Fix build warnings for make * Remove meson.build * Print shift amount in decimal * Patch non LLVM register alias. * Change type of immediate operand to unsiged (due to: #771) * Replace all occurances of a register with its alias. * Fix printing of signed imms * Print rotate amount in decimal * CHange imm type to int64_t to match LLVM imm type. * Fix search for register names, by completing string first. * Print ModImm operands always in decimal * Use number format of previous capstone version. * Correct implicit writes and update_flags according to SBit. * Add missing test for RegImmShift * Reverse incorrect comparision. * Set shift information for move instructions. * Set mem access for all memory operands * Set subtracted flag if offset is negative. * Add flag for post-index memory operands. * Add detail op for BX_RET and MOVPCLR * Use instruction post_index operand. * Add VPOP and VPUSH as unique CS IDs. * Add shifting info for MOVsr. * Add TODOs. * Add in LLVM hardcoded operands to detail. * Move detail editing from InstPrinter to Mapping * Formatting * Add removed check. * Add writeback register and constraints to RFEI instructions. * Translate shift immediate * Print negative immediates * Remove duplicate invalid entry * Add CS groups to instructions * Fix write attriutes of stores. * Add missing names of added instructions * Fix LLVM bug * Add more post_index flags * http -> https * Make generated functions static * Remove tab prefix for alias instructions. * Set ValidateMCOperand to NULL. * Fix AddrMode3Operand operands * Allow getting system and banked register name via API * Add writeback to STC/LDC instructions. * Fix (hopefully) last case where disp is negative and subtracted = true * Remove accidentially introduced regressions
2023-07-19 09:56:27 +00:00
/// Adds a given group to @MI->flat_insn.
2024-02-15 07:53:45 +00:00
/// A group is never added twice.
2023-07-22 13:56:45 -05:00
void add_group(MCInst *MI, unsigned /* arch_group */ group)
{
Architecture updater (auto-sync) - Updating ARM (#1949) * Add auto-sync updater. * Update Capstone core with auto-sync changes. * Update ARM via auto-sync. * Make changes to arch modules which are introduced by auto-sync. * Update tests for ARM. * Fix build warnings for make * Remove meson.build * Print shift amount in decimal * Patch non LLVM register alias. * Change type of immediate operand to unsiged (due to: #771) * Replace all occurances of a register with its alias. * Fix printing of signed imms * Print rotate amount in decimal * CHange imm type to int64_t to match LLVM imm type. * Fix search for register names, by completing string first. * Print ModImm operands always in decimal * Use number format of previous capstone version. * Correct implicit writes and update_flags according to SBit. * Add missing test for RegImmShift * Reverse incorrect comparision. * Set shift information for move instructions. * Set mem access for all memory operands * Set subtracted flag if offset is negative. * Add flag for post-index memory operands. * Add detail op for BX_RET and MOVPCLR * Use instruction post_index operand. * Add VPOP and VPUSH as unique CS IDs. * Add shifting info for MOVsr. * Add TODOs. * Add in LLVM hardcoded operands to detail. * Move detail editing from InstPrinter to Mapping * Formatting * Add removed check. * Add writeback register and constraints to RFEI instructions. * Translate shift immediate * Print negative immediates * Remove duplicate invalid entry * Add CS groups to instructions * Fix write attriutes of stores. * Add missing names of added instructions * Fix LLVM bug * Add more post_index flags * http -> https * Make generated functions static * Remove tab prefix for alias instructions. * Set ValidateMCOperand to NULL. * Fix AddrMode3Operand operands * Allow getting system and banked register name via API * Add writeback to STC/LDC instructions. * Fix (hopefully) last case where disp is negative and subtracted = true * Remove accidentially introduced regressions
2023-07-19 09:56:27 +00:00
#ifndef CAPSTONE_DIET
if (!MI->flat_insn->detail)
return;
cs_detail *detail = MI->flat_insn->detail;
if (detail->groups_count >= MAX_NUM_GROUPS) {
printf("ERROR: Too many groups defined.\n");
return;
}
2024-02-15 07:53:45 +00:00
for (int i = 0; i < detail->groups_count; ++i) {
if (detail->groups[i] == group) {
return;
}
}
Architecture updater (auto-sync) - Updating ARM (#1949) * Add auto-sync updater. * Update Capstone core with auto-sync changes. * Update ARM via auto-sync. * Make changes to arch modules which are introduced by auto-sync. * Update tests for ARM. * Fix build warnings for make * Remove meson.build * Print shift amount in decimal * Patch non LLVM register alias. * Change type of immediate operand to unsiged (due to: #771) * Replace all occurances of a register with its alias. * Fix printing of signed imms * Print rotate amount in decimal * CHange imm type to int64_t to match LLVM imm type. * Fix search for register names, by completing string first. * Print ModImm operands always in decimal * Use number format of previous capstone version. * Correct implicit writes and update_flags according to SBit. * Add missing test for RegImmShift * Reverse incorrect comparision. * Set shift information for move instructions. * Set mem access for all memory operands * Set subtracted flag if offset is negative. * Add flag for post-index memory operands. * Add detail op for BX_RET and MOVPCLR * Use instruction post_index operand. * Add VPOP and VPUSH as unique CS IDs. * Add shifting info for MOVsr. * Add TODOs. * Add in LLVM hardcoded operands to detail. * Move detail editing from InstPrinter to Mapping * Formatting * Add removed check. * Add writeback register and constraints to RFEI instructions. * Translate shift immediate * Print negative immediates * Remove duplicate invalid entry * Add CS groups to instructions * Fix write attriutes of stores. * Add missing names of added instructions * Fix LLVM bug * Add more post_index flags * http -> https * Make generated functions static * Remove tab prefix for alias instructions. * Set ValidateMCOperand to NULL. * Fix AddrMode3Operand operands * Allow getting system and banked register name via API * Add writeback to STC/LDC instructions. * Fix (hopefully) last case where disp is negative and subtracted = true * Remove accidentially introduced regressions
2023-07-19 09:56:27 +00:00
detail->groups[detail->groups_count++] = group;
#endif // CAPSTONE_DIET
}
/// Copies the groups from @imap to @MI->flat_insn.
/// Already present groups will be preserved.
void map_groups(MCInst *MI, const insn_map *imap)
{
#ifndef CAPSTONE_DIET
if (!MI->flat_insn->detail)
return;
cs_detail *detail = MI->flat_insn->detail;
unsigned Opcode = MCInst_getOpcode(MI);
unsigned i = 0;
uint16_t group = imap[Opcode].groups[i];
while (group != 0) {
if (detail->groups_count >= MAX_NUM_GROUPS) {
printf("ERROR: Too many groups defined in instruction mapping.\n");
return;
}
detail->groups[detail->groups_count++] = group;
group = imap[Opcode].groups[++i];
}
#endif // CAPSTONE_DIET
}
/// Returns the pointer to the supllementary information in
/// the instruction mapping table @imap or NULL in case of failure.
const void *map_get_suppl_info(MCInst *MI, const insn_map *imap)
{
#ifndef CAPSTONE_DIET
if (!MI->flat_insn->detail)
return NULL;
unsigned Opcode = MCInst_getOpcode(MI);
return &imap[Opcode].suppl_info;
#else
return NULL;
#endif // CAPSTONE_DIET
}
// Search for the CS instruction id for the given @MC_Opcode in @imap.
// return -1 if none is found.
unsigned int find_cs_id(unsigned MC_Opcode, const insn_map *imap,
2023-05-30 11:09:37 +08:00
unsigned imap_size)
{
// binary searching since the IDs are sorted in order
unsigned int left, right, m;
unsigned int max = imap_size;
right = max - 1;
if (MC_Opcode < imap[0].id || MC_Opcode > imap[right].id)
// not found
return -1;
left = 0;
while (left <= right) {
m = (left + right) / 2;
if (MC_Opcode == imap[m].id) {
return m;
}
if (MC_Opcode < imap[m].id)
right = m - 1;
else
left = m + 1;
}
return -1;
}
/// Sets the Capstone instruction id which maps to the @MI opcode.
/// If no mapping is found the function returns and prints an error.
void map_cs_id(MCInst *MI, const insn_map *imap, unsigned int imap_size)
{
unsigned int i = find_cs_id(MCInst_getOpcode(MI), imap, imap_size);
if (i != -1) {
MI->flat_insn->id = imap[i].mapid;
return;
}
printf("ERROR: Could not find CS id for MCInst opcode: %d\n",
2023-05-30 11:09:37 +08:00
MCInst_getOpcode(MI));
return;
}
/// Returns the operand type information from the
/// mapping table for instruction operands.
/// Only usable by `auto-sync` archs!
const cs_op_type mapping_get_op_type(MCInst *MI, unsigned OpNum,
2023-05-30 11:09:37 +08:00
const map_insn_ops *insn_ops_map,
size_t map_size)
{
assert(MI);
assert(MI->Opcode < map_size);
assert(OpNum < sizeof(insn_ops_map[MI->Opcode].ops) /
2023-05-30 11:09:37 +08:00
sizeof(insn_ops_map[MI->Opcode].ops[0]));
return insn_ops_map[MI->Opcode].ops[OpNum].type;
}
/// Returns the operand access flags from the
/// mapping table for instruction operands.
/// Only usable by `auto-sync` archs!
const cs_ac_type mapping_get_op_access(MCInst *MI, unsigned OpNum,
2023-05-30 11:09:37 +08:00
const map_insn_ops *insn_ops_map,
size_t map_size)
{
assert(MI);
assert(MI->Opcode < map_size);
assert(OpNum < sizeof(insn_ops_map[MI->Opcode].ops) /
2023-05-30 11:09:37 +08:00
sizeof(insn_ops_map[MI->Opcode].ops[0]));
cs_ac_type access = insn_ops_map[MI->Opcode].ops[OpNum].access;
if (MCInst_opIsTied(MI, OpNum) || MCInst_opIsTying(MI, OpNum))
access |= (access == CS_AC_READ) ? CS_AC_WRITE : CS_AC_READ;
return access;
}
/// Returns the operand at detail->arch.operands[op_count + offset]
/// Or NULL if detail is not set or the offset would be out of bounds.
#define DEFINE_get_detail_op(arch, ARCH, ARCH_UPPER) \
2023-05-30 11:09:37 +08:00
cs_##arch##_op *ARCH##_get_detail_op(MCInst *MI, int offset) \
{ \
if (!MI->flat_insn->detail) \
return NULL; \
int OpIdx = MI->flat_insn->detail->arch.op_count + offset; \
if (OpIdx < 0 || OpIdx >= NUM_##ARCH_UPPER##_OPS) { \
return NULL; \
} \
2023-05-30 11:09:37 +08:00
return &MI->flat_insn->detail->arch.operands[OpIdx]; \
}
DEFINE_get_detail_op(arm, ARM, ARM);
DEFINE_get_detail_op(ppc, PPC, PPC);
DEFINE_get_detail_op(tricore, TriCore, TRICORE);
DEFINE_get_detail_op(aarch64, AArch64, AARCH64);
DEFINE_get_detail_op(alpha, Alpha, ALPHA);
DEFINE_get_detail_op(hppa, HPPA, HPPA);
DEFINE_get_detail_op(loongarch, LoongArch, LOONGARCH);
DEFINE_get_detail_op(mips, Mips, MIPS);
DEFINE_get_detail_op(riscv, RISCV, RISCV);
DEFINE_get_detail_op(systemz, SystemZ, SYSTEMZ);
DEFINE_get_detail_op(xtensa, Xtensa, XTENSA);
DEFINE_get_detail_op(bpf, BPF, BPF);
DEFINE_get_detail_op(arc, ARC, ARC);
DEFINE_get_detail_op(sparc, Sparc, SPARC);
/// Returns the operand at detail->arch.operands[index]
/// Or NULL if detail is not set or the index would be out of bounds.
#define DEFINE_get_detail_op_at(arch, ARCH, ARCH_UPPER) \
cs_##arch##_op *ARCH##_get_detail_op_at(MCInst *MI, int index) \
{ \
if (!MI->flat_insn->detail) \
return NULL; \
if (index < 0 || index >= NUM_##ARCH_UPPER##_OPS) { \
return NULL; \
} \
return &MI->flat_insn->detail->arch.operands[index]; \
}
DEFINE_get_detail_op_at(arm, ARM, ARM);
DEFINE_get_detail_op_at(ppc, PPC, PPC);
DEFINE_get_detail_op_at(tricore, TriCore, TRICORE);
DEFINE_get_detail_op_at(aarch64, AArch64, AARCH64);
DEFINE_get_detail_op_at(alpha, Alpha, ALPHA);
DEFINE_get_detail_op_at(hppa, HPPA, HPPA);
DEFINE_get_detail_op_at(loongarch, LoongArch, LOONGARCH);
DEFINE_get_detail_op_at(mips, Mips, MIPS);
DEFINE_get_detail_op_at(riscv, RISCV, RISCV);
DEFINE_get_detail_op_at(systemz, SystemZ, SYSTEMZ);
DEFINE_get_detail_op_at(xtensa, Xtensa, XTENSA);
DEFINE_get_detail_op_at(bpf, BPF, BPF);
DEFINE_get_detail_op_at(arc, ARC, ARC);
DEFINE_get_detail_op_at(sparc, Sparc, SPARC);
/// Returns true if for this architecture the
/// alias operands should be filled.
/// TODO: Replace this with a proper option.
/// So it can be toggled between disas() calls.
bool map_use_alias_details(const MCInst *MI)
{
assert(MI);
return (MI->csh->detail_opt & CS_OPT_ON) &&
!(MI->csh->detail_opt & CS_OPT_DETAIL_REAL);
}
/// Sets the setDetailOps flag to @p Val.
/// If detail == NULLit refuses to set the flag to true.
void map_set_fill_detail_ops(MCInst *MI, bool Val)
{
CS_ASSERT_RET(MI);
if (!detail_is_set(MI)) {
MI->fillDetailOps = false;
return;
}
MI->fillDetailOps = Val;
}
/// Sets the instruction alias flags and the given alias id.
void map_set_is_alias_insn(MCInst *MI, bool Val, uint64_t Alias)
{
CS_ASSERT_RET(MI);
MI->isAliasInstr = Val;
MI->flat_insn->is_alias = Val;
MI->flat_insn->alias_id = Alias;
}
static inline bool char_ends_mnem(const char c, cs_arch arch)
{
switch (arch) {
default:
return (!c || c == ' ' || c == '\t' || c == '.');
case CS_ARCH_PPC:
case CS_ARCH_RISCV:
return (!c || c == ' ' || c == '\t');
Auto-Sync update Sparc LLVM-18 (#2704) * Add Sparc inc fils, delete old files and update AS with Sparc config. * AS: Refuse to run differ if an old file is missing. * AS: Refer to the RefactorGuide.md * Add first translated Sparc files. * Fixup SparcMCTargetDesc.h * Fixup SparcDisassembler.h * Fixup instruction printer. * Fixup SparcInstPrinter * Basic functions of Capstone module * Fix SP sparc namespace prefix. * Fix build script and linking * Fix disassembler not actually reading bytes. * Match \!encoding in llvm-mc output (Sparc has this). * Add Sparc LE and and make v9 a feature to enable. * Update test files for Sparc * Fix tests. * Add assembly tests * AS: Add settings to use assembly tests. * Test fixes * Fix typos * Add reg and imm details. * Add mem details and instruction formats. * Handle condition codes. * Formatting * Add hints. * Add membar and asi tags * Update Python bindings * Add asi and membar to cstest * Restructure test file * Capstone fix for llvm-project/#139284. * Fix branch detail tests * Handle faulty mem operand defintions. * Add membar and asi tests * Add one more branch instruction test. * Add missing call alias * Fix tests. Updated after fixing branch disponents. Issues with the generated assembly tests. The assembly tests don't check the feature flags enabled. And hence V9 tests are added to the none V9 test file. * Fix alias lookup with , in the asm_text * Fix common detail tests. * Fix issue.yaml * Add Sparc changelog * Add changelog for Sparc to v6 guide * Fix incorrect translated array size check. * Reading the ISA and thinking would help... This is not how alignment is calculated -.- * Fix call targets * Remove 'real' BA instruction (which is only an alias). * Add missing property getters. * Add missing format details * Set correct detail struct * Support access detail testing for Sparc. * Add hard-coded special registers tbr, wim, psr * Add alias tests for call and ba. * Fix copy paste mistake. * Add note about big/little endian into guide. * Add implied flag for SparcV9 * Format * Store CC field consistently in an extra field. The CC field used was sometimes stored as register, sometimes as not at all. Now it is consistently stored in a separated field. * Add an invalid ASI tag. * Fix LDSTUB/A memory access and incorrect operand details. * Handle condition codes more elegantly. Also fixes bugs with wrong cc fields, or missing fields. * Add separation ; character for assembly tests. * Apply fix from llvm-project/#143232 * Use enum types for memory operands * Update Pythyon constants
2025-06-24 12:45:34 +00:00
case CS_ARCH_SPARC:
return (!c || c == ' ' || c == '\t' || c == ',');
}
2023-12-02 07:18:58 +00:00
}
/// Sets an alternative id for some instruction.
/// Or -1 if it fails.
/// You must add (<ARCH>_INS_ALIAS_BEGIN + 1) to the id to get the real id.
void map_set_alias_id(MCInst *MI, const SStream *O,
const name_map *alias_mnem_id_map, int map_size)
{
if (!MCInst_isAlias(MI))
return;
char alias_mnem[16] = { 0 };
int i = 0, j = 0;
const char *asm_str_buf = O->buffer;
// Skip spaces and tabs
2023-12-02 07:18:58 +00:00
while (is_blank_char(asm_str_buf[i])) {
if (!asm_str_buf[i]) {
MI->flat_insn->alias_id = -1;
return;
}
++i;
}
for (; j < sizeof(alias_mnem) - 1; ++j, ++i) {
if (char_ends_mnem(asm_str_buf[i], MI->csh->arch))
break;
Architecture updater (auto-sync) - Updating AArch64 (#2026) * Update sysop inc file * Fix missing braces warning * Handle new system operands * Fix build errors by renaming. * Fix segfault * Fix segfault * Add custom MCOperand valiadtors * Add AArch64 case for getFeatureBits * Fix infinite loop * Fix braces warning. * Implement loopuo by name for sys operands * Fix incorrect translation which remove else if statements. * Fix several segfaults * Rename GetRegFromClass patch * Fix segfaults and asserts * Fix segfault * Move MRI setting to Mapping * Remove unused code * Add add_op_X functinos for AArch64. * Add fill detail functins * Handle RegWithShiftExtend operands * Handle TypedVectorList operands. * Handle ComplexRoatation operands * Handle MemExtend operands * Handle ImmRangeScale operands * Handle ExactFPImm operands * Handle GPRSeqPairsClass operands * Handle Imm8OptLsl operands * Handle ImmScale operands * Handle LogicalImm operands * Handle Matrix operands * Handle SME Matrix tiles and vectors. * Handle normal operands. * Fix segfault. * Handle PostInc operands. * Reorder VecLayout enum to have no duplicate enum value. * Handle PredicateAsCounter operands * Handle ZPRasFPR operands * Handle VectorIndex operands * Handle UImm12Offset operands. * Move reg suffix to enum val to single function. * Handle SVERegOp operands * Handle SVELogicalImm operands * Handle SImm operand * Handle PrefetchOp operands * Handle Imm and ImmHex operands * Handle GPR64as32 and GPR64x8 operands * Add missing break * Handle FPImm operand * Handle ExtendedRegister opreand * Handle CondCode operands * Handle BTIHintOp operands * Handle BarrierOption operands * Handle BarrierXSOption * Add not implemeted case again * Handle ArithExtend operands * Handle AdrpLabel and AlignedLabel operands * Handle AMNoIndex operands * Handle AddSubImm operands * Handle MSRSystemRegisters and MRSSystemRegister operands * Handle PSBHntOp and RPRFMOperand operands * Remove unused variables * Handle InverseCondCode operands * Handle ImplicityTypedVectorList operands * Handle ShiftedRegister operands * Handle Shifter operands * Handle SIMDType10Operand operands * Handle SVCROp operands * Handle SVEPattern operands * Handle SVEVecLenSpecifier operands * Handle SysCROperands * Handle SysXzrPair operands * Handle PState operands * Handle VRegOperands * Primt SME oeprands. * Fix cs_operand.h include * Rename arm64 -> aarch64 in python bindings. * Add Python bindings for SH * Fix ARM Python bindings (#2127) * Restructure auto-sync update scripts. * Move Helper functions to Updater dir * Move requirements.txt * Add basic ASUpdater.py * Run black. * Add inc file generater to updater * Add option to select certain inc files fore generation. * Enable clean build and implement patcher for inc files. * Format config * Patch main header files after inc generation. * Implement clang-format function (unused yet, because it takes forever.) * Copy generated inc files to arch dir * Invert clean option (noramlly we need to clean the build dir.) * Clearify arg doc * Rename SystemRegister file for AArch64 * Centralize handling of path variables. * Check if SystemOperands had to be generated before renaming on of its files. * Replace class parameters by calling get_path * Remove updater config which only contained paths. * Add refactor option. * Remove more path handling in the Configurator. * Add translation step to updater. * Fix includes after CppTranslator was moved into the Updater * Remove updater config * Fix several issue in the Configurator * Fix file operations * Remove addition argument from translator. * Add Differ step to updater. * Add path variable for arch_config * Add diff step. * Fix typo * Introduce .clang-format path variable. * Remove duplicate functions * Add option to select update steps to execute. * Check in write functions for write flag. * Rename PatchMainHeader -> HeaderPatcher * Move .gitignore * Add README to vendor dir. * Add all system operands to cstool output * Update cstest with aarch64 changes * Remove wb flag of aarch64 detail struct * Set updates_flag after decoding * Set writeback after decoding. * Rename ARM64 -> AArch64 * Update printer and op mapping * Exit normally * Add AArch64 alias * Fix some tmeplate function calls * Fix flag check after rebase. * Fix build by commentig unnused code. * Add memory operand flag * Handle memory operands printed via generic printOperand function. * Handle UImm memory offsets * Introduce MEM_REG and MEM_IMM op types * Handle scaled memory immediates * Check for op_count before checking for mem op at -1 index. * Update memory operand flags. * Pass imm/reg memory ops in set_imm/reg to set_mem. * Add missing set_sme_operand call and fix assert. * Remove CS_OP_MEM flag before entering switch. * Preidcates are registers. * Add shift info always to the previous operand * Check for generic system regs * Handle NumLanes = 0 LaneKind = q case * Replace printImm call with normal print logic. Otherwise ops get added twice to detail. * Handle FP operands in printOperand. * Add access information to float operands. * Rewrite SME matrix handling. * Set correct SME layouts and allow for immediate range sme offsets. * Handle cases of unknown system alias by setting their raw values * Update cstool and header file with new SME offset handling * Handle SME Tile lists. * Fix build error in cstest * Update MC tests for AArch64 * Handle TLBI operands and fix printing bug. * Fix: Print signed value as signed. * Add more system alias to detail. * Remove duplicate hex prefix * Set correct values for the register info * Replace tabs with white spaces * Move string append logic to own function. * Set DecodeComplete = true before decoding (as originally in the LLVM code). * Change type of feature argument, since only LLVM features are passed, not CS groups. * Imitate lower_bound for the index table binary search. * Remove trailing comments from test files. * Print shift amount in decimal * Save detail of shift alias instructions. * Add extension details fot ext instruction alias * Print LSB and width in decimal * Fix LLVM bug. The feature check for V8_2a doesn't check if all features are enabled. * Fix lower_bounds check. For m == 0 we wrap around 0 of cause. * Fix feature check. Add check for FeatureAll since it includes XS * Operate on temporary MCInst when trying decoding. * Add lower_bound behavior to IndexTypeStr binsearch. * Fix MC tests which were incorrect because of missing FeatureAll check * Add Alias handling for AArch64 * Update system operands with SYSIMM types and add additional sysop category. * Add macros for meta programming (ARM64 <-> AArch64 selection). * Fix union/struct confusion and add raw_value member to uninions. * Allow to set Syntax and mode options for AArch64 * Fix build warning by using correct type * Print shift value in decimal * Add missing call to add_cs_detail. * Update name map files with normalized names. * Remove unused function * Add check if detail should be filled. * Fill detail for real instructions if only real detail is requested. * Add always the extension. * Make dir creation log message debug level * Implement ADR immediate operand printer. See: https://github.com/capstone-engine/llvm-capstone/commit/c3484b1fdc03b479beaf5897eca8ea294d3df909 * Check for flag registers beeing written and update flag. * Move multiple CondCode helpers to aarch64.h because they are so freaking useful. + Print CC if it is EQ * Fix incorrectly initialized CC and VectorLayout. * Add LSL shift type for extensions. * Fix case when shift amount is 0 * Fix post-index memory instructions. * Pass raw immediate through getShiftValue to extract actual shift amount * Setup AArch64 detail ops. * Add flag for operands part of a list. * Set vector indices for all relevant registers. * Add missing call to add_cs_detail for postIncOperands * Add ugly yet reliable way to determine post-index addressing mode * Add support for old Capstone register alias. * Remove leading space before some alias mnemonics. * add AARCH64 to `cmake.sh` * add HAS_AARCH64 to `cs.c` * should probably just reference `cs_operand.h` in `aarch64.h` * hint compiler at `AArch64_SYSREG` enum type for casting purposes * update `Makefile` for AARCH64 leaves `CAPSTONE_HAS_ARM64` supported * `testFeatureBits` platform function check `testFeatureBits` should check if the platform function is visible first * update tests to use AARCH64 convention * hack: avoid enum casts for `MCInst` Values Apple compiler really hates typecasting a enum, even if bounded from a unsigned. Lets set the raw_value directly is a hack and needs proper review * Check for present detail before accessing it. * Add CS only groups * Use general map ins_op type * Fix build warning about str size computation. * Disable warning about unitialized value for GCC 11. Imm is initialized and the warning does not appear in later versions. * Use correct include guard for PPC * Add missing requirements * Update SystemOperand enums. * Fix overlapping comparison warning * Fix reachable assert where OpNum is not of type IMM * Handle 0.0 operand for fcmp * Fix incorrect variable passed. * Fix for MacOS which doesn't know the warning and throws another one. * Make getExtendEncoding static to fix build warning on MSVC. * Fix build error: 'missing binary operator before token' by checking __GNUC__ * Add string search to add vector layout info. * Add missing mem disponents of several ldr and str instructions. * Add 0 immediates to several instructions. * Rename v regs to q and d variant. The cs_regname API can not pass the variant name of the register requested. So we simply emit the default variant name. * Fix incorrect enum value. * Fix tests for system operands. * Fix syntax issues in tests. * Rename Arm64 -> AArch64 Python bindings. * Fix Python bindings C structs. * Fix generation of constants (ARMCC skipped because it starts with ARM) * Update const files * Remove -Wmaybe-uninitialized warning since it fails fuzz build * Add missing comma * Fix case * Fix AArch64 Python bindings: - Do not generate constants automatically (dscript is way too buggy). - Update printing of details. * Rename ARM64 -> AArch64 in test_corpus.py * Rename test_arm64 -> test_aarch64 * Rename ARM-64 -> AArch64 * Fix diff CI test by disassembling AArch64 at former ARM64 place * Fix several wrong types and remove unnecessary memebers from Python binding * Fix: Same printing format of detail for cstool, test_ and test_*.py * Fix: pass correct op index for mov alias with op[1] == reg wzr. * Set prfm op manuall in case of unnown sysop. set_imm would add it to an memory operand wihtout base. * Fix: If barrier ops are not set an assert is reached. We fix it here by simply getting the immediate as the printing code does. --------- Co-authored-by: Peace-Maker <peace-maker@wcfan.de> Co-authored-by: Dayton <5340801+watbulb@users.noreply.github.com>
2023-11-15 04:12:14 +00:00
alias_mnem[j] = asm_str_buf[i];
}
MI->flat_insn->alias_id =
name2id(alias_mnem_id_map, map_size, alias_mnem);
}
2024-08-31 13:33:38 +00:00
/// Does a binary search over the given map and searches for @id.
/// If @id exists in @map, it sets @found to true and returns
/// the value for the @id.
/// Otherwise, @found is set to false and it returns UINT64_MAX.
///
/// Of course it assumes the map is sorted.
uint64_t enum_map_bin_search(const cs_enum_id_map *map, size_t map_len,
const char *id, bool *found)
{
size_t l = 0;
size_t r = map_len;
size_t id_len = strlen(id);
while (l <= r) {
size_t m = (l + r) / 2;
size_t j = 0;
size_t i = 0;
size_t entry_len = strlen(map[m].str);
while (j < entry_len && i < id_len && id[i] == map[m].str[j]) {
++j, ++i;
}
if (i == id_len && j == entry_len) {
*found = true;
return map[m].val;
}
if (id[i] < map[m].str[j]) {
r = m - 1;
} else if (id[i] > map[m].str[j]) {
l = m + 1;
}
if ((m == 0 && id[i] < map[m].str[j]) ||
(l + r) / 2 >= map_len) {
2024-08-31 13:33:38 +00:00
// Break before we go out of bounds.
break;
}
}
*found = false;
return UINT64_MAX;
}