/* Chrysalide - Outil d'analyse de fichiers binaires * symbols.c - gestion des symboles d'un ELF * * Copyright (C) 2009-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 Foobar. If not, see . */ #include "symbols.h" #include #include #include #include #include #include #include #include #include #include #include #include #include "dynamic.h" #include "elf-int.h" #include "loading.h" #include "program.h" #include "section.h" /* ------------------------- CHARGEMENT GLOBAL DES SYMBOLES ------------------------- */ /* Enregistre un point d'entrée au sein d'un binaire ELF. */ static void register_elf_entry_point(GElfFormat *, virt_t, phys_t, GBinRoutine *); /* Enumère tous les points d'entrée principaux d'un binaire ELF. */ static bool load_all_elf_basic_entry_points(GElfFormat *); /* Assure le chargement des symboles internes ELF en différé. */ static bool do_elf_symbol_loading(GElfLoading *, GElfFormat *, bool, phys_t *, GBinSymbol **); /* Charge tous les symboles possibles. */ static void add_all_elf_symbols(GElfFormat *, phys_t, size_t, phys_t, GWorkQueue *, wgroup_id_t, elf_loading_cb, GtkStatusStack *, activity_id_t); /* --------------------------- DETAIL DES SYMBOLES LOCAUX --------------------------- */ /* Assure le chargement des symboles locaux ELF en différé. */ static bool do_elf_local_symbol_loading(GElfLoading *, GElfFormat *, phys_t *); /* Charge tous les symboles internes possibles. */ static bool load_elf_local_symbols(GElfFormat *, wgroup_id_t, GtkStatusStack *); /* --------------------------- DETAIL DE SYMBOLES GLOBAUX --------------------------- */ /* Assure le chargement des symboles globaux ELF en différé. */ static bool do_elf_global_symbol_loading(GElfLoading *, GElfFormat *, phys_t *); /* Dénombre le nombre de symboles en lien avec l'extérieur. */ static bool count_elf_global_symbols(GElfFormat *, GExeFormat *, uint32_t *); /* Charge tous les éléments dynamiques externes possibles. */ static bool load_elf_global_symbols(GElfFormat *, wgroup_id_t, GtkStatusStack *); /* ----------------------- PRISE EN COMPTE DE RELOCALISATIONS ----------------------- */ /* Assure le chargement des relocalisations ELF en différé. */ static bool do_elf_relocation_loading(GElfLoading *, GElfFormat *, phys_t *); /* Charge en mémoire toutes les relocalisations présentes. */ static bool load_elf_relocations(GElfFormat *, const elf_phdr *, elf_rel **, size_t *, GtkStatusStack *); /* Assure l'intégration d'un symbole issu des relocalisations. */ static bool do_elf_relocation_renaming(GElfLoading *, GElfFormat *, GBinSymbol *); /* Applique les étiquettes issues des relocalisations. */ static bool apply_elf_relocations(GElfFormat *, elf_rel *, size_t, sym_iter_t *, GtkStatusStack *); /* ---------------------------------------------------------------------------------- */ /* CHARGEMENT GLOBAL DES SYMBOLES */ /* ---------------------------------------------------------------------------------- */ /****************************************************************************** * * * Paramètres : format = description de l'exécutable à compléter. * status = barre de statut à tenir informée. * * * * Description : Charge en mémoire la liste humaine des symboles. * * * * Retour : Bilan de l'opération. * * * * Remarques : - * * * ******************************************************************************/ bool load_elf_symbols(GElfFormat *format, GtkStatusStack *status) { bool result; /* Bilan à retourner */ wgroup_id_t gid; /* Identifiant pour les tâches */ result = true; gid = g_work_queue_define_work_group(get_work_queue()); /* Symboles internes */ result &= load_elf_local_symbols(format, gid, status); /* Symboles importés et/ou exportés */ if (find_elf_dynamic_program_header(format, (elf_phdr []) { 0 })) { log_variadic_message(LMT_INFO, _("Binary is dynamically linked")); result &= load_elf_global_symbols(format, gid, status); } else log_variadic_message(LMT_INFO, _("Binary is statically linked")); /* Symboles d'entrée, si encore besoin */ /** * Le tri en préalable */ result &= load_all_elf_basic_entry_points(format); return result; } /****************************************************************************** * * * Paramètres : format = description de l'exécutable à compléter. * * vaddr = adresse virtuelle du symbole à insérer. * * len = taille de la routine à ajouter. * * routine = représentation de la fonction repérée. * * * * Description : Enregistre un point d'entrée au sein d'un binaire ELF. * * * * Retour : - * * * * Remarques : - * * * ******************************************************************************/ static void register_elf_entry_point(GElfFormat *format, virt_t vaddr, phys_t len, GBinRoutine *routine) { GBinFormat *base; /* Version basique du format */ virt_t final_vaddr; /* Adresse virtuelle retenue */ bool status; /* Bilan d'une opération */ vmpa2t addr; /* Localisation d'une routine */ mrange_t range; /* Couverture mémoire associée */ GBinSymbol *symbol; /* Nouveau symbole construit */ /* Localisation complète du symbole */ final_vaddr = format->ops.fix_virt(vaddr); status = g_exe_format_translate_address_into_vmpa(G_EXE_FORMAT(format), final_vaddr, &addr); if (!status) return; /* Comptabilisation en tant que symbole */ if (g_binary_format_find_symbol_at(G_BIN_FORMAT(format), &addr, &symbol)) g_object_unref(G_OBJECT(routine)); else { base = G_BIN_FORMAT(format); init_mrange(&range, &addr, len); symbol = G_BIN_SYMBOL(routine); g_binary_symbol_set_range(symbol, &range); g_binary_symbol_set_target_type(symbol, STP_ENTRY_POINT); g_binary_format_add_symbol(base, symbol); /* Comptabilisation pour le désassemblage brut */ g_binary_format_register_code_point(base, vaddr, true); } } /****************************************************************************** * * * Paramètres : format = description de l'exécutable à consulter. * * * * Description : Enumère tous les points d'entrée principaux d'un binaire ELF.* * * * Retour : Bilan de l'opération. * * * * Remarques : - * * * ******************************************************************************/ static bool load_all_elf_basic_entry_points(GElfFormat *format) { virt_t ep; /* Point d'entrée détecté */ GBinRoutine *routine; /* Routine à associer à un pt. */ elf_phdr dynamic; /* En-tête de programme DYNAMIC*/ elf_dyn item_a; /* Premier élément DYNAMIC */ elf_dyn item_b; /* Second élément DYNAMIC */ const GBinContent *content; /* Contenu binaire à lire */ phys_t length; /* Taille totale du contenu */ bool status; /* Bilan d'une opération */ vmpa2t pos; /* Tête de lecture courante */ uint32_t virt_32; /* Adresse virtuelle sur 32b */ uint64_t virt_64; /* Adresse virtuelle sur 64b */ /* Point d'entrée principal éventuel */ ep = ELF_HDR(format, format->header, e_entry); if (ep != 0x0) { routine = try_to_demangle_routine("entry_point"); register_elf_entry_point(format, ep, 0, routine); } /* Chargemet de l'en-tête de programme DYNAMIC */ if (!find_elf_dynamic_program_header(format, &dynamic)) goto laebep_exit; /* Détection des constructeurs & destructeurs */ if (_find_elf_dynamic_item_by_type(format, &dynamic, DT_INIT, &item_a)) { ep = ELF_DYN(format, item_a, d_un.d_ptr); if (ep != 0x0) { routine = try_to_demangle_routine("init_function"); register_elf_entry_point(format, ep, 0, routine); } } if (_find_elf_dynamic_item_by_type(format, &dynamic, DT_FINI, &item_a)) { ep = ELF_DYN(format, item_a, d_un.d_ptr); if (ep != 0x0) { routine = try_to_demangle_routine("termination_function"); register_elf_entry_point(format, ep, 0, routine); } } void load_entry_points_from_array(GElfFormat *fmt, const elf_dyn *ar, const elf_dyn *sz, const char *prefix) { unsigned int i; /* Boucle de parcours */ char fullname[64]; /* Désignation humaine */ assert(sizeof(fullname) >= (strlen(prefix) + sizeof(XSTR(UINT64_MAX) + 1))); content = G_BIN_FORMAT(fmt)->content; status = g_exe_format_translate_address_into_vmpa(G_EXE_FORMAT(format), ELF_DYN(fmt, *ar, d_un.d_val), &pos); if (!status) return; length = get_phy_addr(&pos) + ELF_DYN(fmt, *sz, d_un.d_val); for (i = 0; get_phy_addr(&pos) < length; i++) { /** * Selon la libc d'Android (https://www.codeaurora.org/.../android/bionic/linker/README.TXT) : * * DT_INIT_ARRAY * Points to an array of function addresses that must be * called, in-order, to perform initialization. Some of * the entries in the array can be 0 or -1, and should * be ignored. * * On étend le principe aux sections DT_FINI_ARRAY et DT_PREINIT_ARRAY. */ if (fmt->is_32b) { status = g_binary_content_read_u32(content, &pos, fmt->endian, &virt_32); status &= (virt_32 != 0x0 && virt_32 != 0xffffffff); ep = virt_32; } else { status = g_binary_content_read_u64(content, &pos, fmt->endian, &virt_64); status &= (virt_64 != 0x0 && virt_64 != 0xffffffffffffffff); ep = virt_64; } if (!status) break; snprintf(fullname, sizeof(fullname), "%s%u", prefix, i); routine = try_to_demangle_routine(fullname); register_elf_entry_point(fmt, ep, 0, routine); } } if (_find_elf_dynamic_item_by_type(format, &dynamic, DT_INIT_ARRAY, &item_a)) { if (_find_elf_dynamic_item_by_type(format, &dynamic, DT_INIT_ARRAYSZ, &item_b)) { load_entry_points_from_array(format, &item_a, &item_b, "init_array_function_"); } } if (_find_elf_dynamic_item_by_type(format, &dynamic, DT_FINI_ARRAY, &item_a)) { if (_find_elf_dynamic_item_by_type(format, &dynamic, DT_FINI_ARRAYSZ, &item_b)) { load_entry_points_from_array(format, &item_a, &item_b, "fini_array_function_"); } } if (_find_elf_dynamic_item_by_type(format, &dynamic, DT_PREINIT_ARRAY, &item_a)) { if (_find_elf_dynamic_item_by_type(format, &dynamic, DT_PREINIT_ARRAYSZ, &item_b)) { load_entry_points_from_array(format, &item_a, &item_b, "preinit_array_function_"); } } /* Identification de l'entrée de la PLT */ if (_find_elf_dynamic_item_by_type(format, &dynamic, DT_PLTGOT, &item_a)) { status = g_exe_format_translate_address_into_vmpa(G_EXE_FORMAT(format), ELF_DYN(format, item_a, d_un.d_val), &pos); if (status) { content = G_BIN_FORMAT(format)->content; /* On saute le premier élément... */ if (format->is_32b) status = g_binary_content_read_u32(content, &pos, format->endian, &virt_32); else status = g_binary_content_read_u64(content, &pos, format->endian, &virt_64); while (1) { if (format->is_32b) { status = g_binary_content_read_u32(content, &pos, format->endian, &virt_32); ep = virt_32; } else { status = g_binary_content_read_u64(content, &pos, format->endian, &virt_64); ep = virt_64; } if (!status) break; if (ep != 0x0) { routine = try_to_demangle_routine("plt_entry"); register_elf_entry_point(format, ep, 0, routine); break; } } } } laebep_exit: return true; } /****************************************************************************** * * * Paramètres : loading = chargement de symboles en cours. * * format = format ELF à compléter. * * local = s'apprête-t-on à constuire un symbole interne ? * * iter = tête de lecture évoluant avec le temps. [OUT] * * new = éventuel renseignement du nouveau symbole. [OUT] * * * * Description : Assure le chargement des symboles internes ELF en différé. * * * * Retour : Bilan de l'exécution, utile pour la poursuite du traitement. * * * * Remarques : - * * * ******************************************************************************/ static bool do_elf_symbol_loading(GElfLoading *loading, GElfFormat *format, bool local, phys_t *iter, GBinSymbol **new) { bool result; /* Bilan à retourner */ elf_sym sym; /* Symbole aux infos visées */ virt_t virt; /* Adresse virtuelle */ SymbolStatus status; /* Visibilité du symbole */ GBinFormat *base; /* Version basique du format */ uint32_t index; /* Indice du nom du symbole */ const char *name; /* Nom du symbole trouvé */ GBinSymbol *symbol; /* Nouveau symbole construit */ char alt_name[6 + VMPA_MAX_LEN]; /* Nom abstrait de substitution*/ virt_t original_virt; /* Adresse virtuelle retenue */ vmpa2t addr; /* Localisation d'un symbole */ mrange_t range; /* Couverture mémoire associée */ GBinRoutine *routine; /* Nouvelle routine trouvée */ if (new != NULL) *new = NULL; result = read_elf_symbol(format, iter, &sym); if (!result) goto desl_done; /** * Si l'adresse virtuelle est nulle, on ne peut ratacher le symbole à aucune position... * * On ne réalise donc aucune opération ici, quitte à laisser une seconde passe * s'occuper des symboles importés par exemple. */ virt = ELF_SYM(format, sym, st_value); if (virt == 0) goto desl_done; /** * En ce qui concerne la nature de la visibilité, on distingue les deux situations suivantes : * - zone DYNSYM : uniquement les importations / exportations. * - zone SYMTAB : tous les symboles. * * La première zone doit donc être traitée en amont, et la seconde complète les traitements * avec à priori uniquement des symboles locaux. */ if (local) status = SSS_INTERNAL; else status = ELF_SYM(format, sym, st_shndx) == 0 ? SSS_IMPORTED : SSS_EXPORTED; /* Traitements particuliers */ base = G_BIN_FORMAT(format); index = ELF_SYM(format, sym, st_name); switch (ELF_ST_TYPE(format, sym)) { case STT_OBJECT: name = g_elf_loading_build_name(loading, index, virt, "obj_", alt_name, &addr); if (name == NULL) { symbol = NULL; break; } init_mrange(&range, &addr, ELF_SYM(format, sym, st_size)); symbol = g_binary_symbol_new(&range, STP_OBJECT); g_binary_symbol_set_alt_label(symbol, name); break; case STT_FUNC: original_virt = virt; /* Ajustement de la position */ virt = format->ops.fix_virt(virt); /* Constitution d'une routine */ name = g_elf_loading_build_name(loading, index, virt, "func_", alt_name, &addr); if (name == NULL) { symbol = NULL; break; } routine = try_to_demangle_routine(name); symbol = G_BIN_SYMBOL(routine); init_mrange(&range, &addr, ELF_SYM(format, sym, st_size)); g_binary_symbol_set_range(symbol, &range); /* Comptabilisation pour le désassemblage brut */ g_binary_format_register_code_point(base, original_virt, false); break; default: symbol = NULL; break; } if (symbol != NULL) { g_binary_symbol_set_status(symbol, status); if (new != NULL) { g_object_ref(G_OBJECT(symbol)); *new = symbol; } g_binary_format_add_symbol(base, symbol); } desl_done: return result; } /****************************************************************************** * * * Paramètres : format = description de l'exécutable à compléter. * * sym_start = localisation du début de la zone de symboles. * * count = nombre de descriptions de symbole attendues. * * str_start = début de la zone contenant les descriptions. * * wq = espace de travail dédié. * * gid = groupe de travail impliqué. * * callback = routine de traitements particuliers. * * status = barre de statut à tenir informée. * * msg = identifiant du message de progression. * * * * Description : Charge tous les symboles possibles. * * * * Retour : - * * * * Remarques : - * * * ******************************************************************************/ static void add_all_elf_symbols(GElfFormat *format, phys_t sym_start, size_t count, phys_t str_start, GWorkQueue *wq, wgroup_id_t gid, elf_loading_cb callback, GtkStatusStack *status, activity_id_t msg) { phys_t sym_size; /* Taille de chaque symbole lu */ guint runs_count; /* Qté d'exécutions parallèles */ phys_t run_size; /* Volume réparti par exécution*/ guint i; /* Boucle de parcours */ phys_t begin; /* Début de zone de traitement */ phys_t end; /* Fin d'un zone de traitement */ GElfLoading *loading; /* Tâche de chargement à lancer*/ sym_size = ELF_SIZEOF_SYM(format); runs_count = g_get_num_processors(); run_size = count / runs_count; gtk_status_stack_extend_activity(status, msg, count); for (i = 0; i < runs_count; i++) { begin = sym_start + i * run_size * sym_size; if ((i + 1) == runs_count) end = sym_start + count * sym_size; else end = begin + run_size * sym_size; loading = g_elf_loading_new_for_symbols(format, str_start, sym_start, begin, end, msg, callback); g_work_queue_schedule_work(wq, G_DELAYED_WORK(loading), gid); } } /* ---------------------------------------------------------------------------------- */ /* DETAIL DES SYMBOLES LOCAUX */ /* ---------------------------------------------------------------------------------- */ /****************************************************************************** * * * Paramètres : loading = chargement de symboles externes en cours. * * format = format ELF à compléter. * * iter = tête de lecture évoluant avec le temps. [OUT] * * * * Description : Assure le chargement des symboles locaux ELF en différé. * * * * Retour : Bilan de l'exécution, utile pour la poursuite du traitement. * * * * Remarques : - * * * ******************************************************************************/ static bool do_elf_local_symbol_loading(GElfLoading *loading, GElfFormat *format, phys_t *iter) { bool result; /* Bilan à retourner */ result = do_elf_symbol_loading(loading, format, true, iter, NULL); return result; } /****************************************************************************** * * * Paramètres : format = description de l'exécutable à compléter. * * gid = groupe de travail impliqué. * * status = barre de statut à tenir informée. * * * * Description : Charge tous les symboles internes possibles. * * * * Retour : Bilan de l'opération. * * * * Remarques : - * * * ******************************************************************************/ static bool load_elf_local_symbols(GElfFormat *format, wgroup_id_t gid, GtkStatusStack *status) { bool result; /* Bilan à retourner */ activity_id_t msg; /* Message de progression */ GWorkQueue *queue; /* Gestionnaire de différés */ size_t size; /* Taille de chaque symbole lu */ elf_shdr *symtabs; /* Groupe de sections trouvées */ size_t count; /* Quantité de données */ size_t i; /* Boucle de parcours */ phys_t sym_start; /* Début de la zone à traiter */ phys_t sym_size; /* Taille de cette même zone */ size_t sym_count; /* Nombre de symboles déduits */ elf_shdr strtab; /* Section dédiées aux chaînes */ phys_t str_start; /* Début de cette section */ result = true; msg = gtk_status_stack_add_activity(status, _("Loading local symbols..."), 0); queue = get_work_queue(); size = ELF_SIZEOF_SYM(format); if (find_elf_sections_by_type(format, SHT_SYMTAB, &symtabs, &count)) for (i = 0; i < count; i++) { get_elf_section_content(format, &symtabs[i], &sym_start, &sym_size, NULL); if (sym_size % size != 0) continue; sym_count = sym_size / size; if (!find_elf_section_by_index(format, ELF_SHDR(format, symtabs[i], sh_link), &strtab)) continue; get_elf_section_content(format, &strtab, &str_start, NULL, NULL); add_all_elf_symbols(format, sym_start, sym_count, str_start, queue, gid, do_elf_local_symbol_loading, status, msg); } g_work_queue_wait_for_completion(queue, gid); gtk_status_stack_remove_activity(status, msg); if (symtabs != NULL) free(symtabs); return result; } /* ---------------------------------------------------------------------------------- */ /* DETAIL DE SYMBOLES GLOBAUX */ /* ---------------------------------------------------------------------------------- */ /****************************************************************************** * * * Paramètres : loading = chargement de symboles externes en cours. * * format = format ELF à compléter. * * iter = tête de lecture évoluant avec le temps. [OUT] * * * * Description : Assure le chargement des symboles globaux ELF en différé. * * * * Retour : Bilan de l'exécution, utile pour la poursuite du traitement. * * * * Remarques : - * * * ******************************************************************************/ static bool do_elf_global_symbol_loading(GElfLoading *loading, GElfFormat *format, phys_t *iter) { bool result; /* Bilan à retourner */ GBinSymbol *symbol; /* Nouveau symbole en place */ result = do_elf_symbol_loading(loading, format, false, iter, &symbol); return result; } /****************************************************************************** * * * Paramètres : format = description de l'exécutable à consulter. * * exec = autre vision de ce format. * * count = nombre de symboles présents. [OUT] * * * * Description : Dénombre le nombre de symboles en lien avec l'extérieur. * * * * Retour : Bilan de l'opération. * * * * Remarques : - * * * ******************************************************************************/ static bool count_elf_global_symbols(GElfFormat *format, GExeFormat *exec, uint32_t *count) { bool result; /* Bilan à retourner */ elf_dyn hash; /* Table de type DT_HASH */ bool found; /* Détection validée */ vmpa2t addr; /* Position de départ brute */ result = false; /** * Cf. l'astuce indiquée par : * * - http://www.gabriel.urdhr.fr/2015/09/28/elf-file-format/#symbol-tables * - http://www.sco.com/developers/gabi/latest/ch5.dynamic.html#hash * */ found = find_elf_dynamic_item_by_type(format, DT_HASH, &hash); if (!found) goto cegs_exit; exec = G_EXE_FORMAT(format); result = g_exe_format_translate_address_into_vmpa(exec, ELF_DYN(format, hash, d_un.d_ptr), &addr); if (!result) goto cegs_exit; advance_vmpa(&addr, 4); result = g_binary_content_read_u32(G_BIN_FORMAT(format)->content, &addr, format->endian, count); if (!result) goto cegs_exit; cegs_exit: return result; } /****************************************************************************** * * * Paramètres : format = description de l'exécutable à compléter. * * gid = groupe de travail impliqué. * * status = barre de statut à tenir informée. * * * * Description : Charge tous les éléments dynamiques externes possibles. * * * * Retour : Bilan de l'opération. * * * * Remarques : - * * * ******************************************************************************/ static bool load_elf_global_symbols(GElfFormat *format, wgroup_id_t gid, GtkStatusStack *status) { bool result; /* Bilan à retourner */ GExeFormat *exec; /* Autre vision du format */ elf_dyn strtab; /* Table de type DT_STRTAB */ phys_t str_start; /* Début de zone des chaînes */ elf_dyn symtab; /* Table de type DT_SYMTAB */ phys_t sym_start; /* Début de zone des symboles */ uint32_t count; /* Nombre de symboles présents */ activity_id_t msg; /* Message de progression */ GWorkQueue *queue; /* Gestionnaire de différés */ result = true; /** * Les spécifications ne sont pas très claires sur le nombre de tables * possible... On y parle de LA table des symboles, ce qui laisse penser * qu'il ne peut y en avoir qu'une. */ exec = G_EXE_FORMAT(format); /* Récupération du début des chaînes de description */ result = find_elf_dynamic_item_by_type(format, DT_STRTAB, &strtab); if (!result) goto lees_exit; result = g_exe_format_translate_address_into_offset(exec, ELF_DYN(format, strtab, d_un.d_ptr), &str_start); if (!result) goto lees_exit; /* Récupération du début des définitions de symboles */ result = find_elf_dynamic_item_by_type(format, DT_SYMTAB, &symtab); if (!result) goto lees_exit; result = g_exe_format_translate_address_into_offset(exec, ELF_DYN(format, symtab, d_un.d_ptr), &sym_start); if (!result) goto lees_exit; /* Détermination du nombre d'éléments */ result = count_elf_global_symbols(format, exec, &count); if (!result) goto lees_exit; /* Chargement des symboles */ msg = gtk_status_stack_add_activity(status, _("Loading global symbols..."), 0); queue = get_work_queue(); add_all_elf_symbols(format, sym_start, count, str_start, queue, gid, do_elf_global_symbol_loading, status, msg); g_work_queue_wait_for_completion(queue, gid); gtk_status_stack_remove_activity(status, msg); lees_exit: return result; } /* ---------------------------------------------------------------------------------- */ /* PRISE EN COMPTE DE RELOCALISATIONS */ /* ---------------------------------------------------------------------------------- */ /****************************************************************************** * * * Paramètres : loading = chargement de relocalisations en cours. * * format = format ELF à compléter. * * iter = tête de lecture évoluant avec le temps. [OUT] * * * * Description : Assure le chargement des relocalisations ELF en différé. * * * * Retour : Bilan de l'exécution, utile pour la poursuite du traitement. * * * * Remarques : - * * * ******************************************************************************/ static bool do_elf_relocation_loading(GElfLoading *loading, GElfFormat *format, phys_t *iter) { bool result; /* Bilan à retourner */ elf_rel reloc; /* Relocalisation constituée */ result = read_elf_relocation(format, iter, &reloc); if (result) g_elf_loading_store_relocation(loading, iter, &reloc); return result; } /****************************************************************************** * * * Paramètres : format = informations chargées à consulter. * * dynamic = en-tête de programme de type DYNAMIC. * * relocs = liste des relocalisations triées à charger. [OUT] * * count = taille de cette liste. [OUT] * * status = barre de statut à tenir informée. * * * * Description : Charge en mémoire toutes les relocalisations présentes. * * * * Retour : Bilan de l'opération. * * * * Remarques : - * * * ******************************************************************************/ static bool load_elf_relocations(GElfFormat *format, const elf_phdr *dynamic, elf_rel **relocs, size_t *count, GtkStatusStack *status) { bool result; /* Bilan à retourner */ GExeFormat *exec; /* Autre vision du format */ elf_dyn jmprel; /* Table des relocalisations */ vmpa2t start; /* Position de départ brute */ elf_dyn pltrelsz; /* Taille de table en octets */ uint64_t length; /* Nombre total des éléments */ mrange_t shr_range; /* Emplacement des relocs. #1 */ mrange_t phr_range; /* Emplacement des relocs. #2 */ phys_t rel_size; /* Taille de chaque élément lu */ bool ret; /* Bilan d'un appel */ activity_id_t msg; /* Message de progression */ GWorkQueue *queue; /* Gestionnaire de différés */ wgroup_id_t gid; /* Identifiant pour les tâches */ guint runs_count; /* Qté d'exécutions parallèles */ phys_t run_size; /* Volume réparti par exécution*/ GElfLoading **loadings; /* Tâches de chargement */ guint i; /* Boucle de parcours */ phys_t begin; /* Début de zone de traitement */ phys_t end; /* Fin d'un zone de traitement */ result = true; *relocs = NULL; *count = 0; exec = G_EXE_FORMAT(format); /* Collecte des informations */ if (!_find_elf_dynamic_item_by_type(format, dynamic, DT_JMPREL, &jmprel)) goto ler_exit; result = g_exe_format_translate_address_into_vmpa(exec, ELF_DYN(format, jmprel, d_un.d_ptr), &start); if (!result) goto ler_exit; if (!_find_elf_dynamic_item_by_type(format, dynamic, DT_PLTRELSZ, &pltrelsz)) goto ler_exit; length = ELF_DYN(format, pltrelsz, d_un.d_val); /* Corrélation des informations */ ret = find_elf_section_range_by_name(format, ".rel.plt", &shr_range); if (ret) { init_mrange(&phr_range, &start, length); if (cmp_mrange(&phr_range, &shr_range) != 0) log_simple_message(LMT_BAD_BINARY, _("The linker PLT and the PLT section differ by their area definition.")); } /* Détermination du nombre d'éléments */ rel_size = ELF_SIZEOF_REL(format); if (length % rel_size != 0) { result = false; goto ler_exit; } length /= rel_size; /* Chargement en mémoire des relocalisations */ if (length == 0) goto ler_exit; *relocs = (elf_rel *)malloc(length * sizeof(elf_rel)); *count = length; msg = gtk_status_stack_add_activity(status, _("Loading relocations..."), length); queue = get_work_queue(); gid = g_work_queue_define_work_group(queue); runs_count = g_get_num_processors(); run_size = length / runs_count; loadings = (GElfLoading **)malloc(runs_count * sizeof(GElfLoading *)); for (i = 0; i < runs_count; i++) { begin = get_phy_addr(&start) + i * run_size * rel_size; if ((i + 1) == runs_count) end = get_phy_addr(&start) + length * rel_size; else end = begin + run_size * rel_size; loadings[i] = g_elf_loading_new_for_relocations(format, begin, end, (*relocs) + i * run_size, msg, do_elf_relocation_loading); g_object_ref(G_OBJECT(loadings[i])); g_work_queue_schedule_work(queue, G_DELAYED_WORK(loadings[i]), gid); } g_work_queue_wait_for_completion(queue, gid); gtk_status_stack_remove_activity(status, msg); /* Vérifications du bon déroulement */ for (i = 0; i < runs_count; i++) { result &= g_elf_loading_get_status(loadings[i]); g_object_ref(G_OBJECT(loadings[i])); } free(loadings); if (!result) { free(*relocs); goto ler_exit; } /* Tri de la liste obtenue */ int compare_relocations(const elf_rel *a, const elf_rel *b) { return sort_uint64_t(ELF_REL(format, *a, r_offset), ELF_REL(format, *b, r_offset)); } qsort(*relocs, *count, sizeof(elf_rel), (__compar_fn_t)compare_relocations); ler_exit: return result; } /****************************************************************************** * * * Paramètres : format = informations chargées à consulter. * * status = barre de statut à tenir informée. * * * * Description : Actualise la désignation des fonctions externes à reloger. * * * * Retour : Bilan de l'opération. * * * * Remarques : - * * * ******************************************************************************/ bool refresh_elf_relocations(GElfFormat *format, GtkStatusStack *status) { bool result; /* Bilan à retourner */ elf_phdr dynamic; /* En-tête de programme DYNAMIC*/ elf_rel *relocs; /* Relocalisations présentes */ size_t rel_count; /* Qté de ces relocalisations */ virt_t plt_virt; /* Adresse de la PLT */ GExeFormat *exec; /* Autre vision du format */ vmpa2t plt_addr; /* Localisation complète */ GBinFormat *base; /* Autre vision du format */ size_t first; /* Indice du premier symbole */ sym_iter_t *iter; /* Boucle de parcours */ result = true; if (!find_elf_dynamic_program_header(format, &dynamic)) goto rer_quick_exit; /* Chargement des relocalisations */ if (!load_elf_relocations(format, &dynamic, &relocs, &rel_count, status)) goto rer_quick_exit; /* Localisation du code de la PLT */ if (!resolve_plt_using_got(format, &plt_virt)) goto rer_exit; exec = G_EXE_FORMAT(format); if (!g_exe_format_translate_address_into_vmpa(exec, plt_virt, &plt_addr)) goto rer_exit; /* Parcours des symboles */ base = G_BIN_FORMAT(format); /** * Il existe normalement un symbole "plt_entry" créé au chargement des symboles... */ g_binary_format_lock_symbols_rd(base); result = g_binary_format_find_symbol_index_at(base, &plt_addr, &first); if (result) iter = create_symbol_iterator(base, first); g_binary_format_unlock_symbols_rd(base); if (result) { result = apply_elf_relocations(format, relocs, rel_count, iter, status); delete_symbol_iterator(iter); } rer_exit: if (relocs != NULL) free(relocs); rer_quick_exit: return result; } /****************************************************************************** * * * Paramètres : loading = chargement de relocalisations en cours. * * format = format ELF à compléter. * * symbol = symbole courant issu de la liste à analyser. * * * * Description : Assure l'intégration d'un symbole issu des relocalisations. * * * * Retour : Bilan de l'exécution, utile pour la poursuite du traitement. * * * * Remarques : - * * * ******************************************************************************/ static bool do_elf_relocation_renaming(GElfLoading *loading, GElfFormat *format, GBinSymbol *symbol) { bool result; /* Bilan à retourner */ const mrange_t *range; /* Espace occupé par le symbole*/ SymbolType stype; /* Type de symbole présenté */ uint64_t offset; /* Décalage à retrouver */ elf_rel *reloc; /* Infos de relocalisation */ uint64_t index; /* Indice du symbole concerné */ char *name; /* Nouvelle désignation */ #ifndef NDEBUG const char *label; /* Etiquette courante */ #endif result = false; range = g_binary_symbol_get_range(symbol); stype = g_binary_symbol_get_target_type(symbol); if (stype != STP_ROUTINE && stype != STP_CODE_LABEL && stype != STP_ENTRY_POINT) { g_binary_format_add_error(G_BIN_FORMAT(format), BFE_SPECIFICATION, get_mrange_addr(range), _("The PLT seems to contains more than routines")); goto derr_exit; } /* Assurance du port du type adapté */ g_binary_symbol_set_status(symbol, SSS_IMPORTED); /* Détermination de la relocalisation associée */ result = format->ops.get_linkage_offset(format, range, &offset); if (!result) goto derr_exit; result = g_elf_loading_search_for_relocation(loading, &offset, &reloc); if (!result) goto derr_exit; /* Récupération des données du symbole visé */ index = ELF_REL_SYM(format, *reloc); name = g_elf_loading_build_plt_name(loading, index); #ifndef NDEBUG label = g_binary_symbol_get_label(symbol); if (strncmp(label, "sub_", 4) != 0 && strncmp(label, "loc_", 4) != 0) { if (strncmp(name, label, strlen(label)) != 0) g_binary_format_add_error(G_BIN_FORMAT(format), BFE_SPECIFICATION, get_mrange_addr(range), _("Mismatch detected in the ELF symbol address")); } #endif g_binary_symbol_set_alt_label(symbol, name); free(name); derr_exit: return result; } /****************************************************************************** * * * Paramètres : format = format ELF à compléter. * * relocs = table des relocalisations chargées. * * rel_count = nombre de ces éléments à interpréter. * * iter = itérateur sur les symboles à parcourir. * * status = barre de statut à tenir informée. * * * * Description : Applique les étiquettes issues des relocalisations. * * * * Retour : Bilan des traitements. * * * * Remarques : - * * * ******************************************************************************/ static bool apply_elf_relocations(GElfFormat *format, elf_rel *relocs, size_t rel_count, sym_iter_t *iter, GtkStatusStack *status) { bool result; /* Bilan à retourner */ GExeFormat *exec; /* Autre vision du format */ elf_dyn strtab; /* Table de type DT_STRTAB */ phys_t str_start; /* Début de zone des chaînes */ elf_dyn symtab; /* Table de type DT_SYMTAB */ phys_t sym_start; /* Début de zone des symboles */ uint32_t sym_count; /* Nombre de symboles présents */ activity_id_t msg; /* Message de progression */ GWorkQueue *queue; /* Gestionnaire de différés */ wgroup_id_t gid; /* Identifiant pour les tâches */ GElfLoading *loading; /* Tâche de chargement */ exec = G_EXE_FORMAT(format); /* Récupération du début des chaînes de description */ result = find_elf_dynamic_item_by_type(format, DT_STRTAB, &strtab); if (!result) goto aer_exit; result = g_exe_format_translate_address_into_offset(exec, ELF_DYN(format, strtab, d_un.d_ptr), &str_start); if (!result) goto aer_exit; /* Récupération du début des définitions de symboles */ result = find_elf_dynamic_item_by_type(format, DT_SYMTAB, &symtab); if (!result) goto aer_exit; result = g_exe_format_translate_address_into_offset(exec, ELF_DYN(format, symtab, d_un.d_ptr), &sym_start); if (!result) goto aer_exit; /* Détermination du nombre d'éléments */ result = count_elf_global_symbols(format, exec, &sym_count); if (!result) goto aer_exit; /* Mise en application des références externes */ msg = gtk_status_stack_add_activity(status, _("Applying relocations..."), rel_count); queue = get_work_queue(); gid = g_work_queue_define_work_group(queue); loading = g_elf_loading_new_for_applying(format, iter, str_start, relocs, rel_count, sym_start, sym_count, msg, do_elf_relocation_renaming); g_object_ref(G_OBJECT(loading)); g_work_queue_schedule_work(queue, G_DELAYED_WORK(loading), gid); g_work_queue_wait_for_completion(queue, gid); gtk_status_stack_remove_activity(status, msg); /* Vérification du bon déroulement */ result = g_elf_loading_get_status(loading); g_object_unref(G_OBJECT(loading)); aer_exit: return result; }