/* OpenIDA - Outil d'analyse de fichiers binaires
* macro.c - vue macroscopique des liens entre blocs d'instructions
*
* Copyright (C) 2012 Cyrille Bagard
*
* This file is part of OpenIDA.
*
* OpenIDA is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* OpenIDA is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Foobar. If not, see .
*/
#include "macro.h"
#include
#include "../blocks/flow.h"
#include "../blocks/virtual.h"
/* Indications sur une branche */
typedef struct _branch_info
{
vmpa_t *jumps; /* Jalons de la branche */
size_t count; /* Quantité de ces jalons */
} branch_info;
/**
* Macros pour le marquage des instructions traitées.
* Dans un soucis d'optimisation, on ne traite que les instructions
* démarrant un bloc.
*/
#define MACRO_MARK_AS_PROCESSED(_instr) g_object_set_data(G_OBJECT(_instr), "macro_done", _instr)
#define MACRO_IS_PROCESSED(_instr) (g_object_get_data(G_OBJECT(_instr), "macro_done") != NULL)
#define MACRO_CLEAR_PROCESSED(_instr) g_object_set_data(G_OBJECT(_instr), "macro_done", NULL)
/* Indique si une adresse est retenue comme point de passage. */
static bool is_addr_in_branch(const branch_info *, const vmpa_t *, bool);
/* Identifie les différents points de passage d'une branche. */
static void find_next_jumps(GArchInstruction *, vmpa_t, vmpa_t, branch_info *);
/* Retrouve le point de ralliement entre deux branches. */
static vmpa_t compute_first_common_addr(branch_info *, branch_info *);
/* Retrouve le point de ralliement entre un groupe de branches. */
static vmpa_t compute_first_common_addr_in_group(const branch_info *, size_t);
/* Procède à la définition de bloc regroupant des instructions. */
static GInstrBlock *build_instruction_block(GArchInstruction *, vmpa_t, vmpa_t, vmpa_t);
/******************************************************************************
* *
* Paramètres : info = informations à consulter. *
* addr = adresse à rechercher. *
* fast = autorise une recherche rapide. *
* *
* Description : Indique si une adresse est retenue comme point de passage. *
* *
* Retour : true si le jalon est déjà dans la liste, false sinon. *
* *
* Remarques : - *
* *
******************************************************************************/
static bool is_addr_in_branch(const branch_info *info, const vmpa_t *addr, bool fast)
{
bool result; /* Bilan à retourner */
size_t i; /* Boucle de parcours */
void *ptr; /* Résultat des recherches */
result = false;
if (!fast)
for (i = 0; i < info->count && !result; i++)
result = (info->jumps[i] == *addr);
else
{
ptr = bsearch(addr, info->jumps, info->count, sizeof(vmpa_t), (__compar_fn_t)compare_vmpa);
result = (ptr != NULL);
}
return result;
}
/******************************************************************************
* *
* Paramètres : instrs = ensemble des instructions d'assemblage. *
* start = adresse de début du bloc. *
* end = adresse de fin du bloc (exclusive). *
* count = nombre de sauts détectés. [OUT] *
* *
* Description : Identifie les différents points de passage d'une branche. *
* *
* Retour : Jalons dans le flot d'exécution. *
* *
* Remarques : - *
* *
******************************************************************************/
static void find_next_jumps(GArchInstruction *instrs, vmpa_t start, vmpa_t end, branch_info *info)
{
GArchInstruction *iter; /* Boucle de parcours #1 */
GArchInstruction **dests; /* Instr. visée par une autre */
InstructionLinkType *types; /* Type de lien entre lignes */
size_t dcount; /* Nombre de liens de dest. */
size_t i; /* Boucle de parcours #2 */
vmpa_t addr; /* Adresse de la destination */
/* On évite de boucler... */
if (is_addr_in_branch(info, &start, false))
return;
info->jumps = (vmpa_t *)realloc(info->jumps, ++(info->count) * sizeof(vmpa_t));
info->jumps[info->count - 1] = start;
/* On suit le flot jusqu'à la prochaine bifurcation */
for (iter = g_arch_instruction_find_by_address(instrs, start, true);
iter != NULL;
iter = g_arch_instruction_get_next_iter(instrs, iter, end))
{
if (g_arch_instruction_is_return(iter))
{
iter = NULL;
break;
}
if (!g_arch_instruction_has_destinations(iter))
continue;
dcount = g_arch_instruction_get_destinations(iter, &dests, &types);
for (i = 0; i < dcount; i++)
switch (types[i])
{
case ILT_EXEC_FLOW:
case ILT_JUMP:
case ILT_CASE_JUMP:
case ILT_JUMP_IF_TRUE:
case ILT_JUMP_IF_FALSE:
g_arch_instruction_get_location(dests[i], NULL, NULL, &addr);
find_next_jumps(instrs, addr, end, info);
break;
default:
break;
}
break;
}
/* Si on termine... */
if (iter != NULL && !is_addr_in_branch(info, &end, false))
{
info->jumps = (vmpa_t *)realloc(info->jumps, ++(info->count) * sizeof(vmpa_t));
info->jumps[info->count - 1] = end;
}
}
/******************************************************************************
* *
* Paramètres : a = premier ensemble de jalons à parcourir. *
* b = second ensemble de jalons à parcourir. *
* *
* Description : Retrouve le point de ralliement entre deux branches. *
* *
* Retour : Adresse commune à deux branches. *
* *
* Remarques : - *
* *
******************************************************************************/
static vmpa_t compute_first_common_addr(branch_info *a, branch_info *b)
{
vmpa_t result; /* Adresse trouvée à retourner */
size_t i; /* Boucle de parcours */
/* Valeur conceptuellement impossible à renvoyer */
result = VMPA_MAX;
//qsort(a->jumps, a->count, sizeof(vmpa_t), (__compar_fn_t)compare_vmpa);
//qsort(b->jumps, b->count, sizeof(vmpa_t), (__compar_fn_t)compare_vmpa);
for (i = 0; i < a->count && result == VMPA_MAX; i++)
if (is_addr_in_branch(b, &a->jumps[i], false))
result = a->jumps[i];
return result;
}
/******************************************************************************
* *
* Paramètres : list = liste d'ensembles de jalons à parcourir. *
* count = taille de cette liste. *
* *
* Description : Retrouve le point de ralliement entre un groupe de branches. *
* *
* Retour : Adresse commune aux branches. *
* *
* Remarques : - *
* *
******************************************************************************/
static vmpa_t compute_first_common_addr_in_group(const branch_info *list, size_t count)
{
vmpa_t result; /* Adresse trouvée à retourner */
size_t i; /* Boucle de parcours #1 */
bool keep; /* Candidate à garder ? */
size_t j; /* Boucle de parcours #2 */
/* Valeur conceptuellement impossible à renvoyer */
result = VMPA_MAX;
//qsort(a->jumps, a->count, sizeof(vmpa_t), (__compar_fn_t)compare_vmpa);
//qsort(b->jumps, b->count, sizeof(vmpa_t), (__compar_fn_t)compare_vmpa);
for (i = 0; i < list[0].count && result == VMPA_MAX; i++)
{
keep = true;
for (j = 1; j < count && keep; j++)
keep = is_addr_in_branch(&list[j], &list[0].jumps[i], false);
if (keep)
result = list[0].jumps[i];
}
return result;
}
/******************************************************************************
* *
* Paramètres : instrs = ensemble des instructions d'assemblage. *
* start = adresse de début du bloc. *
* end = adresse de fin du bloc (exclusive). *
* stop = adresse d'arrêt en cas de saut ou VMPA_MAX. *
* *
* Description : Procède à la définition de bloc regroupant des instructions. *
* *
* Retour : Bloc créé et enregistré, ou NULL si erreur. *
* *
* Remarques : - *
* *
******************************************************************************/
static GInstrBlock *build_instruction_block(GArchInstruction *instrs, vmpa_t start, vmpa_t end, vmpa_t stop)
{
GInstrBlock *result; /* Regroupement à retourner */
GInstrBlock *result_cached; /* Temporisation pour unicité */
branch_info main_branch; /* Flot d'exécution complet */
GArchInstruction *first; /* Première instruction */
GArchInstruction *last; /* Dernière instruction */
GArchInstruction *iter; /* Boucle de parcours */
vmpa_t addr; /* Adresse de la destination */
GArchInstruction **dests; /* Instr. visée par une autre */
InstructionLinkType *types; /* Type de lien entre lignes */
size_t dcount; /* Nombre de liens de dest. */
size_t i; /* Boucle de parcours #1 */
GInstrBlock *block; /* Nouveau bloc mis en place */
GInstrBlock *group; /* Regroupement de blocs */
branch_info *cases_branches; /* Branches d'un aiguillage */
size_t cases_count; /* Nombre d'aiguillages */
branch_info true_branch; /* Branche 'condition vraie' */
branch_info false_branch; /* Branche 'condition fausse' */
branch_info *excep_branches; /* Branches d'exceptions */
size_t excep_count; /* Nombre d'exceptions */
vmpa_t next_addr; /* Prochaine instruction visée */
size_t j; /* Boucle de parcours #2 */
vmpa_t stop_addr; /* Adresse de fin de bloc */
result = NULL;
result_cached = NULL;
/**
* Procédure d'ajout de blocs : pour le premier, on conserve le bloc en mémoire
* et on attend. Si rien ne suit, il constitura l'unique retour. Sinon, on
* l'ajoute à partir de la sauvegarde, et le reste suit.
*/
#define DELAYED_BLOCK_ADDING(res, cache, blk) \
do \
{ \
if (res == NULL) \
{ \
if (cache == NULL) \
cache = blk; \
else \
{ \
res = g_virtual_block_new(); \
g_virtual_block_add_child(G_VIRTUAL_BLOCK(res), cache); \
} \
} \
\
if (res != NULL) \
g_virtual_block_add_child(G_VIRTUAL_BLOCK(res), blk); \
\
} \
while (0)
first = NULL;
last = NULL;
memset(&main_branch, 0, sizeof(branch_info));
find_next_jumps(instrs, start, end, &main_branch);
//printf("[+] blocking 0x%08llx -> 0x%08llx... stop @ 0x%08llx\n", start, end, stop);
for (iter = g_arch_instruction_find_by_address(instrs, start, true);
iter != NULL;
)
{
g_arch_instruction_get_location(iter, NULL, NULL, &addr);
if (addr == stop) break;
/* On s'arrêter si l'instruction est déjà décompilée */
if (MACRO_IS_PROCESSED(iter)) break;
if (first == NULL)
first = iter;
last = iter;
/* On n'approfondit que les chemins qui se séparent */
if (!g_arch_instruction_has_destinations(iter))
{
iter = g_arch_instruction_get_next_iter(instrs, iter, end);
continue;
}
/* Adaptations en fonction du type de bifurcation */
dcount = g_arch_instruction_get_destinations(iter, &dests, &types);
next_addr = 0;
cases_branches = NULL;
cases_count = 0;
memset(&true_branch, 0, sizeof(branch_info));
memset(&false_branch, 0, sizeof(branch_info));
excep_branches = NULL;
excep_count = 0;
for (i = 0; i < dcount; i++)
switch (types[i])
{
case ILT_EXEC_FLOW:
case ILT_JUMP:
block = g_flow_block_new(instrs, first, iter);
MACRO_MARK_AS_PROCESSED(first);
first = NULL;
DELAYED_BLOCK_ADDING(result, result_cached, block);
g_arch_instruction_get_location(dests[i], NULL, NULL, &next_addr);
break;
case ILT_CASE_JUMP:
g_arch_instruction_get_location(dests[i], NULL, NULL, &addr);
cases_branches = (branch_info *)realloc(cases_branches,
++cases_count * sizeof(branch_info));
memset(&cases_branches[cases_count - 1], 0, sizeof(branch_info));
find_next_jumps(instrs, addr, end, &cases_branches[cases_count - 1]);
break;
case ILT_JUMP_IF_TRUE:
g_arch_instruction_get_location(dests[i], NULL, NULL, &addr);
find_next_jumps(instrs, addr, end, &true_branch);
break;
case ILT_JUMP_IF_FALSE:
g_arch_instruction_get_location(dests[i], NULL, NULL, &addr);
find_next_jumps(instrs, addr, end, &false_branch);
break;
case ILT_CATCH_EXCEPTION:
g_arch_instruction_get_location(dests[i], NULL, NULL, &addr);
excep_branches = (branch_info *)realloc(excep_branches,
++excep_count * sizeof(branch_info));
memset(&excep_branches[excep_count - 1], 0, sizeof(branch_info));
find_next_jumps(instrs, addr, end, &excep_branches[excep_count - 1]);
break;
default:
if (next_addr == 0)
next_addr = VMPA_MAX;
break;
}
/* Post-traitements de ILT_CASE_JUMP */
if (cases_count > 0)
{
if (first != NULL)
{
block = g_flow_block_new(instrs, first, iter);
MACRO_MARK_AS_PROCESSED(first);
first = NULL;
DELAYED_BLOCK_ADDING(result, result_cached, block);
}
//printf(" --- cases --- start\n");
next_addr = compute_first_common_addr_in_group(cases_branches, cases_count);
//printf(" stop :: 0x%08llx\n", next_addr);
group = g_virtual_block_new();
for (j = 0; j < cases_count; j++)
{
//printf(" ## %zu\n", j);
block = build_instruction_block(instrs, cases_branches[j].jumps[0], end, next_addr);
if (block != NULL)
g_virtual_block_add_child(G_VIRTUAL_BLOCK(group), block);
free(cases_branches[j].jumps);
}
if (g_virtual_block_count_children(G_VIRTUAL_BLOCK(group)) > 0)
DELAYED_BLOCK_ADDING(result, result_cached, group);
else
g_object_unref(G_OBJECT(group));
//printf(" --- cases --- end\n");
free(cases_branches);
}
/* Post-traitements de ILT_CATCH_EXCEPTION */
if (excep_count > 0)
{
if (first != NULL)
{
block = g_flow_block_new(instrs, first, iter);
MACRO_MARK_AS_PROCESSED(first);
first = NULL;
DELAYED_BLOCK_ADDING(result, result_cached, block);
}
for (j = 0; j < excep_count; j++)
{
stop_addr = compute_first_common_addr(&main_branch, &excep_branches[j]);
//next_addr = MIN(next_addr, end);
block = build_instruction_block(instrs, excep_branches[j].jumps[0], end, stop_addr);
if (block != NULL)
g_virtual_block_add_child(G_VIRTUAL_BLOCK(result), block);
free(excep_branches[j].jumps);
}
free(excep_branches);
}
if (next_addr == VMPA_MAX)
{
iter = g_arch_instruction_get_next_iter(instrs, iter, end);
continue;
}
else if (true_branch.count > 0 || false_branch.count > 0)
{
next_addr = compute_first_common_addr(&true_branch, &false_branch);
next_addr = MIN(next_addr, end);
if (first != NULL)
{
block = g_flow_block_new(instrs, first, iter);
MACRO_MARK_AS_PROCESSED(first);
first = NULL;
DELAYED_BLOCK_ADDING(result, result_cached, block);
}
group = g_virtual_block_new();
block = build_instruction_block(instrs, true_branch.jumps[0], end, next_addr);
if (block != NULL)
g_virtual_block_add_child(G_VIRTUAL_BLOCK(group), block);
block = build_instruction_block(instrs, false_branch.jumps[0], end, next_addr);
if (block != NULL)
g_virtual_block_add_child(G_VIRTUAL_BLOCK(group), block);
if (g_virtual_block_count_children(G_VIRTUAL_BLOCK(group)) > 0)
DELAYED_BLOCK_ADDING(result, result_cached, group);
else
g_object_unref(G_OBJECT(group));
free(true_branch.jumps);
free(false_branch.jumps);
if (next_addr == end) break;
}
/* Détermination du prochain point de chute */
iter = g_arch_instruction_find_by_address(instrs, next_addr, true);
}
if (first != NULL && last != NULL)
{
if (!MACRO_IS_PROCESSED(first))
{
//printf("--close?--\n");
block = g_flow_block_new(instrs, first, last);
MACRO_MARK_AS_PROCESSED(first);
//printf("--close!--\n");
DELAYED_BLOCK_ADDING(result, result_cached, block);
}
}
if ((result != NULL ? result : result_cached) == NULL)
{
//printf("WARNING :: null !\n");
//exit(0);
}
return (result != NULL ? result : result_cached);
}
static bool print_blocks(GInstrBlock *blk, BlockVisitOrder order, int *pad)
{
int i;
vmpa_t start, end;
if (order != BVO_OUT)
for (i = 0; i < *pad; i++)
printf(" ");
if (G_IS_FLOW_BLOCK(blk))
{
g_flow_block_get_boundary_addresses(G_FLOW_BLOCK(blk), &start, &end);
printf(" - flow %p : 0x%08lx -> 0x%08lx\n", blk, start, end);
}
else
{
if (order != BVO_OUT)
{
printf(" - virtual %p\n", blk);
*pad += 1;
}
else *pad -= 1;
}
fflush(NULL);
return true;
}
/******************************************************************************
* *
* Paramètres : list = ensemble d'instructions à relier. *
* routines = prototypes existants à insérer. *
* count = quantité de ces prototypes. *
* statusbar = barre de statut avec progression à mettre à jour.*
* id = identifiant du message affiché à l'utilisateur. *
* *
* Description : Regroupe les instructions par blocs. *
* *
* Retour : - *
* *
* Remarques : - *
* *
******************************************************************************/
void group_routines_instructions(GArchInstruction *list, GBinRoutine **routines, size_t count, GtkExtStatusBar *statusbar, guint id)
{
size_t i; /* Boucle de parcours */
vmpa_t start; /* Adresse de départ */
vmpa_t end; /* Adresse de fin */
GInstrBlock *block; /* Regroupement d'instructions */
for (i = 0; i < count; i++)
{
start = g_binary_routine_get_address(routines[i]);
end = start + g_binary_routine_get_size(routines[i]);
//printf("==== %s ====\n", g_binary_routine_to_string(routines[i]));
block = build_instruction_block(list, start, end, VMPA_MAX);
g_binary_routine_set_basic_blocks(routines[i], block);
//g_instr_block_visit(block, (instr_block_visitor_cb)print_blocks, (int []){ 0 });
gtk_extended_status_bar_update_activity(statusbar, id, (i + 1) * 1.0 / count);
}
}