summaryrefslogtreecommitdiff
path: root/src/analysis/disass/disassembler.c
blob: f229af38e61e37d614e0eb70b24bbbfd0db48823 (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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472

/* Chrysalide - Outil d'analyse de fichiers binaires
 * disassembler.c - encadrement des phases de désassemblage
 *
 * Copyright (C) 2010-2017 Cyrille Bagard
 *
 *  This file is part of Chrysalide.
 *
 *  Chrysalide 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.
 *
 *  Chrysalide 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 Chrysalide.  If not, see <http://www.gnu.org/licenses/>.
 */


#include "disassembler.h"


#include <malloc.h>
#include <stdio.h>
#include <string.h>


#include <i18n.h>


#include "fetch.h"
#include "instructions.h"
#include "output.h"
#include "routines.h"
#include "../../arch/storage.h"
#include "../../core/global.h"
#include "../../core/nproc.h"
#include "../../glibext/generators/prologue.h"
#include "../../plugins/pglist.h"



#include "../human/asm/lang.h" // TODO : REMME -> format !



/* Opère sur toutes les instructions. */
static void process_all_instructions(wgroup_id_t, GtkStatusStack *, const char *, ins_fallback_cb, GArchProcessor *, GProcContext *, GExeFormat *);

/* Opère sur toutes les routines. */
static void process_all_routines(GLoadedBinary *, wgroup_id_t, GtkStatusStack *, const char *, rtn_fallback_cb);

/* Réalise un désassemblage effectif. */
static void compute_disassembly(GLoadedBinary *, GProcContext *, wgroup_id_t, GtkStatusStack *);



/******************************************************************************
*                                                                             *
*  Paramètres  : gid      = groupe de travail impliqué.                       *
*                status   = barre de statut à tenir informée.                 *
*                msg      = message à faire paraître pour la patience.        *
*                fallback = routine de traitements particuliers.              *
*                proc     = ensemble d'instructions désassemblées.            *
*                ctx      = contexte fourni pour suivre le désassemblage.     *
*                format   = accès aux données du binaire d'origine.           *
*                                                                             *
*  Description : Opère sur toutes les instructions.                           *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void process_all_instructions(wgroup_id_t gid, GtkStatusStack *status, const char *msg, ins_fallback_cb fallback, GArchProcessor *proc, GProcContext *ctx, GExeFormat *format)
{
    guint runs_count;                       /* Qté d'exécutions parallèles */
    size_t ins_count;                       /* Quantité d'instructions     */
    size_t run_size;                        /* Volume réparti par exécution*/
    GWorkQueue *queue;                      /* Gestionnaire de différés    */
    activity_id_t id;                       /* Identifiant de progression  */
    guint i;                                /* Boucle de parcours          */
    size_t begin;                           /* Début de bloc de traitement */
    size_t end;                             /* Fin d'un bloc de traitement */
    GInstructionsStudy *study;              /* Tâche d'étude à programmer  */

    runs_count = get_max_online_threads();

    g_arch_processor_lock(proc);

    ins_count = g_arch_processor_count_instructions(proc);

    g_arch_processor_unlock(proc);

    run_size = ins_count / runs_count;

    queue = get_work_queue();

    id = gtk_status_stack_add_activity(status, msg, ins_count);

    for (i = 0; i < runs_count; i++)
    {
        begin = i * run_size;

        if ((i + 1) == runs_count)
            end = ins_count;
        else
            end = begin + run_size;

        study = g_instructions_study_new(proc, ctx, format, begin, end, id, fallback);

        g_work_queue_schedule_work(queue, G_DELAYED_WORK(study), gid);

    }

    g_work_queue_wait_for_completion(queue, gid);

    gtk_status_stack_remove_activity(status, id);

}


/******************************************************************************
*                                                                             *
*  Paramètres  : binary   = binaire chargé comprenant les routines à traiter. *
*                gid      = groupe de travail impliqué.                       *
                 status   = barre de statut à tenir informée.                 *
*                msg      = message à faire paraître pour la patience.        *
*                fallback = routine de traitements particuliers.              *
*                                                                             *
*  Description : Opère sur toutes les routines.                               *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void process_all_routines(GLoadedBinary *binary, wgroup_id_t gid, GtkStatusStack *status, const char *msg, rtn_fallback_cb fallback)
{
    GBinFormat *format;                     /* Format associé au binaire   */
    GBinPortion *portions;                  /* Couche première de portions */
    size_t sym_count;                       /* Nombre de ces symboles      */
    guint runs_count;                       /* Qté d'exécutions parallèles */
    size_t run_size;                        /* Volume réparti par exécution*/
    GWorkQueue *queue;                      /* Gestionnaire de différés    */
    activity_id_t id;                       /* Identifiant de progression  */
    guint i;                                /* Boucle de parcours          */
    size_t begin;                           /* Début de bloc de traitement */
    size_t end;                             /* Fin d'un bloc de traitement */
    GRoutinesStudy *study;                  /* Tâche d'étude à programmer  */

    format = G_BIN_FORMAT(g_loaded_binary_get_format(binary));

    portions = g_exe_format_get_portions(G_EXE_FORMAT(format));

    g_binary_format_lock_symbols_rd(format);

    sym_count = g_binary_format_count_symbols(format);

    runs_count = get_max_online_threads();

    run_size = sym_count / runs_count;

    queue = get_work_queue();

    id = gtk_status_stack_add_activity(status, msg, sym_count);

    for (i = 0; i < runs_count; i++)
    {
        begin = i * run_size;

        if ((i + 1) == runs_count)
            end = sym_count;
        else
            end = begin + run_size;

        study = g_routines_study_new(binary, portions, begin, end, id, fallback);

        g_work_queue_schedule_work(queue, G_DELAYED_WORK(study), gid);

    }

    g_work_queue_wait_for_completion(queue, gid);

    gtk_status_stack_remove_activity(status, id);

    g_binary_format_unlock_symbols_rd(format);

    g_object_unref(G_OBJECT(portions));

    g_object_unref(G_OBJECT(format));

}


/******************************************************************************
*                                                                             *
*  Paramètres  : binary  = représentation de binaire chargé.                  *
*                context = contexte de désassemblage utilisé.                 *
*                gid     = groupe de travail dédié.                           *
*                status  = barre de statut à tenir informée.                  *
*                                                                             *
*  Description : Réalise un désassemblage effectif.                           *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void compute_disassembly(GLoadedBinary *binary, GProcContext *context, wgroup_id_t gid, GtkStatusStack *status)
{
    GArchProcessor *proc;                   /* Architecture du binaire     */
    GExeFormat *format;                     /* Format du binaire représenté*/
    GBinContent *content;                   /* Contenu brut représenté     */
    const gchar *id;                        /* Identifiant court et unique */
    GAsmStorage *storage;                   /* Cache propre à constituer   */
    bool cached;                            /* Instructions en cache       */
    GArchInstruction **instrs;              /* Instructions résultantes    */
    size_t count;                           /* Quantité de ces instructions*/

    /**
     * Récupération des objets utiles.
     */

    proc = g_loaded_binary_get_processor(binary);

    format = g_loaded_binary_get_format(binary);

    g_binary_format_preload_disassembling_context(G_BIN_FORMAT(format), context, status);

    /**
     * Etape zéro : récupération des instructions depuis un cache, si ce dernier exitste.
     */

    content = g_loaded_content_get_content(G_LOADED_CONTENT(binary));

    id = g_binary_content_get_checksum(content);

    storage = g_asm_storage_new_compressed(proc, id);

    g_object_unref(G_OBJECT(content));

    cached = g_asm_storage_has_cache(storage);

    if (cached)
        cached = g_asm_storage_open(storage, G_BIN_FORMAT(format), gid);

    g_object_unref(G_OBJECT(storage));

    /**
     * Première étape : collecte des instructions.
     */

    if (!cached)
    {
        instrs = disassemble_binary_content(binary, context, gid, status, &count);

        g_arch_processor_set_instructions(proc, instrs, count);

        process_disassembly_event(PGA_DISASSEMBLY_RAW, binary, status, context);

    }

    /**
     * Seconde étape : liaisons des instructions.
     */

    if (!cached)
    {
        process_all_instructions(gid, status, _("Calling 'link' hook on all instructions..."),
                                 g_instructions_study_do_link_operation,
                                 proc, context, format);

        process_disassembly_event(PGA_DISASSEMBLY_HOOKED_LINK, binary, status, context);

    }

    /**
     * Troisième étape : exécution d'éventuels post-traitements.
     */

    process_all_instructions(gid, status, _("Calling 'post' hook on all instructions..."),
                             g_instructions_study_do_post_operation,
                             proc, context, format);

    process_disassembly_event(PGA_DISASSEMBLY_HOOKED_POST, binary, status, context);

    /**
     * Quatrième étape : établissement des couvertures de routines restantes.
     */

    process_all_routines(binary, gid, status,
                         _("Finding remaining limits..."),
                         g_routines_study_compute_limits);

    process_disassembly_event(PGA_DISASSEMBLY_LIMITED, binary, status, context);

    /**
     * Cinquième étape : liaisons entre instructions.
     */

    if (!cached)
    {
        process_all_instructions(gid, status, _("Establishing links betweek all instructions..."),
                                 g_instructions_study_establish_links,
                                 proc, context, format);

        process_disassembly_event(PGA_DISASSEMBLY_LINKED, binary, status, context);

    }

    /**
     * Sixième étape : regroupement en blocs basiques.
     */

    process_all_routines(binary, gid, status,
                         _("Control-flow analysis for routines..."),
                         g_routines_study_handle_blocks);

    process_disassembly_event(PGA_DISASSEMBLY_GROUPED, binary, status, context);

    /**
     * Nettoyage final et sortie !
     */

    g_object_unref(G_OBJECT(format));

    g_object_unref(G_OBJECT(proc));

}


/******************************************************************************
*                                                                             *
*  Paramètres  : binary  = représentation de binaire chargé.                  *
*                gid     = groupe de travail dédié.                           *
*                status  = barre de statut à tenir informée.                  *
*                context = contexte de désassemblage. [OUT]                   *
*                                                                             *
*  Description : Procède au désassemblage d'un contenu binaire donné.         *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

void disassemble_binary(GLoadedBinary *binary, wgroup_id_t gid, GtkStatusStack *status, GProcContext **context)
{
    GArchProcessor *proc;                   /* Architecture du binaire     */

    /* Préparatifs */

    process_disassembly_event(PGA_DISASSEMBLY_STARTED, binary, status, NULL);

    proc = g_loaded_binary_get_processor(binary);

    *context = g_arch_processor_get_context(proc);

    g_object_unref(G_OBJECT(proc));

    /* Lancement des opérations ! */

    compute_disassembly(binary, *context, gid, status);

    process_disassembly_event(PGA_DISASSEMBLY_ENDED, binary, status, *context);

}


/******************************************************************************
*                                                                             *
*  Paramètres  : binary  = représentation de binaire chargé.                  *
*                context = contexte de désassemblage utilisé.                 *
*                status  = barre de statut à tenir informée.                  *
*                cache   = tampon de code mis en place. [OUT]                 *
*                                                                             *
*  Description : Imprime le résultat d'un désassemblage.                      *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

void output_disassembly(GLoadedBinary *binary, GProcContext *context, GtkStatusStack *status, GBufferCache **cache)
{
    GBinFormat *format;                     /* Format associé au binaire   */
    GBinContent *content;                   /* Contenu bianire manipulé    */
    GCodingLanguage *lang;                  /* Langage de sortie préféré   */
    char **text;                            /* Contenu brute à imprimer    */
    const char *desc;                       /* Désignation du binaire      */
    const gchar *checksum;                  /* Identifiant de binaire      */
    GIntroGenerator *generator;             /* Générateur constitué        */

    /**
     * Initialisation des biens communs.
     */

    format = G_BIN_FORMAT(g_loaded_binary_get_format(binary));
    content = g_binary_format_get_content(format);
    lang = g_asm_language_new();

    *cache = g_buffer_cache_new(content);

    /**
     * Impression du prologue.
     */

    text = calloc(4, sizeof(char *));

    /* Introduction */

    text[0] = strdup(_("Disassembly generated by Chrysalide"));
    text[1] = strdup(_("Chrysalide is free software - © 2008-2018 Cyrille Bagard"));

    /* Fichier */

    desc = g_binary_content_describe(content, true);

    asprintf(&text[2], "%s%s", _("Source: "), desc);

    /* Checksum SHA256 */

    checksum = g_binary_content_get_checksum(content);

    asprintf(&text[3], "%s%s", _("Sha256: "), checksum);

    /* Intégration finale */

    generator = g_intro_generator_new(format, lang, text, 4);

    g_buffer_cache_append(*cache, G_LINE_GENERATOR(generator), BLF_NONE);

    /**
     * Impression des instructions désassemblées.
     */

    print_disassembled_instructions(*cache, lang, binary, G_PRELOAD_INFO(context), status);

    /**
     * Rajout de tous les éléments mis en place automatiquement.
     */

    void add_to_collection(GDbItem *item, gpointer unused)
    {
        g_object_ref(G_OBJECT(item));

        g_loaded_binary_add_to_collection(binary, item);

    }

    g_proc_context_foreach_db_item(context, (GFunc)add_to_collection, NULL);

    /**
     * Nettoyage avant sortie.
     */

    g_object_unref(G_OBJECT(lang));
    g_object_unref(G_OBJECT(content));
    g_object_unref(G_OBJECT(format));

    g_object_unref(G_OBJECT(context));

}