summaryrefslogtreecommitdiff
path: root/plugins/androhelpers/try_n_catch.c
blob: fc7b2bbea80d06cbfeb1a8802e95eb51b07fddb9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346

/* OpenIDA - Outil d'analyse de fichiers binaires
 * try_n_catch.c - support des exceptions chez Android
 *
 * 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 <http://www.gnu.org/licenses/>.
 */


#include "try_n_catch.h"


#include <malloc.h>


#include <format/dex/dex-int.h>
#include <format/dex/pool.h>
#include <../i18n.h>



/* Mémorisation d'un lien vers un gestionnaire */
typedef struct _caught_exception
{
    GArchInstruction *instr;                /* Première instruction visée  */
    char *desc;                             /* Nom de l'exception          */

} caught_exception;



/* Valide la zone couverte par le gestionnaire d'exceptions. */
static bool check_covered_area(const try_item *, const GBinRoutine *);

/* Construit une liste pointant sur les différentes gestions. */
static caught_exception *build_destinations_list(GLoadedBinary *, const try_item *, const encoded_catch_handler_list *, const GBinRoutine *, size_t *);

/* Rattache les gestionnaires d'exception à leur code couvert. */
static void attach_caught_code(GLoadedBinary *, const try_item *, const encoded_catch_handler_list *, const GBinRoutine *);

/* Recherche et met en avant tous les gestionnaires d'exception. */
static void look_for_exception_handlers(GLoadedBinary *, const GDexFormat *, GDexMethod *);



/******************************************************************************
*                                                                             *
*  Paramètres  : try     = informations sur la gestion à consulter.           *
*                routine = routine associée, pour validation.                 *
*                                                                             *
*  Description : Valide la zone couverte par le gestionnaire d'exceptions.    *
*                                                                             *
*  Retour      : Validité de la zone couverte.                                *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static bool check_covered_area(const try_item *try, const GBinRoutine *routine)
{
    off_t length;                           /* Taille de la zone de code   */
    vmpa_t covered_start;                   /* Début de la zone couverte   */
    vmpa_t covered_end;                     /* Fin de la zone couverte     */

    length = g_binary_routine_get_size(routine);

    covered_start = try->start_addr * sizeof(uint16_t);
    covered_end = covered_start + try->insn_count * sizeof(uint16_t);

    return (covered_end <= length);

}


/******************************************************************************
*                                                                             *
*  Paramètres  : binary  = représentation binaire à traiter.                  *
*                try     = informations sur la gestion à consulter.           *
*                hlist   = liste de tous les gestionnaires en place.          *
*                routine = routine associée, pour l'accès au instructions.    *
*                count   = quantité de destinations trouvées. [OUT]           *
*                                                                             *
*  Description : Construit une liste pointant sur les différentes gestions.   *
*                                                                             *
*  Retour      : Adresse des codes à lier systématiquement.                   *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static caught_exception *build_destinations_list(GLoadedBinary *binary, const try_item *try, const encoded_catch_handler_list *hlist, const GBinRoutine *routine, size_t *count)
{
    caught_exception *result;               /* Liste à retourner           */
    GDexFormat *format;                     /* Format du binaire chargé    */
    vmpa_t start;                           /* Début du code de la routine */
    GArchInstruction *instrs;               /* Instructions Dalvik         */
    uleb128_t index;                        /* Indice du bon gestionnaire  */
    encoded_catch_handler *handlers;        /* Groupe de gestionnaires     */
    leb128_t max;                           /* Quantité d'exception        */
    leb128_t i;                             /* Boucle de parcours          */
    vmpa_t handler_addr;                    /* Adresse du code de gestion  */
    GDataType *type;                        /* Type de l'exception         */

    format = G_DEX_FORMAT(g_loaded_binary_get_format(binary));

    start = g_binary_routine_get_address(routine);

    instrs = g_loaded_binary_get_instructions(binary);
    instrs = g_arch_instruction_find_by_address(instrs, start, true);

    for (index = 0; index < hlist->size; index++)
        if (try->handler_off == hlist->list[index].offset)
            break;

    if (index == hlist->size)
    {
        *count = 0;
        return NULL;
    }

    handlers = &hlist->list[index];
    max = leb128_abs(handlers->size);

    *count = max + (handlers->size < 0 ? 1 : 0);
    result = (caught_exception *)calloc(*count, sizeof(caught_exception));

    *count = 0;

    for (i = 0; i < max; i++)
    {
        handler_addr = start + handlers->handlers[i].addr * sizeof(uint16_t);
        result[*count].instr = g_arch_instruction_find_by_address(instrs, handler_addr, true);

        if (result[*count].instr == NULL)
            continue;

        type = get_type_from_dex_pool(format, handlers->handlers[i].type_idx);
        result[*count].desc = g_data_type_to_string(type);

        (*count)++;

    }

    if (handlers->size < 0)
    {
        handler_addr = start + handlers->catch_all_addr * sizeof(uint16_t);
        result[*count].instr = g_arch_instruction_find_by_address(instrs, handler_addr, true);

        if (result[*count].instr != NULL)
        {
            result[*count].desc = strdup(_("default"));
            (*count)++;
        }

    }

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : binary   = représentation binaire à traiter.                 *
*                try      = informations sur la gestion à consulter.          *
*                handlers = liste de tous les gestionnaires en place.         *
*                routine  = routine associée, pour l'accès au instructions.   *
*                                                                             *
*  Description : Rattache les gestionnaires d'exception à leur code couvert.  *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void attach_caught_code(GLoadedBinary *binary, const try_item *try, const encoded_catch_handler_list *handlers, const GBinRoutine *routine)
{
    vmpa_t start;                           /* Début de la zone couverte   */
    vmpa_t end;                             /* Début de la zone couverte   */
    GArchInstruction *instrs;               /* Instructions Dalvik         */
    GArchInstruction *first;                /* Première instruction        */
    GArchInstruction *next;                 /* Dernière instruction + 1    */
    GArchInstruction *prev;                 /* Instruction à détacher      */
    GArchInstruction *iter;                 /* Boucle de parcours          */
    size_t dests_count;                     /* Nombre de points d'arrivée  */
    caught_exception *dests;                /* Points d'arrivée            */
    size_t i;                               /* Boucle de parcours          */

    start = g_binary_routine_get_address(routine);
    start += try->start_addr * sizeof(uint16_t);

    end = start + try->insn_count * sizeof(uint16_t);

    instrs = g_loaded_binary_get_instructions(binary);
    first = g_arch_instruction_find_by_address(instrs, start, true);
    next = g_arch_instruction_find_by_address(instrs, end, true);

    /* Si des détachements sont nécessaires... */

    if (!g_arch_instruction_has_sources(first))
    {
        prev = g_arch_instruction_get_prev_iter(instrs, first);
        g_arch_instruction_link_with(prev, first, ILT_EXEC_FLOW);
    }

    if (!g_arch_instruction_has_sources(next))
    {
        prev = g_arch_instruction_get_prev_iter(instrs, next);
        g_arch_instruction_link_with(prev, next, ILT_EXEC_FLOW);
    }

    /* Détermination du code des exceptions */
    dests = build_destinations_list(binary, try, handlers, routine, &dests_count);

    if (dests != NULL)
    {
        /* Rattachements */
        for (iter = first;
             iter != NULL;
             iter = g_arch_instruction_get_next_iter(instrs, iter, end))
        {
            if (!g_arch_instruction_has_destinations(iter))
                continue;

            for (i = 0; i < dests_count; i++)
                g_arch_instruction_link_with(iter, dests[i].instr, ILT_CATCH_EXCEPTION);

        }

        /* Libération de la mémoire utilisée */

        for (i = 0; i < dests_count; i++)
            free(dests[i].desc);

        free(dests);

    }

}


/******************************************************************************
*                                                                             *
*  Paramètres  : binary = représentation binaire à traiter.                   *
*                format = format du binaire Dex.                              *
*                method = méthode à analyser.                                 *
*                                                                             *
*  Description : Recherche et met en avant tous les gestionnaires d'exception.*
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void look_for_exception_handlers(GLoadedBinary *binary, const GDexFormat *format, GDexMethod *method)
{
    const code_item *body;                  /* Description du corps        */
    GBinRoutine *routine;                   /* Abstraction globale         */
    uint16_t i;                             /* Boucle de parcours          */

    body = g_dex_method_get_dex_body(method);

    if (body->tries_size == 0)
        return;

    routine = g_dex_method_get_routine(method);

    for (i = 0; i < body->tries_size; i++)
    {
        if (!check_covered_area(&body->tries[i], routine))
            continue;

        attach_caught_code(binary, &body->tries[i], body->handlers, routine);

    }

}


/******************************************************************************
*                                                                             *
*  Paramètres  : binary = représentation binaire à traiter.                   *
*                                                                             *
*  Description : Traite tous les gestionnaires d'exception trouvés.           *
*                                                                             *
*  Retour      : true si une action a été menée, false sinon.                 *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

bool process_exception_handlers(GLoadedBinary *binary)
{
    GDexFormat *format;                     /* Format du binaire chargé    */
    size_t cls_count;                       /* Nombre de classes trouvées  */
    size_t i;                               /* Boucle de parcours #1       */
    GDexClass *class;                       /* Classe à analyser           */
    size_t meth_count;                      /* Nombre de méthodes trouvées */
    size_t j;                               /* Boucle de parcours #2       */
    GDexMethod *method;                     /* Méthode à parcourir         */

    if (!G_IS_DEX_FORMAT(g_loaded_binary_get_format(binary)))
        return false;

    format = G_DEX_FORMAT(g_loaded_binary_get_format(binary));

    cls_count = g_dex_format_count_classes(format);
    for (i = 0; i < cls_count; i++)
    {
        class = g_dex_format_get_class(format, i);

        meth_count = g_dex_class_count_methods(class, false);
        for (j = 0; j < meth_count; j++)
        {
            method = g_dex_class_get_method(class, false, j);
            look_for_exception_handlers(binary, format, method);
        }

        meth_count = g_dex_class_count_methods(class, true);
        for (j = 0; j < meth_count; j++)
        {
            method = g_dex_class_get_method(class, true, j);
            look_for_exception_handlers(binary, format, method);
        }

    }

    return true;

}