/**********************************************************************
 * Copyright (c) 2005, 2007 IBM Corporation and others.
 * All rights reserved.   This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 * $Id: agentDebug.c,v 1.2 2007/04/06 00:32:59 jkubasta Exp $
 * 
 * Contributors: 
 * IBM - Initial API and implementation
 **********************************************************************/

#include "agentDebug.h"
#include "JvmpiWriter.h"
#include "print.h"

#ifdef _SHOOTDEBUG

void jvmpiAgent_dumpStack(ThreadPrivateStorage *tps, char * buffer)
{
 unsigned long i;
 sprintf(buffer, "*****************************INTERNAL_STACK\n");
 jvmpiAgent_print(buffer);

 for (i=0; i < jvmpiAgent_TOS(tps); i++)
 {
  HashEntry *methodHashEntry = jvmpiAgent_Peek(tps, i)->methodHashEntry;
  if (methodHashEntry)
  {
   jvmpiAgent_printMethod(methodHashEntry->u.methodEntry, buffer);
  }
 }
}



void jvmpiAgent_dumpJVMStack(JNIEnv *thread, char * buffer)
{
 int i,j,tos;
 jint depth = 200;
 JVMPI_CallTrace *callTraceBuffer = jvmpiAgent_Calloc(sizeof(JVMPI_CallTrace));
 ThreadLocalStorage *tps = jvmpiAgent_getThreadLocalStorage(thread, FALSE);

 sprintf(buffer, "*****************************JVM_STACK   %d FRAMES\n",callTraceBuffer->num_frames);
 jvmpiAgent_print(buffer);

 callTraceBuffer->env_id = thread;
 callTraceBuffer->frames = jvmpiAgent_Calloc(depth *sizeof(JVMPI_CallFrame));
 _jvmpiAgent_jvmpiInterface->GetCallTrace(callTraceBuffer, depth);

 tos = jvmpiAgent_TOS(tps);
 for (i = 0; i<callTraceBuffer->num_frames; i++)
 {
  HashEntry *methodHashEntry = jvmpiAgent_FindSymbol(callTraceBuffer->frames[i].method_id, Method_t, FALSE);
  if (!methodHashEntry)
  {
   StackEntry *stackEntry;
   jobjectID class_id = _jvmpiAgent_jvmpiInterface->GetMethodClass(callTraceBuffer->frames[i].method_id);
   HashEntry *classHashEntry = jvmpiAgent_FindClassSymbol(class_id);
   assert(0);
   if (!classHashEntry && class_id != 0)
   {
    REQUEST_EVENT(JVMPI_EVENT_CLASS_LOAD, (void *)class_id);
   }
   methodHashEntry = jvmpiAgent_FindMethodSymbol(callTraceBuffer->frames[i].method_id);
   tos = jvmpiAgent_TOS(tps);
   for (j = 0; j < tos; j++)
   {
	stackEntry = jvmpiAgent_Peek(tps, j);
	assert(methodHashEntry == stackEntry->methodHashEntry);
   }

   jvmpiAgent_printMethod(methodHashEntry->u.methodEntry, buffer);
  }
  else
  {
   /* This is just a temporary path for debugging purposes. */
   /*jobjectID class_id = _jvmpiAgent_jvmpiInterface->GetMethodClass(callTraceBuffer->frames[i].method_id); */
   /*assert(class_id && methodHashEntry->u.methodEntry->classEntry->id == (jint)class_id); */
   jvmpiAgent_printMethod(methodHashEntry->u.methodEntry, buffer);
  }
 }
}

#endif  /* _DEBUG */
