/* OpenIDA - Outil d'analyse de fichiers binaires
 * pool.c - opérandes pointant vers la table des constantes
 *
 * Copyright (C) 2010-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 "pool.h"


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


#include <i18n.h>


#include "../../operand-int.h"
#include "../../../format/dex/pool.h"



/* Définition d'un opérande visant un élément de table de constantes Dalvik (instance) */
struct _GDalvikPoolOperand
{
    GArchOperand parent;                    /* Instance parente            */

    const GDexFormat *format;               /* Lien vers le contenu réel   */
    DalvikPoolType type;                    /* Type de table visée         */
    uint32_t index;                         /* Indice de l'élément visé    */

};


/* Définition d'un opérande visant un élément de table de constantes Dalvik (classe) */
struct _GDalvikPoolOperandClass
{
    GArchOperandClass parent;               /* Classe parente              */

};


/* Initialise la classe des opérandes de constante Dalvik. */
static void g_dalvik_pool_operand_class_init(GDalvikPoolOperandClass *);

/* Initialise une instance d'opérande de constante Dalvik. */
static void g_dalvik_pool_operand_init(GDalvikPoolOperand *);

/* Traduit un opérande en version humainement lisible. */
static void g_dalvik_pool_operand_print(const GDalvikPoolOperand *, GBufferLine *, AsmSyntax);



/* Indique le type défini par la GLib pour un un élément de table de constantes Dalvik. */
G_DEFINE_TYPE(GDalvikPoolOperand, g_dalvik_pool_operand, G_TYPE_ARCH_OPERAND);


/******************************************************************************
*                                                                             *
*  Paramètres  : klass = classe à initialiser.                                *
*                                                                             *
*  Description : Initialise la classe des opérandes de constante Dalvik.      *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void g_dalvik_pool_operand_class_init(GDalvikPoolOperandClass *klass)
{

}


/******************************************************************************
*                                                                             *
*  Paramètres  : operand = instance à initialiser.                            *
*                                                                             *
*  Description : Initialise une instance d'opérande de constante Dalvik.      *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void g_dalvik_pool_operand_init(GDalvikPoolOperand *operand)
{
    GArchOperand *parent;                   /* Instance parente            */

    parent = G_ARCH_OPERAND(operand);

    parent->print = (operand_print_fc)g_dalvik_pool_operand_print;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : format = format du fichier contenant le code.                *
*                type   = type de table visée avec la référence.              *
*                data   = flux de données à analyser.                         *
*                pos    = position courante dans ce flux. [OUT]               *
*                len    = taille totale des données à analyser.               *
*                size   = taille de l'opérande, et donc du registre.          *
*                endian = ordre des bits dans la source.                      *
*                                                                             *
*  Description : Crée un opérande visant un élément constant Dalvik.          *
*                                                                             *
*  Retour      : Opérande mis en place.                                       *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

GArchOperand *g_dalvik_pool_operand_new(const GDexFormat *format, DalvikPoolType type, const bin_t *data, off_t *pos, off_t len, MemoryDataSize size, SourceEndian endian)
{
    GDalvikPoolOperand *result;             /* Structure à retourner       */
    uint8_t index8;                         /* Indice sur 8 bits           */
    uint16_t index16;                       /* Indice sur 16 bits          */
    bool test;                              /* Bilan de lecture            */

    switch (size)
    {
        case MDS_8_BITS:
            test = read_u8(&index8, data, pos, len, endian);
            break;
        case MDS_16_BITS:
            test = read_u16(&index16, data, pos, len, endian);
            break;
        default:
            test = false;
            break;
    }

    if (!test)
        return NULL;

    result = g_object_new(G_TYPE_DALVIK_POOL_OPERAND, NULL);

    result->format = format;
    result->type = type;
    result->index = (size == MDS_8_BITS ? index8 : index16);

    return G_ARCH_OPERAND(result);

}


/******************************************************************************
*                                                                             *
*  Paramètres  : operand = opérande à traiter.                                *
*                line    = ligne tampon où imprimer l'opérande donné.         *
*                syntax  = type de représentation demandée.                   *
*                                                                             *
*  Description : Traduit un opérande en version humainement lisible.          *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void g_dalvik_pool_operand_print(const GDalvikPoolOperand *operand, GBufferLine *line, AsmSyntax syntax)
{
    const char *string;                     /* Chaîne de caractères #1     */
    GDataType *type;                        /* Type à représenter          */
    size_t len;                             /* Taille du texte à créer     */
    char *tmp;                              /* Chaîne de caractères #2     */
    GBinVariable *field;                    /* Champ à représenter         */
    GBinRoutine *routine;                   /* Routine à représenter       */

    switch (operand->type)
    {
        case DPT_NONE:
            g_buffer_line_insert_text(line, BLC_ASSEMBLY, "????", 4, RTT_ERROR);
            break;

        case DPT_STRING:
            string = get_string_from_dex_pool(operand->format, operand->index);

            if (string != NULL)
            {
                g_buffer_line_insert_text(line, BLC_ASSEMBLY, "\"", 1, RTT_STRING);
                g_buffer_line_insert_text(line, BLC_ASSEMBLY, string, strlen(string), RTT_STRING);
                g_buffer_line_insert_text(line, BLC_ASSEMBLY, "\"", 1, RTT_STRING);
            }
            else
            {
                len = strlen(_("<bad string index (%d)>")) + 10 /* 4294967295U */ + 1;
                tmp = calloc(len, sizeof(char));
                snprintf(tmp, len, _("<bad string index (%d)>"), operand->index);

                g_buffer_line_insert_text(line, BLC_ASSEMBLY, tmp, len - 1, RTT_ERROR);

                free(tmp);

            }

            break;

        case DPT_TYPE:
            type = get_type_from_dex_pool(operand->format, operand->index);

            if (type != NULL)
            {
                tmp = g_data_type_to_string(type);
                g_object_unref(G_OBJECT(type));

                g_buffer_line_insert_text(line, BLC_ASSEMBLY, "<", 1, RTT_HOOK);
                g_buffer_line_insert_text(line, BLC_ASSEMBLY, tmp, strlen(tmp), RTT_VAR_NAME);
                g_buffer_line_insert_text(line, BLC_ASSEMBLY, ">", 1, RTT_HOOK);

            }
            else
            {
                len = strlen(_("<bad type index (%d)>")) + 10 /* 4294967295U */ + 1;
                tmp = calloc(len, sizeof(char));
                snprintf(tmp, len, _("<bad type index (%d)>"), operand->index);

                g_buffer_line_insert_text(line, BLC_ASSEMBLY, tmp, len - 1, RTT_ERROR);

            }

            free(tmp);

            break;

        case DPT_PROTO:
            g_buffer_line_insert_text(line, BLC_ASSEMBLY, "proto(/*TODO*/)", 5, RTT_SECTION);
            break;

        case DPT_FIELD:
            field = get_field_from_dex_pool(operand->format, operand->index);

            if (field != NULL)
            {
                tmp = g_binary_variable_to_string(field, false);
                g_object_unref(G_OBJECT(field));

                g_buffer_line_insert_text(line, BLC_ASSEMBLY, "<", 1, RTT_HOOK);
                g_buffer_line_insert_text(line, BLC_ASSEMBLY, tmp, strlen(tmp), RTT_VAR_NAME);
                g_buffer_line_insert_text(line, BLC_ASSEMBLY, ">", 1, RTT_HOOK);

            }
            else
            {
                len = strlen(_("<bad field index (%d)>")) + 10 /* 4294967295U */ + 1;
                tmp = calloc(len, sizeof(char));
                snprintf(tmp, len, _("<bad field index (%d)>"), operand->index);

                g_buffer_line_insert_text(line, BLC_ASSEMBLY, tmp, len - 1, RTT_ERROR);

            }

            free(tmp);

            break;

        case DPT_METHOD:
            routine = get_routine_from_dex_pool(operand->format, operand->index);

            if (routine != NULL)
            {
                tmp = g_binary_routine_to_string(routine);
                g_object_unref(G_OBJECT(routine));

                g_buffer_line_insert_text(line, BLC_ASSEMBLY, "<", 1, RTT_HOOK);
                g_buffer_line_insert_text(line, BLC_ASSEMBLY, tmp, strlen(tmp), RTT_VAR_NAME);
                g_buffer_line_insert_text(line, BLC_ASSEMBLY, ">", 1, RTT_HOOK);

            }
            else
            {
                len = strlen(_("<bad method index (%d)>")) + 10 /* 4294967295U */ + 1;
                tmp = calloc(len, sizeof(char));
                snprintf(tmp, len, _("<bad method index (%d)>"), operand->index);

                g_buffer_line_insert_text(line, BLC_ASSEMBLY, tmp, len - 1, RTT_ERROR);

            }

            free(tmp);

            break;

    }

}


/******************************************************************************
*                                                                             *
*  Paramètres  : operand = opérande à consulter.                              *
*                                                                             *
*  Description : Indique la nature de la table de constantes visée ici.       *
*                                                                             *
*  Retour      : Type de table constantes visée.                              *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

DalvikPoolType g_dalvik_pool_operand_get_pool_type(const GDalvikPoolOperand *operand)
{
    return operand->type;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : operand = opérande à consulter.                              *
*                                                                             *
*  Description : Indique l'indice de l'élément dans la table de constantes.   *
*                                                                             *
*  Retour      : Indice de l'élément visé dans la table de constantes.        *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

uint32_t g_dalvik_pool_operand_get_index(const GDalvikPoolOperand *operand)
{
    return operand->index;

}