/* OpenIDA - Outil d'analyse de fichiers binaires
 * instruction.c - équivalent Python du fichier "arch/instruction.h"
 *
 * Copyright (C) 2012 Cyrille Bagard
 *
 *  This file is part of OpenIDA.
 *
 *  OpenIDA is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  OpenIDA is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */


#include "instruction.h"


#include <pygobject.h>
#include <stdbool.h>
#include <string.h>


#include <arch/instruction.h>


#include "../quirks.h"



/* --------------------- ITERATEUR POUR BOUCLE SUR INSTRUCTIONS --------------------- */


/* Itérateur pour les instructions */
typedef struct _PyArchInstructionIter
{
    PyObject_HEAD                           /* A laisser en premier        */

    GArchInstruction *head;                 /* Ancrage supposé             */
    PyObject *current;                      /* Départ, puis parcours...    */
    bool started;                           /* Démarrage effectué ?        */

} PyArchInstructionIter;


/* Prépare l'itérateur pour un parcours d'instructions. */
static PyObject *py_arch_instruction_iterator_create(PyObject *);

/* Libère la mémoire d'un itérateur de 'ArchInstruction'. */
static void py_arch_instruction_iterator_dealloc(PyArchInstructionIter *);

/* Fournit l'élément suivant dans un parcours d'instructions. */
static PyObject *py_arch_instruction_iterator_next(PyArchInstructionIter *);



/* --------------------- INSTRUCTIONS D'ARCHITECTURES EN PYTHON --------------------- */


/* Crée un nouvel objet Python de type 'ArchInstruction'. */
static PyObject *py_arch_instruction_new(PyTypeObject *, PyObject *, PyObject *);

/* Prépare un parcours d'instructions. */
static PyObject *py_arch_instruction_get_iter(PyObject *);

/* Fournit la valeur associée à une propriété donnée. */
static PyObject *py_arch_instruction_get_location(PyObject *, char *);

/* Fournit le nom humain de l'instruction manipulée. */
static PyObject *py_arch_instruction_get_keyword(PyObject *, void *);



/* ---------------------------------------------------------------------------------- */
/*                       ITERATEUR POUR BOUCLE SUR INSTRUCTIONS                       */
/* ---------------------------------------------------------------------------------- */


/******************************************************************************
*                                                                             *
*  Paramètres  : origin = élément à l'origine du parcours.                    *
*                                                                             *
*  Description : Prépare l'itérateur pour un parcours d'instructions.         *
*                                                                             *
*  Retour      : Instance d'itérateur prête à emploi.                         *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static PyObject *py_arch_instruction_iterator_create(PyObject *origin)
{
    PyArchInstructionIter *result;          /* Nouvelle instance à renvoyer*/
    PyObject *module;                       /* Module d'appartenance       */
    PyTypeObject *type;                     /* Type d'objet à créer        */

    module = PyImport_ImportModule("pychrysalide.arch");
    type = (PyTypeObject *)PyObject_GetAttrString(module, "ArchInstructionIterator");
    Py_DECREF(module);

    result = (PyArchInstructionIter *)type->tp_alloc(type, 0);
    Py_DECREF(type);

    if (result != NULL)
    {
        Py_INCREF(origin);
        result->head = G_ARCH_INSTRUCTION(pygobject_get(origin));
        g_object_ref(G_OBJECT(result->head));

        result->current = origin;
    }

    return (PyObject *)result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : self = instance d'objet à supprimer.                         *
*                                                                             *
*  Description : Libère la mémoire d'un itérateur de 'ArchInstruction'.       *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void py_arch_instruction_iterator_dealloc(PyArchInstructionIter *self)
{
    PyObject *first;                        /* Récupération de la première */

    first = pychrysalide_get_pygobject(G_OBJECT(self->head));

    Py_DECREF(first);
    g_object_unref(G_OBJECT(self->head));

#if PY_VERSION_HEX < 0x03000000
    self->ob_type->tp_free((PyObject *)self);
#else
    Py_TYPE(self)->tp_free((PyObject *)self);
#endif

}


/******************************************************************************
*                                                                             *
*  Paramètres  : self = instance manipulée à traiter.                         *
*                                                                             *
*  Description : Fournit l'élément suivant dans un parcours d'instructions.   *
*                                                                             *
*  Retour      : Point suivant du parcours ou NULL.                           *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static PyObject *py_arch_instruction_iterator_next(PyArchInstructionIter *self)
{
    PyObject *result;                       /* Elément à retourner         */
    GArchInstruction *next;                 /* Elément réel suivant        */

    if (!self->started)
    {
        self->started = true;
        result = self->current;
        Py_INCREF(result);

    }
    else
    {
        next = G_ARCH_INSTRUCTION(pygobject_get(self->current));
        next = g_arch_instruction_get_next_iter(self->head, next, VMPA_MAX);

        if (next != NULL)
        {
            result = pygobject_new(G_OBJECT(next));
            self->current = result;
        }
        else result = NULL;

    }

    Py_XINCREF(result);
    return (PyObject *)result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : module = module dont la définition est à compléter.          *
*                                                                             *
*  Description : Permet une itération de 'pychrysalide.arch.ArchInstruction'. *
*                                                                             *
*  Retour      : Bilan de l'opération.                                        *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

bool register_python_arch_instruction_iterator(PyObject *module)
{
    int ret;                                /* Bilan d'un appel            */

    static PyTypeObject py_arch_instruction_iterator_type = {

        PyObject_HEAD_INIT(NULL)

        .tp_name        = "pychrysalide.arch.ArchInstructionIterator",
        .tp_basicsize   = sizeof(PyArchInstructionIter),

        .tp_dealloc     = (destructor)py_arch_instruction_iterator_dealloc,

        .tp_flags       = Py_TPFLAGS_HAVE_ITER | Py_TPFLAGS_HAVE_CLASS,

        .tp_doc         = "PyChrysalide architecture instruction iterator",

        .tp_iter        = PyObject_SelfIter,
        .tp_iternext    = (iternextfunc)py_arch_instruction_iterator_next

    };

    if (PyType_Ready(&py_arch_instruction_iterator_type) < 0)
        return false;

    Py_INCREF(&py_arch_instruction_iterator_type);
    ret = PyModule_AddObject(module, "ArchInstructionIterator", (PyObject *)&py_arch_instruction_iterator_type);

    return (ret == 0);

}



/* ---------------------------------------------------------------------------------- */
/*                       INSTRUCTIONS D'ARCHITECTURES EN PYTHON                       */
/* ---------------------------------------------------------------------------------- */


/******************************************************************************
*                                                                             *
*  Paramètres  : type = type de l'objet à instancier.                         *
*                args = arguments fournis à l'appel.                          *
*                kwds = arguments de type key=val fournis.                    *
*                                                                             *
*  Description : Crée un nouvel objet Python de type 'ArchInstruction'.       *
*                                                                             *
*  Retour      : Instance Python mise en place.                               *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static PyObject *py_arch_instruction_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    Py_RETURN_NONE;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : self = instance manipulée à traiter.                         *
*                                                                             *
*  Description : Prépare un parcours d'instructions.                          *
*                                                                             *
*  Retour      : Point de départ d'un parcours.                               *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static PyObject *py_arch_instruction_get_iter(PyObject *self)
{
    return py_arch_instruction_iterator_create(self);

}


/******************************************************************************
*                                                                             *
*  Paramètres  : self = classe représentant une instruction.                  *
*                name = nom de la propriété à lire.                           *
*                                                                             *
*  Description : Fournit la valeur associée à une propriété donnée.           *
*                                                                             *
*  Retour      : Valeur associée à la propriété consultée.                    *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static PyObject *py_arch_instruction_get_location(PyObject *self, char *name)
{
    PyObject *result;                       /* Trouvailles à retourner     */
    GArchInstruction *instr;                /* Version native              */
    off_t offset;                           /* Position dans le fichier    */
    off_t length;                           /* Taille de l'instruction     */
    vmpa_t address;                         /* Position en mémoire         */

    instr = G_ARCH_INSTRUCTION(pygobject_get(self));
    g_arch_instruction_get_location(instr, &offset, &length, &address);

    if (strcmp(name, "offset") == 0)
        result = PyLong_FromLong(offset);

    else if (strcmp(name, "length") == 0)
        result = PyLong_FromLong(length);

    else if (strcmp(name, "address") == 0)
        result = PyLong_FromLongLong(address);

    else
        result = NULL;

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : self   = classe représentant une instruction.                *
*                unused = adresse non utilisée ici.                           *
*                                                                             *
*  Description : Fournit le nom humain de l'instruction manipulée.            *
*                                                                             *
*  Retour      : Valeur associée à la propriété consultée.                    *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static PyObject *py_arch_instruction_get_keyword(PyObject *self, void *unused)
{
    PyObject *result;                       /* Trouvailles à retourner     */
    GArchInstruction *instr;                /* Version native              */
    const char *kw;                         /* Valeur récupérée            */

    instr = G_ARCH_INSTRUCTION(pygobject_get(self));
    kw = g_arch_instruction_get_keyword(instr);

    result = PyString_FromString(kw);

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : module = module dont la définition est à compléter.          *
*                                                                             *
*  Description : Prend en charge l'objet 'pychrysalide.arch.ArchInstruction'. *
*                                                                             *
*  Retour      : Bilan de l'opération.                                        *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

bool register_python_arch_instruction(PyObject *module)
{
    PyObject *pygobj_mod;                   /* Module Python-GObject       */
    int ret;                                /* Bilan d'un appel            */

    static PyMethodDef py_arch_instruction_methods[] = {
        { NULL }
    };

    static PyGetSetDef py_arch_instruction_getseters[] = {
        {
            "offset", (getter)py_arch_instruction_get_location, (setter)NULL,
            "Provide the location of the instruction in the binary file.", "offset"
        },
        {
            "length", (getter)py_arch_instruction_get_location, (setter)NULL,
            "Provide the length of the instruction.", "length"
        },
        {
            "address", (getter)py_arch_instruction_get_location, (setter)NULL,
            "Provide the location of the instruction in memory.", "address"
        },
        {
            "keyword", (getter)py_arch_instruction_get_keyword, (setter)NULL,
            "Give le name of the assembly instruction.", NULL
        },
        { NULL }
    };

    static PyTypeObject py_arch_instruction_type = {

        PyObject_HEAD_INIT(NULL)

        .tp_name        = "pychrysalide.arch.ArchInstruction",
        .tp_basicsize   = sizeof(PyGObject),

        .tp_flags       = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,

        .tp_doc         = "PyChrysalide architecture instruction",

        .tp_methods     = py_arch_instruction_methods,
        .tp_getset      = py_arch_instruction_getseters,
        .tp_new         = (newfunc)py_arch_instruction_new,

        .tp_iter        = (getiterfunc)py_arch_instruction_get_iter

    };

    pygobj_mod = PyImport_ImportModule("gobject");
    if (pygobj_mod == NULL) return false;

    py_arch_instruction_type.tp_base = (PyTypeObject *)PyObject_GetAttrString(pygobj_mod, "GObject");
    Py_DECREF(pygobj_mod);

    if (PyType_Ready(&py_arch_instruction_type) < 0)
        return false;

    Py_INCREF(&py_arch_instruction_type);
    ret = PyModule_AddObject(module, "ArchInstruction", (PyObject *)&py_arch_instruction_type);

    pygobject_register_class(module, "GArchInstruction", G_TYPE_ARCH_INSTRUCTION,
                             &py_arch_instruction_type,
                             Py_BuildValue("(O)", py_arch_instruction_type.tp_base));

    return (ret == 0);

}