/* Chrysalide - Outil d'analyse de fichiers binaires
 * debugger.c - débogage d'une cible en Java.
 *
 * Copyright (C) 2010-2012 Cyrille Bagard
 *
 *  This file is part of Chrysalide.
 *
 *  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 "debugger.h"


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


#include <i18n.h>


#include "packet.h"
#include "tcp.h"
#include "../debugger-int.h"
#include "../stream.h"
#include "../../gui/panels/log.h"





/* Débogueur utilisant un serveur JAVA (instance) */
struct _GJavaDebugger
{
    GBinaryDebugger parent;                 /* A laisser en premier        */

    GDebugStream *stream;

};

/* Débogueur utilisant un serveur JAVA (classe) */
struct _GJavaDebuggerClass
{
    GBinaryDebuggerClass parent;            /* A laisser en premier        */

};





/* Initialise la classe du débogueur utilisant Java. */
static void g_java_debugger_class_init(GJavaDebuggerClass *);

/* Procède à l'initialisation du débogueur utilisant Java. */
static void g_java_debugger_init(GJavaDebugger *);

/* Procède au démarrage effectif de la session de débogage. */
static bool g_java_debugger_attach(GJavaDebugger *);

/* Fournit les identifiants de tous les threads actifs. */
static pid_t *g_java_debugger_list_all_threads(GJavaDebugger *, char ***, size_t *);

/* Fournit la liste des frames courantes d'un thread donné. */
static dbg_frame_t *g_java_debugger_get_frames_stack(GJavaDebugger *, pid_t, size_t *);



/* Indique le type défini par la GLib pour le débogueur java. */
G_DEFINE_TYPE(GJavaDebugger, g_java_debugger, G_TYPE_BINARY_DEBUGGER);



/******************************************************************************
*                                                                             *
*  Paramètres  : klass = classe de débogueur à initialiser.                   *
*                                                                             *
*  Description : Initialise la classe du débogueur utilisant Java.            *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void g_java_debugger_class_init(GJavaDebuggerClass *klass)
{

}


/******************************************************************************
*                                                                             *
*  Paramètres  : debugger = instance de débogueur à préparer.                 *
*                                                                             *
*  Description : Procède à l'initialisation du débogueur utilisant Java.      *
*                                                                             *
*  Retour      : -                                                            *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static void g_java_debugger_init(GJavaDebugger *debugger)
{
    GBinaryDebugger *parent;                /* Instance parente            */

    parent = G_BINARY_DEBUGGER(debugger);

    parent->attach = (attach_debugger_fc)g_java_debugger_attach;

    parent->all_threads = (dbg_list_all_threads_fc)g_java_debugger_list_all_threads;
    parent->frames_stack = (dbg_get_frames_stack_fc)g_java_debugger_get_frames_stack;

#if 0
    parent->run = (basic_debugger_fc)g_java_debugger_run;
    parent->resume = (resume_debugger_fc)g_java_debugger_resume;
    parent->kill = (basic_debugger_fc)g_java_debugger_kill;
#endif


}


/******************************************************************************
*                                                                             *
*  Paramètres  : binary  = binaire représenter à déboguer.                    *
*                options = paramètres destinés au débogage.                   *
*                                                                             *
*  Description : Crée un débogueur utilisant un serveur Java distant.         *
*                                                                             *
*  Retour      : Instance de débogueur mise en place ou NULL.                 *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

GBinaryDebugger *g_java_debugger_new(GLoadedBinary *binary, void *options)
{
    GBinaryDebugger *result;                /* Débogueur à retourner       */

    result = g_object_new(G_TYPE_JAVA_DEBUGGER, NULL);


    G_JAVA_DEBUGGER(result)->stream = g_jdwp_tcp_client_new("localhost", "9000");

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : debugger = instance du module de débogage chargé.            *
*                                                                             *
*  Description : Procède au démarrage effectif de la session de débogage.     *
*                                                                             *
*  Retour      : Bilan de l'opération.                                        *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static bool g_java_debugger_attach(GJavaDebugger *debugger)
{
    bool result;                            /* Bilan à retourner           */
    GDebugPacket *req;                      /* Requête à formuler          */
    GDebugPacket *ret;                      /* Obtention de la réponse     */
    jdwp_payload *payload;                  /* Charge utile d'une réponse  */

    req = NULL;
    ret = NULL;

    /* Connexion physique */

    result = g_debug_stream_connect(debugger->stream);
    if (!result) goto gjda_error;

    result = false;

    /* Demande de version */

    req = g_debug_stream_get_free_packet(debugger->stream);

    g_jdwp_packet_set_request_header(G_JDWP_PACKET(req),
                                     JDWP_CST_VIRTUAL_MACHINE, JDWP_CMD_VM_VERSION);

    if (!g_debug_stream_send_packet(debugger->stream, req))
        goto gjda_req_error;

    ret = g_debug_stream_recv_packet(debugger->stream,
                                     (filter_packet_fc)g_jdwp_packet_is_reply, req);
    if (!ret) goto gjda_req_error;

    if (!g_jdwp_packet_parse_payload(G_JDWP_PACKET(ret),
                                     JDWP_CST_VIRTUAL_MACHINE, JDWP_CMD_VM_VERSION))
        goto gjda_ret_error;

    payload = g_jdwp_packet_get_payload(G_JDWP_PACKET(ret));

    log_variadic_message(LMT_INFO, _("The debugger is '%s' (JRE %d.%d; VM %s)."),
                         payload->vs_reply.description.value,
                         payload->vs_reply.jdwp_major, payload->vs_reply.jdwp_minor,
                         payload->vs_reply.vm_version.value);

    g_debug_stream_mark_packet_as_free(debugger->stream, req);
    g_debug_stream_mark_packet_as_free(debugger->stream, ret);

    /* Récupération des tailles d'identifiants */

    req = g_debug_stream_get_free_packet(debugger->stream);

    g_jdwp_packet_set_request_header(G_JDWP_PACKET(req),
                                     JDWP_CST_VIRTUAL_MACHINE, JDWP_CMD_VM_ID_SIZES);

    if (!g_debug_stream_send_packet(debugger->stream, req))
        goto gjda_req_error;

    ret = g_debug_stream_recv_packet(debugger->stream,
                                     (filter_packet_fc)g_jdwp_packet_is_reply, req);
    if (!ret) goto gjda_req_error;

    if (!g_jdwp_packet_parse_payload(G_JDWP_PACKET(ret),
                                     JDWP_CST_VIRTUAL_MACHINE, JDWP_CMD_VM_ID_SIZES))
        goto gjda_ret_error;

    payload = g_jdwp_packet_get_payload(G_JDWP_PACKET(ret));

    g_jdwp_packet_set_sizes(G_JDWP_PACKET(ret), &payload->sz_reply);

    result = true;

 gjda_ret_error:

    g_debug_stream_mark_packet_as_free(debugger->stream, ret);

 gjda_req_error:

    g_debug_stream_mark_packet_as_free(debugger->stream, req);

 gjda_error:

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : debugger = instance du module de débogage chargé.            *
*                names    = désignations de tous les threads ou NULL. [OUT]   *
*                count    = nombre de threads actifs. [OUT]                   *
*                                                                             *
*  Description : Fournit les identifiants de tous les threads actifs.         *
*                                                                             *
*  Retour      : Liste des threads décomptés.                                 *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static pid_t *g_java_debugger_list_all_threads(GJavaDebugger *debugger, char ***names, size_t *count)
{
    pid_t *result;                          /* Bilan à retourner           */
    GDebugPacket *req;                      /* Requête à formuler          */
    GDebugPacket *ret;                      /* Obtention de la réponse     */
    jdwp_payload *payload;                  /* Charge utile d'une réponse  */
    size_t i;                               /* Boucle de parcours          */
    GDebugPacket *sub_req;                  /* Requête à formuler          */
    jdwp_cmd_thread_name_request ident;     /* Indentification d'un thread */
    GDebugPacket *sub_ret;                  /* Obtention de la réponse     */
    jdwp_payload *sub_payload;              /* Charge utile d'une réponse  */

    result = NULL;
    *count = 0;

    req = g_debug_stream_get_free_packet(debugger->stream);

    g_jdwp_packet_set_request_header(G_JDWP_PACKET(req),
                                     JDWP_CST_VIRTUAL_MACHINE, JDWP_CMD_VM_ALL_THREADS);

    if (!g_debug_stream_send_packet(debugger->stream, req))
        goto gjdlat_req_error;

    ret = g_debug_stream_recv_packet(debugger->stream,
                                     (filter_packet_fc)g_jdwp_packet_is_reply, req);
    if (!ret) goto gjdlat_req_error;

    if (!g_jdwp_packet_parse_payload(G_JDWP_PACKET(ret),
                                     JDWP_CST_VIRTUAL_MACHINE, JDWP_CMD_VM_ALL_THREADS))
        goto gjdlat_ret_error;

    payload = g_jdwp_packet_get_payload(G_JDWP_PACKET(ret));

    *count = payload->th_reply.count;
    result = (pid_t *)calloc(*count, sizeof(pid_t));

    if (names != NULL)
        *names = (char **)calloc(*count, sizeof(char *));

    for (i = 0; i < *count; i++)
    {
        result[i] = (pid_t)payload->th_reply.threads[i];

        if (names != NULL)
        {
            sub_req = g_debug_stream_get_free_packet(debugger->stream);

            g_jdwp_packet_set_request_header(G_JDWP_PACKET(sub_req),
                                             JDWP_CST_THREAD_REFERENCE, JDWP_CMD_THREAD_NAME);

            ident.id = result[i];
            g_jdwp_packet_set_payload(G_JDWP_PACKET(sub_req), (jdwp_payload *)&ident);

            if (!g_debug_stream_send_packet(debugger->stream, sub_req))
            {
                g_debug_stream_mark_packet_as_free(debugger->stream, sub_req);
                (*names)[i] = strdup("???");
                continue;
            }

            sub_ret = g_debug_stream_recv_packet(debugger->stream,
                                                 (filter_packet_fc)g_jdwp_packet_is_reply, sub_req);
            if (!sub_ret)
            {
                g_debug_stream_mark_packet_as_free(debugger->stream, sub_req);
                (*names)[i] = strdup("???");
                continue;
            }

            if (!g_jdwp_packet_parse_payload(G_JDWP_PACKET(sub_ret),
                                             JDWP_CST_THREAD_REFERENCE, JDWP_CMD_THREAD_NAME))
            {
                g_debug_stream_mark_packet_as_free(debugger->stream, sub_req);
                g_debug_stream_mark_packet_as_free(debugger->stream, sub_ret);
                (*names)[i] = strdup("???");
                continue;
            }

            sub_payload = g_jdwp_packet_get_payload(G_JDWP_PACKET(sub_ret));

            (*names)[i] = strdup(sub_payload->th_name.name.value);

            g_debug_stream_mark_packet_as_free(debugger->stream, sub_req);
            g_debug_stream_mark_packet_as_free(debugger->stream, sub_ret);

        }

    }

 gjdlat_ret_error:

    g_debug_stream_mark_packet_as_free(debugger->stream, ret);

 gjdlat_req_error:

    g_debug_stream_mark_packet_as_free(debugger->stream, req);

    return result;

}


/******************************************************************************
*                                                                             *
*  Paramètres  : debugger = instance du module de débogage chargé.            *
*                thread   = thread concerné par l'analyse.                    *
*                count    = nombre de frames en place. [OUT]                  *
*                                                                             *
*  Description : Fournit la liste des frames courantes d'un thread donné.     *
*                                                                             *
*  Retour      : Liste des frames trouvées.                                   *
*                                                                             *
*  Remarques   : -                                                            *
*                                                                             *
******************************************************************************/

static dbg_frame_t *g_java_debugger_get_frames_stack(GJavaDebugger *debugger, pid_t thread, size_t *count)
{
    dbg_frame_t *result;                    /* Bilan à retourner           */
    GDebugPacket *req;                      /* Requête à formuler          */
    jdwp_cmd_thread_frames_request frames;  /* Ciblage du thread désiré    */
    GDebugPacket *ret;                      /* Obtention de la réponse     */
    jdwp_payload *payload;                  /* Charge utile d'une réponse  */
    size_t i;                               /* Boucle de parcours          */

    result = NULL;
    *count = 0;

    req = g_debug_stream_get_free_packet(debugger->stream);

    g_jdwp_packet_set_request_header(G_JDWP_PACKET(req),
                                     JDWP_CST_THREAD_REFERENCE, JDWP_CMD_THREAD_FRAMES);

    frames.id = thread;
    frames.start = 0;
    frames.length = ALL_FRAMES;
    g_jdwp_packet_set_payload(G_JDWP_PACKET(req), (jdwp_payload *)&frames);

    if (!g_debug_stream_send_packet(debugger->stream, req))
        goto gjdgsf_req_error;

    ret = g_debug_stream_recv_packet(debugger->stream,
                                     (filter_packet_fc)g_jdwp_packet_is_reply, req);
    if (!ret) goto gjdgsf_req_error;

    if (!g_jdwp_packet_parse_payload(G_JDWP_PACKET(ret),
                                     JDWP_CST_THREAD_REFERENCE, JDWP_CMD_THREAD_FRAMES))
        goto gjdgsf_ret_error;

    payload = g_jdwp_packet_get_payload(G_JDWP_PACKET(ret));

    *count = payload->th_frames.count;
    result = (dbg_frame_t *)calloc(*count, sizeof(dbg_frame_t));

    for (i = 0; i < *count; i++)
    {
        /* TODO */
        result[i].addr = payload->th_frames.frames[i].location.index;

    }

 gjdgsf_ret_error:

    g_debug_stream_mark_packet_as_free(debugger->stream, ret);

 gjdgsf_req_error:

    g_debug_stream_mark_packet_as_free(debugger->stream, req);

    return result;

}