stacktrace.cc 22.4 KB
Newer Older
1 2
// stacktrace.cc - Functions for unwinding & inspecting the call stack.

3
/* Copyright (C) 2005, 2006  Free Software Foundation
4 5 6 7 8 9 10 11

   This file is part of libgcj.

This software is copyrighted work licensed under the terms of the
Libgcj License.  Please consult the file "LIBGCJ_LICENSE" for
details.  */

#include <config.h>
12
#include <platform.h>
13 14 15 16 17 18 19 20

#include <jvm.h>
#include <gcj/cni.h>
#include <java-interp.h>
#include <java-stack.h>

#include <stdio.h>

21
#include <java/lang/Boolean.h>
22 23
#include <java/lang/Class.h>
#include <java/lang/Long.h>
24
#include <java/lang/reflect/Method.h>
25
#include <java/security/AccessController.h>
26
#include <java/util/ArrayList.h>
27
#include <java/util/IdentityHashMap.h>
28
#include <gnu/classpath/jdwp/Jdwp.h>
29
#include <gnu/classpath/VMStackWalker.h>
30 31
#include <gnu/java/lang/MainThread.h>
#include <gnu/gcj/runtime/NameFinder.h>
32
#include <gnu/gcj/runtime/StringBuffer.h>
33 34

#include <sysdep/backtrace.h>
35
#include <sysdep/descriptor.h>
36 37 38 39 40 41

using namespace java::lang;
using namespace java::lang::reflect;
using namespace java::util;
using namespace gnu::gcj::runtime;

Andrew Haley committed
42 43 44 45
#ifdef __ARM_EABI_UNWINDER__
#define _URC_NORMAL_STOP _URC_FAILURE
#endif

46 47 48 49
// Maps ncode values to their containing native class.
// NOTE: Currently this Map contradicts class GC for native classes. This map
// (and the "new class stack") will need to use WeakReferences in order to 
// enable native class GC.
50
java::util::IdentityHashMap *_Jv_StackTrace::ncodeMap;
51 52 53 54 55 56 57 58 59 60 61 62 63 64

// Check the "class stack" for any classes initialized since we were last 
// called, and add them to ncodeMap.
void 
_Jv_StackTrace::UpdateNCodeMap ()
{
  // The Map should be large enough so that a typical Java app doesn't cause 
  // it to rehash, without using too much memory. ~5000 entries should be 
  // enough.
  if (ncodeMap == NULL)
    ncodeMap = new java::util::IdentityHashMap (5087);
  
  jclass klass;
  while ((klass = _Jv_PopClass ()))
65 66 67 68 69 70 71 72 73 74 75 76 77 78
    {
      //printf ("got %s\n", klass->name->data);
      for (int i = 0; i < klass->method_count; i++)
	{
	  _Jv_Method *method = &klass->methods[i];
	  void *ncode = method->ncode;
	  // Add non-abstract methods to ncodeMap.
	  if (ncode)
	    {
	      ncode = UNWRAP_FUNCTION_DESCRIPTOR (ncode);
	      ncodeMap->put ((java::lang::Object *) ncode, klass);
	    }
	}
    }
79 80 81 82 83 84 85 86 87 88 89 90 91 92
}

// Given a native frame, return the class which this code belongs 
// to. Returns NULL if this IP is not associated with a native Java class.
// If NCODE is supplied, it will be set with the ip for the entry point of the 
// enclosing method.
jclass
_Jv_StackTrace::ClassForFrame (_Jv_StackFrame *frame)
{
  JvAssert (frame->type == frame_native);
  jclass klass = NULL;

  // look it up in ncodeMap
  if (frame->start_ip)
93 94 95 96 97 98 99
    {
      klass = (jclass) ncodeMap->get ((jobject) frame->start_ip);

      // Exclude interpreted classes
      if (klass != NULL && _Jv_IsInterpretedClass (klass))
	klass = NULL;
    }
100 101 102 103 104 105 106 107 108 109 110 111 112

  return klass;
}

_Unwind_Reason_Code
_Jv_StackTrace::UnwindTraceFn (struct _Unwind_Context *context, void *state_ptr)
{
  _Jv_UnwindState *state = (_Jv_UnwindState *) state_ptr;
  jint pos = state->pos;

  // Check if the trace buffer needs to be extended.
  if (pos == state->length)
    {
113
      int newLength = state->length * 2;
114 115 116 117 118
      void *newFrames = _Jv_AllocBytes (newLength * sizeof(_Jv_StackFrame));
      memcpy (newFrames, state->frames, state->length * sizeof(_Jv_StackFrame));      
      state->frames = (_Jv_StackFrame *) newFrames;
      state->length = newLength;
    }
119 120 121

  void *func_addr = (void *) _Unwind_GetRegionStart (context);

122 123 124 125 126
  // If we see the interpreter's main function, "pop" an entry off the 
  // interpreter stack and use that instead, so that the trace goes through 
  // the java code and not the interpreter itself. This assumes a 1:1 
  // correspondance between call frames in the interpreted stack and occurances
  // of _Jv_InterpMethod::run() on the native stack.
127
#ifdef INTERPRETER
128 129 130 131 132 133 134
  void *interp_run = NULL;
  
  if (::gnu::classpath::jdwp::Jdwp::isDebugging)
  	interp_run = (void *) &_Jv_InterpMethod::run_debug;
  else
    interp_run = (void *) &_Jv_InterpMethod::run;
  	
135
  if (func_addr == UNWRAP_FUNCTION_DESCRIPTOR (interp_run))
136 137
    {
      state->frames[pos].type = frame_interpreter;
138 139 140
      _Jv_Frame *frame = static_cast<_Jv_Frame *> (state->interp_frame);
      state->frames[pos].interp.meth 
        = static_cast<_Jv_InterpMethod *> (frame->self);
141
      state->frames[pos].interp.pc = state->interp_frame->pc;
142
      state->interp_frame = state->interp_frame->next_interp;
143
    }
144 145 146 147 148 149 150
  else 
  // We handle proxies in the same way as interpreted classes
  if (_Jv_is_proxy (func_addr))
    {
      state->frames[pos].type = frame_proxy;
      state->frames[pos].proxyClass = state->interp_frame->proxyClass;
      state->frames[pos].proxyMethod = state->interp_frame->proxyMethod;
151
      state->interp_frame = state->interp_frame->next_interp;
152 153
    }
  else 
154
#endif
155
    {
156
#ifdef HAVE_GETIPINFO
157 158 159 160 161 162 163 164
      _Unwind_Ptr ip;
      int ip_before_insn = 0;
      ip = _Unwind_GetIPInfo (context, &ip_before_insn);

      // If the unwinder gave us a 'return' address, roll it back a little
      // to ensure we get the correct line number for the call itself.
      if (! ip_before_insn)
	--ip;
165
#endif
166
      state->frames[pos].type = frame_native;
167
#ifdef HAVE_GETIPINFO
168
      state->frames[pos].ip = (void *) ip;
169 170 171
#else
      state->frames[pos].ip = (void *) _Unwind_GetIP (context);
#endif
172
      state->frames[pos].start_ip = func_addr;
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204
    }

  _Unwind_Reason_Code result = _URC_NO_REASON;
  if (state->trace_function != NULL)
    result = (state->trace_function) (state);
  state->pos++;
  return result;
}

// Return a raw stack trace from the current point of execution. The raw 
// trace will include all functions that have unwind info.
_Jv_StackTrace *
_Jv_StackTrace::GetStackTrace(void)
{
  int trace_size = 100;
  _Jv_StackFrame frames[trace_size];
  _Jv_UnwindState state (trace_size);
  state.frames = (_Jv_StackFrame *) &frames;

  _Unwind_Backtrace (UnwindTraceFn, &state);
  
  // Copy the trace and return it.
  int traceSize = sizeof (_Jv_StackTrace) + 
    (sizeof (_Jv_StackFrame) * state.pos);
  _Jv_StackTrace *trace = (_Jv_StackTrace *) _Jv_AllocBytes (traceSize);
  trace->length = state.pos;
  memcpy (trace->frames, state.frames, sizeof (_Jv_StackFrame) * state.pos);  
  return trace;
}

void
_Jv_StackTrace::getLineNumberForFrame(_Jv_StackFrame *frame, NameFinder *finder, 
205 206
				      jstring *sourceFileName, jint *lineNum,
				      jstring *methodName)
207
{
208
#ifdef INTERPRETER
209 210 211 212 213 214
  if (frame->type == frame_interpreter)
    {
      _Jv_InterpMethod *interp_meth = frame->interp.meth;
      _Jv_InterpClass *interp_class = 
	 (_Jv_InterpClass *) interp_meth->defining_class->aux_info;
      *sourceFileName = interp_class->source_file_name;
215 216 217
      // The interpreter advances the PC before executing an instruction,
      // so roll-back 1 byte to ensure the line number is accurate.
      *lineNum = interp_meth->get_source_line(frame->interp.pc - 1);
218 219
      return;
    }
220
#endif
221

222 223 224 225 226 227 228
  if (frame->type == frame_proxy)
    {
      *sourceFileName = NULL;
      *lineNum = 0;
      return;
    }

229 230 231
  // Use _Jv_platform_dladdr() to determine in which binary the address IP
  // resides.
  _Jv_AddrInfo info;
232
  jstring binaryName = NULL;
233
  const char *argv0 = _Jv_GetSafeArg(0);
234 235 236

  void *ip = frame->ip;
  _Unwind_Ptr offset = 0;
237

238
  if (_Jv_platform_dladdr (ip, &info))
239
    {
240 241
      if (info.file_name)
	binaryName = JvNewStringUTF (info.file_name);
242 243 244
      else
        return;

245 246
      if (*methodName == NULL && info.sym_name)
	*methodName = JvNewStringUTF (info.sym_name);
247

248
      // addr2line expects relative addresses for shared libraries.
249
      if (strcmp (info.file_name, argv0) == 0)
250 251
        offset = (_Unwind_Ptr) ip;
      else
252
        offset = (_Unwind_Ptr) ip - (_Unwind_Ptr) info.base;
253

254 255 256 257 258 259
#ifndef HAVE_GETIPINFO
      // The unwinder gives us the return address. In order to get the right
      // line number for the stack trace, roll it back a little.
      offset -= 1;
#endif

260 261 262
      finder->lookup (binaryName, (jlong) offset);
      *sourceFileName = finder->getSourceFile();
      *lineNum = finder->getLineNum();
263 264 265 266 267 268 269 270 271 272 273
      if (*lineNum == -1 && NameFinder::showRaw())
        {
          gnu::gcj::runtime::StringBuffer *t =
            new gnu::gcj::runtime::StringBuffer(binaryName);
          t->append ((jchar)' ');
          t->append ((jchar)'[');
          // + 1 to compensate for the - 1 adjustment above;
          t->append (Long::toHexString (offset + 1));
          t->append ((jchar)']');
          *sourceFileName = t->toString();
        }
274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
    }
}

// Look up class and method info for the given stack frame, setting 
// frame->klass and frame->meth if they are known.
void
_Jv_StackTrace::FillInFrameInfo (_Jv_StackFrame *frame)
{
  jclass klass = NULL;
  _Jv_Method *meth = NULL;
  
  if (frame->type == frame_native)
    {
      klass = _Jv_StackTrace::ClassForFrame (frame);

      if (klass != NULL)
	// Find method in class
	for (int j = 0; j < klass->method_count; j++)
	  {
293
	    void *wncode = UNWRAP_FUNCTION_DESCRIPTOR (klass->methods[j].ncode);
294
	    if (wncode == frame->start_ip)
295 296 297 298 299 300
	      {
		meth = &klass->methods[j];
		break;
	      }
	  }
    }
301 302 303 304 305
  else if (frame->type == frame_proxy)
    {
      klass = frame->proxyClass;
      meth = frame->proxyMethod;
    }
306
#ifdef INTERPRETER
307 308 309 310 311 312
  else if (frame->type == frame_interpreter)
    {
      _Jv_InterpMethod *interp_meth = frame->interp.meth;
      klass = interp_meth->defining_class;
      meth = interp_meth->self;
    }
313
#endif
314 315 316 317 318 319 320 321 322 323 324 325 326 327
  else
    JvFail ("Unknown frame type");
  
  frame->klass = klass;
  frame->meth = meth;
}

// Convert raw stack frames to a Java array of StackTraceElement objects.
JArray< ::java::lang::StackTraceElement *>*
_Jv_StackTrace::GetStackTraceElements (_Jv_StackTrace *trace, 
  Throwable *throwable __attribute__((unused)))
{
  ArrayList *list = new ArrayList ();

Eric Botcazou committed
328
#if defined (__USING_SJLJ_EXCEPTIONS__) && ! defined (WIN32)
329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346
  // We can't use the nCodeMap without unwinder support. Instead,
  // fake the method name by giving the IP in hex - better than nothing.  
  jstring hex = JvNewStringUTF ("0x");

  for (int i = 0; i < trace->length; i++)
    {
      jstring sourceFileName = NULL;
      jint lineNum = -1;
      _Jv_StackFrame *frame = &trace->frames[i];
      
      jstring className = NULL;
      jstring methodName = hex->concat (Long::toHexString ((jlong) frame->ip));

      StackTraceElement *element = new StackTraceElement (sourceFileName, 
	lineNum, className, methodName, 0);    
      list->add (element);
    }

Eric Botcazou committed
347
#else /* __USING_SJLJ_EXCEPTIONS__ && !WIN32 */
348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382

  //JvSynchronized (ncodeMap);
  UpdateNCodeMap ();

  NameFinder *finder = new NameFinder();
  int start_idx = 0;
  int end_idx = trace->length - 1;

  // First pass: strip superfluous frames from beginning and end of the trace.  
  for (int i = 0; i < trace->length; i++)
    {
      _Jv_StackFrame *frame = &trace->frames[i];
      FillInFrameInfo (frame);

      if (!frame->klass || !frame->meth)
        // Not a Java frame.
        continue;

      // Throw away the top of the stack till we see:
      //  - the constructor(s) of this Throwable, or
      //  - the Throwable.fillInStackTrace call.
      if (frame->klass == throwable->getClass()
          && strcmp (frame->meth->name->chars(), "<init>") == 0)
        start_idx = i + 1;

      if (frame->klass == &Throwable::class$
          && strcmp (frame->meth->name->chars(), "fillInStackTrace") == 0)
	start_idx = i + 1;

      // End the trace at the application's main() method if we see call_main.
      if (frame->klass == &gnu::java::lang::MainThread::class$
          && strcmp (frame->meth->name->chars(), "call_main") == 0)
	end_idx = i - 1;
    }
  
383 384 385
  const jboolean remove_unknown 
    = gnu::gcj::runtime::NameFinder::removeUnknown();

386 387 388 389 390
  // Second pass: Look up line-number info for remaining frames.
  for (int i = start_idx; i <= end_idx; i++)
    {
      _Jv_StackFrame *frame = &trace->frames[i];
      
391 392
      if (frame->klass == NULL && remove_unknown)
	// Not a Java frame.
393
	continue;
394 395 396 397 398

      jstring className = NULL;
      if (frame->klass != NULL)
	className = frame->klass->getName ();

399 400 401 402 403 404 405
      jstring methodName = NULL;
      if (frame->meth)
        methodName = JvNewStringUTF (frame->meth->name->chars());
      
      jstring sourceFileName = NULL;
      jint lineNum = -1;
      
406 407
      getLineNumberForFrame(frame, finder, &sourceFileName, &lineNum, 
			    &methodName);
408 409 410 411 412 413 414
      
      StackTraceElement *element = new StackTraceElement (sourceFileName, lineNum,
        className, methodName, 0);
      list->add (element);
    }
  
  finder->close();
Eric Botcazou committed
415
#endif /* __USING_SJLJ_EXCEPTIONS__ && !WIN32 */
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509

  JArray<Object *> *array = JvNewObjectArray (list->size (), 
    &StackTraceElement::class$, NULL);

  return (JArray<StackTraceElement *>*) list->toArray (array);
}

struct CallingClassTraceData
{
  jclass checkClass;    
  jclass foundClass;
  _Jv_Method *foundMeth;
  bool seen_checkClass;
};

_Unwind_Reason_Code
_Jv_StackTrace::calling_class_trace_fn (_Jv_UnwindState *state)
{
  CallingClassTraceData *trace_data = (CallingClassTraceData *)
    state->trace_data;
  _Jv_StackFrame *frame = &state->frames[state->pos];
  FillInFrameInfo (frame);

  if (trace_data->seen_checkClass
      && frame->klass
      && frame->klass != trace_data->checkClass)
    {
      trace_data->foundClass = frame->klass;
      trace_data->foundMeth = frame->meth;
      return _URC_NORMAL_STOP;
    }
  
  if (frame->klass == trace_data->checkClass)
    trace_data->seen_checkClass = true;
    
  return _URC_NO_REASON;
}

// Find the class immediately above the given class on the call stack. Any 
// intermediate non-Java 
// frames are ignored. If the calling class could not be determined (eg because 
// the unwinder is not supported on this platform), NULL is returned.
// This function is used to implement calling-classloader checks and reflection
// accessibility checks.
// CHECKCLASS is typically the class calling GetCallingClass. The first class
// above CHECKCLASS on the call stack will be returned.
jclass
_Jv_StackTrace::GetCallingClass (jclass checkClass)
{
  jclass result = NULL;
  GetCallerInfo (checkClass, &result, NULL);
  return result;
}

void
_Jv_StackTrace::GetCallerInfo (jclass checkClass, jclass *caller_class,
  _Jv_Method **caller_meth)
{
  int trace_size = 20;
  _Jv_StackFrame frames[trace_size];
  _Jv_UnwindState state (trace_size);
  state.frames = (_Jv_StackFrame *) &frames;

  CallingClassTraceData trace_data;
  trace_data.checkClass = checkClass;
  trace_data.seen_checkClass = false;
  trace_data.foundClass = NULL;
  trace_data.foundMeth = NULL;

  state.trace_function = calling_class_trace_fn;
  state.trace_data = (void *) &trace_data;

  //JvSynchronized (ncodeMap);
  UpdateNCodeMap ();

  _Unwind_Backtrace (UnwindTraceFn, &state);
  
  if (caller_class)
    *caller_class = trace_data.foundClass;
  if (caller_meth)
    *caller_meth = trace_data.foundMeth;
}

_Unwind_Reason_Code
_Jv_StackTrace::non_system_trace_fn (_Jv_UnwindState *state)
{
  _Jv_StackFrame *frame = &state->frames[state->pos];
  FillInFrameInfo (frame);
  
  ClassLoader *classLoader = NULL;

  if (frame->klass)
    {
      classLoader = frame->klass->getClassLoaderInternal();
510
#ifdef INTERPRETER
Tom Tromey committed
511
      if (classLoader != NULL)
512 513 514 515
        {
          state->trace_data = (void *) classLoader;
	  return _URC_NORMAL_STOP;
	}
516
#endif
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541
    }

  return _URC_NO_REASON;
}

ClassLoader *
_Jv_StackTrace::GetFirstNonSystemClassLoader ()
{
  int trace_size = 32;
  _Jv_StackFrame frames[trace_size];
  _Jv_UnwindState state (trace_size);
  state.frames = (_Jv_StackFrame *) &frames;
  state.trace_function = non_system_trace_fn;
  state.trace_data = NULL;

  //JvSynchronized (ncodeMap);
  UpdateNCodeMap ();
  
  _Unwind_Backtrace (UnwindTraceFn, &state);

  if (state.trace_data)
    return (ClassLoader *) state.trace_data;
  
  return NULL;
}
542

543 544 545 546 547 548
struct AccessControlTraceData
{
  jint length;
  jboolean privileged;
};

549 550 551
_Unwind_Reason_Code
_Jv_StackTrace::accesscontrol_trace_fn (_Jv_UnwindState *state)
{
552 553
  AccessControlTraceData *trace_data = (AccessControlTraceData *)
    state->trace_data;
554 555 556
  _Jv_StackFrame *frame = &state->frames[state->pos];
  FillInFrameInfo (frame);

557 558 559
  if (!(frame->klass && frame->meth))
    return _URC_NO_REASON;

560 561 562 563 564
  trace_data->length++;

  // If the previous frame was a call to doPrivileged, then this is
  // the last frame we look at.
  if (trace_data->privileged)
565 566 567 568
    return _URC_NORMAL_STOP;
  
  if (frame->klass == &::java::security::AccessController::class$
      && strcmp (frame->meth->name->chars(), "doPrivileged") == 0)
569
    trace_data->privileged = true;
570 571 572 573

  return _URC_NO_REASON;
}

574
jobjectArray
575
_Jv_StackTrace::GetAccessControlStack (void)
576
{
577 578 579 580
  int trace_size = 100;
  _Jv_StackFrame frames[trace_size];
  _Jv_UnwindState state (trace_size);
  state.frames = (_Jv_StackFrame *) &frames;
581 582 583 584 585

  AccessControlTraceData trace_data;
  trace_data.length = 0;
  trace_data.privileged = false;
  
586
  state.trace_function = accesscontrol_trace_fn;
587
  state.trace_data = (void *) &trace_data;
588 589

  UpdateNCodeMap();
590 591
  _Unwind_Backtrace (UnwindTraceFn, &state);

592
  JArray<jclass> *classes = (JArray<jclass> *)
593 594
    _Jv_NewObjectArray (trace_data.length, &::java::lang::Class::class$, NULL);
  jclass *c = elements (classes);
595

596
  for (int i = 0, j = 0; i < state.pos; i++)
597
    {
598
      _Jv_StackFrame *frame = &state.frames[i];
599 600 601 602 603 604
      if (!frame->klass || !frame->meth)
	continue;
      c[j] = frame->klass;
      j++;
    }

605 606 607 608 609 610 611
  jobjectArray result =
    (jobjectArray) _Jv_NewObjectArray (2, &::java::lang::Object::class$,
					 NULL);
  jobject *r = elements (result);
  r[0] = (jobject) classes;
  r[1] = (jobject) new Boolean (trace_data.privileged);
  
612 613
  return result;
}
614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828

JArray<jclass> *
_Jv_StackTrace::GetStackWalkerStack ()
{
  int trace_size = 100;
  _Jv_StackFrame frames[trace_size];
  _Jv_UnwindState state (trace_size);
  state.frames = (_Jv_StackFrame *) &frames;

  UpdateNCodeMap ();
  _Unwind_Backtrace (UnwindTraceFn, &state);

  int num_frames = 0, start_frame = -1;
  enum
    {
      VMSW_GETCLASSCONTEXT,
      JLRM_INVOKE_OR_USER_FN,
      USER_FN
    }
  expect = VMSW_GETCLASSCONTEXT;
  for (int i = 0; i < state.pos; i++)
    {
      _Jv_StackFrame *frame = &state.frames[i];
      FillInFrameInfo (frame);
      if (!frame->klass || !frame->meth)
	continue;

      switch (expect)
	{
	case VMSW_GETCLASSCONTEXT:
	  JvAssert (
	    frame->klass == &::gnu::classpath::VMStackWalker::class$
	    && strcmp (frame->meth->name->chars(), "getClassContext") == 0);
	  expect = JLRM_INVOKE_OR_USER_FN;
	  break;

	case JLRM_INVOKE_OR_USER_FN:
	  if (frame->klass != &::java::lang::reflect::Method::class$
	      || strcmp (frame->meth->name->chars(), "invoke") != 0)
	    start_frame = i;
	  expect = USER_FN;
	  break;

	case USER_FN:
	  if (start_frame == -1)
	    start_frame = i;
	  break;
	}

      if (start_frame != -1)
	{
	  if (frame->klass == &::gnu::java::lang::MainThread::class$)
	    break;
	  num_frames++;
	}
    }
  JvAssert (num_frames > 0 && start_frame > 0);

  JArray<jclass> *result = (JArray<jclass> *)
    _Jv_NewObjectArray (num_frames, &::java::lang::Class::class$, NULL);
  jclass *c = elements (result);

  for (int i = start_frame, j = 0; i < state.pos && j < num_frames; i++)
    {
      _Jv_StackFrame *frame = &state.frames[i];
      if (!frame->klass || !frame->meth)
	continue;
      c[j] = frame->klass;
      j++;
    }
 
  return result;
}

typedef enum
  {
    VMSW_GET_CALLING_ITEM,
    JLRM_INVOKE_OR_CALLER,
    CALLER,
    CALLER_OF_CALLER
  } gswcc_expect;

struct StackWalkerTraceData
{
  gswcc_expect expect;
  jclass result;
};

_Unwind_Reason_Code
_Jv_StackTrace::stackwalker_trace_fn (_Jv_UnwindState *state)
{
  StackWalkerTraceData *trace_data = (StackWalkerTraceData *)
    state->trace_data;
  _Jv_StackFrame *frame = &state->frames[state->pos];
  FillInFrameInfo (frame);

  if (!(frame->klass && frame->meth))
    return _URC_NO_REASON;

  switch (trace_data->expect)
    {
    case VMSW_GET_CALLING_ITEM:
      JvAssert (frame->klass == &::gnu::classpath::VMStackWalker::class$);
      trace_data->expect = JLRM_INVOKE_OR_CALLER;
      break;

    case JLRM_INVOKE_OR_CALLER:
      if (frame->klass == &::java::lang::reflect::Method::class$
	  && strcmp (frame->meth->name->chars(), "invoke") == 0)
	trace_data->expect = CALLER;
      else
	trace_data->expect = CALLER_OF_CALLER;
      break;

    case CALLER:
      trace_data->expect = CALLER_OF_CALLER;
      break;

    case CALLER_OF_CALLER:
      trace_data->result = frame->klass;
      return _URC_NORMAL_STOP;
    }

  return _URC_NO_REASON;
}

jclass
_Jv_StackTrace::GetStackWalkerCallingClass (void)
{
  int trace_size = 100;
  _Jv_StackFrame frames[trace_size];
  _Jv_UnwindState state (trace_size);
  state.frames = (_Jv_StackFrame *) &frames;

  StackWalkerTraceData trace_data;
  trace_data.expect = VMSW_GET_CALLING_ITEM;
  trace_data.result = NULL;
  
  state.trace_function = stackwalker_trace_fn;
  state.trace_data = (void *) &trace_data;

  UpdateNCodeMap();
  _Unwind_Backtrace (UnwindTraceFn, &state);

  return trace_data.result;
}

struct StackWalkerNNLTraceData
{
  gswcc_expect expect;
  ClassLoader *result;
};

_Unwind_Reason_Code
_Jv_StackTrace::stackwalker_nnl_trace_fn (_Jv_UnwindState *state)
{
  StackWalkerNNLTraceData *trace_data = (StackWalkerNNLTraceData *)
    state->trace_data;
  _Jv_StackFrame *frame = &state->frames[state->pos];
  FillInFrameInfo (frame);

  if (!(frame->klass && frame->meth))
    return _URC_NO_REASON;

  switch (trace_data->expect)
    {
    case VMSW_GET_CALLING_ITEM:
      JvAssert (frame->klass == &::gnu::classpath::VMStackWalker::class$);
      trace_data->expect = JLRM_INVOKE_OR_CALLER;
      break;

    case JLRM_INVOKE_OR_CALLER:
      if (frame->klass == &::java::lang::reflect::Method::class$
	  && strcmp (frame->meth->name->chars(), "invoke") == 0)
	trace_data->expect = CALLER;
      else
	trace_data->expect = CALLER_OF_CALLER;
      break;

    case CALLER:
      trace_data->expect = CALLER_OF_CALLER;
      break;

    case CALLER_OF_CALLER:
      ClassLoader *cl = frame->klass->getClassLoaderInternal ();
      if (cl != NULL)
	{
	  trace_data->result = cl;
	  return _URC_NORMAL_STOP;
	}
    }

  return _URC_NO_REASON;
}

ClassLoader *
_Jv_StackTrace::GetStackWalkerFirstNonNullLoader (void)
{
  int trace_size = 100;
  _Jv_StackFrame frames[trace_size];
  _Jv_UnwindState state (trace_size);
  state.frames = (_Jv_StackFrame *) &frames;

  StackWalkerNNLTraceData trace_data;
  trace_data.expect = VMSW_GET_CALLING_ITEM;
  trace_data.result = NULL;
  
  state.trace_function = stackwalker_nnl_trace_fn;
  state.trace_data = (void *) &trace_data;

  UpdateNCodeMap();
  _Unwind_Backtrace (UnwindTraceFn, &state);

  return trace_data.result;
}