/* Chrysalide - Outil d'analyse de fichiers binaires
 * immediate.c - opérandes représentant des valeurs numériques
 *
 * Copyright (C) 2020-2024 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 "immediate.h"


#include <assert.h>
#include <stdarg.h>



#if 0

#include <ctype.h>
#include <inttypes.h>
#include <limits.h>
#include <malloc.h>
#include <stdio.h>


#include <i18n.h>

#endif



#include "immediate-int.h"
#include "../../common/asm.h"
#include "../../common/sort.h"
#include "../../glibext/comparable-int.h"
#include "../../glibext/hashable-int.h"
#include "../../glibext/serialize-int.h"
#include "../../glibext/strbuilder-int.h"



/* ------------------------- OPERANDE POUR VALEUR IMMEDIATE ------------------------- */


/* Initialise la classe des opérandes de valeur immédiate. */
static void g_immediate_operand_class_init(GImmediateOperandClass *);

/* Procède à l'initialisation de l'interface de comparaison. */
static void g_immediate_operand_comparable_object_iface_init(GComparableObjectInterface *);

/* Procède à l'initialisation de l'interface de détermination. */
static void g_immediate_operand_hashable_object_iface_init(GHashableObjectInterface *);

/* Procède à l'initialisation de l'interface de sérialisation. */
static void g_immediate_operand_serializable_iface_init(GSerializableObjectInterface *);

/* Procède à l'initialisation de l'interface d'exportation. */
static void g_immediate_operand_string_builder_iface_init(GStringBuilderInterface *, gpointer);

#if 0

/* Procède à l'initialisation de l'interface de ciblage. */
static void g_immediate_operand_targetable_interface_init(GTargetableOperandInterface *);

/* Procède à l'initialisation de l'interface de renommage. */
static void g_immediate_operand_renameable_interface_init(GRenameableOperandInterface *);

#endif

/* Initialise un opérande de valeur immédiate. */
static void g_immediate_operand_init(GImmediateOperand *);

/* Supprime toutes les références externes. */
static void g_immediate_operand_dispose(GObject *);

/* Procède à la libération totale de la mémoire. */
static void g_immediate_operand_finalize(GObject *);



/* ---------------------- COMPARAISON DETAILLEE DE DEUX OBJETS ---------------------- */


/* Réalise une comparaison étendue entre objets. */
static int g_immediate_operand_compare(const GComparableObject *, const GComparableObject *);



/* ---------------------- CALCUL D'UNE EMPREINTE DE L'INSTANCE ---------------------- */


/* Calcule l'empreinte sur 32 bits d'un objet. */
static guint g_immediate_operand_hash(const GHashableObject *);



/* ------------------- MECANISMES DE CONSERVATION ET RESTAURATION ------------------- */


/* Charge un objet depuis un flux de données. */
static bool g_immediate_operand_load(GSerializableObject *, GObjectStorage *, int);

/* Sauvegarde un objet dans un flux de données. */
static bool g_immediate_operand_store(const GSerializableObject *, GObjectStorage *, int);



/* ----------------- EXPORTATION SOUS FORME DE CHAINE DE CARACTERES ----------------- */


/* Exporte une chaîne de caractères à partir d'un objet. */
static bool g_immediate_operand_to_string(const GStringBuilder *, unsigned int, sized_binary_t *);





/* ---------------------------------------------------------------------------------- */
/*                           OPERANDE POUR VALEUR IMMEDIATE                           */
/* ---------------------------------------------------------------------------------- */


/* Indique le type défini pour un opérande de valeur numérique. */
G_DEFINE_TYPE_WITH_CODE(GImmediateOperand, g_immediate_operand, G_TYPE_ARCH_OPERAND,
                        G_IMPLEMENT_INTERFACE(G_TYPE_COMPARABLE_OBJECT, g_immediate_operand_comparable_object_iface_init)
                        G_IMPLEMENT_INTERFACE(G_TYPE_HASHABLE_OBJECT, g_immediate_operand_hashable_object_iface_init)
                        G_IMPLEMENT_INTERFACE(G_TYPE_SERIALIZABLE_OBJECT, g_immediate_operand_serializable_iface_init)
                        G_IMPLEMENT_INTERFACE(G_TYPE_STRING_BUILDER, g_immediate_operand_string_builder_iface_init)
                        G_IMPLEMENT_INTERFACE_IF_SYM(g_arch_operand_ui_get_type, g_immediate_operand_ui_arch_operand_ui_iface_init));


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

static void g_immediate_operand_class_init(GImmediateOperandClass *klass)
{
    GObjectClass *object;                   /* Autre version de la classe  */

    object = G_OBJECT_CLASS(klass);

    object->dispose = g_immediate_operand_dispose;
    object->finalize = g_immediate_operand_finalize;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : iface = interface GLib à initialiser.                        *
*                                                                             *
*  Description : Procède à l'initialisation de l'interface de comparaison.    *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void g_immediate_operand_comparable_object_iface_init(GComparableObjectInterface *iface)
{
    iface->compare = g_immediate_operand_compare;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : iface = interface GLib à initialiser.                        *
*                                                                             *
*  Description : Procède à l'initialisation de l'interface de détermination.  *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void g_immediate_operand_hashable_object_iface_init(GHashableObjectInterface *iface)
{
    iface->hash = g_immediate_operand_hash;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : iface = interface GLib à initialiser.                        *
*                                                                             *
*  Description : Procède à l'initialisation de l'interface de sérialisation.  *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void g_immediate_operand_serializable_iface_init(GSerializableObjectInterface *iface)
{
    iface->load = g_immediate_operand_load;
    iface->store = g_immediate_operand_store;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : iface  = interface GLib à initialiser.                       *
*                unused = pointeur non utilisé ici.                           *
*                                                                             *
*  Description : Procède à l'initialisation de l'interface d'exportation.     *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void g_immediate_operand_string_builder_iface_init(GStringBuilderInterface *iface, gpointer unused)
{
    iface->to_string = g_immediate_operand_to_string;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : operand = instance à initialiser.                            *
*                                                                             *
*  Description : Initialise un opérande de valeur immédiate.                  *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void g_immediate_operand_init(GImmediateOperand *operand)
{
    immop_extra_data_t extra;               /* Données insérées à consulter*/

    extra = GET_IMM_OP_EXTRA(operand);

    extra.size = MDS_UNDEFINED;

    extra.def_display = IOD_HEX;
    extra.display = IOD_COUNT;

    SET_IMM_OP_EXTRA(operand, &extra);

    operand->raw = 0;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : object = instance d'objet GLib à traiter.                    *
*                                                                             *
*  Description : Supprime toutes les références externes.                     *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void g_immediate_operand_dispose(GObject *object)
{
    G_OBJECT_CLASS(g_immediate_operand_parent_class)->dispose(object);

}


/******************************************************************************
*                                                                             *
*  Paramètres  : object = instance d'objet GLib à traiter.                    *
*                                                                             *
*  Description : Procède à la libération totale de la mémoire.                *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void g_immediate_operand_finalize(GObject *object)
{
    G_OBJECT_CLASS(g_immediate_operand_parent_class)->finalize(object);

}


/******************************************************************************
*                                                                             *
*  Paramètres  : size  = taille de l'opérande souhaitée.                      *
*                value = valeur sur x bits à venir récupérer.                 *
*                                                                             *
*  Description : Crée un opérande réprésentant une valeur numérique.          *
*                                                                             *
*  Retour      : Instruction mise en place.                                   *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

GArchOperand *g_immediate_operand_new_from_value(MemoryDataSize size, uint64_t value)
{
    GImmediateOperand *result;                    /* Opérande à retourner        */

    result = g_object_new(G_TYPE_IMMEDIATE_OPERAND, NULL);

    if (!g_immediate_operand_create_from_value(result, size, value))
        g_clear_object(&result);

    return G_ARCH_OPERAND(result);

}


/******************************************************************************
*                                                                             *
*  Paramètres  : operand = instance à initialiser pleinement.                 *
*                size    = taille de l'opérande souhaitée.                    *
*                value   = valeur sur x bits à venir récupérer.               *
*                                                                             *
*  Description : Met en place un opérande réprésentant une valeur numérique.  *
*                                                                             *
*  Retour      : Bilan de l'opération.                                        *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

bool g_immediate_operand_create_from_value(GImmediateOperand *operand, MemoryDataSize size, uint64_t value)
{
    bool result;                            /* Bilan à retourner           */
    immop_extra_data_t extra;               /* Données insérées à consulter*/

    result = (size != MDS_UNDEFINED);

    if (result)
    {
        extra = GET_IMM_OP_EXTRA(operand);

        extra.size = size;

        operand->raw = value;

        SET_IMM_OP_EXTRA(operand, &extra);

    }

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : size    = taille de l'opérande souhaitée.                    *
*                content = flux de données à analyser.                        *
*                addr    = position courante dans ce flux. [OUT]              *
*                low     = position éventuelle des 4 bits visés. [OUT]        *
*                endian  = ordre des bits dans la source.                     *
*                                                                             *
*  Description : Crée un opérande réprésentant une valeur numérique.          *
*                                                                             *
*  Retour      : Instruction mise en place.                                   *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

GArchOperand *g_immediate_operand_new_from_data(MemoryDataSize size, const GBinContent *content, vmpa2t *addr, bool *low, SourceEndian endian)
{
    GImmediateOperand *result;                    /* Opérande à retourner        */

    result = g_object_new(G_TYPE_IMMEDIATE_OPERAND, NULL);

    if (!g_immediate_operand_create_from_data(result, size, content, addr, low, endian))
        g_clear_object(&result);

    return G_ARCH_OPERAND(result);

}


/******************************************************************************
*                                                                             *
*  Paramètres  : operand = instance à initialiser pleinement.                 *
*                size    = taille de l'opérande souhaitée.                    *
*                content = flux de données à analyser.                        *
*                addr    = position courante dans ce flux. [OUT]              *
*                low     = position éventuelle des 4 bits visés. [OUT]        *
*                endian  = ordre des bits dans la source.                     *
*                                                                             *
*  Description : Crée un opérande réprésentant une valeur numérique.          *
*                                                                             *
*  Retour      : Instruction mise en place.                                   *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

bool g_immediate_operand_create_from_data(GImmediateOperand *operand, MemoryDataSize size, const GBinContent *content, vmpa2t *addr, bool *low, SourceEndian endian)
{
    bool result;                            /* Bilan à retourner           */
    uint64_t raw;                           /* Valeur brute lue            */
    uint8_t uval8;                          /* Valeur sur 8 bits           */
    uint16_t uval16;                        /* Valeur sur 16 bits          */
    uint32_t uval32;                        /* Valeur sur 32 bits          */
    uint64_t uval64;                        /* Valeur sur 64 bits          */
    int8_t sval8;                           /* Valeur sur 8 bits           */
    int16_t sval16;                         /* Valeur sur 16 bits          */
    int32_t sval32;                         /* Valeur sur 32 bits          */
    int64_t sval64;                         /* Valeur sur 64 bits          */

    switch (size)
    {
        case MDS_4_BITS_UNSIGNED:
            result = g_binary_content_read_u4(content, addr, low, &uval8);
            if (result)
                raw = uval8;
            break;

        case MDS_8_BITS_UNSIGNED:
            result = g_binary_content_read_u8(content, addr, &uval8);
            if (result)
                raw = uval8;
            break;

        case MDS_16_BITS_UNSIGNED:
            result = g_binary_content_read_u16(content, addr, endian, &uval16);
            if (result)
                raw = uval16;
            break;

        case MDS_32_BITS_UNSIGNED:
            result = g_binary_content_read_u32(content, addr, endian, &uval32);
            if (result)
                raw = uval32;
            break;

        case MDS_64_BITS_UNSIGNED:
            result = g_binary_content_read_u64(content, addr, endian, &uval64);
            if (result)
                raw = uval64;
            break;

        case MDS_4_BITS_SIGNED:
            result = g_binary_content_read_s4(content, addr, low, &sval8);
            if (result)
                raw = sval8;
            break;

        case MDS_8_BITS_SIGNED:
            result = g_binary_content_read_s8(content, addr, &sval8);
            if (result)
                raw = sval8;
            break;

        case MDS_16_BITS_SIGNED:
            result = g_binary_content_read_s16(content, addr, endian, &sval16);
            if (result)
                raw = sval16;
            break;

        case MDS_32_BITS_SIGNED:
            result = g_binary_content_read_s32(content, addr, endian, &sval32);
            if (result)
                raw = sval32;
            break;

        case MDS_64_BITS_SIGNED:
            result = g_binary_content_read_s64(content, addr, endian, &sval64);
            if (result)
                raw = sval64;
            break;

        case MDS_UNDEFINED:
            result = false;
            break;

    }

    if (result)
        result = g_immediate_operand_create_from_value(operand, size, raw);

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : operand = structure dont le contenu est à consulter.         *
*                                                                             *
*  Description : Renseigne la taille de la valeur indiquée à la construction. *
*                                                                             *
*  Retour      : Taille de la valeur représentée en mémoire.                  *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

MemoryDataSize g_immediate_operand_get_size(const GImmediateOperand *operand)
{
    MemoryDataSize result;                  /* Taille à retourner          */
    immop_extra_data_t extra;               /* Données insérées à consulter*/

    extra = GET_IMM_OP_EXTRA(operand);

    result = extra.size;

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : operand = structure dont le contenu est à consulter.         *
*                size  = taille de l'opérande souhaitée.                      *
*                ...  = valeur sur x bits à venir récupérer.                  *
*                                                                             *
*  Description : Fournit la valeur portée par une opérande numérique.         *
*                                                                             *
*  Retour      : Bilan de l'opération.                                        *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

bool g_immediate_operand_get_value(const GImmediateOperand *operand, MemoryDataSize size, ...)
{
    bool result;                            /* Bilan à retourner           */
    immop_extra_data_t extra;               /* Données insérées à consulter*/
    va_list ap;                             /* Liste des compléments       */
    uint8_t *uval8;                         /* Valeur sur 8 bits           */
    uint16_t *uval16;                       /* Valeur sur 16 bits          */
    uint32_t *uval32;                       /* Valeur sur 32 bits          */
    uint64_t *uval64;                       /* Valeur sur 64 bits          */
    int8_t *sval8;                          /* Valeur sur 8 bits           */
    int16_t *sval16;                        /* Valeur sur 16 bits          */
    int32_t *sval32;                        /* Valeur sur 32 bits          */
    int64_t *sval64;                        /* Valeur sur 64 bits          */

    result = false;

    extra = GET_IMM_OP_EXTRA(operand);

    if (extra.size != size)
        goto exit;

    va_start(ap, size);

    switch (size)
    {
        /* Pour GCC... */
        case MDS_UNDEFINED:
            goto exit;
            break;
        case MDS_4_BITS_UNSIGNED:
        case MDS_8_BITS_UNSIGNED:
            uval8 = va_arg(ap, uint8_t *);
            *uval8 = operand->raw;
            break;
        case MDS_16_BITS_UNSIGNED:
            uval16 = va_arg(ap, uint16_t *);
            *uval16 = operand->raw;
            break;
        case MDS_32_BITS_UNSIGNED:
            uval32 = va_arg(ap, uint32_t *);
            *uval32 = operand->raw;
            break;
        case MDS_64_BITS_UNSIGNED:
            uval64 = va_arg(ap, uint64_t *);
            *uval64 = operand->raw;
            break;
        case MDS_4_BITS_SIGNED:
        case MDS_8_BITS_SIGNED:
            sval8 = va_arg(ap, int8_t *);
            *sval8 = operand->raw;
            break;
        case MDS_16_BITS_SIGNED:
            sval16 = va_arg(ap, int16_t *);
            *sval16 = operand->raw;
            break;
        case MDS_32_BITS_SIGNED:
            sval32 = va_arg(ap, int32_t *);
            *sval32 = operand->raw;
            break;
        case MDS_64_BITS_SIGNED:
            sval64 = va_arg(ap, int64_t *);
            *sval64 = operand->raw;
            break;
    }

    va_end(ap);

    result = true;

 exit:

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : operand = structure dont le contenu est à actualiser. [OUT]  *
*                size    = taille de l'opérande souhaitée.                    *
*                value   = valeur sur x bits à venir récupérer.               *
*                                                                             *
*  Description : Définit la nouvelle valeur de l'opérande à une valeur.       *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

void g_immediate_operand_set_value(GImmediateOperand *operand, MemoryDataSize size, uint64_t value)
{
    immop_extra_data_t extra;               /* Données insérées à consulter*/

    assert(size != MDS_UNDEFINED);

    extra = GET_IMM_OP_EXTRA(operand);

    extra.size = size;

    operand->raw = value;

    SET_IMM_OP_EXTRA(operand, &extra);

}


/******************************************************************************
*                                                                             *
*  Paramètres  : operand = opérande à consulter.                              *
*                                                                             *
*  Description : Fournit la valeur brute représentée par l'opérande.          *
*                                                                             *
*  Retour      : Valeur destinée à un usage interne.                          *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

uint64_t g_immediate_operand_get_raw_value(const GImmediateOperand *operand)
{
    uint64_t result;                        /* Valeur brute à retourner    */

    result = operand->raw;

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : operand = structure dont le contenu est à consulter.         *
*                                                                             *
*  Description : Indique le signe d'une valeur immédiate.                     *
*                                                                             *
*  Retour      : true si la valeur est strictement négative, false sinon.     *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

bool g_immediate_operand_is_negative(const GImmediateOperand *operand)
{
    bool result;                            /* Bilan à renvoyer            */
    immop_extra_data_t extra;               /* Données insérées à consulter*/

    extra = GET_IMM_OP_EXTRA(operand);

    switch (extra.size)
    {
        case MDS_4_BITS_SIGNED:
        case MDS_8_BITS_SIGNED:
        case MDS_16_BITS_SIGNED:
        case MDS_32_BITS_SIGNED:
        case MDS_64_BITS_SIGNED:
            /**
             * Pour les valeurs plus petites que 64 bits, le compilateur
             * réalise une extension de signe lors du transtypage.
             */
            result = (operand->raw & 0x8000000000000000ll);
            break;
        default:
            result = false;
            break;
    }

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : operand = structure dont le contenu est à actualiser. [OUT]  *
*                display = format global d'un affichage de valeur.            *
*                                                                             *
*  Description : Définit le format textuel par défaut de la valeur.           *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

void g_immediate_operand_set_default_display(GImmediateOperand *operand, ImmOperandDisplay display)
{
    immop_extra_data_t extra;               /* Données insérées à consulter*/

    extra = GET_IMM_OP_EXTRA(operand);

    extra.def_display = display;

    SET_IMM_OP_EXTRA(operand, &extra);

}


/******************************************************************************
*                                                                             *
*  Paramètres  : operand = structure dont le contenu est à consulter.         *
*                                                                             *
*  Description : Indique le format textuel par défaut de la valeur.           *
*                                                                             *
*  Retour      : Format global d'un affichage de valeur.                      *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

ImmOperandDisplay g_immediate_operand_get_default_display(const GImmediateOperand *operand)
{
    ImmOperandDisplay result;               /* Affichage à retourner       */
    immop_extra_data_t extra;               /* Données insérées à consulter*/

    extra = GET_IMM_OP_EXTRA(operand);

    result = extra.def_display;

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : operand = structure dont le contenu est à actualiser. [OUT]  *
*                display = format global d'un affichage de valeur.            *
*                                                                             *
*  Description : Définit la grande ligne du format textuel de la valeur.      *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

void g_immediate_operand_set_display(GImmediateOperand *operand, ImmOperandDisplay display)
{
    immop_extra_data_t extra;               /* Données insérées à consulter*/

    extra = GET_IMM_OP_EXTRA(operand);

    extra.display = display;

    SET_IMM_OP_EXTRA(operand, &extra);

}


/******************************************************************************
*                                                                             *
*  Paramètres  : operand = structure dont le contenu est à consulter.         *
*                                                                             *
*  Description : Indique la grande ligne du format textuel de la valeur.      *
*                                                                             *
*  Retour      : Format global d'un affichage de valeur.                      *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

ImmOperandDisplay g_immediate_operand_get_display(const GImmediateOperand *operand)
{
    ImmOperandDisplay result;               /* Affichage à retourner       */
    immop_extra_data_t extra;               /* Données insérées à consulter*/

    extra = GET_IMM_OP_EXTRA(operand);

    if (extra.display != IOD_COUNT)
        result = extra.display;
    else
        result = extra.def_display;

    return result;

}



/* ---------------------------------------------------------------------------------- */
/*                        COMPARAISON DETAILLEE DE DEUX OBJETS                        */
/* ---------------------------------------------------------------------------------- */


/******************************************************************************
*                                                                             *
*  Paramètres  : object = premier objet à consulter pour une comparaison.     *
*                other  = second objet à consulter pour une comparaison.      *
*                                                                             *
*  Description : Réalise une comparaison étendue entre objets.                *
*                                                                             *
*  Retour      : Bilan de la comparaison.                                     *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static int g_immediate_operand_compare(const GComparableObject *object, const GComparableObject *other)
{
    int result;                             /* Bilan à retourner           */
    GComparableObjectInterface *iface;      /* Interface utilisée          */
    GComparableObjectInterface *parent_iface; /* Interface parente         */
    GImmediateOperand *operand_a;           /* Version spécialisée #0      */
    GImmediateOperand *operand_b;           /* Version spécialisée #1      */
    immop_extra_data_t extra_a;             /* Données insérées à consulter*/
    immop_extra_data_t extra_b;             /* Données insérées à consulter*/

    iface = G_COMPARABLE_OBJECT_GET_IFACE(object);

    parent_iface = g_type_interface_peek_parent(iface);

    result = parent_iface->compare(object, other);

    if (result == 0)
    {
        operand_a = G_IMMEDIATE_OPERAND(object);

        extra_a = GET_IMM_OP_EXTRA(operand_a);

        operand_b = G_IMMEDIATE_OPERAND(other);

        extra_b = GET_IMM_OP_EXTRA(operand_b);

        result = sort_unsigned_long(extra_a.size, extra_b.size);

        if (result == 0)
            sort_uint64_t(operand_a->raw, operand_b->raw);

        if (result == 0)
            result = sort_unsigned_long(extra_a.def_display, extra_b.def_display);

        if (result == 0)
            result = sort_unsigned_long(extra_a.display, extra_b.display);

    }

    return result;

}



/* ---------------------------------------------------------------------------------- */
/*                        CALCUL D'UNE EMPREINTE DE L'INSTANCE                        */
/* ---------------------------------------------------------------------------------- */


/******************************************************************************
*                                                                             *
*  Paramètres  : object = objet dont l'instance est à consulter.              *
*                                                                             *
*  Description : Calcule l'empreinte sur 32 bits d'un objet.                  *
*                                                                             *
*  Retour      : Valeur de représentation, unique pour l'objet ou non.        *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static guint g_immediate_operand_hash(const GHashableObject *object)
{
    guint result;                           /* Valeur à retourner          */
    GHashableObjectInterface *iface;        /* Interface utilisée          */
    GHashableObjectInterface *parent_iface; /* Interface parente           */
    GImmediateOperand *operand;             /* Version spécialisée         */

    iface = G_HASHABLE_OBJECT_GET_IFACE(object);

    parent_iface = g_type_interface_peek_parent(iface);

    result = parent_iface->hash(object);

    operand = G_IMMEDIATE_OPERAND(object);

    result ^= (operand->raw & 0xffffffff);
    result ^= (operand->raw >> 32);

    return result;

}



/* ---------------------------------------------------------------------------------- */
/*                     MECANISMES DE CONSERVATION ET RESTAURATION                     */
/* ---------------------------------------------------------------------------------- */


/******************************************************************************
*                                                                             *
*  Paramètres  : object  = élément GLib à constuire.                          *
*                storage = conservateur de données à manipuler.               *
*                fd      = flux ouvert en lecture.                            *
*                                                                             *
*  Description : Charge un objet depuis un flux de données.                   *
*                                                                             *
*  Retour      : Bilan de l'opération.                                        *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static bool g_immediate_operand_load(GSerializableObject *object, GObjectStorage *storage, int fd)
{
    bool result;                            /* Bilan à retourner           */
    GSerializableObjectInterface *iface;    /* Interface utilisée          */
    GSerializableObjectInterface *parent_iface; /* Interface parente       */
    uleb128_t val;                          /* Valeur sauvegardée          */
    GImmediateOperand *operand;             /* Version spécialisée         */

    iface = G_SERIALIZABLE_OBJECT_GET_IFACE(object);

    parent_iface = g_type_interface_peek_parent(iface);

    result = parent_iface->load(object, storage, fd);

    if (result)
    {
        result = load_uleb128(&val, fd);

        if (result)
        {
            operand = G_IMMEDIATE_OPERAND(object);
            operand->raw = val;
        }

    }

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : object  = élément GLib à consulter.                          *
*                storage = conservateur de données à manipuler.               *
*                fd      = flux ouvert en écriture.                           *
*                                                                             *
*  Description : Sauvegarde un objet dans un flux de données.                 *
*                                                                             *
*  Retour      : Bilan de l'opération.                                        *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static bool g_immediate_operand_store(const GSerializableObject *object, GObjectStorage *storage, int fd)
{
    bool result;                            /* Bilan à retourner           */
    GSerializableObjectInterface *iface;    /* Interface utilisée          */
    GSerializableObjectInterface *parent_iface; /* Interface parente       */
    GImmediateOperand *operand;             /* Version spécialisée         */

    iface = G_SERIALIZABLE_OBJECT_GET_IFACE(object);

    parent_iface = g_type_interface_peek_parent(iface);

    result = parent_iface->store(object, storage, fd);
    if (!result) goto exit;

    operand = G_IMMEDIATE_OPERAND(object);

    result = store_uleb128((uleb128_t []) { operand->raw }, fd);

 exit:

    return result;

}



/* ---------------------------------------------------------------------------------- */
/*                   EXPORTATION SOUS FORME DE CHAINE DE CARACTERES                   */
/* ---------------------------------------------------------------------------------- */


/******************************************************************************
*                                                                             *
*  Paramètres  : operand = opérande à transcrire.                             *
*                display = type d'affichage demandé.                          *
*                value   = valeur portée par l'opérande transcrite. [OUT]     *
*                                                                             *
*  Description : Construit la chaîne de caractères correspondant à l'opérande.*
*                                                                             *
*  Retour      : Nombre de caractères utilisés.                               *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

size_t _g_immediate_operand_to_string(const GImmediateOperand *operand, ImmOperandDisplay display, char value[IMM_MAX_SIZE])
{
    size_t result;                          /* Longueur à retourner        */
    immop_extra_data_t extra;               /* Données insérées à consulter*/
    unsigned int range;                     /* Catégorie de la taille      */
    const char *prefix;                     /* Entrée en matière           */
    const char *suffix;                     /* Sortie de matière           */
    const char *alternate;                  /* Préfixe de forme alternative*/
    const char *intro;                      /* Introduction du formatage   */
    bool do_padding;                        /* Indication de bourrage      */
    const char *zpad;                       /* Remplissage par des zéros   */
    const char *lmod;                       /* Modification de longueur    */
    const char *conv;                       /* Opérateur de conversion     */
    char binval[65];                        /* Conversion intégrée         */
    unsigned int max;                       /* Indice du plus fort bit     */
    unsigned int i;                         /* Boucle de parcours          */
    char format[16 + 65];                   /* Format d'impression final   */

    static const char *zpad_defs[] = { "", "02", "04", "08", "016" };
    static const char *lmod_defs[] = { "hh", "hh", "h", "", __PRI64_PREFIX };
    static const char *conv_si_defs[] = { "", "o", "d", "x", "c" };
    static const char *conv_us_defs[] = { "", "o", "u", "x", "c" };

    assert(display < IOD_COUNT);

    extra = GET_IMM_OP_EXTRA(operand);

    range = MDS_RANGE(extra.size);

    /* Encadrement pour les caractères */
    if (display == IOD_CHAR)
    {
        prefix = "'";
        suffix = "'";
    }
    else
    {
        prefix = "";
        suffix = "";
    }

    /* Préfix de forme '0x', 'b' ou '0' */
    switch (display)
    {
        case IOD_BIN:
            alternate = "b";
            break;
        case IOD_OCT:
            alternate = "0";
            break;
        case IOD_HEX:
            alternate = "0x";
            break;
        default:
            alternate = "";
            break;
    }

    /* Va-t-on réellement avoir besoin d'un formatage ? */
    if (display != IOD_BIN)
        intro = "%";
    else
        intro = "";

    /* Drapeau de remplissage ? */

    do_padding = g_arch_operand_has_flag(G_ARCH_OPERAND(operand), IOF_ZERO_PADDING_BY_DEFAULT | IOF_ZERO_PADDING);

    if (do_padding)
    {
        if (extra.display != IOD_COUNT)
            do_padding = (extra.display == IOD_BIN || extra.display == IOD_HEX);
        else
            do_padding = (extra.def_display == IOD_BIN || extra.def_display == IOD_HEX);
    }

    switch (display)
    {
        case IOD_BIN:
        case IOD_CHAR:
        case IOD_OCT:
        case IOD_DEC:
            zpad = "";
            break;
        default:
            zpad = (do_padding ? zpad_defs[range] : "");
            break;
    }

    /* Modification de la longueur fournie */

    if (display != IOD_BIN)
        lmod = lmod_defs[range];
    else
        lmod = "";

    /* Spécification de la conversion */

    if (display != IOD_BIN)
    {
        if (MDS_IS_SIGNED(extra.size))
            conv = conv_si_defs[display];
        else
            conv = conv_us_defs[display];

    }
    else
    {
        if (do_padding)
            max = range * 8;

        else
        {
            if (!msb_64(operand->raw, &max))
            {
                conv = "0";
                max = 0;
            }
        }

        if (max > 0)
        {
            conv = binval;

            for (i = max; i > 0; i--)
                binval[max - i] = (operand->raw & (1llu << (i - 1)) ? '1' : '0');

            binval[max] = '\0';

        }

    }

    /* Impression finale */

    snprintf(format, sizeof(format), "%s%s%s%s%s%s%s", prefix, alternate, intro, zpad, lmod, conv, suffix);

    switch (extra.size)
    {
        case MDS_UNDEFINED:
            result = snprintf(value, IMM_MAX_SIZE, "<? undef value ?>");
            break;

        case MDS_4_BITS_UNSIGNED:
            result = snprintf(value, IMM_MAX_SIZE, format, (uint8_t)operand->raw);
            break;

        case MDS_8_BITS_UNSIGNED:
            result = snprintf(value, IMM_MAX_SIZE, format, (uint8_t)operand->raw);
            break;

        case MDS_16_BITS_UNSIGNED:
            result = snprintf(value, IMM_MAX_SIZE, format, (uint16_t)operand->raw);
            break;

        case MDS_32_BITS_UNSIGNED:
            result = snprintf(value, IMM_MAX_SIZE, format, (uint32_t)operand->raw);
            break;

        case MDS_64_BITS_UNSIGNED:
            result = snprintf(value, IMM_MAX_SIZE, format, (uint64_t)operand->raw);
            break;

        case MDS_4_BITS_SIGNED:
            result = snprintf(value, IMM_MAX_SIZE, format, (int8_t)operand->raw);
            break;

        case MDS_8_BITS_SIGNED:
            result = snprintf(value, IMM_MAX_SIZE, format, (int8_t)operand->raw);
            break;

        case MDS_16_BITS_SIGNED:
            result = snprintf(value, IMM_MAX_SIZE, format, (int16_t)operand->raw);
            break;

        case MDS_32_BITS_SIGNED:
            result = snprintf(value, IMM_MAX_SIZE, format, (int32_t)operand->raw);
            break;

        case MDS_64_BITS_SIGNED:
            result = snprintf(value, IMM_MAX_SIZE, format, (int64_t)operand->raw);
            break;

        default:
            assert(false);
            result = 0;
            break;

    }

    assert(result > 0);

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : builder = objet dont l'instance est exportable.              *
*                flags   = éventuelles indications pour l'opération.          *
*                out     = chaîne de caractères mise en place. [OUT]          *
*                                                                             *
*  Description : Exporte une chaîne de caractères à partir d'un objet.        *
*                                                                             *
*  Retour      : Bilan de l'opération.                                        *
*                                                                             *
*  Remarques   : La sortie out est à nettoyer avec exit_sized_binary() après  *
*                usage.                                                       *
*                                                                             *
******************************************************************************/

static bool g_immediate_operand_to_string(const GStringBuilder *builder, unsigned int flags, sized_binary_t *out)
{
    bool result;                            /* Bilan à retourner           */
    const GImmediateOperand *operand;       /* Version spécialisée         */
    ImmOperandDisplay display;              /* Type d'affichage courant    */
    char value[IMM_MAX_SIZE];               /* Chaîne à imprimer           */
    size_t len;                             /* Taille de l'élément inséré  */

    operand = G_IMMEDIATE_OPERAND(builder);

    display = g_immediate_operand_get_display(operand);

    len =  _g_immediate_operand_to_string(operand, display, value);

    result = (len > 0);

    if (result)
        add_to_sized_binary(out, value, len);

    return result;

}