From aaf31c6adef93c9d9de13e35044a110afebc3fdd Mon Sep 17 00:00:00 2001 From: Brian Barrett Date: Thu, 27 Jul 2006 02:56:02 +0000 Subject: [PATCH] * Make the backtrace printing functionality a framework * Copy Linux and Solaris backtrace support from util/stacktrace.c * Added backtrace support for Mac OS X. This commit was SVN r11023. --- NEWS | 1 + config/ompi_check_func_lib.m4 | 4 +- configure.ac | 8 +- opal/mca/backtrace/Makefile.am | 41 + opal/mca/backtrace/backtrace.h | 75 + opal/mca/backtrace/base/Makefile.am | 23 + opal/mca/backtrace/base/backtrace_component.c | 74 + opal/mca/backtrace/base/base.h | 77 + opal/mca/backtrace/configure.m4 | 21 + opal/mca/backtrace/darwin/Makefile.am | 30 + .../MoreDebugging/MoreAddrToSym.c | 339 ++++ .../MoreDebugging/MoreAddrToSym.h | 143 ++ .../MoreDebugging/MoreBacktrace.c | 1755 +++++++++++++++++ .../MoreDebugging/MoreBacktrace.h | 274 +++ .../MoreBacktraceTest/._MainWindow.nib | Bin 0 -> 82 bytes .../MoreBacktraceTest/._main.nib | Bin 0 -> 82 bytes .../MoreBacktraceTest/Info.plist | 26 + .../MainWindow.nib/classes.nib | 4 + .../MoreBacktraceTest/MainWindow.nib/info.nib | 18 + .../MainWindow.nib/objects.xib | 81 + .../MoreBacktraceTest/MoreBacktraceTest.c | 573 ++++++ .../project.pbxproj | 424 ++++ .../MoreBacktraceTestCommon.c | 765 +++++++ .../MoreBacktraceTestCommon.h | 127 ++ .../MoreBacktraceTest/MoreBacktraceTestTool.c | 169 ++ .../MoreBacktraceTest/main.nib/classes.nib | 4 + .../MoreBacktraceTest/main.nib/info.nib | 19 + .../MoreBacktraceTest/main.nib/objects.xib | 101 + .../darwin/MoreBacktrace/MoreSetup.h | 1 + opal/mca/backtrace/darwin/backtrace_darwin.c | 105 + .../darwin/backtrace_darwin_component.c | 47 + opal/mca/backtrace/darwin/configure.m4 | 43 + opal/mca/backtrace/darwin/configure.params | 15 + opal/mca/backtrace/execinfo/Makefile.am | 23 + .../backtrace/execinfo/backtrace_execinfo.c | 61 + .../execinfo/backtrace_execinfo_component.c | 47 + opal/mca/backtrace/execinfo/configure.m4 | 39 + opal/mca/backtrace/execinfo/configure.params | 15 + opal/mca/backtrace/none/Makefile.am | 23 + opal/mca/backtrace/none/backtrace_none.c | 33 + .../backtrace/none/backtrace_none_component.c | 47 + opal/mca/backtrace/none/configure.m4 | 30 + opal/mca/backtrace/none/configure.params | 15 + opal/mca/backtrace/printstack/Makefile.am | 23 + .../printstack/backtrace_printstack.c | 38 + .../backtrace_printstack_component.c | 47 + opal/mca/backtrace/printstack/configure.m4 | 39 + .../mca/backtrace/printstack/configure.params | 15 + opal/util/stacktrace.c | 27 +- 49 files changed, 5876 insertions(+), 33 deletions(-) create mode 100644 opal/mca/backtrace/Makefile.am create mode 100644 opal/mca/backtrace/backtrace.h create mode 100644 opal/mca/backtrace/base/Makefile.am create mode 100644 opal/mca/backtrace/base/backtrace_component.c create mode 100644 opal/mca/backtrace/base/base.h create mode 100644 opal/mca/backtrace/configure.m4 create mode 100644 opal/mca/backtrace/darwin/Makefile.am create mode 100644 opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreAddrToSym.c create mode 100644 opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreAddrToSym.h create mode 100644 opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktrace.c create mode 100644 opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktrace.h create mode 100644 opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/._MainWindow.nib create mode 100644 opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/._main.nib create mode 100644 opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/Info.plist create mode 100644 opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MainWindow.nib/classes.nib create mode 100644 opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MainWindow.nib/info.nib create mode 100644 opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MainWindow.nib/objects.xib create mode 100644 opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MoreBacktraceTest.c create mode 100644 opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MoreBacktraceTest.xcodeproj/project.pbxproj create mode 100644 opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MoreBacktraceTestCommon.c create mode 100644 opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MoreBacktraceTestCommon.h create mode 100644 opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MoreBacktraceTestTool.c create mode 100644 opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/main.nib/classes.nib create mode 100644 opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/main.nib/info.nib create mode 100644 opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/main.nib/objects.xib create mode 100644 opal/mca/backtrace/darwin/MoreBacktrace/MoreSetup.h create mode 100644 opal/mca/backtrace/darwin/backtrace_darwin.c create mode 100644 opal/mca/backtrace/darwin/backtrace_darwin_component.c create mode 100644 opal/mca/backtrace/darwin/configure.m4 create mode 100644 opal/mca/backtrace/darwin/configure.params create mode 100644 opal/mca/backtrace/execinfo/Makefile.am create mode 100644 opal/mca/backtrace/execinfo/backtrace_execinfo.c create mode 100644 opal/mca/backtrace/execinfo/backtrace_execinfo_component.c create mode 100644 opal/mca/backtrace/execinfo/configure.m4 create mode 100644 opal/mca/backtrace/execinfo/configure.params create mode 100644 opal/mca/backtrace/none/Makefile.am create mode 100644 opal/mca/backtrace/none/backtrace_none.c create mode 100644 opal/mca/backtrace/none/backtrace_none_component.c create mode 100644 opal/mca/backtrace/none/configure.m4 create mode 100644 opal/mca/backtrace/none/configure.params create mode 100644 opal/mca/backtrace/printstack/Makefile.am create mode 100644 opal/mca/backtrace/printstack/backtrace_printstack.c create mode 100644 opal/mca/backtrace/printstack/backtrace_printstack_component.c create mode 100644 opal/mca/backtrace/printstack/configure.m4 create mode 100644 opal/mca/backtrace/printstack/configure.params diff --git a/NEWS b/NEWS index a99d658f78..652a480d86 100644 --- a/NEWS +++ b/NEWS @@ -25,6 +25,7 @@ version 1.0. 1.2 --- +- Added stacktrace support for Solaris and Mac OS X. - Update event library to libevent-1.1a - Fixed standards conformance issues with MPI_ERR_TRUNCATED and setting MPI_ERROR during MPI_TEST/MPI_WAIT. diff --git a/config/ompi_check_func_lib.m4 b/config/ompi_check_func_lib.m4 index 837c8b12ec..40e542eedc 100644 --- a/config/ompi_check_func_lib.m4 +++ b/config/ompi_check_func_lib.m4 @@ -17,7 +17,7 @@ dnl dnl $HEADER$ dnl -# OMPI_CHECK_FUNC_LIB(func, lib) +# OMPI_CHECK_FUNC_LIB(func, lib, [action-if-found], [action-if-not-found]) # ------------------------------ # Try to find function func, first with the present LIBS, second with # lib added to LIBS. If func is found with the libraries listed in @@ -42,6 +42,6 @@ AC_DEFUN([OMPI_CHECK_FUNC_LIB],[ # see if we actually have $1. Use AC_CHECK_FUNCS so that it # does the glibc "not implemented" check. Will use the current LIBS, # so will check in -l$2 if we decided we needed it above - AC_CHECK_FUNCS([$1]) + AC_CHECK_FUNCS([$1], $3, $4) AS_VAR_POPDEF([ompi_var])dnl ]) diff --git a/configure.ac b/configure.ac index 827b428dd0..316b60f2d4 100644 --- a/configure.ac +++ b/configure.ac @@ -570,8 +570,7 @@ AC_CHECK_HEADERS([alloca.h aio.h arpa/inet.h dirent.h \ sys/resource.h sys/select.h sys/socket.h sys/sockio.h \ stdarg.h sys/stat.h sys/statvfs.h sys/time.h sys/tree.h \ sys/types.h sys/uio.h sys/utsname.h sys/wait.h syslog.h \ - time.h termios.h ulimit.h unistd.h util.h utmp.h malloc.h \ - ucontext.h]) + time.h termios.h ulimit.h unistd.h util.h utmp.h malloc.h]) # Needed to work around Darwin requiring sys/socket.h for # net/if.h @@ -689,16 +688,13 @@ AC_CHECK_LIB([socket], [socket]) # Solaris has sched_yeild in -lrt, usually in libc OMPI_CHECK_FUNC_LIB([sched_yield], [rt]) -# FreeBSD has backtrace in -lexecinfo, usually in libc -OMPI_CHECK_FUNC_LIB([backtrace], [execinfo]) - # IRIX has dirname in -lgen, usually in libc OMPI_CHECK_FUNC_LIB([dirname], [gen]) # Darwin doesn't need -lm, as it's a symlink to libSystem.dylib OMPI_CHECK_FUNC_LIB([ceil], [m]) -AC_CHECK_FUNCS([asprintf snprintf vasprintf vsnprintf openpty isatty htonl ntohl htons ntohs getpwuid fork waitpid execve pipe ptsname setsid mmap mallopt tcgetpgrp printstack]) +AC_CHECK_FUNCS([asprintf snprintf vasprintf vsnprintf openpty isatty htonl ntohl htons ntohs getpwuid fork waitpid execve pipe ptsname setsid mmap mallopt tcgetpgrp]) # # Make sure we can copy va_lists (need check declared, not linkable) diff --git a/opal/mca/backtrace/Makefile.am b/opal/mca/backtrace/Makefile.am new file mode 100644 index 0000000000..d5403a1686 --- /dev/null +++ b/opal/mca/backtrace/Makefile.am @@ -0,0 +1,41 @@ +# +# Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana +# University Research and Technology +# Corporation. All rights reserved. +# Copyright (c) 2004-2005 The University of Tennessee and The University +# of Tennessee Research Foundation. All rights +# reserved. +# Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, +# University of Stuttgart. All rights reserved. +# Copyright (c) 2004-2005 The Regents of the University of California. +# All rights reserved. +# $COPYRIGHT$ +# +# Additional copyrights may follow +# +# $HEADER$ +# + +# main library setup +noinst_LTLIBRARIES = libmca_backtrace.la +libmca_backtrace_la_SOURCES = + +# header setup +nobase_opal_HEADERS = + +# local files +headers = backtrace.h +libmca_backtrace_la_SOURCES += $(headers) + +# Conditionally install the header files +if WANT_INSTALL_HEADERS +nobase_opal_HEADERS += $(headers) +opaldir = $(includedir)/openmpi/opal/mca/backtrace +else +opaldir = $(includedir) +endif + +include base/Makefile.am + +distclean-local: + rm -f base/static-components.h diff --git a/opal/mca/backtrace/backtrace.h b/opal/mca/backtrace/backtrace.h new file mode 100644 index 0000000000..5feda167e5 --- /dev/null +++ b/opal/mca/backtrace/backtrace.h @@ -0,0 +1,75 @@ +/* + * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana + * University Research and Technology + * Corporation. All rights reserved. + * Copyright (c) 2004-2005 The University of Tennessee and The University + * of Tennessee Research Foundation. All rights + * reserved. + * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, + * University of Stuttgart. All rights reserved. + * Copyright (c) 2004-2006 The Regents of the University of California. + * All rights reserved. + * $COPYRIGHT$ + * + * Additional copyrights may follow + * + * $HEADER$ + */ + +#ifndef OPAL_MCA_BACKTRACE_BACKTRACE_H +#define OPAL_MCA_BACKTRACE_BACKTRACE_H + +#include "opal_config.h" + +#include "opal/mca/mca.h" +#include "opal/mca/base/base.h" + +/* + * Most of this file is just for ompi_info. There are two interface + * functions, both of which are called directly. The joy of link-time + * components. + */ + + +/* + * print back trace to FILE file + * + * \note some attempts made to be signal safe. + */ +void opal_backtrace_print(FILE *file); + +/* + * Return back trace in buffer. buffer will be allocated by the + * backtrace component, but should be free'ed by the caller. + * + * \note Probably bad to call this from a signal handler. + * + */ +int opal_backtrace_buffer(char*** messages, int *len); + + +/** + * Structure for backtrace v1.0.0 components. + * Chained to MCA v1.0.0 + */ +struct opal_backtrace_base_component_1_0_0_t { + /** MCA base component */ + mca_base_component_t backtracec_version; + /** MCA base data */ + mca_base_component_data_1_0_0_t backtracec_data; +}; +/** + * Convenience typedef + */ +typedef struct opal_backtrace_base_component_1_0_0_t opal_backtrace_base_component_1_0_0_t; + +/* + * Macro for use in components that are of type backtrace v1.0.0 + */ +#define OPAL_BACKTRACE_BASE_VERSION_1_0_0 \ + /* backtrace v1.0 is chained to MCA v1.0 */ \ + MCA_BASE_VERSION_1_0_0, \ + /* backtrace v1.0 */ \ + "backtrace", 1, 0, 0 + +#endif /* OPAL_MCA_BACKTRACE_BACKTRACE_H */ diff --git a/opal/mca/backtrace/base/Makefile.am b/opal/mca/backtrace/base/Makefile.am new file mode 100644 index 0000000000..ed88ad439e --- /dev/null +++ b/opal/mca/backtrace/base/Makefile.am @@ -0,0 +1,23 @@ +# +# Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana +# University Research and Technology +# Corporation. All rights reserved. +# Copyright (c) 2004-2005 The University of Tennessee and The University +# of Tennessee Research Foundation. All rights +# reserved. +# Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, +# University of Stuttgart. All rights reserved. +# Copyright (c) 2004-2005 The Regents of the University of California. +# All rights reserved. +# $COPYRIGHT$ +# +# Additional copyrights may follow +# +# $HEADER$ +# + +headers += \ + base/base.h + +libmca_backtrace_la_SOURCES += \ + base/backtrace_component.c diff --git a/opal/mca/backtrace/base/backtrace_component.c b/opal/mca/backtrace/base/backtrace_component.c new file mode 100644 index 0000000000..947040bc12 --- /dev/null +++ b/opal/mca/backtrace/base/backtrace_component.c @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana + * University Research and Technology + * Corporation. All rights reserved. + * Copyright (c) 2004-2005 The University of Tennessee and The University + * of Tennessee Research Foundation. All rights + * reserved. + * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, + * University of Stuttgart. All rights reserved. + * Copyright (c) 2004-2005 The Regents of the University of California. + * All rights reserved. + * $COPYRIGHT$ + * + * Additional copyrights may follow + * + * $HEADER$ + */ + + +#include "opal_config.h" + +#include "opal/constants.h" +#include "opal/util/output.h" +#include "opal/mca/mca.h" +#include "opal/mca/base/base.h" +#include "opal/mca/base/mca_base_param.h" +#include "opal/mca/backtrace/backtrace.h" +#include "opal/mca/backtrace/base/base.h" + + +/* + * The following file was created by configure. It contains extern + * statements and the definition of an array of pointers to each + * component's public mca_base_component_t struct. + */ +#include "opal/mca/backtrace/base/static-components.h" + + +/* + * Globals + */ +opal_list_t opal_backtrace_base_components_opened; + + +int +opal_backtrace_base_open(void) +{ + /* Open up all available components */ + if (OPAL_SUCCESS != + mca_base_components_open("backtrace", 0, + mca_backtrace_base_static_components, + &opal_backtrace_base_components_opened, + true)) { + return OPAL_ERROR; + } + + /* All done */ + return OPAL_SUCCESS; +} + + +int +opal_backtrace_base_close(void) +{ + /* Close all components that are still open (this should only + happen during laminfo). */ + mca_base_components_close(0, + &opal_backtrace_base_components_opened, + NULL); + OBJ_DESTRUCT(&opal_backtrace_base_components_opened); + + /* All done */ + return OPAL_SUCCESS; +} diff --git a/opal/mca/backtrace/base/base.h b/opal/mca/backtrace/base/base.h new file mode 100644 index 0000000000..0c185517b7 --- /dev/null +++ b/opal/mca/backtrace/base/base.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana + * University Research and Technology + * Corporation. All rights reserved. + * Copyright (c) 2004-2005 The University of Tennessee and The University + * of Tennessee Research Foundation. All rights + * reserved. + * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, + * University of Stuttgart. All rights reserved. + * Copyright (c) 2004-2006 The Regents of the University of California. + * All rights reserved. + * $COPYRIGHT$ + * + * Additional copyrights may follow + * + * $HEADER$ + * + */ + +#ifndef OPAL_BACKTRACE_BASE_H +#define OPAL_BACKTRACE_BASE_H + +#include "opal_config.h" + +#include "opal/mca/backtrace/backtrace.h" + + +/* + * Global functions for MCA overall backtrace open and close + */ + +#if defined(c_plusplus) || defined(__cplusplus) +extern "C" { +#endif + + /** + * Initialize the backtrace MCA framework + * + * @retval OPAL_SUCCESS Upon success + * @retval OPAL_ERROR Upon failure + * + * This must be the first function invoked in the backtrace MCA + * framework. It initializes the backtrace MCA framework, finds + * and opens backtrace components, etc. + * + * This function is invoked during opal_init() and during the + * initialization of the special case of the laminfo command. + * + * This function fills in the internal global variable + * opal_backtrace_base_components_opened, which is a list of all + * backtrace components that were successfully opened. This + * variable should \em only be used by other backtrace base + * functions -- it is not considered a public interface member -- + * and is only mentioned here for completeness. + */ + OMPI_DECLSPEC int opal_backtrace_base_open(void); + + + /** + * Shut down the backtrace MCA framework. + * + * @retval OPAL_SUCCESS Always + * + * This function shuts down everything in the backtrace MCA + * framework, and is called during opal_finalize() and the + * special case of the laminfo command. + * + * It must be the last function invoked on the backtrace MCA framework. + */ + OMPI_DECLSPEC int opal_backtrace_base_close(void); + + extern opal_list_t opal_backtrace_base_components_opened; + +#if defined(c_plusplus) || defined(__cplusplus) +} +#endif +#endif /* OPAL_BASE_BACKTRACE_H */ diff --git a/opal/mca/backtrace/configure.m4 b/opal/mca/backtrace/configure.m4 new file mode 100644 index 0000000000..5f48820531 --- /dev/null +++ b/opal/mca/backtrace/configure.m4 @@ -0,0 +1,21 @@ +dnl -*- shell-script -*- +dnl +dnl Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana +dnl University Research and Technology +dnl Corporation. All rights reserved. +dnl Copyright (c) 2004-2005 The University of Tennessee and The University +dnl of Tennessee Research Foundation. All rights +dnl reserved. +dnl Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, +dnl University of Stuttgart. All rights reserved. +dnl Copyright (c) 2004-2006 The Regents of the University of California. +dnl All rights reserved. +dnl $COPYRIGHT$ +dnl +dnl Additional copyrights may follow +dnl +dnl $HEADER$ +dnl + +dnl we only want one :) +m4_define(MCA_backtrace_CONFIGURE_MODE, STOP_AT_FIRST) diff --git a/opal/mca/backtrace/darwin/Makefile.am b/opal/mca/backtrace/darwin/Makefile.am new file mode 100644 index 0000000000..af77e4e8a5 --- /dev/null +++ b/opal/mca/backtrace/darwin/Makefile.am @@ -0,0 +1,30 @@ +# +# Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana +# University Research and Technology +# Corporation. All rights reserved. +# Copyright (c) 2004-2005 The University of Tennessee and The University +# of Tennessee Research Foundation. All rights +# reserved. +# Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, +# University of Stuttgart. All rights reserved. +# Copyright (c) 2004-2005 The Regents of the University of California. +# All rights reserved. +# $COPYRIGHT$ +# +# Additional copyrights may follow +# +# $HEADER$ +# + +AM_CPPFLAGS = -I$(srcdir)/MoreBacktrace + +noinst_LTLIBRARIES = libmca_backtrace_darwin.la + +libmca_backtrace_darwin_la_SOURCES = \ + backtrace_darwin.c \ + backtrace_darwin_component.c \ + MoreBacktrace/MoreSetup.h \ + MoreBacktrace/MoreDebugging/MoreAddrToSym.c \ + MoreBacktrace/MoreDebugging/MoreAddrToSym.h \ + MoreBacktrace/MoreDebugging/MoreBacktrace.c \ + MoreBacktrace/MoreDebugging/MoreBacktrace.h diff --git a/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreAddrToSym.c b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreAddrToSym.c new file mode 100644 index 0000000000..2f473e29c5 --- /dev/null +++ b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreAddrToSym.c @@ -0,0 +1,339 @@ +/* + File: MoreAddrToSym.c + + Contains: Code for mapping addresses to their symbolic names. + + Written by: DTS + + Copyright: Copyright (c) 2006 by Apple Computer, Inc., All Rights Reserved. + + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. + ("Apple") in consideration of your agreement to the following terms, and your + use, installation, modification or redistribution of this Apple software + constitutes acceptance of these terms. If you do not agree with these terms, + please do not use, install, modify or redistribute this Apple software. + + In consideration of your agreement to abide by the following terms, and subject + to these terms, Apple grants you a personal, non-exclusive license, under AppleÕs + copyrights in this original Apple software (the "Apple Software"), to use, + reproduce, modify and redistribute the Apple Software, with or without + modifications, in source and/or binary forms; provided that if you redistribute + the Apple Software in its entirety and without modifications, you must retain + this notice and the following text and disclaimers in all such redistributions of + the Apple Software. Neither the name, trademarks, service marks or logos of + Apple Computer, Inc. may be used to endorse or promote products derived from the + Apple Software without specific prior written permission from Apple. Except as + expressly stated in this notice, no other rights or licenses, express or implied, + are granted by Apple herein, including but not limited to any patent rights that + may be infringed by your derivative works or by other works in which the Apple + Software may be incorporated. + + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED + WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN + COMBINATION WITH YOUR PRODUCTS. + + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION + OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT + (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Change History (most recent first): + +$Log: MoreAddrToSym.c,v $ +Revision 1.2 2006/01/22 22:47:13 eskimo1 +Significant rewrite to account for changes in MoreBacktrace. Still not as functional as I'd like. + +Revision 1.1 2003/04/04 15:02:57 eskimo1 +First checked in. This code still has bugs, but I've written enough code that checking in is a good idea. + + +*/ + +///////////////////////////////////////////////////////////////// + +// Our Prototypes + +#include "MoreAddrToSym.h" + +// Mac OS Interfaces + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// MIB Prototypes + +///////////////////////////////////////////////////////////////// + +extern int MoreAToSCreate(size_t count, MoreAToSSymInfo *symbols[]) + // See comments in header. +{ + int err; + + assert(symbols != NULL); + assert(*symbols == NULL); + + err = 0; + *symbols = calloc(count, sizeof(MoreAToSSymInfo)); + if (*symbols == NULL) { + err = ENOMEM; + } + + assert( (err == 0) == (*symbols != NULL) ); + + return err; +} + +extern void MoreAToSDestroy(size_t count, MoreAToSSymInfo symbols[]) + // See comments in header. +{ + size_t index; + + if (symbols != NULL) { + for (index = 0; index < count; index++) { + free( (void *) symbols[index].symbolName ); + } + free(symbols); + } +} + +static int ReplaceSymbolIfBetter( + MoreAToSSymInfo * existingSymbol, + MoreAToSSymbolType symbolType, + const char * symbolName, + MoreAToSOffset symbolOffset +) + // Check to see whether the symbolic information defined by symbolType, + // symbolName, and symbolOffset is 'better' than the symbolic information + // in existingSymbol. If so, replace the old information with the new. + // In this case, 'better' is defined as being having a smaller + // symbolOffset, that is, we've found a symbol that's closer to the + // requested address. + // + // The idea behind this code is that one day I'll come up with multiple + // ways to get at symbolic information, and then I'll only keep the best + // result. However, I don't really use this functionality yet. +{ + int err; + bool replace; + + assert(existingSymbol != NULL); + assert(symbolType != kMoreAToSNoSymbol); + assert(symbolName != NULL); + assert( (existingSymbol->symbolType == kMoreAToSNoSymbol) == (existingSymbol->symbolName == NULL) ); + + err = 0; + + if (existingSymbol->symbolType == kMoreAToSNoSymbol) { + replace = true; + } else { + replace = (symbolOffset < existingSymbol->symbolOffset); + } + + if (replace) { + char * tmp; + + tmp = strdup(symbolName); + if (tmp == NULL) { + err = ENOMEM; + } else { + free( (void *) existingSymbol->symbolName ); + + existingSymbol->symbolType = symbolType; + existingSymbol->symbolName = tmp; + existingSymbol->symbolOffset = symbolOffset; + } + } + + return err; +} + +// FindOwnerOfPC and GetFunctionName countesy of Ed Wynne. Don't ask me +// how it works, or I'll start to whimper. Actually, I have a fairly good idea +// how it works, and a fairly good idea how to fix its more serious problems, +// but I just don't have time at the moment. + +static const struct mach_header *FindOwnerOfPC(unsigned int pc) +{ + unsigned int count,index,offset,cmdex; + struct segment_command * seg; + struct load_command * cmd; + const struct mach_header * header; + + count = _dyld_image_count(); + for (index = 0;index < count;index += 1) + { + header = _dyld_get_image_header(index); + offset = _dyld_get_image_vmaddr_slide(index); + cmd = (struct load_command*)((char*)header + sizeof(struct mach_header)); + for (cmdex = 0;cmdex < header->ncmds;cmdex += 1,cmd = (struct load_command*)((char*)cmd + cmd->cmdsize)) + { + switch(cmd->cmd) + { + case LC_SEGMENT: + seg = (struct segment_command*)cmd; + if ((pc >= (seg->vmaddr + offset)) && (pc < (seg->vmaddr + offset + seg->vmsize))) + return header; + break; + } + } + } + + return NULL; +} + +static const char *GetFunctionName(unsigned int pc,unsigned int *offset, bool *publicSymbol) +{ + struct segment_command *seg_linkedit = NULL; + struct segment_command *seg_text = NULL; + struct symtab_command *symtab = NULL; + struct load_command *cmd; + const struct mach_header*header; + unsigned int vm_slide,file_slide; + struct nlist *sym,*symbase; + char *strings,*name; + unsigned int base,index; + + header = FindOwnerOfPC(pc); + if (header != NULL) + { + cmd = (struct load_command*)((char*)header + sizeof(struct mach_header)); + for (index = 0;index < header->ncmds;index += 1,cmd = (struct load_command*)((char*)cmd + cmd->cmdsize)) + { + switch(cmd->cmd) + { + case LC_SEGMENT: + if (!strcmp(((struct segment_command*)cmd)->segname,SEG_TEXT)) + seg_text = (struct segment_command*)cmd; + else if (!strcmp(((struct segment_command*)cmd)->segname,SEG_LINKEDIT)) + seg_linkedit = (struct segment_command*)cmd; + break; + + case LC_SYMTAB: + symtab = (struct symtab_command*)cmd; + break; + } + } + + if ((seg_text == NULL) || (seg_linkedit == NULL) || (symtab == NULL)) + { + *offset = 0; + return NULL; + } + + vm_slide = (unsigned long)header - (unsigned long)seg_text->vmaddr; + file_slide = ((unsigned long)seg_linkedit->vmaddr - (unsigned long)seg_text->vmaddr) - seg_linkedit->fileoff; + symbase = (struct nlist*)((unsigned long)header + (symtab->symoff + file_slide)); + strings = (char*)((unsigned long)header + (symtab->stroff + file_slide)); + + // Look for a global symbol. + for (index = 0,sym = symbase;index < symtab->nsyms;index += 1,sym += 1) + { + if (sym->n_type != N_FUN) + continue; + + name = sym->n_un.n_strx ? (strings + sym->n_un.n_strx) : NULL; + base = sym->n_value + vm_slide; + + for (index += 1,sym += 1;index < symtab->nsyms;index += 1,sym += 1) + if (sym->n_type == N_FUN) + break; + + if ((pc >= base) && (pc <= (base + sym->n_value)) && (name != NULL) && (strlen(name) > 0)) + { + *offset = pc - base; + *publicSymbol = true; + return strdup(name); + } + } + + // Look for a reasonably close private symbol. + for (name = NULL,base = 0xFFFFFFFF,index = 0,sym = symbase;index < symtab->nsyms;index += 1,sym += 1) + { + if ((sym->n_type & 0x0E) != 0x0E) + continue; + + if ((sym->n_value + vm_slide) > pc) + continue; + + if ((base != 0xFFFFFFFF) && ((pc - (sym->n_value + vm_slide)) >= (pc - base))) + continue; + + name = sym->n_un.n_strx ? (strings + sym->n_un.n_strx) : NULL; + base = sym->n_value + vm_slide; + } + + *offset = pc - base; + *publicSymbol = false; + return (name != NULL) ? strdup(name) : NULL; + } + + *offset = 0; + return NULL; +} + +extern int MoreAToSCopySymbolNamesUsingDyld( + size_t count, + MoreAToSAddr addresses[], + MoreAToSSymInfo symbols[] +) + // See comments in header. +{ + int err; + size_t index; + + assert(addresses != NULL); + assert(symbols != NULL); + + err = 0; + for (index = 0; index < count; index++) { + const char * thisSymbol; + const char * cleanSymbol; + unsigned int thisSymbolOffset; + bool thisSymbolPublic; + MoreAToSSymbolType thisSymbolType; + + thisSymbol = NULL; + if (addresses[index] != 0) { // NULL is never a useful symbol + thisSymbol = GetFunctionName( (unsigned int) addresses[index], &thisSymbolOffset, &thisSymbolPublic); + } + if (thisSymbol != NULL) { + + // Mach-O symbols virtually always start with '_'. If there's one there, + // let's strip it. + + if (thisSymbol[0] == '_') { + cleanSymbol = &thisSymbol[1]; + } else { + cleanSymbol = thisSymbol; + } + + if (thisSymbolPublic) { + thisSymbolType = kMoreAToSDyldPubliSymbol; + } else { + thisSymbolType = kMoreAToSDyldPrivateSymbol; + } + + err = ReplaceSymbolIfBetter(&symbols[index], thisSymbolType, cleanSymbol, thisSymbolOffset); + } + + free( (void *) thisSymbol); + + if (err != 0) { + break; + } + } + + return err; +} diff --git a/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreAddrToSym.h b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreAddrToSym.h new file mode 100644 index 0000000000..eeb8a51cf4 --- /dev/null +++ b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreAddrToSym.h @@ -0,0 +1,143 @@ +/* + File: MoreAddrToSym.h + + Contains: Code for mapping addresses to their symbolic names. + + Written by: DTS + + Copyright: Copyright (c) 2006 by Apple Computer, Inc., All Rights Reserved. + + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. + ("Apple") in consideration of your agreement to the following terms, and your + use, installation, modification or redistribution of this Apple software + constitutes acceptance of these terms. If you do not agree with these terms, + please do not use, install, modify or redistribute this Apple software. + + In consideration of your agreement to abide by the following terms, and subject + to these terms, Apple grants you a personal, non-exclusive license, under AppleÕs + copyrights in this original Apple software (the "Apple Software"), to use, + reproduce, modify and redistribute the Apple Software, with or without + modifications, in source and/or binary forms; provided that if you redistribute + the Apple Software in its entirety and without modifications, you must retain + this notice and the following text and disclaimers in all such redistributions of + the Apple Software. Neither the name, trademarks, service marks or logos of + Apple Computer, Inc. may be used to endorse or promote products derived from the + Apple Software without specific prior written permission from Apple. Except as + expressly stated in this notice, no other rights or licenses, express or implied, + are granted by Apple herein, including but not limited to any patent rights that + may be infringed by your derivative works or by other works in which the Apple + Software may be incorporated. + + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED + WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN + COMBINATION WITH YOUR PRODUCTS. + + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION + OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT + (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Change History (most recent first): + +$Log: MoreAddrToSym.h,v $ +Revision 1.2 2006/01/22 22:47:15 eskimo1 +Significant rewrite to account for changes in MoreBacktrace. Still not as functional as I'd like. + +Revision 1.1 2003/04/04 15:03:00 eskimo1 +First checked in. This code still has bugs, but I've written enough code that checking in is a good idea. + + +*/ + +#pragma once + +///////////////////////////////////////////////////////////////// + +// MoreIsBetter Setup + +#include "MoreSetup.h" + +// Mac OS Interfaces + +#include +#include + +///////////////////////////////////////////////////////////////// + +#ifdef __cplusplus +extern "C" { +#endif + +// IMPORTANT: +// This code is currently broken in two ways: +// +// o If the binary has debugging symbols, you often get a debugging +// symbol rather than a real symbol. I believe this is caused by +// handling of N_FUN in the GetFunctionName routine. Furthermore, +// I believe that it did work previous but something changed in the +// Mach-O headers to break it. This warrants serious investigation. +// +// You can work around this problem by removing the debug symbols +// using: +// +// $ strip -S YourBinaryName +// +// o It doesn't handle 64-bit Mach-O binaries. This is a simple +// limitation of the code, and it should be relatively easy to fix. +// +// I intend to fix both of these problems with a future rewrite. +// Until then, I've decided to live with them. + +typedef uint64_t MoreAToSAddr; +typedef uint64_t MoreAToSOffset; + +enum MoreAToSSymbolType { + kMoreAToSNoSymbol = 0, + kMoreAToSDyldPubliSymbol, + kMoreAToSDyldPrivateSymbol +}; +typedef enum MoreAToSSymbolType MoreAToSSymbolType; + +struct MoreAToSSymInfo { + MoreAToSSymbolType symbolType; + const char * symbolName; + MoreAToSOffset symbolOffset; +}; +typedef struct MoreAToSSymInfo MoreAToSSymInfo; + +extern int MoreAToSCreate(size_t count, MoreAToSSymInfo *symbols[]); + // Creates a blank MoreAToSSymInfo array with count entries. + // You must dispose of it using MoreAToSDestroy. + // + // symbols must not be NULL + // *symbols must be NULL + // Returns 0 on success, an errno-style error code otherwise + // On success, *symbols will not be NULL + // On error, *symbols will be NULL + +extern void MoreAToSDestroy(size_t count, MoreAToSSymInfo symbols[]); + // Destroys a MoreAToSDestroy array (blank or filled in) of + // count entries. + +extern int MoreAToSCopySymbolNamesUsingDyld( + size_t count, + MoreAToSAddr addresses[], + MoreAToSSymInfo symbols[] +); + // Given count values in the addresses array, works out the symbolic + // information for those values and returns it in the symbols array. + // + // Returns 0 on success, an errno-style error code otherwise + // + // Note that not being able to map an address to a symbol is not + // considered an error. Rather, you get NULL back in the symbolName + // field of the corresponding symbols array element. + +#ifdef __cplusplus +} +#endif diff --git a/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktrace.c b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktrace.c new file mode 100644 index 0000000000..3f899e008a --- /dev/null +++ b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktrace.c @@ -0,0 +1,1755 @@ +/* + File: MoreBacktrace.c + + Contains: Code for generating backtraces. + + Written by: DTS + + Copyright: Copyright (c) 2006 by Apple Computer, Inc., All Rights Reserved. + + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. + ("Apple") in consideration of your agreement to the following terms, and your + use, installation, modification or redistribution of this Apple software + constitutes acceptance of these terms. If you do not agree with these terms, + please do not use, install, modify or redistribute this Apple software. + + In consideration of your agreement to abide by the following terms, and subject + to these terms, Apple grants you a personal, non-exclusive license, under AppleÕs + copyrights in this original Apple software (the "Apple Software"), to use, + reproduce, modify and redistribute the Apple Software, with or without + modifications, in source and/or binary forms; provided that if you redistribute + the Apple Software in its entirety and without modifications, you must retain + this notice and the following text and disclaimers in all such redistributions of + the Apple Software. Neither the name, trademarks, service marks or logos of + Apple Computer, Inc. may be used to endorse or promote products derived from the + Apple Software without specific prior written permission from Apple. Except as + expressly stated in this notice, no other rights or licenses, express or implied, + are granted by Apple herein, including but not limited to any patent rights that + may be infringed by your derivative works or by other works in which the Apple + Software may be incorporated. + + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED + WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN + COMBINATION WITH YOUR PRODUCTS. + + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION + OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT + (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Change History (most recent first): + +$Log: MoreBacktrace.c,v $ +Revision 1.6 2006/01/23 18:32:52 eskimo1 +Correct uninitialised variable pointed out by the compiler. + +Revision 1.5 2006/01/23 00:59:36 eskimo1 +Added lots of comments describing the stack structure for each architecture. Also filled in one of the blank with regards stack offsets on older systems. + +Revision 1.4 2006/01/22 22:46:46 eskimo1 +Complete rewrite to account for architecture independence. + +Revision 1.3 2003/04/09 22:48:11 eskimo1 +Added comments. + +Revision 1.2 2003/04/09 22:30:14 eskimo1 +Lots of changes. Rewrote the core to work properly. We now handle leaf routines correctly in the common cases, and document the cases that we don't handle. Also added lots of comments. + +Revision 1.1 2003/04/04 15:03:04 eskimo1 +First checked in. This code still has bugs, but I've written enough code that checking in is a good idea. + + +*/ + +///////////////////////////////////////////////////////////////// + +// Our Prototypes + +#include "MoreBacktrace.h" + +// Mac OS Interfaces + +#include +#include +#include +#include +#include +#include +#include + +#if defined(__cplusplus) + extern "C" { +#endif + +// Some extra Mach interfaces that we don't need in the public header. +// Again, we need C++ guards. + +#include +#include + +// We want both PowerPC and Intel thread state information. +// By default, the system only gives us the one that's appropriate +// for our machine. So we include both here. + +#include +#include + +#if defined(__cplusplus) + } +#endif + +///////////////////////////////////////////////////////////////// + +// A new architecture will require substantial changes to this file. + +#if ! (TARGET_CPU_PPC || TARGET_CPU_PPC64 || TARGET_CPU_X86 ) + #error MoreBacktrace: What architecture? +#endif + +///////////////////////////////////////////////////////////////// +#pragma mark ***** Generic Utilities + +struct OSRelease { + int major; + int minor; + int bug; +}; +typedef struct OSRelease OSRelease; + +static int GetOSRelease(OSRelease *releasePtr) + // Get the Darwin OS release using uname. I can't use gestaltSystemVersion + // because it's part of CoreServices, and CoreServices is not available + // to 64-bit programs on Mac OS X 10.4.x. +{ + int err; + struct utsname names; + int scanResult; + + assert(releasePtr != NULL); + + err = uname(&names); + if (err < 0) { + err = errno; + } + if (err == 0) { + // Parse the three dot separated components of the release string. + // If we don't get exactly three, we've confused and we error. + + scanResult = sscanf(names.release, "%d.%d.%d", &releasePtr->major, &releasePtr->minor, &releasePtr->bug); + if (scanResult != 3) { + err = EINVAL; + } + } + + assert( (err == 0) == (releasePtr->major != 0) ); + + return err; +} + +///////////////////////////////////////////////////////////////// +#pragma mark ***** Architecture Specification + +typedef struct MoreBTContext MoreBTContext; + // forward declaration + +// Architecture Callbacks -- Called by the core to do architecture-specific tasks. + +typedef int (*MoreBTHandleLeafProc)(MoreBTContext *context, MoreBTAddr *pcPtr, MoreBTAddr *fpPtr); + // This callback is called by the core to start a backtrace. + // It should extract the first PC and frame from the thread state + // in the context and return them to the core. Also, if the + // routine detects a frameless leaf routine, it should add a + // dummy frame for that routine (by calling AddFrame). + // + // On entry, context will be a valid context (as determined by ValidateContext). + // On entry, pcPtr will not be NULL. + // Returns an errno-style error code, + // On entry, fpPtr will not be NULL. + // On success, *pcPtr must be the PC of the first non-leaf frame. + // On success, *fpPtr must be the frame pointer of the first non-leaf frame. + +typedef bool (*MoreBTValidPCProc)(MoreBTContext *context, MoreBTAddr pc); + // This callback is called by the core to check whether a PC address + // is valid. This is architecture-specific; for example, on PowerPC a + // PC value must be a multiple of 4, whereas an Intel an instruction + // can start at any address. + // + // At a minimum, an implementation is expected to check the PC's alignment + // and read the instruction at the PC. + // + // IMPORTANT: + // The core code assumes that (MoreBTAddr) -1 is never a valid PC. + // If that isn't true for your architecture, you'll need to eliminate + // that assumption from the core. + // + // On entry, context will be a valid context (as determined by ValidateContext). + // On entry, pc can be any value. + // Returns true if the PC looks reasonably valid, false otherwise. + +typedef int (*MoreBTGetFrameNextPCProc)(MoreBTContext *context, MoreBTAddr thisFrame, MoreBTAddr nextFrame, MoreBTAddr *nextPCPtr); + // This callback is called by the core to get the PC associated with + // the next frame. This is necessary because different architectures + // store the PC in different places. Specifically, PowerPC stores + // the PC of a frame in that frame, whereas Intel stores the PC of + // a frame in the previous frame (that is, the PC value in the frame + // is actually a return address). + // + // On entry, context will be a valid context (as determined by ValidateContext). + // On entry, thisFrame will be a valid frame. + // On entry, nextFrame will be the valid frame following thisFrame. + // On entry, nextPCPtr will not be NULL. + // Returns an errno-style error code. + // On success, *nextPCPtr must be the PC associated with nextFrame. + +typedef int (*MoreBTCrossSignalFrameProc)(MoreBTContext *context, MoreBTAddr thisFrame, MoreBTAddr *nextPCPtr, MoreBTAddr *nextFramePtr); + // This callback is called by the core when it detects a cross signal + // frame and wants to cross that frame in an architecture-specific + // manner. The code gets a pointer to the cross-signal handler frame + // and is expected to return the PC and frame pointer of the first + // non-leaf frame on the other side. Furthermore, it must detect if + // the first frame on the other side is a leaf frame and add a + // dummy frame for that routine (by calling AddFrame) before returning. + // + // An implementation does not have to check the validity of the + // returned PC and frame. The core will do that for you. + // + // On entry, context will be a valid context (as determined by ValidateContext). + // On entry, thisFrame will be a valid cross-signal handler frame. + // On entry, nextPCPtr will not be NULL. + // On entry, nextFramePtr will not be NULL. + // Returns an errno-style error code. + // On success, *nextPCPtr must be the PC of the next non-leaf frame. + // On success, *nextFramePtr must be the PC of the next non-leaf frame. + +// Architecture Specification Structure -- Aggregates all of the information +// associated with a particular architecture. + +struct MoreBTArchInfo { + + // Information to identify the architecture + + cpu_type_t cputype; // per NXGetLocalArchInfo in + cpu_subtype_t cpusubtype; // per NXGetLocalArchInfo in + bool is64Bit; + + // Misc information about the architecture + + enum NXByteOrder byteOrder; // per + MoreBTAddr frameAlignMask; // mask to detect frame misalignment + // FP & frameAlignMask must be 0 for a valid frame + // Architecture-specific backtrace callbacks + + MoreBTHandleLeafProc handleLeaf; // described in detail above + MoreBTValidPCProc validPC; // described in detail above + MoreBTGetFrameNextPCProc getFrameNextPC; // described in detail above + MoreBTCrossSignalFrameProc crossSignalFrame; // described in detail above + + // Specification of how to call thread_get_state + + thread_state_flavor_t stateFlavor; + mach_msg_type_number_t stateCount; +}; +typedef struct MoreBTArchInfo MoreBTArchInfo; + +static bool TaskIs64Bits(task_t task) + // Returns true if the specified task if a 64-bit task. + // The current implementation works by looking to see + // if the task uses any address space above the 4 GB boundary. + // This is less than ideal, but it's the best I can think of + // right now. +{ + bool result; + + assert(task != MACH_PORT_NULL); + + // If mach_vm_region is NULL, we're running prior to 10.4, where no + // task can be 64-bit. + + result = false; + if ( mach_vm_region != NULL ) { + kern_return_t err; + mach_vm_address_t addr; + mach_vm_size_t size; + vm_region_basic_info_data_64_t info; + mach_msg_type_number_t count; + mach_port_t junkPort; + + // Look for a VM region above 4 GB. In practice this generally + // picks up the stack. However, at a minimum, this should always + // pick up the comm page. If such a region exists, the task must + // be 64-bit. + + addr = 0x0000000100000000LL; + count = VM_REGION_BASIC_INFO_COUNT_64; + junkPort = MACH_PORT_NULL; + err = mach_vm_region( + task, + &addr, + &size, + VM_REGION_BASIC_INFO_64, + (vm_region_info_t) &info, + &count, + &junkPort + ); + if (err == KERN_SUCCESS) { + assert(addr >= 0x0000000100000000LL); + assert(count == VM_REGION_BASIC_INFO_COUNT_64); + result = true; + } + + assert(junkPort == MACH_PORT_NULL); + } + return result; +} + +static const MoreBTArchInfo kArchitectures[4]; + // forward declaration + +static const MoreBTArchInfo * GetTaskArch(task_t task) + // Returns a pointer to the architecture associated with the specific + // task, or NULL if it's an architecture we don't know about. + // + // This is one place that trips up cross-architecture backtraces. + // For this to work properly, we have to work out the architecture + // of the remote task. There's no API to do this. The standard + // approach is to find dyld in the remote task and see what + // architecture it is (from its Mach image header). + // + // However, as I've not yet written code to find dyld (what an + // ugly kludge that is), I've installed a less than ideal solution, + // which is to assume that the remote task is the same architecture + // as the local task, modulo 32- vs 64-bit differences. This is + // fine for most uses. +{ + const NXArchInfo * localArch; + bool targetIs64Bits; + const MoreBTArchInfo * result; + + assert(task != MACH_PORT_NULL); + + localArch = NXGetLocalArchInfo(); + assert(localArch != NULL); // in debug builds, we want to know if this fails + + targetIs64Bits = TaskIs64Bits(task); + + result = NULL; + if (localArch != NULL) { + const MoreBTArchInfo * thisArch; + + // Look through the architecture array for an architecture + // that matches the local architecture, but with the correct + // address space size (as determined by TaskIs64Bits, above). + // Also, we prefer architectures with an exact CPU subtype + // match, but we'll accept those with a 0 CPU subtype. + + thisArch = &kArchitectures[0]; + while ( (thisArch->cputype != 0) && (result == NULL) ) { + if ( (thisArch->cputype == localArch->cputype) + && ((thisArch->cpusubtype == 0) || (thisArch->cpusubtype == localArch->cpusubtype)) + && (thisArch->is64Bit == targetIs64Bits) + ) { + result = thisArch; + } else { + thisArch += 1; + } + } + } + + return result; +} + +///////////////////////////////////////////////////////////////// +#pragma mark ***** Backtrace Core + +// Memory Read Callback + +typedef int (*MoreBTReadBytesProc)(MoreBTContext *context, MoreBTAddr src, void *dst, size_t size); + // This function pointer is called by the core backtrace code + // when it needs to read memory. The callback should do a safe + // read of size bytes from src into the buffer specified by + // dst. By "safe" we mean that the routine should return an error + // if the read can't be done (typically because src is a pointer to + // unmapped memory). + // + // On entry, context will be a valid context (as determined by ValidateContext). + // On entry, src can be any value. + // On entry, dst will not be NULL. + // On entry, size will be greater than 0. + // Returns an errno-style error code. + // On success, the routine has copied size bytes of data from the address src + // in the remote task to the address dst in the local task. + // On error, the value at dst is unspecified. + // + // Note: + // In previous versions of MoreBacktrace, I supported alternative ways to + // read bytes from the target. For example, I could use the Carbon + // exception handler mechanism to read + // data from the current task in a safe fashion. This was useful because + // it would work on both Mac OS X and traditional Mac OS. Now that I + // require Mac OS X and Mach-O, I can just use the Mach routines to do + // my reading. However, I've left the abstraction layer in place, + // Just In Case (tm). + +struct MoreBTContext { + + // Internal parameters that are set up by the caller + // of the core backtrace code. + + const MoreBTArchInfo * arch; + task_t task; + const void * threadState; // architecture-specific current thread state + // for example, on Intel this is i386_thread_state_t + MoreBTReadBytesProc readBytes; // described in detail above + void * readBytesRefCon; // currently unused + + // Stuff worked out internally by InitContext. + + bool swapBytes; // true if target and current task have different byte orders + MoreBTAddr sigTrampLowerBound; // address of _sigtramp in target + MoreBTAddr sigTrampUpperBound; + + // Parameters from client. + + MoreBTAddr stackBottom; + MoreBTAddr stackTop; + MoreBTFrame * frameArray; // array contents filled out by core + size_t frameArrayCount; + size_t frameCountOut; // returned by core +}; + +static bool ValidateContext(const MoreBTContext *context) +{ + return (context != NULL) + && (context->arch != NULL) + && (context->task != MACH_PORT_NULL) + && (context->readBytes != NULL) + && (context->sigTrampLowerBound != 0) + && (context->sigTrampLowerBound < context->sigTrampUpperBound) + && (context->stackBottom <= context->stackTop) + && ((context->frameArrayCount == 0) || (context->frameArray != NULL)) + && (context->threadState != NULL); +} + +static int ReadAddr(MoreBTContext *context, MoreBTAddr addr, MoreBTAddr *valuePtr) + // Reads an address (that is, a pointer) from the target task, + // returning an error if the memory is unmapped. + // + // On entry, context will be a valid context (as determined by ValidateContext). + // On entry, addr can be any value. + // On entry, valuePtr must not be NULL. + // Returns an errno-style error code. + // On success, *valuePtr will be the value of the pointer stored at addr in + // the target task. +{ + int err; + MoreBTAddr value; + + assert(ValidateContext(context)); + assert(valuePtr != NULL); + + if (context->arch->is64Bit) { + + // Read directly into value, and then swap all 8 bytes. + + err = context->readBytes(context, addr, &value, sizeof(value)); + if (err == 0) { + if (context->swapBytes) { + value = OSSwapInt64(value); + } + } + } else { + uint32_t tmpAddr; + + // Read into a temporary address, swap 4 bytes, then copy that + // into value. tmpAddr is unsigned, so we zero fill the top + // 32 bits. + + err = context->readBytes(context, addr, &tmpAddr, sizeof(tmpAddr)); + if (err == 0) { + if (context->swapBytes) { + tmpAddr = OSSwapInt32(tmpAddr); + } + value = tmpAddr; + } + } + if (err == 0) { + *valuePtr = value; + } + + return err; +} + +static void AddFrame(MoreBTContext *context, MoreBTAddr pc, MoreBTAddr fp, MoreBTFlags flags) + // Adds a frame to the end of the output array with the + // value specified by pc, fp, and flags. + // + // On entry, context will be a valid context (as determined by ValidateContext). +{ + // Only actually output the frame if the client supplied an array + // and we we haven't filled it up yet. + + assert(ValidateContext(context)); + + if ( (context->frameArray != NULL) && (context->frameCountOut < context->frameArrayCount) ) { + MoreBTFrame * frameOutPtr; + + frameOutPtr = &context->frameArray[context->frameCountOut]; + frameOutPtr->pc = pc; + frameOutPtr->fp = fp; + frameOutPtr->flags = flags; + } + + // Always increment the frame count. + + context->frameCountOut += 1; +} + +static int InitSigTrampAddress(MoreBTContext *context) + // Fills out the sigTrampLowerBound and sigTrampUpperBound fields of + // the context to be the address and bound of the _sigtramp routine. + // I need this information to be able to detect and cross signal + // frames correctly. + // + // Doing this correctly requires the ability to map symbols to addresses + // in the remote task, something for which I haven't yet written the code. + // So, we just make some risky assumptions: + // + // o _sigtramp is at the same address in the target task as it is in + // our task. This would fail if the target task was a different + // architecture, so we outlaw that. It can also fail if System + // frameworks was relocated in the target task, something that's + // possible and, with my current code base, hard to detect. + // + // o I assume a fixed length of 0x100 for the _sigtramp code. Needless to + // say, this is completely bogus. + // + // On entry, context isn't yet a fully valid context because the + // sigtramp fields haven't been set up yet. + // Returns an errno-style error code. + // On success, context is a valid context. +{ + int err; + extern void _sigtramp(void); + + assert(context != NULL); + + if ( context->arch != GetTaskArch(mach_task_self()) ) { + fprintf(stderr, "MoreBacktrace: Cross architecture backtrace not supported because of problems finding _sigtramp.\n"); + err = ENOTSUP; + } else { + context->sigTrampLowerBound = (uintptr_t) &_sigtramp; + context->sigTrampUpperBound = context->sigTrampLowerBound + 0x100; + err = 0; + } + + assert( (err != 0) || ValidateContext(context) ); + + return err; +} + +static OSRelease gOSRelease; + +static int InitContext( + MoreBTContext * context, + const MoreBTArchInfo * arch, + task_t task, + const void * threadState, + MoreBTReadBytesProc readBytes, + void * readBytesRefCon, + MoreBTAddr stackBottom, + MoreBTAddr stackTop, + MoreBTFrame * frameArray, + size_t frameArrayCount +) + // Initialises a MoreBTContext to appropriate values based on + // the input parameters and various default values and values + // derived from the input parameters. + // + // On entry, context must not be NULL (but it's not yet a valid context). + // On entry, arch must not be NULL. + // On entry, task must not be MACH_PORT_NULL. + // On entry, threadState must not be NULL. + // On entry, readBytes must not be NULL. + // Returns an errno-style error code. + // On success, context will be a valid context. +{ + int err; + + assert(context != NULL); + assert(arch != NULL); + assert(task != MACH_PORT_NULL); + assert(threadState != NULL); + assert(readBytes != NULL); + + memset(context, 0, sizeof(*context)); + + // We don't check these input parameters here. Instead the + // check is done by the ValidateContext call below. + + context->stackBottom = stackBottom; + context->stackTop = stackTop; + context->frameArray = frameArray; + context->frameArrayCount = frameArrayCount; + + context->arch = arch; + context->task = task; + context->threadState = threadState; + context->readBytes = readBytes; + context->readBytesRefCon = readBytesRefCon; + + context->swapBytes = (arch->byteOrder != NXGetLocalArchInfo()->byteorder); + + err = 0; + if (gOSRelease.major == 0) { + err = GetOSRelease(&gOSRelease); + } + if (err == 0) { + err = InitSigTrampAddress(context); + } + + assert( (err != 0) || ValidateContext(context) ); + + return err; +} + +static int BacktraceCore(MoreBTContext *context) + // The core backtrace code. This routine is called by all of the various + // exported routines. It implements the core backtrace functionality. + // All of the parameters to this routine are contained within + // the context. This routine traces back through the stack (using the + // readBytes callback in the context to actually read memory) creating + // a backtrace. +{ + int err; + MoreBTAddr thisPC; + MoreBTAddr thisFrame; + MoreBTAddr lowerBound; + MoreBTAddr upperBound; + bool stopNow; + + assert(ValidateContext(context)); + + lowerBound = context->stackBottom; + upperBound = context->stackTop; + if (upperBound == 0) { + if (context->arch->is64Bit) { + // This actually generates a theoretical off-by-one error (a fp of + // 0xFFFFFFFF FFFFFFFF is falsely considered invalid), but that's + // not a problem in practice. + upperBound = 0xFFFFFFFFFFFFFFFFLL; + } else { + upperBound = 0x0000000100000000LL; + } + } + + // If you supply bounds, they must make sense. + + assert(upperBound >= lowerBound); + + // Handle any leaf frames, and also return to us the initial + // PC and FP. + + assert(context->frameCountOut == 0); // set up by memset in InitContext + err = context->arch->handleLeaf(context, &thisPC, &thisFrame); + + // Handle the normal frames. + + if (err == 0) { + stopNow = false; + do { + MoreBTFrame * frameOutPtr; + MoreBTFrame tmpFrameOut; + MoreBTAddr nextFrame; + MoreBTAddr nextPC; + + // Output to a tmpFrameOut unless the client has supplied + // a buffer and there's sufficient space left in it. + // + // IMPORTANT: + // You can't just add the frame information (possibly by calling + // AddFrame) at the end of this loop, because the crossSignalFrame + // callback may add its own frame, and we have to make sure that + // this frame is allocated before that one. + + if ( (context->frameArray != NULL) && (context->frameCountOut < context->frameArrayCount) ) { + frameOutPtr = &context->frameArray[context->frameCountOut]; + } else { + frameOutPtr = &tmpFrameOut; + } + context->frameCountOut += 1; + + // Record this entry. + + frameOutPtr->pc = thisPC; + frameOutPtr->fp = thisFrame; + frameOutPtr->flags = 0; + + // Now set the flags to indicate the validity of specific information. + + // Check the validity of the PC. Don't set the err here; a bad PC value + // does not cause us to quit the backtrace. + + if ( ! context->arch->validPC(context, thisPC) ) { + frameOutPtr->flags |= kMoreBTPCBadMask; + } else { + // On PowerPC I used to report the address of the call, + // rather than the return address. That was easy: I just + // decremented the returned PC by 4. However, this is + // much harder on Intel, where instructions are of variable + // length. So, I decided to do what Apple's tools do, + // and just report the return address. + } + + // Check the validity of the frame pointer. A bad frame pointer *does* + // cause us to stop tracing. + + if ( (thisFrame == 0) + || (thisFrame & context->arch->frameAlignMask) + || (thisFrame < lowerBound) + || (thisFrame >= upperBound) + ) { + frameOutPtr->flags |= kMoreBTFrameBadMask; + stopNow = true; + } + + if ( (err == 0) && ! stopNow) { + + // Move to the next frame, either by crossing a signal handler frame + // or by the usual mechanism. + + if ( !(frameOutPtr->flags & kMoreBTPCBadMask) + && ( thisPC >= context->sigTrampLowerBound ) + && ( thisPC < context->sigTrampUpperBound ) + ) { + + // If this frame is running in _sigtramp, get nextPC and nextFrame + // by delving into the signal handler stack block. + + frameOutPtr->flags |= kMoreBTSignalHandlerMask; + err = context->arch->crossSignalFrame(context, thisFrame, &nextPC, &nextFrame); + + } else { + + // Read the next frame pointer. A failure here causes us to quit + // backtracing. Note that we set kMoreBTFrameBadMask in frameOutPtr + // because, if we can't read the contents of the frame pointer, the + // frame pointer itself must be bad. + + err = ReadAddr(context, thisFrame, &nextFrame); + if (err != 0) { + frameOutPtr->flags |= kMoreBTFrameBadMask; + nextFrame = (MoreBTAddr) -1; + // No need to set stopNow because err != 0 will + // terminate loop. + } + + // Also get the PC of the next frame, or set it to dummy value if + // there is no next frame or we can't get the PC from that frame. + + if ( (frameOutPtr->flags & kMoreBTFrameBadMask) + || (context->arch->getFrameNextPC(context, thisFrame, nextFrame, &nextPC) != 0) + ) { + nextPC = (MoreBTAddr) -1; // an odd value, to trigger above check on next iteration + } + } + + // Set up for the next iteration. + + if (err == 0) { + lowerBound = thisFrame; + thisPC = nextPC; + thisFrame = nextFrame; + } + } + } while ( (err == 0) && ! stopNow ); + } + + assert(ValidateContext(context)); + + return err; +} + +#pragma mark ***** Mach Infrastructure + +static int MachReadBytes(MoreBTContext *context, MoreBTAddr src, void *dst, size_t size) + // A memory read callback for Mach. This simply calls through + // to the Mach [mach_]vm_read primitive, which does more-or-less + // what we want. + // + // See the description of MoreBTReadBytesProc for information about + // the parameters. +{ + int err; + int junk; + vm_offset_t dataRead; + mach_msg_type_number_t sizeRead; + + assert(ValidateContext(context)); + assert(dst != NULL); + assert(size > 0); + + // I used to use mach_vm_read_overwrite, which has a better semantic match for + // what I'm trying to do than mach_vm_read, but it has some serious problems + // on some systems (at least Mac OS X 10.4.4 on PowerPC G4 and G5). So I've + // reverting to using [mach_]vm_read, which means I have to vm_deallocate + // the space afterwards. Such is life, kerplunk. + + if (mach_vm_read != NULL) { + err = mach_vm_read( + context->task, + src, + size, + &dataRead, + &sizeRead + ); + } else { + #if MORE_DEBUG + // If I'm running 32-bits, vm_read's arguments are only 32-bits, + // and thus an attempt to read a 64-bit address is bad. This + // should never happen because systems that support 64-bit + // addresses also support mach_vm_read. But if it does happen, + // I want to know about it (and investigate what's going on). + + if ( ! TaskIs64Bits(mach_task_self()) ) { + assert( (src & 0xFFFFFFFF00000000LL) == 0 ); + assert( ((src + size) & 0xFFFFFFFF00000000LL) == 0 ); + } + #endif + + err = vm_read( + context->task, + (vm_address_t) src, + size, + &dataRead, + &sizeRead + ); + } + if (err == 0) { + if (sizeRead != size) { + err = KERN_FAILURE; + } else { + memcpy(dst, (void *) dataRead, size); + } + + // Note that I can use vm_deallocate instead of mach_vm_deallocate because + // I know that the thing I'm deallocating is in the my address space, and + // thus vm_deallocate, whose parameters scale with the caller's address space, + // is just fine. mach_vm_deallocate would work just as well, but that would + // put another unnecessary dependency on Mac OS X 10.4. + + junk = vm_deallocate(mach_task_self(), dataRead, sizeRead); + assert(junk == 0); + } + return err; +} + +static int MoreBacktraceMach( + const MoreBTArchInfo * arch, + task_t task, + const void * threadState, + MoreBTAddr stackBottom, + MoreBTAddr stackTop, + MoreBTFrame * frameArray, + size_t frameArrayCount, + size_t * frameCountPtr +) + // Common code for the two exported backtrace routines. + // Backtraces a given task, of a given architecture, starting + // with the specified thread state. The other parameters + // are directly from the client. + // + // Returns an errno-style error code. +{ + int err; + MoreBTContext context; + + assert(arch != NULL); + assert(task != MACH_PORT_NULL); + assert(threadState != NULL); + assert( ((stackBottom == 0) && (stackBottom == stackTop)) || (stackBottom < stackTop) ); + assert( (frameArrayCount == 0) || (frameArray != NULL) ); + assert( frameCountPtr != NULL ); + + // Create the context, do the backtrace, and return the frame count. + + err = InitContext( + &context, + arch, + task, + threadState, + MachReadBytes, + NULL, + stackBottom, + stackTop, + frameArray, + frameArrayCount + ); + if (err == 0) { + err = BacktraceCore(&context); + } + *frameCountPtr = context.frameCountOut; + + return err; +} + +#pragma mark ***** CPU Specific + +#pragma mark - PowerPC + +/* PowerPC Stack Frame Basics + -------------------------- + + + Offset Size Purpose + ------ ---- ------- + low memory + fp == sp == r1 -> 0 X pointer to next frame + X X place to save CR + 2X X place to save LR + 3X 2X reserved + 5X X place to save TOC (CFM only) + high memory + + + where X is the address size (4 bytes for 32-bits, + 8 bytes for 64-bits) + + To get from one frame to the next, you have to indirect an offset + of 0. To extract the PC from a frame (which, notably, is the + address of the code running in that frame, not a return address), you + have to indirect an offset of 2X bytes (8 or 16). + + There's enough commonality between 32- and 64-bit PowerPC architectures + that it's easy to handle them both with the same code. +*/ + +static bool PowerPCIsSystemCall(MoreBTContext *context, MoreBTAddr pc) + // Using the PC from the thread state, walk back through + // the code stream for 3 instructions looking for a "sc" instruction. + // If we find one, it's almost certain that we're in a system call + // frameless leaf routine. +{ + int err; + bool isSystemCall; + int count; + uint8_t inst[4]; + + isSystemCall = false; + count = 0; + do { + err = context->readBytes(context, pc, &inst, sizeof(inst)); + if (err == 0) { + isSystemCall = (inst[0] == 0x44) // PPC "sc" instruction + && (inst[1] == 0x00) // PPC instructions are always big + && (inst[2] == 0x00) // endian, so we compare it byte at + && (inst[3] == 0x02); // time for endian neutrality + + } + if ( (err == 0) && ! isSystemCall ) { + count += 1; + pc -= sizeof(inst); + } + } while ( (err == 0) && ! isSystemCall && (count < 3) ); + err = 0; + + return isSystemCall; +} + +static int PowerPCHandleLeaf(MoreBTContext *context, MoreBTAddr *pcPtr, MoreBTAddr *framePtr) + // This is the handleLeaf routine for the PowerPC + // architecture. See the description of MoreBTHandleLeafProc + // for a detailed discussion of its parameters. + // + // The top most frame may be in a weird state because of the + // possible variations in the routine prologue. There are a + // variety of combinations, such as: + // + // 1. a normal routine, with its return address stored in + // its caller's stack frame + // + // 2. a system call routine, which is a leaf routine with + // no frame and the return address is in LR + // + // 3. a leaf routine with no frame, where the return address + // is in LR + // + // 4. a leaf routine with no frame that accesses a global, where + // the return address is in r0 + // + // 5. a normal routine that was stopped midway through + // constructing its prolog, where the return address is + // typically in r0 + // + // Of these, 1 and 2 are most common, and they're the cases I + // handle. General support for all of the cases requires the + // ability to accurately determine the start of the routine + // which is not something that I can do with my current + // infrastructure. + // + // Note that don't handle any cases where the return address is + // in r0, although r0 is available as part of the threadState + // if I need it in the future. +{ + int err; + MoreBTAddr pc; + MoreBTAddr lr; + + // Get the pc and lr from the thread state. + + if (context->arch->is64Bit) { + pc = ((const ppc_thread_state64_t *) context->threadState)->srr0; + lr = ((const ppc_thread_state64_t *) context->threadState)->lr; + } else { + pc = ((const ppc_thread_state_t *) context->threadState)->srr0; + lr = ((const ppc_thread_state_t *) context->threadState)->lr; + } + + // If we find that we're in a system call frameless leaf routine, + // add a dummy stack frame (with no frame, because the frame actually + // belows to frameArray[1]). + + err = 0; + if ( PowerPCIsSystemCall(context, pc) ) { + + AddFrame(context, pc, 0, kMoreBTFrameBadMask); + + pc = lr; + } + + // Pass the initial pc and frame back to the caller. + + *pcPtr = pc; + if (context->arch->is64Bit) { + *framePtr = ((const ppc_thread_state64_t *) context->threadState)->r1; + } else { + *framePtr = ((const ppc_thread_state_t *) context->threadState)->r1; + } + + return err; +} + +static bool PowerPCValidPC(MoreBTContext *context, MoreBTAddr pc) + // This is the validPC routine for the PowerPC + // architecture. See the description of + // MoreBTValidPCProc for a detailed discussion + // of its parameters. + // + // PowerPC instructions must be word aligned. Also, I check that + // it's possible to read the instruction. I don't do anything + // clever like check that the resulting value is a valid instruction. +{ + uint32_t junkInst; + + return ((pc & 0x03) == 0) && (context->readBytes(context, pc, &junkInst, sizeof(junkInst)) == 0); +} + +static int PowerPCGetFrameNextPC(MoreBTContext *context, MoreBTAddr thisFrame, MoreBTAddr nextFrame, MoreBTAddr *nextPCPtr) + // This is the getFrameNextPC routine for the PowerPC + // architecture. See the description of + // MoreBTGetFrameNextPCProc for a detailed discussion + // of its parameters. +{ + MoreBTAddr offset; + + if ( context->arch->is64Bit ) { + offset = 16; + } else { + offset = 8; + } + + return ReadAddr(context, nextFrame + offset, nextPCPtr); +} + +/* PowerPC Signal Stack Frames + --------------------------- + In the current Mac OS X architecture, there is no guaranteed reliable + way to backtrace a PowerPC signal stack frame. The problem is that the + kernel pushes a variable amount of data on to the stack when it invokes the + user space signal trampoline (_sigtramp), and the only handle to the + information about how much data was pushed is passed in a register + parameter to _sigtramp. _sigtramp stashes that value away in a + non-volatile register. So, when _sigtramp calls the user-supplied + signal handler, there's no way to work out where that register + ends up being saved. + + Thus, we devolve into guesswork. It turns out that the offset from + the stack of the kernel data to the information we need (the place + where the interrupted thread's registers were stored) is a (relatively) + constant for any given system release. So, we can just simply add the + appropriate offset to the frame pointer and grab the data we need. + + On recent systems (10.3 and later) this fails if the signal handle + requests 'dual contexts', that is, it requests both 32- and 64-bit + PowerPC registers. In that case, the size of the pushed data changes, + and that affects the relative alignment of the data and the stack + pointer, and things break. I don't know of any way to work around + this . + + Finally, these constant vary from release to release. + This code handles the significant cases that I know about (Mac OS X 10.1.x + and earlier, Mac OS X 10.2, and Mac OS 10.3 and later), but there's no + guarantee that this offset won't change again in the future. + + When the kernel invokes the user space signal trampoline, it pushes + the following items on to the stack. + + Mac OS X 10.1.x + --------------- + Size Purpose + ---- ------- + low memory + 0x030 bytes for C linkage + 0x040 bytes for saving PowerPC parameters + 0x0c0 ppc_saved_state + 0x110 ppc_float_state + 0x018 struct sigcontext + 0x0e0 red zone + high memory + The previous frame's SP is at offset 0x00C within + ppc_saved_state, which makes it equal to + 0x030 + 0x040 + 0x00C, or 0x07C. The offset to + the previous PC (0x84) follows from that. + + Mac OS X 10.2.x + --------------- + Size Purpose + ---- ------- + low memory + 0x030 bytes for C linkage + 0x040 bytes for saving PowerPC parameters + 0x008 alignment padding + 0x408 struct mcontext, comprised of: + 0x020 ppc_exception_state_t + 0x0A0 ppc_thread_state_t + 0x108 ppc_float_state_t + 0x240 ppc_vector_state_t + 0x040 siginfo_t + 0x020 ucontext + 0x0e0 red zone + high memory + The previous frame's SP is at offset 0x00C within + ppc_thread_state_t, which it equal to + 0x030 + 0x040 + 0x008 + 0x020 + 0x00C, or 0x0A4. + The offsets to the previous PC and LR (0x98 and 0x128) + follow from that. + + Mac OS X 10.3.x and 10.4.x + -------------------------- + Size, 32 Size, 64 Purpose + -------- -------- ------- + low memory + align16 align32 alignment + 0x030 0x030 bytes for C linkage + 0x040 0x040 bytes for saving PowerPC parameters + 0x008 0x018 alignment + 0x040 0x068 siginfo_t, user_siginfo_t + 0x020 0x038 ucontext64 + 0x408 [0x408] mcontext + [0x498] 0x498 mcontext64 + align16 align32 alignment + 0x0e0 0x140 redzone + high memory + Some things to note about the above diagram: + + o The items in square brackets are only pushed if the signal + handler requests dual contexts. + + o For a 64-bit process, the kernel aligns the stack to a + 32 byte boundary, even though the runtime architecture + only requires a 16 byte boundary. + + o The final alignment is done last, but the space that it + creates is effectively created between the parameter save + area and the [user_]siginfo_t because the C linkage area + and param save areas are both defined to be a fixed offset + from the frame pointer. + + On 32-bit, the previous PC is stored at offset 0x18 within + the siginfo_t and the previous SP is stored at offset 0x024. + So the total offset is 0x030 + 0x040 + 0x008 + 0x018/0x024, + or 0x090 and 0x09C, respectively. + + On 64-bit, the previous PC is stored at offset 0x018 within + the user_siginfo_t and the previous SP is stored at offset 0x030. + So the total offset is 0x030 + 0x040 + 0x018 + 0x018/0x030, + or 0x0A0 and 0x0B8, respectively. + + To get the previous LR (necessary for tracing through + frameless leaf routines that are interrupted by a signal, + most notably system calls), you have to delve even further up + the stack, into the mcontext structures. I won't bore you + with the details. +*/ + +static int PowerPCCrossSignalFrame(MoreBTContext *context, MoreBTAddr thisFrame, MoreBTAddr *nextPCPtr, MoreBTAddr *nextFramePtr) + // This is the crossSignalFrame routine for the PowerPC + // architecture. See the description of MoreBTCrossSignalFrameProc + // for a detailed discussion of its parameters. +{ + int err; + MoreBTAddr nextFrame; + MoreBTAddr offsetToPC; + MoreBTAddr offsetToFP; + MoreBTAddr offsetToLR; + + assert(gOSRelease.major != 0); + + if (context->arch->is64Bit) { + offsetToPC = 0xa0; + offsetToFP = 0xb8; + offsetToLR = 0x260; + } else { + if ( gOSRelease.major < 6 ) { // Darwin 6 == Mac OS X 10.2 + // 10.0 through 10.1.x + assert(false); // these values haven't been tested + offsetToPC = 0x84; + offsetToFP = 0x7c; + // offsetToLR = ?; + } else if ( gOSRelease.major < 7 ) { // Darwin 7 == Mac OS X 10.3 + // Mac OS X 10.2.x + assert(false); // these values haven't been tested + offsetToPC = 0x98; + offsetToFP = 0xa4; + offsetToLR = 0x128; + // What about G5 10.2.x systems? It's probably the same + // as 10.3, but I'm not sure and, even if I was, I have no + // idea how to detect such a system at runtime. + } else { + // Mac OS X 10.3 and later + offsetToPC = 0x90; + offsetToFP = 0x9c; + offsetToLR = 0x188; + } + } + + // Read the address of the frame below the _sigtramp frame, because + // that where all the action is. + + err = ReadAddr(context, thisFrame, &nextFrame); + + // Go grab the saved PC and SP. + + if (err == 0) { + err = ReadAddr(context, nextFrame + offsetToPC, nextPCPtr); + } + if (err == 0) { + err = ReadAddr(context, nextFrame + offsetToFP, nextFramePtr); + } + + // If the PC is a system call, add a dummy leaf for that PC + // and then get the next frame's PC from LR. + + if ( (err == 0) && PowerPCIsSystemCall(context, *nextPCPtr) ) { + AddFrame(context, *nextPCPtr, 0, kMoreBTFrameBadMask); + + err = ReadAddr(context, nextFrame + offsetToLR, nextPCPtr); + } + + return err; +} + +#pragma mark - Intel + +/* Intel Stack Frame Basics + ------------------------ + + Offset Size Purpose + ------ ---- ------- + low memory + sp == esp -> -?? ?? general work area + -?? ?? local variables + fp == ebp -> 0 4 pointer to next frame + 4 4 return address + -?? ?? parameters + high memory + + The stack frame on Intel is remarkably traditional. Two registers + are used to manage the stack: esp points to the bottom of the stack, + and ebp points to the stack frame itself. The memory at offset 0 + stores the address of the next stack frame. The memory at offset 4 + stores the saved PC for the next stack frame (that is, the return + address for this stack frame). +*/ + +static bool IntelIsSystemCall(MoreBTContext *context, MoreBTAddr pc) + // Using the PC from the thread state, look back in the code + // stream to see if the previous bytes look something like a + // system call. This is a heuristic rather than solid design. + // Because Intel instructions are of variable length, there's no + // guarantee that these bytes are part of some other instruction. + // Still, it works most of the time. + // + // The instruction's were looking for are the two system call + // primitives on Mac OS X: + // + // o INT 81 is used for Mach system calls + // o sysenter is used by BSD system calls + // + // We detect INT 81 simply by looking for its bytes. It's no + // so easy to detect sysenter, because the PC we get is an + // address in the specific system call, which actually calls + // another routine (_sysenter_trap) to do the sysenter. + // We look for the CALL disp32 instruction and, if we see, + // work out the address that it calls. We then get the + // instructions from that address. If that looks like a + // sysenter, we're probably looking at a system call. +{ + int err; + bool isSystemCall; + uint8_t buf[5]; + uint32_t sysEnterOffset; + + isSystemCall = false; + err = context->readBytes(context, pc - sizeof(buf), buf, sizeof(buf)); + if (err == 0) { + isSystemCall = ( buf[3] == 0xcd && buf[4] == 0x81); // INT 81 + + if ( ! isSystemCall && (buf[0] == 0xe8) ) { // CALL disp32 + // Get the disp32. + + sysEnterOffset = (buf[1] | (buf[2] << 8) | (buf[3] << 16) | (buf[4] << 24)); + + // Read the instructions at that offset from the PC and see if they're + // the standard _sysenter_trap code. + // + // It's a happy coincidence that the size of the _sysenter_trap code is + // 5 bytes, which is also the size of the buffer that I have lying around + // to read the instructions in front of the PC. The upshot is that I can + // reuse buf rather than needing a second one. + + err = context->readBytes(context, pc + sysEnterOffset, buf, sizeof(buf)); + if (err == 0) { + isSystemCall = (buf[0] == 0x5a) // pop %edx + && (buf[1] == 0x89) && (buf[2] == 0xe1) // mov %esp,%ecx + && (buf[3] == 0x0f) && (buf[4] == 0x34); // sysenter + } + } + } + return isSystemCall; +} + +static int IntelHandleLeaf(MoreBTContext *context, MoreBTAddr *pcPtr, MoreBTAddr *framePtr) + // This is the handleLeaf routine for the Intel + // architecture. See the description of MoreBTHandleLeafProc + // for a detailed discussion of its parameters. + // + // I don't have the experience or the time to fully analyse + // the leaf routine problem for Intel. Rather, I just implemented + // a simple system call check, much like I did on PowerPC. This + // seems to be effective in the cases that I care about. +{ + int err; + MoreBTAddr pc; + + pc = ((const i386_thread_state_t *) context->threadState)->eip; + + // If the PC is a system call, add a dummy leaf for that PC + // and then get the next frame's PC from the top of stack. + + err = 0; + if ( IntelIsSystemCall(context, pc) ) { + AddFrame(context, pc, 0, kMoreBTFrameBadMask); + + err = ReadAddr(context, ((const i386_thread_state_t *) context->threadState)->esp, &pc); + } + if (err == 0) { + *pcPtr = pc; + *framePtr = ((const i386_thread_state_t *) context->threadState)->ebp; + } + + return err; +} + +static bool IntelValidPC(MoreBTContext *context, MoreBTAddr pc) + // This is the validPC routine for the Intel + // architecture. See the description of + // MoreBTValidPCProc for a detailed discussion + // of its parameters. + // + // Intel instructions are not aligned in any way. All, I can do + // is check for known bad values ((MoreBTAddr) -1 is used as a + // known bad value by the core) and check that I can read at least + // byte of instruction from the address. +{ + uint8_t junkInst; + + return (pc != (MoreBTAddr) -1) && (context->readBytes(context, pc, &junkInst, sizeof(junkInst)) == 0); +} + +static int IntelGetFrameNextPC(MoreBTContext *context, MoreBTAddr thisFrame, MoreBTAddr nextFrame, MoreBTAddr *nextPCPtr) + // This is the getFrameNextPC routine for the Intel + // architecture. See the description of + // MoreBTGetFrameNextPCProc for a detailed discussion + // of its parameters. + // + // This is very easy on Intel, because it's the return address, + // which is at a fixed offset in the frame. +{ + return ReadAddr(context, thisFrame + 4, nextPCPtr); +} + +/* Intel Signal Stack Frames + ------------------------- + Cross signal stack frames is much more reliable on Intel. The parameters + to _sigtramp are stored on the stack, and you can reliably pick them up + from there. + + Size Purpose + ---- ------- + low memory + + frame -> 0x004 pre-signal frame pointer + 0x018 struct sigframe + 0x020? pad + 0x258 struct mcontext + 0x00c i386_exception_state_t + 0x040 i386_thread_state_t + 0x20c i386_float_state_t + 0x040 siginfo_t + 0x020 struct ucontext + high memory + + Things to note about the above: + + o The kernel aligns the stack such that the catcher field of the + sigframe structure is aligned on a 16 byte boundary. This means that + there's a variable amount of pad between sigframe and mcontext. + This isn't a problem because the sigframe structure contains a + field (sinfo) that's a pointer to the siginfo_t. + + The sinfo field of the sigframe structure is at offset 0x10. Once you + account for the pre-signal frame pointer that's pushed on to the stack + by _sigtramp, you need to go 0x14 bytes up the frame to get the sinfo + field, which is a pointer to a siginfo_t structure. The kernel places + the pre-signal PC and SP in fields in that structure (si_addr and + pad[0], offset 0x18 and 0x24 respectively). + + Finally, if we detect a frameless leaf routine past the signal frame, + we extract its return address from the top of stack. +*/ + +static int IntelCrossSignalFrame(MoreBTContext *context, MoreBTAddr thisFrame, MoreBTAddr *nextPCPtr, MoreBTAddr *nextFramePtr) + // This is the crossSignalFrame routine for the Intel + // architecture. See the description of + // MoreBTCrossSignalFrameProc for a detailed discussion + // of its parameters. +{ + int err; + MoreBTAddr sigInfo; + MoreBTAddr preSignalSP; + + // Get the siginfo_t pointer from the parameters to _sigtramp + // (the sinfo field of sigframe). + + err = ReadAddr(context, thisFrame + 0x14, &sigInfo); + + // Get the previous PC from si_addr field of siginfo_t. + + if (err == 0) { + err = ReadAddr(context, sigInfo + 0x18, nextPCPtr); + } + + // Get the previous frame by simply reading from the frame pointer. + // Because of the way things work, this ends up being correct. + + if (err == 0) { + err = ReadAddr(context, thisFrame, nextFramePtr); + } + + // Finally, if we detect a leaf routine, add a dummy frame for it + // and then get the pre-signal SP (from the pad[0] of siginfo_t) + // and, assuming that the top word on the stack is a return address, + // use it for the next PC. + + if ( (err == 0) && IntelIsSystemCall(context, *nextPCPtr) ) { + AddFrame(context, *nextPCPtr, 0, kMoreBTFrameBadMask); + + err = ReadAddr(context, sigInfo + 0x24, &preSignalSP); + + if (err == 0) { + err = ReadAddr(context, preSignalSP, nextPCPtr); + } + } + + return err; +} + +// kArchitectures is an array of all the architectures we support. +// Things to notes: +// +// o GetTaskArch processes this in a forward direction. If you +// list a more-specific architecture, you should list it before +// the less-specific one. +// +// o The table is terminated by a NULL architecture, signified by +// a 0 in the cputype field. +// +// See the comments near MoreBTArchInfo for a detailed description of +// each field. + +static const MoreBTArchInfo kArchitectures[] = { + { // PowerPC + CPU_TYPE_POWERPC, // cputype + 0, // subcputype + false, // is64Bit + NX_BigEndian, // byteOrder + 15, // frameAlignMask + PowerPCHandleLeaf, // handleLeaf + PowerPCValidPC, // validPC + PowerPCGetFrameNextPC, // getFrameNextPC + PowerPCCrossSignalFrame, // crossSignalFrame + PPC_THREAD_STATE, // stateFlavor + PPC_THREAD_STATE_COUNT // stateCount + }, + { // PowerPC64 + CPU_TYPE_POWERPC, // cputype + 0, // subcputype + true, // is64Bit + NX_BigEndian, // byteOrder + 15, // frameAlignMask + PowerPCHandleLeaf, // handleLeaf + PowerPCValidPC, // validPC + PowerPCGetFrameNextPC, // getFrameNextPC + PowerPCCrossSignalFrame, // crossSignalFrame + PPC_THREAD_STATE64, // stateFlavor + PPC_THREAD_STATE64_COUNT // stateCount + }, + { // Intel + CPU_TYPE_X86, // cputype + 0, // subcputype + false, // is64Bit + NX_LittleEndian, // byteOrder + 3, // frameAlignMask + // Apple's i386 API requires that the stack be 16 byte aligned, + // but it says nothing about the frame. It turns out that the + // frame is typically 8 byte aligned, but I can't find any + // documentation that requires that, so I'm only checking 4 byte + // alignment. + IntelHandleLeaf, // handleLeaf + IntelValidPC, // validPC + IntelGetFrameNextPC, // getFrameNextPC + IntelCrossSignalFrame, // crossSignalFrame + i386_THREAD_STATE, // stateFlavor + i386_THREAD_STATE_COUNT // stateCount + } + /* null terminator */ + +}; + +#pragma mark ***** Public Interface + +extern int MoreBacktraceMachThread( + task_t task, + thread_t thread, + MoreBTAddr stackBottom, + MoreBTAddr stackTop, + MoreBTFrame * frameArray, + size_t frameArrayCount, + size_t * frameCountPtr +) + // See comments in header. +{ + int err; + const MoreBTArchInfo * arch; + mach_msg_type_number_t stateCount; + void * threadState; + + assert(task != MACH_PORT_NULL); + assert(thread != MACH_PORT_NULL); + assert( ((stackBottom == 0) && (stackBottom == stackTop)) || (stackBottom < stackTop) ); + assert( (frameArrayCount == 0) || (frameArray != NULL) ); + assert( frameCountPtr != NULL ); + + threadState = NULL; + + // Get the architecture of the task, and us that to allocate enough + // space for the thread's state. + + err = 0; + arch = GetTaskArch(task); + if (arch == NULL) { + err = EINVAL; + } + if (err == 0) { + stateCount = arch->stateCount; + + threadState = malloc(stateCount * sizeof(int)); + if (threadState == NULL) { + err = ENOMEM; + } + } + + // Get the thread state. + + if (err == 0) { + err = thread_get_state(thread, arch->stateFlavor, (thread_state_t) threadState, &stateCount); + } + + // Do the backtrace. + + if (err == 0) { + err = MoreBacktraceMach( + arch, + task, + threadState, + stackBottom, + stackTop, + frameArray, + frameArrayCount, + frameCountPtr + ); + } + + // Clean up. + + free(threadState); + + return err; +} + +// InitThreadState is a macro that initialises an architecture-specific +// thread state structure from the current CPU registers. This only +// initialises enough fields to support a backtrace. + +#if TARGET_CPU_PPC + +#if 0 /* OMPI CHANGE */ + #define InitThreadState(threadState) \ + do { \ + uint32_t tmpPC = 0; \ + uint32_t tmpFP = 0; \ + asm { \ + bl next ; \ + next: mflr tmpPC ; \ + mr tmpFP,sp \ + } \ + ((ppc_thread_state_t *) threadState)->srr0 = tmpPC; \ + ((ppc_thread_state_t *) threadState)->r1 = tmpFP; \ + } while (0) + +#else /* OMPI CHANGE */ + #define InitThreadState(threadState) \ + do { \ + uint32_t tmpPC = 0; \ + uint32_t tmpFP = 0; \ + asm("\tmflr %0\n" \ + "\tmr %1,r1" \ + : "=r"(tmpPC), "=r"(tmpFP)); \ + ((ppc_thread_state_t *) threadState)->srr0 = tmpPC; \ + ((ppc_thread_state_t *) threadState)->r1 = tmpFP; \ + } while (0) + +#endif /* OMPI CHANGE */ + +#elif TARGET_CPU_PPC64 + +#if 0 /* OMPI CHANGE */ + #define InitThreadState(threadState) \ + do { \ + uint64_t tmpPC = 0; \ + uint64_t tmpFP = 0; \ + asm { \ + bl next ; \ + next: mflr tmpPC ; \ + mr tmpFP,sp \ + } \ + ((ppc_thread_state64_t *) threadState)->srr0 = tmpPC; \ + ((ppc_thread_state64_t *) threadState)->r1 = tmpFP; \ + } while (0) + +#else /* OMPI CHANGE */ + #define InitThreadState(threadState) \ + do { \ + uint64_t tmpPC = 0; \ + uint64_t tmpFP = 0; \ + asm("\tmflr %0\n" \ + "\tmr %1,r1" \ + : "=r"(tmpPC), "=r"(tmpFP)); \ + ((ppc_thread_state_t *) threadState)->srr0 = tmpPC; \ + ((ppc_thread_state_t *) threadState)->r1 = tmpFP; \ + } while (0) + +#endif /* OMPI CHANGE */ + +#elif TARGET_CPU_X86 + + // Have to use bizarr-o GCC syntax because the compiler is barfing on the + // block syntax, but only for Intel. *sigh* + + #define InitThreadState(threadState) \ + do { \ + uint32_t tmpPC = 0; \ + uint32_t tmpFP = 0; \ + asm( "\tcall Lnext\nLnext: pop %0\n" \ + "\tmov %%ebp,%1" \ + : "=r" (tmpPC) , "=r" (tmpFP) ); \ + ((i386_thread_state_t *) threadState)->eip = tmpPC; \ + ((i386_thread_state_t *) threadState)->ebp = tmpFP; \ + } while (0) + +#else + #error What architecture? +#endif + +extern int MoreBacktraceMachSelf( + MoreBTAddr stackBottom, + MoreBTAddr stackTop, + MoreBTFrame * frameArray, + size_t frameArrayCount, + size_t * frameCountPtr +) + // See comments in header. +{ + int err; + const MoreBTArchInfo * arch; + void * threadState; + + assert( ((stackBottom == 0) && (stackBottom == stackTop)) || (stackBottom < stackTop) ); + assert( (frameArrayCount == 0) || (frameArray != NULL) ); + assert( frameCountPtr != NULL ); + + threadState = NULL; + + // Get the architecture of the current task, and us that to allocate + // enough space for our thread's state. + + err = 0; + arch = GetTaskArch(mach_task_self()); + if (arch == NULL) { + err = EINVAL; + } + if (err == 0) { + threadState = calloc(arch->stateCount, sizeof(int)); + if (threadState == NULL) { + err = ENOMEM; + } + } + + // Initialise the thread state, then do the backtrace. + + if (err == 0) { + InitThreadState(threadState); + + err = MoreBacktraceMach( + GetTaskArch(mach_task_self()), + mach_task_self(), + threadState, + stackBottom, + stackTop, + frameArray, + frameArrayCount, + frameCountPtr + ); + } + + // Clean up. + + free(threadState); + + return err; +} diff --git a/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktrace.h b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktrace.h new file mode 100644 index 0000000000..70ee5aafd4 --- /dev/null +++ b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktrace.h @@ -0,0 +1,274 @@ +/* + File: MoreBacktrace.h + + Contains: Code for generating backtraces. + + Written by: DTS + + Copyright: Copyright (c) 2006 by Apple Computer, Inc., All Rights Reserved. + + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. + ("Apple") in consideration of your agreement to the following terms, and your + use, installation, modification or redistribution of this Apple software + constitutes acceptance of these terms. If you do not agree with these terms, + please do not use, install, modify or redistribute this Apple software. + + In consideration of your agreement to abide by the following terms, and subject + to these terms, Apple grants you a personal, non-exclusive license, under AppleÕs + copyrights in this original Apple software (the "Apple Software"), to use, + reproduce, modify and redistribute the Apple Software, with or without + modifications, in source and/or binary forms; provided that if you redistribute + the Apple Software in its entirety and without modifications, you must retain + this notice and the following text and disclaimers in all such redistributions of + the Apple Software. Neither the name, trademarks, service marks or logos of + Apple Computer, Inc. may be used to endorse or promote products derived from the + Apple Software without specific prior written permission from Apple. Except as + expressly stated in this notice, no other rights or licenses, express or implied, + are granted by Apple herein, including but not limited to any patent rights that + may be infringed by your derivative works or by other works in which the Apple + Software may be incorporated. + + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED + WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN + COMBINATION WITH YOUR PRODUCTS. + + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION + OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT + (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Change History (most recent first): + +$Log: MoreBacktrace.h,v $ +Revision 1.4 2006/01/22 22:46:48 eskimo1 +Complete rewrite to account for architecture independence. + +Revision 1.3 2003/04/09 22:48:15 eskimo1 +Added comments. + +Revision 1.2 2003/04/09 21:58:18 eskimo1 +Removed the "uncertain PC" flag. I may need to bring it back later, but for now I never use it so there's no point declaring it. + +Revision 1.1 2003/04/04 15:03:08 eskimo1 +First checked in. This code still has bugs, but I've written enough code that checking in is a good idea. + + +*/ + +#pragma once + +///////////////////////////////////////////////////////////////// + +// MoreIsBetter Setup + +#include "MoreSetup.h" + +// Mac OS Interfaces + +// Put inside extern "C" guards for the C++ build +// because the Mach header files don't always have them. + +#if defined(__cplusplus) + extern "C" { +#endif + +#include + +#if defined(__cplusplus) + } +#endif + +#include + +///////////////////////////////////////////////////////////////// + +#ifdef __cplusplus +extern "C" { +#endif + +///////////////////////////////////////////////////////////////// + +#if TARGET_RT_MAC_CFM + #error MoreBacktrace no longer supports CFM builds. +#endif + +///////////////////////////////////////////////////////////////// + +/* Overview + -------- + This module implements a number of backtrace routines. All + of the routines are implemented in terms of a common core. + The code is structured in a very generic way. For example, if + you were running on a version of Mach that support inter-machine + messaging, it would be feasible to do a backtrace of a PowerPC + program from program executing a completely different instruction + set architecture (ISA). + + IMPORTANT: + The current code does not support cross-architecture backtraces + because of technical limitations (specifically, I haven't had + time to implement cross-architecture symbol translation, which + is required for cross-architecture backtraces to work properly; + see the comments for InitSigTrampAddress in the implementation + file for the details). + + Backtraces are inherently processor-specific. Internal to this + module is a ISA later than adapts the backtrace for various ISA. + Currently it supports PowerPC (32-bit), PowerPC (64-bit), and + Intel (32-bit). + + If you're curious about how stack frames work for each ISA, check + out the comments in the implementation file. The comments in the + header focus on how you use these routines. +*/ + +/* Changes Since Previous Version + ------------------------------ + If you used the previous version of this code, please note the + following changes: + + o Everything has changed (-: + + I completely rewrote this code to support multiple architectures. + By including support for PowerPC (64-bit), I was forced to + eliminate my dependencies on CoreServices (which isn't available + to PowerPC (64-bit) on Mac OS X 10.4.x), which means now I depend + solely on the System framework. Also, because I had to support + Intel, which requires Mach-O, I decided to drop support for CFM. + My theory is that anyone who wants to adopt the new version of this + module is doing so because they're porting to Intel, and those folks + have to leave their CFM build behind. + + The good news is that the new implementation is very similar + in spirit to the old, and it should be very easy for you to + adopt the new code. +*/ + +// Within this module, I treat all addresses as 64-bit. That way +// the code doesn't change for 64-bit and 32-bit architectures. +// +// Note: +// I could have made this type scale with the current pointer size, +// but my eventual goal is to support cross-architecture backtraces, +// which means I wanted a size that's at least as big as the 'largest' +// architecture I support. + +typedef uint64_t MoreBTAddr; + +// The following flags provide information about a specific frame in +// a backtrace. +// +// IMPORTANT: +// kMoreBTFrameBadMask is set for the last frame in the backtrace +// (where we've run off the end of the stack), but it can also be set +// for intermediate frames (where we've detected a frameless leaf +// routine, either at the top of the stack or as part of crossing +// a signal frame). + +typedef int MoreBTFlags; +enum { + kMoreBTFrameBadMask = 0x0001, // this frame pointer is bad + kMoreBTPCBadMask = 0x0002, // this PC is bad + kMoreBTSignalHandlerMask = 0x0004 // this frame is a signal handler +}; + +// The end result of a backtrace is an array of MoreBTFrame +// structures describing a particular frame in the backtrace. +// +// Note: +// The PC points to the code that's using the frame. It is not +// the return address for that code. On architectures where the +// frame holds the return address (Intel, but not PowerPC), I do +// the appropriate corrections. + +struct MoreBTFrame { + MoreBTAddr pc; // PC for this function invocation + MoreBTAddr fp; // frame pointer for this function invocation + MoreBTFlags flags; // various flags, see above +}; +typedef struct MoreBTFrame MoreBTFrame; + +/* Common Parameters + ----------------- + All of the backtrace routines accept certain common parameters. + + o function result -- This is an errno-style error code. + + o stackBottom and stackTop -- These define the extent of the stack + which you are tracing. If this information isn't handy, supply + 0 for both. Supplying meaningful values can reduce the number + of bogus frames reported if the stack is corrupt. + + o frameArray and frameArrayCount -- These define an array of stack + frames that the routines fill out. You can supply NULL and 0 + (respectively) if you're not interested in getting the actual + frame data (typically you do this to get the count of the number + of frames via frameCount). The routines do not fail if this + buffer is exhausted. Instead they simply return as many frames + as they can and continue tracing, returning an accurate value + for frameCount. + + o frameCountPtr -- You can use this to get back an accurate count of + the number of frames in the stack. If you're not interested + in this information, you can pass NULL. + + IMPORTANT: + Because of the above, on return, *frameCountPtr can be larger than + frameArrayCount. + + The following assertions apply to these common parameters. + + o On entry, stackBottom and stackTop must both be zero, or stackBottom + must be strictly less than stackTop. + + o On entry, if frameArrayCount is not zero, frameArray must be not NULL. + + o On entry, frameCountPtr must not be NULL. + + o On return, *frameCountPtr will be the number of frames that were + found. On success, this is likely to be a meaningful number. On + error, this just indicates how far we got. + + o On return, if frameArrayCount is not NULL, frame data has been placed + into the frame array. The number of valid entries is + min(frameArray, *frameArrayCount). +*/ + +extern int MoreBacktraceMachSelf( + MoreBTAddr stackBottom, + MoreBTAddr stackTop, + MoreBTFrame * frameArray, + size_t frameArrayCount, + size_t * frameCountPtr +); + // Does a backtrace of the current thread. All of the parameters + // are described by the "Common Parameters" section above. + +extern int MoreBacktraceMachThread( + task_t task, + thread_t thread, + MoreBTAddr stackBottom, + MoreBTAddr stackTop, + MoreBTFrame * frameArray, + size_t frameArrayCount, + size_t * frameCountPtr +); + // Does a backtrace of a particular thread within a particular tasks. + // The common parameters (stackBottom and later) are described by the + // "Common Parameters" section above. The task parameter must a + // task control port; for a thread in the current task, use + // mach_task_self to get this value. The thread parameter is the thread + // to sample. It's generally inappropriate to use mach_thread_self + // (call MoreBacktraceMachSelf instead), but it does work. + // + // On entry, task must not be MACH_PORT_NULL. + // On entry, thread must not be MACH_PORT_NULL. + +#ifdef __cplusplus +} +#endif diff --git a/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/._MainWindow.nib b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/._MainWindow.nib new file mode 100644 index 0000000000000000000000000000000000000000..a27ec3d3d7333fae0c7aed9b6bf8641543f53668 GIT binary patch literal 82 mcmZQz6=P>$V!#9-F-{;h0%8Rq2JwS{7!3Xc0W+9|sTBZ|IRw`L literal 0 HcmV?d00001 diff --git a/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/._main.nib b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/._main.nib new file mode 100644 index 0000000000000000000000000000000000000000..a27ec3d3d7333fae0c7aed9b6bf8641543f53668 GIT binary patch literal 82 mcmZQz6=P>$V!#9-F-{;h0%8Rq2JwS{7!3Xc0W+9|sTBZ|IRw`L literal 0 HcmV?d00001 diff --git a/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/Info.plist b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/Info.plist new file mode 100644 index 0000000000..91aeafeae4 --- /dev/null +++ b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/Info.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + English + CFBundleExecutable + MoreBacktraceTest + CFBundleIconFile + + CFBundleIdentifier + com.apple.dts.MoreIsBetter.MoreBacktraceTest + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + MoreBacktraceTest + CFBundlePackageType + APPL + CFBundleSignature + ???? + CFBundleVersion + 0.1 + CSResourcesFileMapped + + + diff --git a/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MainWindow.nib/classes.nib b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MainWindow.nib/classes.nib new file mode 100644 index 0000000000..ea58db1189 --- /dev/null +++ b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MainWindow.nib/classes.nib @@ -0,0 +1,4 @@ +{ +IBClasses = (); +IBVersion = 1; +} diff --git a/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MainWindow.nib/info.nib b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MainWindow.nib/info.nib new file mode 100644 index 0000000000..09b2b34345 --- /dev/null +++ b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MainWindow.nib/info.nib @@ -0,0 +1,18 @@ + + + + + IBDocumentLocation + 69 10 356 240 0 0 1280 832 + IBFramework Version + 443.0 + IBOpenObjects + + 166 + + IBSystem Version + 8G32 + targetFramework + IBCarbonFramework + + diff --git a/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MainWindow.nib/objects.xib b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MainWindow.nib/objects.xib new file mode 100644 index 0000000000..c651f32744 --- /dev/null +++ b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MainWindow.nib/objects.xib @@ -0,0 +1,81 @@ + + + IBCarbonFramework + + NSApplication + + + + 51 8 649 747 + MoreBacktraceTest + + 0 0 598 739 + + + 20 20 40 245 + MoreBacktraceMachSelf + btMS + + + 20 251 40 488 + MoreBacktraceMachThread + btMT + + + 23 536 39 613 + PIDT + + + 22 494 38 525 + PID: + + + 52 257 72 482 + Signal Test + btST + + + 52 20 72 245 + Stack Smash Test + btSS + + + 95 23 575 716 + ETXT + + + + FALSE + FALSE + FALSE + FALSE + 1 + + + + + + + + + + + + + + + + + + + + + + + Files Owner + + MainWindow + + + 248 + diff --git a/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MoreBacktraceTest.c b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MoreBacktraceTest.c new file mode 100644 index 0000000000..502374188d --- /dev/null +++ b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MoreBacktraceTest.c @@ -0,0 +1,573 @@ +/* + File: MoreBacktraceTest.c + + Contains: A simple program to test MoreBacktrace. + + Written by: DTS + + Copyright: Copyright (c) 2006 by Apple Computer, Inc., All Rights Reserved. + + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. + ("Apple") in consideration of your agreement to the following terms, and your + use, installation, modification or redistribution of this Apple software + constitutes acceptance of these terms. If you do not agree with these terms, + please do not use, install, modify or redistribute this Apple software. + + In consideration of your agreement to abide by the following terms, and subject + to these terms, Apple grants you a personal, non-exclusive license, under AppleÕs + copyrights in this original Apple software (the "Apple Software"), to use, + reproduce, modify and redistribute the Apple Software, with or without + modifications, in source and/or binary forms; provided that if you redistribute + the Apple Software in its entirety and without modifications, you must retain + this notice and the following text and disclaimers in all such redistributions of + the Apple Software. Neither the name, trademarks, service marks or logos of + Apple Computer, Inc. may be used to endorse or promote products derived from the + Apple Software without specific prior written permission from Apple. Except as + expressly stated in this notice, no other rights or licenses, express or implied, + are granted by Apple herein, including but not limited to any patent rights that + may be infringed by your derivative works or by other works in which the Apple + Software may be incorporated. + + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED + WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN + COMBINATION WITH YOUR PRODUCTS. + + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION + OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT + (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Change History (most recent first): + +*/ + +///////////////////////////////////////////////////////////////// + +#include "MoreSetup.h" + +// System prototypes + +#include + +// Our interfaces + +#include "MoreBacktraceTestCommon.h" + +///////////////////////////////////////////////////////////////// +#pragma mark ***** Utilities + +static OSStatus GetControlByIDQ(WindowRef inWindow, OSType signature, SInt32 id, ControlRef *outControl) + // A simple wrapper around GetControlByID. +{ + ControlID theID; + + theID.signature = signature; + theID.id = id; + return GetControlByID(inWindow, &theID, outControl); +} + +static OSStatus FindFinderProcess(ProcessSerialNumber *psnPtr) + // Find the ProcessSerialNumber of the Finder process. +{ + OSStatus err; + ProcessInfoRec info; + Boolean found; + + psnPtr->lowLongOfPSN = kNoProcess; + psnPtr->highLongOfPSN = kNoProcess; + + found = false; + do { + err = GetNextProcess(psnPtr); + if (err == noErr) { + memset(&info, 0, sizeof(info)); + + err = GetProcessInformation(psnPtr, &info); + if (err == noErr) { + found = (info.processSignature == 'MACS'); + } + } + } while ( (err == noErr) && ! found ); + + return err; +} + +///////////////////////////////////////////////////////////////// +#pragma mark ***** Compile-Time Parameters + +// We hard-code our output to Monaco 10. This is bad programming, +// but it suffices for a simple hack like this. + +static const UInt8 kOutputFont[] = "\pMonaco"; +static const SInt16 kOutputSize = 10; + +// The main text field will display about 70 frames, so that's all that +// we ask for. This is more than enough for our tests. + +enum { + kFrameCount = 70 +}; + +///////////////////////////////////////////////////////////////// +#pragma mark ***** GUI Infrastructure + +static void DoAbout(void) + // Displays the about box. +{ + SInt16 junkHit; + + (void) StandardAlert(kAlertPlainAlert, "\pMoreBacktraceTest", "\pA simple program to test MoreBacktrace.\r\rDTS\r\r© 2006 Apple Computer, Inc.", NULL, &junkHit); +} + +static void DisplayError(OSStatus errNum) +{ + OSStatus junk; + Str255 errStr; + SInt16 junkHit; + + if ( (errNum != noErr) && (errNum != userCanceledErr) ) { + NumToString(errNum, errStr); + + junk = StandardAlert(kAlertStopAlert, "\pError.", errStr, NULL, &junkHit); + assert(junk == noErr); + } +} + +static ControlRef gOutputText = NULL; +static ControlRef gPIDText = NULL; + +static OSStatus SetOutputText(CFStringRef newText) + // Put newText into the output edit text control. + // We use an edit text control because it's + // a) easy, b) handles multiple lines of text, and + // c) allows the user to copy the results. +{ + OSStatus err; + + assert(newText != NULL); + + err = SetControlData(gOutputText, kControlEntireControl, kControlEditTextCFStringTag, sizeof(newText), &newText); + Draw1Control(gOutputText); + + return err; +} + +static void ClearOutput(void) + // Clear the output text. +{ + OSStatus junk; + + junk = SetOutputText(CFSTR("")); + assert(junk == noErr); +} + +static OSStatus OutputFrames(char *bt) + // Output a textual description of frameCount frames from frameArray + // into the output text control. Actually generating the text from + // the frame array is handled by the common test code; all we have + // to do here is reflow the text into two columns so it fits in + // our text field. +{ + OSStatus err; + Boolean removedOne; + size_t row; + size_t col; + CFStringRef btStr; + CFArrayRef frameStrings; + size_t frameCount; + size_t frameIndex; + CFMutableStringRef result; + + btStr = NULL; + frameStrings = NULL; + result = NULL; + + // Remove any trailing newlines. + + removedOne = false; + do { + size_t len; + + len = strlen(bt); + if (len > 0 && bt[len] == '\n') { + bt[len] = 0; + removedOne = true; + } + } while ( removedOne ); + + // Break the string up into lines. + + err = noErr; + btStr = CFStringCreateWithCString(NULL, bt, kCFStringEncodingUTF8); + if (btStr == NULL) { + err = coreFoundationUnknownErr; + } + + if (err == noErr) { + frameStrings = CFStringCreateArrayBySeparatingStrings(NULL, btStr, CFSTR("\n")); + if (frameStrings == NULL) { + err = coreFoundationUnknownErr; + } + assert(frameStrings != NULL); + } + + // Count the frames and then place it into the output text field. + + if (err == noErr) { + frameCount = (size_t) CFArrayGetCount(frameStrings); + + result = CFStringCreateMutable(NULL, 0); + if (result == NULL) { + err = coreFoundationUnknownErr; + } + } + if (err == noErr) { + if ( frameCount > (kFrameCount / 2) ) { + + // We need two columns, so reflow. Nasty. + + for (row = 0; row < (kFrameCount / 2); row++) { + for (col = 0; col < 2; col++) { + frameIndex = (col * (kFrameCount / 2)) + row; + + if (frameIndex < frameCount) { + CFStringRef frameStr; + CFStringRef frameStrTrimmed; + CFStringRef columnPad; + + columnPad = NULL; + frameStrTrimmed = NULL; + + frameStr = CFArrayGetValueAtIndex(frameStrings, frameIndex); + assert(frameStr != NULL); + + if ( CFStringGetLength(frameStr) > 56 ) { + frameStrTrimmed = CFStringCreateWithSubstring(NULL, frameStr, CFRangeMake(0, 56)); + columnPad = CFStringCreateWithCString(NULL, "", kCFStringEncodingUTF8); + } else { + frameStrTrimmed = CFRetain(frameStr); + if (col == 0) { + columnPad = CFStringCreateWithFormat(NULL, NULL, CFSTR("%*.*s"), 56 - CFStringGetLength(frameStr), 56 - CFStringGetLength(frameStr), ""); + } else { + columnPad = CFStringCreateWithCString(NULL, "", kCFStringEncodingUTF8); + } + } + assert(frameStrTrimmed != NULL); + assert(columnPad != NULL); + + if ( (frameStrTrimmed != NULL) && (columnPad != NULL) ) { + CFStringAppendFormat(result, NULL, CFSTR("%@%@"), frameStrTrimmed, columnPad); + if (col == 0) { + CFStringAppend(result, CFSTR(" ")); + } + } + + if (columnPad != NULL) { + CFRelease(columnPad); + } + if (frameStrTrimmed != NULL) { + CFRelease(frameStrTrimmed); + } + } + } + CFStringAppend(result, CFSTR("\r")); + } + } else { + + // We can get away with a single column. + + for (frameIndex = 0; frameIndex < frameCount; frameIndex++) { + CFStringAppendFormat(result, NULL, CFSTR("%@\r"), CFArrayGetValueAtIndex(frameStrings, frameIndex)); + } + } + } + + // Put the string into the control. + + if (err == noErr) { + err = SetOutputText(result); + } + + // Clean up. + + if (btStr != NULL) { + CFRelease(btStr); + } + if (frameStrings != NULL) { + CFRelease(frameStrings); + } + if (result != NULL) { + CFRelease(result); + } + + return err; +} + +///////////////////////////////////////////////////////////////// +#pragma mark ***** Test Handlers + +static void GUITestMoreBacktraceMachSelf(void) + // Run in response to a click of the "MoreBacktraceMachSelf" + // button. It does the test and displays the result. +{ + OSStatus err; + char * bt; + + ClearOutput(); + + bt = NULL; + err = TestMoreBacktraceMachSelf(&bt); + if (err == noErr) { + err = OutputFrames(bt); + } + DisplayError(err); + free(bt); +} + +static void GUITestMoreBacktraceMachThread(void) + // Run in response to a click of the "MoreBacktraceMachThread" + // button. It does the test and displays the result. It gets + // the target PID from the "PID" field. +{ + OSStatus err; + CFStringRef pidStr; + pid_t pid; + char * bt; + + ClearOutput(); + + bt = NULL; + pidStr = NULL; + + // Get the PID of the process to sample from the + // gPIDText edit text control and convert that to + // the Mach task control port. + + err = GetControlData(gPIDText, kControlEntireControl, kControlEditTextCFStringTag, sizeof(pidStr), &pidStr, NULL); + if (err == noErr) { + pid = (pid_t) CFStringGetIntValue(pidStr); + } + if (err == noErr) { + err = TestMoreBacktraceMachThread(pid, &bt); + } + if (err == noErr) { + err = OutputFrames(bt); + } + DisplayError(err); + + // Clean up. + + free(bt); + if (pidStr != NULL) { + CFRelease(pidStr); + } +} + +static void GUITestSignalBacktrace(void) + // Run in response to a click of the "Signal Test" + // button. It does the test and displays the result. +{ + OSStatus err; + char * bt; + + bt = NULL; + + ClearOutput(); + + // Call a routine that sends a signal to us. + + err = TestMoreBacktraceMachSelfSignal(false, &bt); + if (err == noErr) { + err = OutputFrames(bt); + } + DisplayError(err); + + free(bt); +} + +static void GUITestStackSmash(void) + // Run in response to a click of the "Stack Smash Test" + // button. It does the test and displays the result. +{ + OSStatus err; + char * bt; + + ClearOutput(); + + bt = NULL; + + err = TestMoreBacktraceMachThreadStackSmash(&bt); + if (err == noErr) { + err = OutputFrames(bt); + } + DisplayError(err); + + free(bt); +} + +///////////////////////////////////////////////////////////////// +#pragma mark ***** Boilerplate Application Stuff + +static EventHandlerUPP gApplicationEventHandlerUPP; // -> ApplicationEventHandler + +static const EventTypeSpec kApplicationEvents[] = { {kEventClassCommand, kEventCommandProcess} }; + +static pascal OSStatus ApplicationEventHandler(EventHandlerCallRef inHandlerCallRef, + EventRef inEvent, void *inUserData) + // Dispatches HICommands to their implementations. +{ + OSStatus err; + HICommand command; + #pragma unused(inHandlerCallRef) + #pragma unused(inUserData) + + assert( GetEventClass(inEvent) == kEventClassCommand ); + assert( GetEventKind(inEvent) == kEventCommandProcess); + + err = GetEventParameter(inEvent, kEventParamDirectObject, typeHICommand, NULL, sizeof(command), NULL, &command); + if (err == noErr) { + switch (command.commandID) { + case kHICommandAbout: + DoAbout(); + break; + case 'btMS': + GUITestMoreBacktraceMachSelf(); + break; + case 'btMT': + GUITestMoreBacktraceMachThread(); + break; + case 'btST': + GUITestSignalBacktrace(); + break; + case 'btSS': + GUITestStackSmash(); + break; + default: + err = eventNotHandledErr; + break; + } + } + + return err; +} + +int main(int argc, char* argv[]) +{ + OSStatus err; + IBNibRef nibRef; + WindowRef window; + #pragma unused(argc) + #pragma unused(argv) + + // DebugStr("\pmain"); + + nibRef = NULL; + + // Create menu bar from NIB. + + err = CreateNibReference(CFSTR("main"), &nibRef); + if (err == noErr) { + err = SetMenuBarFromNib(nibRef, CFSTR("MenuBar")); + } + if (nibRef != NULL) { + DisposeNibReference(nibRef); + nibRef = NULL; + } + + // Create main window from NIB. + + if (err == noErr) { + err = CreateNibReference(CFSTR("MainWindow"), &nibRef); + } + if (err == noErr) { + err = CreateWindowFromNib(nibRef, CFSTR("MainWindow"), &window); + } + if (nibRef != NULL) { + DisposeNibReference(nibRef); + nibRef = NULL; + } + + // Install our HICommand handler. + + if (err == noErr) { + gApplicationEventHandlerUPP = NewEventHandlerUPP(ApplicationEventHandler); + assert(gApplicationEventHandlerUPP != NULL); + + err = InstallApplicationEventHandler(gApplicationEventHandlerUPP, + GetEventTypeCount(kApplicationEvents), + kApplicationEvents, NULL, NULL); + } + + // Get the output static text control and set it to Monaco 9. + + if (err == noErr) { + err = GetControlByIDQ(window, 'ETXT', 0, &gOutputText); + } + if (err == noErr) { + ControlFontStyleRec styleRec; + SInt16 monacoFontNum; + + GetFNum(kOutputFont, &monacoFontNum); + + styleRec.flags = kControlUseFontMask | kControlUseSizeMask; + styleRec.font = monacoFontNum; + styleRec.size = kOutputSize; + + err = SetControlData(gOutputText, kControlEntireControl, kControlStaticTextStyleTag, + sizeof(styleRec), &styleRec); + } + + // Get the PID edit text field and initialise it to the Finder's PID. + + if (err == noErr) { + err = GetControlByIDQ(window, 'PIDT', 0, &gPIDText); + } + if (err == noErr) { + ProcessSerialNumber finderPSN; + pid_t finderPID; + CFStringRef finderPIDStr; + + finderPIDStr = NULL; + + err = FindFinderProcess(&finderPSN); + if (err == noErr) { + err = GetProcessPID(&finderPSN, &finderPID); + } + if (err == noErr) { + finderPIDStr = CFStringCreateWithFormat(NULL, NULL, CFSTR("%ld"), (long) finderPID); + if (finderPIDStr == NULL) { + err = coreFoundationUnknownErr; + } + } + if (err == noErr) { + err = SetControlData(gPIDText, kControlEntireControl, kControlEditTextCFStringTag, sizeof(finderPIDStr), &finderPIDStr); + } + + if (finderPIDStr) { + CFRelease(finderPIDStr); + } + + // I don't want to refuse to start up just because this code failed, + // so swallow any error. + + assert(err == noErr); + err = noErr; + } + + if (err == noErr) { + // The window was created hidden so show it. + + ShowWindow( window ); + + // Call the event loop + + RunApplicationEventLoop(); + } + + return (err == noErr) ? EXIT_SUCCESS : EXIT_FAILURE; +} diff --git a/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MoreBacktraceTest.xcodeproj/project.pbxproj b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MoreBacktraceTest.xcodeproj/project.pbxproj new file mode 100644 index 0000000000..bf7cb6a84d --- /dev/null +++ b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MoreBacktraceTest.xcodeproj/project.pbxproj @@ -0,0 +1,424 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 42; + objects = { + +/* Begin PBXBuildFile section */ + E42C50FB097D62FC00D1B30B /* MoreBacktrace.h in Headers */ = {isa = PBXBuildFile; fileRef = E4D9D9CA043A170400002802 /* MoreBacktrace.h */; }; + E42C50FC097D62FC00D1B30B /* MoreSetup.h in Headers */ = {isa = PBXBuildFile; fileRef = E4D9D9CD043A171200002802 /* MoreSetup.h */; }; + E42C5104097D62FC00D1B30B /* MoreAddrToSym.h in Headers */ = {isa = PBXBuildFile; fileRef = E4E6C079043DD1A000002802 /* MoreAddrToSym.h */; }; + E42C5108097D62FC00D1B30B /* main.nib in Resources */ = {isa = PBXBuildFile; fileRef = E4D9D9D3043AEDB800002802 /* main.nib */; }; + E42C5109097D62FC00D1B30B /* MainWindow.nib in Resources */ = {isa = PBXBuildFile; fileRef = E4A2067F0444ADE300002802 /* MainWindow.nib */; }; + E42C510B097D62FC00D1B30B /* MoreBacktrace.c in Sources */ = {isa = PBXBuildFile; fileRef = E4D9D9C9043A170400002802 /* MoreBacktrace.c */; }; + E42C510C097D62FC00D1B30B /* MoreBacktraceTest.c in Sources */ = {isa = PBXBuildFile; fileRef = E4D9D9CF043A172300002802 /* MoreBacktraceTest.c */; }; + E42C5114097D62FC00D1B30B /* MoreAddrToSym.c in Sources */ = {isa = PBXBuildFile; fileRef = E4E6C078043DD1A000002802 /* MoreAddrToSym.c */; }; + E42C5117097D62FC00D1B30B /* Carbon.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 20286C33FDCF999611CA2CEA /* Carbon.framework */; }; + E42C5285097D728200D1B30B /* MoreBacktraceTestTool.c in Sources */ = {isa = PBXBuildFile; fileRef = E42C5163097D6D7400D1B30B /* MoreBacktraceTestTool.c */; }; + E4CA23DB0982F7690043C210 /* MoreBacktrace.c in Sources */ = {isa = PBXBuildFile; fileRef = E4D9D9C9043A170400002802 /* MoreBacktrace.c */; }; + E4CA24050982FE650043C210 /* MoreBacktraceTestCommon.c in Sources */ = {isa = PBXBuildFile; fileRef = E4CA24040982FE650043C210 /* MoreBacktraceTestCommon.c */; }; + E4CA24060982FE650043C210 /* MoreBacktraceTestCommon.c in Sources */ = {isa = PBXBuildFile; fileRef = E4CA24040982FE650043C210 /* MoreBacktraceTestCommon.c */; }; + E4CA24080982FE6C0043C210 /* MoreBacktraceTestCommon.h in Headers */ = {isa = PBXBuildFile; fileRef = E4CA24070982FE6C0043C210 /* MoreBacktraceTestCommon.h */; }; + E4CA25F709831B6D0043C210 /* MoreAddrToSym.c in Sources */ = {isa = PBXBuildFile; fileRef = E4E6C078043DD1A000002802 /* MoreAddrToSym.c */; }; +/* End PBXBuildFile section */ + +/* Begin PBXBuildStyle section */ + 4A9504C5FFE6A39111CA0CBA /* Development */ = { + isa = PBXBuildStyle; + buildSettings = { + COPY_PHASE_STRIP = NO; + GCC_DYNAMIC_NO_PIC = NO; + GCC_ENABLE_FIX_AND_CONTINUE = YES; + GCC_GENERATE_DEBUGGING_SYMBOLS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + OPTIMIZATION_CFLAGS = "-O0"; + ZERO_LINK = YES; + }; + name = Development; + }; + 4A9504C6FFE6A39111CA0CBA /* Deployment */ = { + isa = PBXBuildStyle; + buildSettings = { + COPY_PHASE_STRIP = YES; + GCC_ENABLE_FIX_AND_CONTINUE = NO; + ZERO_LINK = NO; + }; + name = Deployment; + }; +/* End PBXBuildStyle section */ + +/* Begin PBXFileReference section */ + 20286C33FDCF999611CA2CEA /* Carbon.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Carbon.framework; path = /System/Library/Frameworks/Carbon.framework; sourceTree = ""; }; + E42C511D097D62FC00D1B30B /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.xml; path = Info.plist; sourceTree = ""; }; + E42C511E097D62FC00D1B30B /* MoreBacktraceTest.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = MoreBacktraceTest.app; sourceTree = BUILT_PRODUCTS_DIR; }; + E42C5163097D6D7400D1B30B /* MoreBacktraceTestTool.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = MoreBacktraceTestTool.c; sourceTree = ""; }; + E42C5172097D6E1D00D1B30B /* MoreBacktraceTestTool */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; path = MoreBacktraceTestTool; sourceTree = BUILT_PRODUCTS_DIR; }; + E4A2067F0444ADE300002802 /* MainWindow.nib */ = {isa = PBXFileReference; lastKnownFileType = wrapper.nib; path = MainWindow.nib; sourceTree = ""; }; + E4CA24040982FE650043C210 /* MoreBacktraceTestCommon.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = MoreBacktraceTestCommon.c; sourceTree = ""; }; + E4CA24070982FE6C0043C210 /* MoreBacktraceTestCommon.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; path = MoreBacktraceTestCommon.h; sourceTree = ""; }; + E4D9D9C9043A170400002802 /* MoreBacktrace.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; name = MoreBacktrace.c; path = ../MoreBacktrace.c; sourceTree = SOURCE_ROOT; }; + E4D9D9CA043A170400002802 /* MoreBacktrace.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = MoreBacktrace.h; path = ../MoreBacktrace.h; sourceTree = SOURCE_ROOT; }; + E4D9D9CD043A171200002802 /* MoreSetup.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = MoreSetup.h; path = ../../MoreSetup.h; sourceTree = SOURCE_ROOT; }; + E4D9D9CF043A172300002802 /* MoreBacktraceTest.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; path = MoreBacktraceTest.c; sourceTree = ""; }; + E4D9D9D3043AEDB800002802 /* main.nib */ = {isa = PBXFileReference; lastKnownFileType = wrapper.nib; path = main.nib; sourceTree = ""; }; + E4E6C078043DD1A000002802 /* MoreAddrToSym.c */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.c; name = MoreAddrToSym.c; path = ../MoreAddrToSym.c; sourceTree = SOURCE_ROOT; }; + E4E6C079043DD1A000002802 /* MoreAddrToSym.h */ = {isa = PBXFileReference; fileEncoding = 30; lastKnownFileType = sourcecode.c.h; name = MoreAddrToSym.h; path = ../MoreAddrToSym.h; sourceTree = SOURCE_ROOT; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + E42C5116097D62FC00D1B30B /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + E42C5117097D62FC00D1B30B /* Carbon.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E42C5170097D6E1D00D1B30B /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 195DF8CFFE9D517E11CA2CBB /* Products */ = { + isa = PBXGroup; + children = ( + E42C511E097D62FC00D1B30B /* MoreBacktraceTest.app */, + E42C5172097D6E1D00D1B30B /* MoreBacktraceTestTool */, + ); + name = Products; + sourceTree = ""; + }; + 20286C29FDCF999611CA2CEA /* MoreBacktraceTest */ = { + isa = PBXGroup; + children = ( + E4DA7D6B09843FE2000630D1 /* Test Code */, + 20286C2AFDCF999611CA2CEA /* Reusable Code */, + 195DF8CFFE9D517E11CA2CBB /* Products */, + E42C511D097D62FC00D1B30B /* Info.plist */, + ); + name = MoreBacktraceTest; + sourceTree = ""; + }; + 20286C2AFDCF999611CA2CEA /* Reusable Code */ = { + isa = PBXGroup; + children = ( + E4E6C079043DD1A000002802 /* MoreAddrToSym.h */, + E4E6C078043DD1A000002802 /* MoreAddrToSym.c */, + E4D9D9CA043A170400002802 /* MoreBacktrace.h */, + E4D9D9C9043A170400002802 /* MoreBacktrace.c */, + E4D9D9CD043A171200002802 /* MoreSetup.h */, + ); + name = "Reusable Code"; + sourceTree = ""; + }; + E4DA7D6B09843FE2000630D1 /* Test Code */ = { + isa = PBXGroup; + children = ( + E42C5163097D6D7400D1B30B /* MoreBacktraceTestTool.c */, + E4D9D9CF043A172300002802 /* MoreBacktraceTest.c */, + E4CA24070982FE6C0043C210 /* MoreBacktraceTestCommon.h */, + E4CA24040982FE650043C210 /* MoreBacktraceTestCommon.c */, + E4D9D9D3043AEDB800002802 /* main.nib */, + E4A2067F0444ADE300002802 /* MainWindow.nib */, + 20286C33FDCF999611CA2CEA /* Carbon.framework */, + ); + name = "Test Code"; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXHeadersBuildPhase section */ + E42C50FA097D62FC00D1B30B /* Headers */ = { + isa = PBXHeadersBuildPhase; + buildActionMask = 2147483647; + files = ( + E42C50FB097D62FC00D1B30B /* MoreBacktrace.h in Headers */, + E42C50FC097D62FC00D1B30B /* MoreSetup.h in Headers */, + E42C5104097D62FC00D1B30B /* MoreAddrToSym.h in Headers */, + E4CA24080982FE6C0043C210 /* MoreBacktraceTestCommon.h in Headers */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXHeadersBuildPhase section */ + +/* Begin PBXNativeTarget section */ + E42C50F9097D62FC00D1B30B /* App */ = { + isa = PBXNativeTarget; + buildConfigurationList = E42C5119097D62FC00D1B30B /* Build configuration list for PBXNativeTarget "App" */; + buildPhases = ( + E42C50FA097D62FC00D1B30B /* Headers */, + E42C5107097D62FC00D1B30B /* Resources */, + E42C510A097D62FC00D1B30B /* Sources */, + E42C5116097D62FC00D1B30B /* Frameworks */, + E42C5118097D62FC00D1B30B /* Rez */, + ); + buildRules = ( + ); + buildSettings = { + FRAMEWORK_SEARCH_PATHS = ""; + HEADER_SEARCH_PATHS = ""; + INSTALL_PATH = "$(HOME)/Applications"; + LIBRARY_SEARCH_PATHS = ""; + OTHER_CFLAGS = ""; + OTHER_LDFLAGS = ""; + OTHER_REZFLAGS = ""; + PRODUCT_NAME = MoreBacktraceTest; + SECTORDER_FLAGS = ""; + WARNING_CFLAGS = ( + "-Wmost", + "-Wno-four-char-constants", + "-Wno-unknown-pragmas", + ); + WRAPPER_EXTENSION = app; + }; + dependencies = ( + ); + name = App; + productInstallPath = "$(HOME)/Applications"; + productName = MoreBacktraceTest; + productReference = E42C511E097D62FC00D1B30B /* MoreBacktraceTest.app */; + productType = "com.apple.product-type.application"; + }; + E42C5171097D6E1D00D1B30B /* Tool */ = { + isa = PBXNativeTarget; + buildConfigurationList = E42C5179097D6E2E00D1B30B /* Build configuration list for PBXNativeTarget "Tool" */; + buildPhases = ( + E42C516F097D6E1D00D1B30B /* Sources */, + E42C5170097D6E1D00D1B30B /* Frameworks */, + ); + buildRules = ( + ); + buildSettings = { + GCC_ENABLE_FIX_AND_CONTINUE = YES; + GCC_MODEL_TUNING = G5; + INSTALL_PATH = "$(HOME)/bin"; + PREBINDING = NO; + PRODUCT_NAME = MoreBacktraceTestTool; + ZERO_LINK = YES; + }; + dependencies = ( + ); + name = Tool; + productName = MoreBacktraceTestTool; + productReference = E42C5172097D6E1D00D1B30B /* MoreBacktraceTestTool */; + productType = "com.apple.product-type.tool"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 20286C28FDCF999611CA2CEA /* Project object */ = { + isa = PBXProject; + buildConfigurationList = E42C5087097D61DA00D1B30B /* Build configuration list for PBXProject "MoreBacktraceTest" */; + buildSettings = { + }; + buildStyles = ( + 4A9504C5FFE6A39111CA0CBA /* Development */, + 4A9504C6FFE6A39111CA0CBA /* Deployment */, + ); + hasScannedForEncodings = 1; + mainGroup = 20286C29FDCF999611CA2CEA /* MoreBacktraceTest */; + projectDirPath = ""; + targets = ( + E42C50F9097D62FC00D1B30B /* App */, + E42C5171097D6E1D00D1B30B /* Tool */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + E42C5107097D62FC00D1B30B /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + E42C5108097D62FC00D1B30B /* main.nib in Resources */, + E42C5109097D62FC00D1B30B /* MainWindow.nib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXRezBuildPhase section */ + E42C5118097D62FC00D1B30B /* Rez */ = { + isa = PBXRezBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXRezBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + E42C510A097D62FC00D1B30B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + E42C510B097D62FC00D1B30B /* MoreBacktrace.c in Sources */, + E42C510C097D62FC00D1B30B /* MoreBacktraceTest.c in Sources */, + E42C5114097D62FC00D1B30B /* MoreAddrToSym.c in Sources */, + E4CA24050982FE650043C210 /* MoreBacktraceTestCommon.c in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; + E42C516F097D6E1D00D1B30B /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + E42C5285097D728200D1B30B /* MoreBacktraceTestTool.c in Sources */, + E4CA23DB0982F7690043C210 /* MoreBacktrace.c in Sources */, + E4CA24060982FE650043C210 /* MoreBacktraceTestCommon.c in Sources */, + E4CA25F709831B6D0043C210 /* MoreAddrToSym.c in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin XCBuildConfiguration section */ + E42C5088097D61DA00D1B30B /* Development */ = { + isa = XCBuildConfiguration; + buildSettings = { + COPY_PHASE_STRIP = NO; + DEPLOYMENT_POSTPROCESSING = NO; + GCC_DYNAMIC_NO_PIC = YES; + GCC_GENERATE_DEBUGGING_SYMBOLS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_LABEL = YES; + GCC_WARN_UNUSED_PARAMETER = YES; + GCC_WARN_UNUSED_VALUE = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.1; + PREBINDING = NO; + SDKROOT = /Developer/SDKs/MacOSX10.4u.sdk; + WARNING_CFLAGS = "-Wall"; + ZERO_LINK = NO; + }; + name = Development; + }; + E42C5089097D61DA00D1B30B /* Deployment */ = { + isa = XCBuildConfiguration; + buildSettings = { + COPY_PHASE_STRIP = YES; + DEPLOYMENT_POSTPROCESSING = YES; + GCC_DYNAMIC_NO_PIC = YES; + GCC_GENERATE_DEBUGGING_SYMBOLS = YES; + GCC_OPTIMIZATION_LEVEL = s; + GCC_WARN_ABOUT_MISSING_PROTOTYPES = YES; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_LABEL = YES; + GCC_WARN_UNUSED_PARAMETER = YES; + GCC_WARN_UNUSED_VALUE = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.1; + PREBINDING = NO; + SDKROOT = /Developer/SDKs/MacOSX10.4u.sdk; + WARNING_CFLAGS = "-Wall"; + ZERO_LINK = NO; + }; + name = Deployment; + }; + E42C511A097D62FC00D1B30B /* Development */ = { + isa = XCBuildConfiguration; + buildSettings = { + ARCHS = ( + ppc, + i386, + ); + INFOPLIST_FILE = Info.plist; + PRODUCT_NAME = MoreBacktraceTest; + WRAPPER_EXTENSION = app; + }; + name = Development; + }; + E42C511B097D62FC00D1B30B /* Deployment */ = { + isa = XCBuildConfiguration; + buildSettings = { + ARCHS = ( + ppc, + i386, + ); + INFOPLIST_FILE = Info.plist; + PRODUCT_NAME = MoreBacktraceTest; + WRAPPER_EXTENSION = app; + }; + name = Deployment; + }; + E42C517A097D6E2E00D1B30B /* Development */ = { + isa = XCBuildConfiguration; + buildSettings = { + ARCHS = ( + ppc, + ppc64, + i386, + ); + BUILD_VARIANTS = normal; + INSTALL_PATH = "$(HOME)/bin"; + OTHER_CFLAGS = "-fasm-blocks"; + OTHER_LDFLAGS = ( + "-pagezero_size", + 1000, + ); + PRODUCT_NAME = MoreBacktraceTestTool; + }; + name = Development; + }; + E42C517B097D6E2E00D1B30B /* Deployment */ = { + isa = XCBuildConfiguration; + buildSettings = { + ARCHS = ( + ppc, + ppc64, + i386, + ); + BUILD_VARIANTS = normal; + INSTALL_PATH = "$(HOME)/bin"; + OTHER_CFLAGS = "-fasm-blocks"; + OTHER_LDFLAGS = ( + "-pagezero_size", + 1000, + ); + PRODUCT_NAME = MoreBacktraceTestTool; + }; + name = Deployment; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + E42C5087097D61DA00D1B30B /* Build configuration list for PBXProject "MoreBacktraceTest" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + E42C5088097D61DA00D1B30B /* Development */, + E42C5089097D61DA00D1B30B /* Deployment */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Development; + }; + E42C5119097D62FC00D1B30B /* Build configuration list for PBXNativeTarget "App" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + E42C511A097D62FC00D1B30B /* Development */, + E42C511B097D62FC00D1B30B /* Deployment */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Development; + }; + E42C5179097D6E2E00D1B30B /* Build configuration list for PBXNativeTarget "Tool" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + E42C517A097D6E2E00D1B30B /* Development */, + E42C517B097D6E2E00D1B30B /* Deployment */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Development; + }; +/* End XCConfigurationList section */ + }; + rootObject = 20286C28FDCF999611CA2CEA /* Project object */; +} diff --git a/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MoreBacktraceTestCommon.c b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MoreBacktraceTestCommon.c new file mode 100644 index 0000000000..b10155e815 --- /dev/null +++ b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MoreBacktraceTestCommon.c @@ -0,0 +1,765 @@ +/* + File: MoreBacktraceTestCommon.c + + Contains: Common code for testing MoreBacktrace. + + Written by: DTS + + Copyright: Copyright (c) 2006 by Apple Computer, Inc., All Rights Reserved. + + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. + ("Apple") in consideration of your agreement to the following terms, and your + use, installation, modification or redistribution of this Apple software + constitutes acceptance of these terms. If you do not agree with these terms, + please do not use, install, modify or redistribute this Apple software. + + In consideration of your agreement to abide by the following terms, and subject + to these terms, Apple grants you a personal, non-exclusive license, under AppleÕs + copyrights in this original Apple software (the "Apple Software"), to use, + reproduce, modify and redistribute the Apple Software, with or without + modifications, in source and/or binary forms; provided that if you redistribute + the Apple Software in its entirety and without modifications, you must retain + this notice and the following text and disclaimers in all such redistributions of + the Apple Software. Neither the name, trademarks, service marks or logos of + Apple Computer, Inc. may be used to endorse or promote products derived from the + Apple Software without specific prior written permission from Apple. Except as + expressly stated in this notice, no other rights or licenses, express or implied, + are granted by Apple herein, including but not limited to any patent rights that + may be infringed by your derivative works or by other works in which the Apple + Software may be incorporated. + + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED + WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN + COMBINATION WITH YOUR PRODUCTS. + + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION + OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT + (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Change History (most recent first): + +$Log: MoreBacktraceTestCommon.c,v $ +Revision 1.5 2006/01/23 19:26:07 eskimo1 +Spin on a volatile int because the compiler doesn't like spinning an a volatile pointer (even after I declare it correctly). + +Revision 1.1 2006/01/22 22:47:49 eskimo1 +A new module that abstracts the test code out of the GUI test app so that it can also be used by the command line tool. + + +*/ + +///////////////////////////////////////////////////////////////// + +// Our Prototypes + +#include "MoreBacktraceTestCommon.h" + +// Mac OS Interfaces + +#include +#include +#include +#include + +// MIB Interfaces + +#include "MoreAddrToSym.h" + +///////////////////////////////////////////////////////////////// + +#pragma mark ***** Backtrace To Text + +// TestMoreBacktraceFramesToText uses a memory based (FILE *) (created using +// fwopen) to collect its results. WriteCallback is the routine that handles +// writes for this (FILE *). WriteCallbackContext holds its state. + +struct WriteCallbackContext { + size_t dataSize; // current data size + char * data; // current data +}; +typedef struct WriteCallbackContext WriteCallbackContext; + +static int WriteCallback(void *cookie, const char *data, int dataSize) + // Passed as a write callback to fwopen to create a memory-based + // (FILE *). See for details. +{ + int err; + int result; + char * tmp; + WriteCallbackContext * context; + + // Recover our context from the cookie. + + context = (WriteCallbackContext *) cookie; + + // Allocate a new buffer to accommodate the old data and the new. + + err = 0; + tmp = malloc(context->dataSize + dataSize); + if (tmp == NULL) { + err = ENOMEM; + } + + // Fill it in. + + if (err == 0) { + memcpy(tmp, context->data, context->dataSize); // old data + memcpy(tmp + context->dataSize, data, dataSize); // new data + + free(context->data); + context->data = tmp; + context->dataSize += dataSize; + } + + // Clean up. + + if (err == 0) { + result = dataSize; + } else { + errno = err; + result = -1; + } + return result; +} + +extern int TestMoreBacktraceFramesToText( + const MoreBTFrame frames[], + size_t frameCount, + bool lookupSymbolNames, + char ** btPtr +) + // See comments in header. +{ + int err; + int junk; + WriteCallbackContext resultContext; + FILE * result; + size_t frameIndex; + MoreAToSSymInfo * symbols; + + assert(frames != NULL); + assert(btPtr != NULL); + assert(*btPtr == NULL); + + result = NULL; + resultContext.dataSize = 0; + resultContext.data = NULL; + symbols = NULL; + + // Create an array of NULL CFStringRefs to hold the symbol pointers. + + err = MoreAToSCreate(frameCount, &symbols); + + // If we've been asked to look up the symbols, do so. + + if ( (err == 0) && lookupSymbolNames) { + MoreAToSAddr *addresses; + + // Allocate an array for the addresses and fill it in. + + addresses = (MoreAToSAddr *) malloc(frameCount * sizeof(*addresses)); + if (addresses == NULL) { + err = ENOMEM; + } + if (err == 0) { + for (frameIndex = 0; frameIndex < frameCount; frameIndex++) { + if (frames[frameIndex].flags & kMoreBTPCBadMask) { + addresses[frameIndex] = 0; + } else { + addresses[frameIndex] = frames[frameIndex].pc; + } + } + } + + // Call MoreAddrToSym module to do the job. + + if (err == 0) { + err = MoreAToSCopySymbolNamesUsingDyld(frameCount, addresses, symbols); + } + + free(addresses); + } + + // Create the output string, starting with an empty string and then + // appending an entry for each frame. This uses the little known + // ability of BSD to create a (FILE *) with custom I/O routines. In this + // case, I have a write routine that outputs to a memory buffer (the + // details of which are held in resultContext). + + if (err == 0) { + result = fwopen(&resultContext, WriteCallback); + if (result == NULL) { + err = errno; + } + } + if (err == 0) { + int ptrWidth; + + // Determine whether we can treat the backtrace is 32-bit or whether we have to + // output the full 64-bits of each pointer. + + ptrWidth = 8; + for (frameIndex = 0; frameIndex < frameCount; frameIndex++) { + const MoreBTFrame * thisFrame; + + thisFrame = &frames[frameIndex]; + + if ( !(thisFrame->flags & kMoreBTPCBadMask) && (thisFrame->pc & 0xFFFFFFFF00000000LL) ) { + ptrWidth = 16; + } + if ( !(thisFrame->flags & kMoreBTFrameBadMask) && (thisFrame->fp & 0xFFFFFFFF00000000LL) ) { + ptrWidth = 16; + } + } + + // Now output each entry. + + for (frameIndex = 0; frameIndex < frameCount; frameIndex++) { + const char *thisSymbol; + + // First the frame number and the flags. + + junk = fprintf(result, "%2zu %c%c%c ", + frameIndex, + (frames[frameIndex].flags & kMoreBTFrameBadMask) ? 'F' : 'f', + (frames[frameIndex].flags & kMoreBTPCBadMask) ? 'P' : 'p', + (frames[frameIndex].flags & kMoreBTSignalHandlerMask) ? 'S' : 's' + ); + assert(junk > 0); + + // Then the frame pointer. + + if (frames[frameIndex].flags & kMoreBTFrameBadMask) { + fprintf(result, "%*s ", ptrWidth, ""); + } else { + fprintf(result, "%*llx ", ptrWidth, frames[frameIndex].fp); + } + + // Then the PC. + + if (frames[frameIndex].flags & kMoreBTPCBadMask) { + fprintf(result, "%*s ", ptrWidth, ""); + } else { + fprintf(result, "%*llx ", ptrWidth, frames[frameIndex].pc); + } + + // Finally the symbolic name, if present. + + thisSymbol = symbols[frameIndex].symbolName; + if (thisSymbol != NULL) { + junk = fprintf(result, " %s+%04llx", thisSymbol, symbols[frameIndex].symbolOffset); + assert(junk > 0); + } + + junk = fprintf(result, "\n"); + assert(junk > 0); + } + } + + // Null terminate the string. + + if (err == 0) { + junk = fputc(0, result); + assert(junk >= 0); + } + + // Clean up. + + if (result != NULL) { + junk = fclose(result); + assert(junk == 0); + } + if (err == 0) { + *btPtr = resultContext.data; // all good, return resultContext.data to the client + } else { + free(resultContext.data); // all bad, free up resultContext.data and leave *btPtr as NULL + } + MoreAToSDestroy(frameCount, symbols); + + assert( (err == 0) == (*btPtr != NULL) ); + + return err; +} + +#pragma mark ***** Self Test + +// To simplify the test code, I receive the backtrace into a fixed size array. +// The number of elements in this array, 70, is the number that I can reasonably +// display in the window of the GUI app. I've carried it forward into the common +// code because I don't see any pressing need to change it. + +enum { + kFrameCount = 70 +}; + +extern int TestMoreBacktraceMachSelf(char **btPtr) + // See comments in header. +{ + int err; + MoreBTFrame frames[kFrameCount]; + size_t frameCount; + size_t validFrames; + + assert( btPtr != NULL); + assert(*btPtr == NULL); + + frameCount = sizeof(frames) / sizeof(*frames); + err = MoreBacktraceMachSelf(0, 0, frames, frameCount, &validFrames); + if (err == 0) { + if (validFrames > frameCount) { + validFrames = frameCount; + } + err = TestMoreBacktraceFramesToText(frames, validFrames, true, btPtr); + } + + assert( (err == 0) == (*btPtr != NULL) ); + + return err; +} + +#pragma mark ***** Other Task Test + +extern int TestMoreBacktraceMachThread(pid_t pid, char **btPtr) + // See comments in header. +{ + int err; + int junk; + MoreBTFrame frames[kFrameCount]; + size_t frameCount; + size_t validFrames; + task_t targetTask; + bool didSuspend; + thread_array_t threadList; + mach_msg_type_number_t threadCount; + + assert(pid > 0); + assert(btPtr != NULL); + assert(*btPtr == NULL); + + targetTask = MACH_PORT_NULL; + threadList = NULL; + didSuspend = false; + + frameCount = 0; // just to quieten a warning + + // Convert pid to the Mach task control port. + + err = task_for_pid(mach_task_self(), pid, &targetTask); + if (err == 0) { + if (targetTask == mach_task_self()) { + err = -1; // this won't go well + } + } + + // Suspend the task while we sample it. Otherwise the + // list of threads might change. + + if (err == 0) { + err = task_suspend(targetTask); + didSuspend = (err == 0); + } + if (err == 0) { + err = task_threads(targetTask, &threadList, &threadCount); + } + if (err == 0) { + // A task without any threads makes no sense. + + assert(threadCount > 0); + + // We always sample the first thread. This has no real + // significance because Mach doesn't guarantee to return + // the threads in any particular order. In a real tool + // you'd iterate over all of the threads and sample each, + // but I have no way of displaying the results in my + // test framework. + + frameCount = sizeof(frames) / sizeof(*frames); + err = MoreBacktraceMachThread(targetTask, threadList[0], 0, 0, frames, frameCount, &validFrames); + } + + // Resume the task as quickly as possibly after the backtrace. + + if (didSuspend) { + junk = task_resume(targetTask); + assert(junk == 0); + } + + // Create the text output without symbols. + + if (err == 0) { + if (validFrames > frameCount) { + validFrames = frameCount; + } + err = TestMoreBacktraceFramesToText(frames, validFrames, false, btPtr); + } + + // Clean up. + + junk = mach_port_deallocate(mach_task_self(), targetTask); + assert(junk == 0); + if (threadList != NULL) { + mach_msg_type_number_t thisThread; + + for (thisThread = 0; thisThread < threadCount; thisThread++) { + junk = mach_port_deallocate(mach_task_self(), threadList[thisThread]); + assert(junk == 0); + } + junk = vm_deallocate(mach_task_self(), (vm_address_t) threadList, threadCount * sizeof(*threadList)); + assert(junk == 0); + } + + assert( (err == 0) == (*btPtr != NULL) ); + + return err; +} + +#pragma mark ***** Signal Test + +// The following are set by the signal handler when it runs. + +static volatile int gError = -1; +static char volatile * gBacktrace = NULL; + +static void MySIGUSR1Handler(int signal) + // Handle SIGUSR1. Note that we call many functions + // here that aren't "signal safe". However, we know + // that this signal isn't happening asynchronously, + // we're sending it to ourselves via a call to "pthread_kill", + // so most of the unsafeness is moot. Still, if this + // wasn't a just test program I'd figure out a better way. +{ + int err; + char * tmp; + assert(signal == SIGUSR1); + + fprintf(stderr, "MySIGUSR1Handler calls TestMoreBacktraceMachSelf.\n"); + tmp = (char *) gBacktrace; + err = TestMoreBacktraceMachSelf(&tmp); + gBacktrace = tmp; // Because the code in TestSignalBacktraceNested + gError = err; // might be spinning on gError, assign that last. +} + +static int TestSignalBacktraceNested(bool nonLeaf) + // Send a SIGUSR1 to ourselves. +{ + int err; + + if ( ! nonLeaf ) { + + // This is the standard branch. We use pthread_kill to send a signal + // to ourself. + + err = pthread_kill(pthread_self(), SIGUSR1); + } else { + + // Use this branch of the code, in tandem with sending the SIGUSR1 from + // the command line, to test the case where a signal interrupts a non-leaf + // routine. I added this because pthread_kill (well, actually __pthread_kill) + // is a system call leaf routine, so the main test only checks the + // in leaf routine case. + // + // Also, this is a hard spin loop because I can't + // add a delay call because then it's likely that the signal would come + // in while we're blocked in the delay, and then we're back to the leaf + // routine test again. + + fprintf(stderr, "Signal this process using:\n"); + fprintf(stderr, "\n"); + fprintf(stderr, "$ kill -USR1 %ld\n", (long) getpid()); + + while (gError == -1) { + // do nothing + } + err = 0; + } + return err; +} + +extern int TestMoreBacktraceMachSelfSignal(bool nonLeaf, char **btPtr) + // See comments in header. +{ + int err; + int junk; + struct sigaction oldSig; + struct sigaction newSig; + + assert(btPtr != NULL); + assert(*btPtr == NULL); + + assert(gBacktrace == NULL); + assert(gError == -1); + + // Install MySIGUSR1Handler as the SIGUSR1 handler. + + memset(&newSig, 0, sizeof(newSig)); + newSig.sa_handler = &MySIGUSR1Handler; + err = sigaction(SIGUSR1, &newSig, &oldSig); + if (err < 0) { + err = errno; + } + + if (err == 0) { + + // Call a routine that sends a signal to us. + + err = TestSignalBacktraceNested(nonLeaf); + + // Restore the old signal handler. + + junk = sigaction(SIGUSR1, &oldSig, NULL); + assert(junk == 0); + + if (err == 0) { + err = gError; // get the error from the signal handler + gError = -1; // just for tidiness + } + } + + if (err == 0) { + *btPtr = (char *) gBacktrace; // get the backtrace from the signal handler + gBacktrace = NULL; // just for tidiness + } + + assert( (err == 0) == (*btPtr != NULL) ); + + return err; +} + +#pragma mark ***** Stack Smash Test + +// This test works by create a dummy thread that blocks forever deep in nested +// routines, then smashing its stack. + +static pthread_t gDeadThread; + // The dummy thread itself. + +static pthread_mutex_t gDeadThreadReadyMutex; +static pthread_cond_t gDeadThreadReadyCond; + // A condition variable that protects gDeadThreadReady and gDeadThreadID. + +static volatile bool gDeadThreadReady = false; + // True if the dead thread is ready to be smashed. + +static volatile thread_t gDeadThreadID = MACH_PORT_NULL; + // The Mach thread ID of the thread. + +static void DeadThreadNested4(void) + // The victim routine itself. +{ + int junk; + + // Set our condition to true. + + junk = pthread_mutex_lock(&gDeadThreadReadyMutex); + assert(junk == 0); + + gDeadThreadReady = true; + gDeadThreadID = mach_thread_self(); + + junk = pthread_mutex_unlock(&gDeadThreadReadyMutex); + assert(junk == 0); + + // Signal the main thread who is waiting on our condition. + + junk = pthread_cond_signal(&gDeadThreadReadyCond); + assert(junk == 0); + + // Loop forever. + + do { + (void) pause(); + } while (true); +} + +static void DeadThreadNested3(void) + // A few nested procedures so you get an interesting trace. +{ + DeadThreadNested4(); +} + +static void DeadThreadNested2(void) + // A few nested procedures so you get an interesting trace. +{ + DeadThreadNested3(); +} + +static void DeadThreadNested1(void) + // A few nested procedures so you get an interesting trace. +{ + DeadThreadNested2(); +} + +static void * DeadThread(void *param) + // The thread entry point for the victim thread. +{ + #pragma unused(param) + DeadThreadNested1(); + return NULL; +} + +static int StartDeadThread(void) + // Start a victim thread whose stack we intend to smash + // in order to test our handling of bad pointers in a + // stack crawl. + // + // Returns an errno-style error. +{ + int err; + int junk; + thread_t threadID; + MoreBTFrame frames[10]; + size_t frameCount; + size_t validFrames; + + // Init resources required for condition variable. + + err = pthread_mutex_init(&gDeadThreadReadyMutex, NULL); + if (err == 0) { + err = pthread_cond_init(&gDeadThreadReadyCond, NULL); + } + + // Start the thread. + + if (err == 0) { + err = pthread_create(&gDeadThread, NULL, DeadThread, NULL); + } + if (err == 0) { + junk = pthread_detach(gDeadThread); + assert(junk == 0); + } + + // Wait for the condition. + + if (err == 0) { + threadID = MACH_PORT_NULL; + do { + junk = pthread_mutex_lock(&gDeadThreadReadyMutex); + assert(junk == 0); + + if (gDeadThreadReady) { + threadID = gDeadThreadID; + } + + if (threadID == MACH_PORT_NULL) { + junk = pthread_cond_wait(&gDeadThreadReadyCond, &gDeadThreadReadyMutex); + assert(junk == 0); + } + + junk = pthread_mutex_unlock(&gDeadThreadReadyMutex); + assert(junk == 0); + } while ( threadID == MACH_PORT_NULL ); + } + + // Take a backtrace. + + if (err == 0) { + frameCount = sizeof(frames) / sizeof(frames[0]); + + err = MoreBacktraceMachThread( + mach_task_self(), + threadID, + 0, + 0, + frames, + frameCount, + &validFrames + ); + } + if (err == 0) { + if (validFrames < frameCount) { + err = -1; + } else if (validFrames > frameCount) { + validFrames = frameCount; + } + } + if ( (err == 0) && true) { + char * bt; + + bt = NULL; + + err = TestMoreBacktraceFramesToText(frames, validFrames, true, &bt); + if (err == 0) { + fprintf(stderr, "Pre-smash backtrace:\n"); + fprintf(stdout, "%s\n", bt); + } + + free(bt); + + err = 0; + } + + // Now let's use that backtrace to vandalise the stack! + + if (err == 0) { + int i; + char * busErrorAddress; + char ** fp; + + // I don't want to use 0 for the Mac OS X bus error value, because + // it's a little obvious. Instead I use a value that's in the bottom + // page (ie is less than 0x1000) and is easily recognisable. + + busErrorAddress = (char *) (intptr_t) 0xfec; + + // 1. We go down 4 frames on the stack and smash the next + // frame pointer. + + fp = (char **) (intptr_t) frames[4].fp; + fp[0] = busErrorAddress; + + // 2. We go down 2 frames on the stack and smash the + // return address. As its location is architecture dependent, + // we just smash 8 words and hope that we get it (-: + + fp = (char **) (intptr_t) frames[2].fp; + for (i = 0; i < 8; i++) { + fp[i] = busErrorAddress; + } + } + + return err; +} + +extern int TestMoreBacktraceMachThreadStackSmash(char **btPtr) + // See comments in header. +{ + int err; + MoreBTFrame frames[kFrameCount]; + size_t frameCount; + size_t validFrames; + + assert( btPtr != NULL); + assert(*btPtr == NULL); + + // Start a thread that just blocks indefinitely. In the + // process, smash its stack. + + err = 0; + if ( ! gDeadThreadReady ) { + err = StartDeadThread(); + } + assert( (err != 0) || (gDeadThreadReady && (gDeadThreadID != MACH_PORT_NULL)) ); + + // Take a backtrace of that thread and return it. + + if (err == 0) { + frameCount = sizeof(frames) / sizeof(*frames); + err = MoreBacktraceMachThread(mach_task_self(), gDeadThreadID, 0, 0, frames, frameCount, &validFrames); + } + if (err == 0) { + if (validFrames > frameCount) { + validFrames = frameCount; + } + err = TestMoreBacktraceFramesToText(frames, validFrames, true, btPtr); + } + + assert( (err == 0) == (*btPtr != NULL) ); + + return err; +} diff --git a/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MoreBacktraceTestCommon.h b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MoreBacktraceTestCommon.h new file mode 100644 index 0000000000..645b7a855a --- /dev/null +++ b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MoreBacktraceTestCommon.h @@ -0,0 +1,127 @@ +/* + File: MoreBacktraceTestCommon.h + + Contains: Common code for testing backtraces. + + Written by: DTS + + Copyright: Copyright (c) 2006 by Apple Computer, Inc., All Rights Reserved. + + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. + ("Apple") in consideration of your agreement to the following terms, and your + use, installation, modification or redistribution of this Apple software + constitutes acceptance of these terms. If you do not agree with these terms, + please do not use, install, modify or redistribute this Apple software. + + In consideration of your agreement to abide by the following terms, and subject + to these terms, Apple grants you a personal, non-exclusive license, under AppleÕs + copyrights in this original Apple software (the "Apple Software"), to use, + reproduce, modify and redistribute the Apple Software, with or without + modifications, in source and/or binary forms; provided that if you redistribute + the Apple Software in its entirety and without modifications, you must retain + this notice and the following text and disclaimers in all such redistributions of + the Apple Software. Neither the name, trademarks, service marks or logos of + Apple Computer, Inc. may be used to endorse or promote products derived from the + Apple Software without specific prior written permission from Apple. Except as + expressly stated in this notice, no other rights or licenses, express or implied, + are granted by Apple herein, including but not limited to any patent rights that + may be infringed by your derivative works or by other works in which the Apple + Software may be incorporated. + + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED + WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN + COMBINATION WITH YOUR PRODUCTS. + + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION + OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT + (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Change History (most recent first): + +$Log: MoreBacktraceTestCommon.h,v $ +Revision 1.1 2006/01/22 22:47:51 eskimo1 +A new module that abstracts the test code out of the GUI test app so that it can also be used by the command line tool. + + +*/ + +#pragma once + +///////////////////////////////////////////////////////////////// + +// MoreIsBetter Setup + +#include "MoreSetup.h" + +// Mac OS Interfaces + +#include +#include + +// MIB Interfaces + +#include "MoreBacktrace.h" + +///////////////////////////////////////////////////////////////// + +#ifdef __cplusplus +extern "C" { +#endif + +///////////////////////////////////////////////////////////////// + +// This module contains common test code that's shared between the application +// and the command line tool. + +extern int TestMoreBacktraceFramesToText( + const MoreBTFrame frames[], + size_t frameCount, + bool lookupSymbolNames, + char ** btPtr +); + // Converts a backtrace (specified by frames and frameCount) + // to textual form, returning a pointer to the text in *btPtr. + // Each line is separated by a '\n' and the entire string + // is null terminated. The caller is responsible for disposing + // of this result using free. + // + // If lookupSymbolNames is true, + // the textual representation will contain symbols generated + // using the MoreAddrToSym module. Given that this module + // only supports looking up symbols in the current task + // (at least currently), you should only pass true to this + // parameter if the backtrace came from the current task. + // + // On entry, frames must not be NULL. + // On entry, btPtr must not be NULL. + // On entry, *btPtr must be NULL. + // Returns an errno-style error code. + // On success, *btPtr will not be NULL. + // On error, *btPtr will be NULL. + +// The following routines run a variety of different backtrace tests. +// This each return an errno-style error code, and set *btPtr as +// specified by TestMoreBacktraceFramesToText. + +extern int TestMoreBacktraceMachSelf(char **btPtr); + // Backtrace the current thread. + +extern int TestMoreBacktraceMachThread(pid_t pid, char **btPtr); + // Backtrace a random thread in the specified task. + +extern int TestMoreBacktraceMachSelfSignal(bool nonLeaf, char **btPtr); + // Backtrace across a signal handler. If nonLeaf is set, + // this requires user intervention to deliver the signal. + +extern int TestMoreBacktraceMachThreadStackSmash(char **btPtr); + // Backtrace a thread with a smashed stack. + +#ifdef __cplusplus +} +#endif diff --git a/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MoreBacktraceTestTool.c b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MoreBacktraceTestTool.c new file mode 100644 index 0000000000..bb1a411585 --- /dev/null +++ b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/MoreBacktraceTestTool.c @@ -0,0 +1,169 @@ +/* + File: MoreBacktraceTestTool.c + + Contains: Command line tool to test MoreBacktrace. + + Written by: DTS + + Copyright: Copyright (c) 2006 by Apple Computer, Inc., All Rights Reserved. + + Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. + ("Apple") in consideration of your agreement to the following terms, and your + use, installation, modification or redistribution of this Apple software + constitutes acceptance of these terms. If you do not agree with these terms, + please do not use, install, modify or redistribute this Apple software. + + In consideration of your agreement to abide by the following terms, and subject + to these terms, Apple grants you a personal, non-exclusive license, under AppleÕs + copyrights in this original Apple software (the "Apple Software"), to use, + reproduce, modify and redistribute the Apple Software, with or without + modifications, in source and/or binary forms; provided that if you redistribute + the Apple Software in its entirety and without modifications, you must retain + this notice and the following text and disclaimers in all such redistributions of + the Apple Software. Neither the name, trademarks, service marks or logos of + Apple Computer, Inc. may be used to endorse or promote products derived from the + Apple Software without specific prior written permission from Apple. Except as + expressly stated in this notice, no other rights or licenses, express or implied, + are granted by Apple herein, including but not limited to any patent rights that + may be infringed by your derivative works or by other works in which the Apple + Software may be incorporated. + + The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO + WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED + WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR + PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN + COMBINATION WITH YOUR PRODUCTS. + + IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE + GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION + OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT + (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + Change History (most recent first): + +*/ + +///////////////////////////////////////////////////////////////// + +// System interfaces + +#include +#include +#include +#include +#include +#include + +// MIB interfaces + +#include "MoreBacktraceTestCommon.h" + +///////////////////////////////////////////////////////////////// + +static void PrintUsage(const char *argv0) + // Print the program's usage. +{ + const char *command; + + command = strrchr(argv0, '/'); + if (command == NULL) { + command = argv0; + } else { + command += 1; + } + fprintf(stderr, "usage: %s command...\n", command); + fprintf(stderr, " commands: -self\n"); + fprintf(stderr, " commands: -signal\n"); + fprintf(stderr, " commands: -signal-nonleaf\n"); + fprintf(stderr, " commands: -pid \n"); + fprintf(stderr, " commands: -smash\n"); +} + + +int main(int argc, char **argv) +{ + int err; + int retVal; + const char * builtArch; + bool printUsage; + int argIndex; + pid_t pid; + + // Just for convenience's sake, print out the architecture of the + // code we're actually running. In the world of universal binaries, + // Rosseta, and PowerPC 32- and 64-bit, it's often hard to remember + // what's what. + + #if TARGET_CPU_PPC + builtArch = "ppc"; + #elif TARGET_CPU_PPC64 + builtArch = "ppc64"; + #elif TARGET_CPU_X86 + builtArch = "i386"; + #else + #error What are you building? + #endif + fprintf(stderr, "Built for %s.\n", builtArch); + + // Process command line arguments. + + retVal = EXIT_SUCCESS; + printUsage = false; + if (argc < 2) { + printUsage = true; + } else { + argIndex = 1; + while (argIndex < argc) { + char * bt; + + err = 0; + bt = NULL; + if ( strcmp(argv[argIndex], "-self") == 0 ) { + argIndex += 1; + err = TestMoreBacktraceMachSelf(&bt); + } else if ( strcmp(argv[argIndex], "-pid") == 0 ) { + argIndex += 1; + if (argIndex < argc) { + pid = (pid_t) atol(argv[argIndex]); + argIndex += 1; + + err = TestMoreBacktraceMachThread(pid, &bt); + } else { + printUsage = true; + } + } else if ( strcmp(argv[argIndex], "-signal") == 0 ) { + argIndex += 1; + err = TestMoreBacktraceMachSelfSignal(false, &bt); + } else if ( strcmp(argv[argIndex], "-signal-nonleaf") == 0 ) { + argIndex += 1; + err = TestMoreBacktraceMachSelfSignal(true, &bt); + } else if ( strcmp(argv[argIndex], "-smash") == 0 ) { + argIndex += 1; + err = TestMoreBacktraceMachThreadStackSmash(&bt); + if (err == 0) { + fprintf(stderr, "Post-smash backtrace:\n"); + } + } else { + argIndex = argc; + printUsage = true; + } + + if ( (err == 0) && (bt != NULL) ) { + fprintf(stdout, "%s\n", bt); + } else { + fprintf(stderr, "Failed to backtrace (error %d).\n", err); + } + free(bt); + } + } + + if (printUsage) { + PrintUsage(argv[0]); + retVal = EXIT_FAILURE; + } + + return retVal; +} diff --git a/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/main.nib/classes.nib b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/main.nib/classes.nib new file mode 100644 index 0000000000..ea58db1189 --- /dev/null +++ b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/main.nib/classes.nib @@ -0,0 +1,4 @@ +{ +IBClasses = (); +IBVersion = 1; +} diff --git a/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/main.nib/info.nib b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/main.nib/info.nib new file mode 100644 index 0000000000..10cf223a4c --- /dev/null +++ b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/main.nib/info.nib @@ -0,0 +1,19 @@ + + + + + IBDocumentLocation + 69 10 356 240 0 0 1280 832 + IBEditorPositions + + 29 + 69 252 216 44 0 0 1280 1002 + + IBFramework Version + 443.0 + IBSystem Version + 8G32 + targetFramework + IBCarbonFramework + + diff --git a/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/main.nib/objects.xib b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/main.nib/objects.xib new file mode 100644 index 0000000000..7cb232eab4 --- /dev/null +++ b/opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktraceTest/main.nib/objects.xib @@ -0,0 +1,101 @@ + + + IBCarbonFramework + + NSApplication + + + + main + + + MoreBacktraceTest + + MoreBacktraceTest + + + About MoreBacktraceTest + 0 + abou + + + _NSAppleMenu + + + + Window + + Window + + + Zoom Window + zoom + + + TRUE + Minimize Window + m + mini + + + TRUE + Minimize All Windows + m + 1572864 + mina + + + TRUE + + + TRUE + Bring All to Front + bfrt + + + TRUE + Arrange in Front + 1572864 + frnt + + + _NSWindowsMenu + + + + _NSMainMenu + + + + + + + + + + + + + + + + + + + + + + + + + + + + + Files Owner + + MenuBar + + + 246 + diff --git a/opal/mca/backtrace/darwin/MoreBacktrace/MoreSetup.h b/opal/mca/backtrace/darwin/MoreBacktrace/MoreSetup.h new file mode 100644 index 0000000000..9527272a59 --- /dev/null +++ b/opal/mca/backtrace/darwin/MoreBacktrace/MoreSetup.h @@ -0,0 +1 @@ +/* File: MoreSetup.h Contains: Sets up conditions etc for MoreIsBetter. Written by: Pete Gontier Copyright: Copyright (c) 1998-2001 by Apple Computer, Inc., All Rights Reserved. Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Computer, Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under AppleÕs copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Computer, Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Change History (most recent first): $Log: MoreSetup.h,v $ Revision 1.14 2002/11/08 22:43:02 eskimo1 A bunch of key changes. We no longer include in the Mach-O builds, which means that individual MoreIsBetter modules can decide what frameworks they're dependent on. Also changed MoreIsBetter to use the standard C assert mechanism. Revision 1.13 2001/11/07 15:55:15 eskimo1 Tidy up headers, add CVS logs, update copyright. <12> 21/9/01 Quinn Fix CF framework includes workaround. <11> 21/9/01 Quinn Changes for CWPro7 Mach-O build. <10> 15/2/01 Quinn MoreIsBetter now requires UI 3.4 (pre-release) or later. <9> 8/2/01 Quinn Modern versions of MIB require UI 3.3.2 or higher. <8> 22/11/00 Quinn Switch to "MacErrors.h". <7> 22/4/99 Quinn Add a check for the Universal Interfaces version. MoreIsBetter requires Universal Interfaces 3.2 or higher (because many of its component parts do). <6> 2/11/99 PCG add comments because Andy rightfully pointed out my original attempts sucked; also, remove some excessive TARGET_CARBON gymnastics <5> 1/22/99 PCG TARGET_CARBON <4> 11/11/98 PCG fix header <3> 11/10/98 PCG separate change histories <2> 10/11/98 Quinn Convert "MorePrefix.h" to "MoreSetup.h". <1> 10/11/98 Quinn Changed name from "MorePrefix.h" to "MoreSetup.h". Start of "MorePrefix.h" change history (most recent first): <3> 5/11/98 Quinn Use MoreAssertQ instead of MoreAssert. <2> 7/24/98 PCG rid of triplet #includes <2> 6/23/98 PCG add copyright disclaimer stuff <1> 6/23/98 PCG initial checkin */ #pragma once // // We never want to use old names or locations. // Since these settings must be consistent all the way through // a compilation unit, and since we don't want to silently // change them out from under a developer who uses a prefix // file (C/C++ panel of Target Settings), we simply complain // if they are already set in a way we don't like. // #ifndef OLDROUTINELOCATIONS #define OLDROUTINELOCATIONS 0 #elif OLDROUTINELOCATIONS #error OLDROUTINELOCATIONS must be FALSE when compiling MoreIsBetter. #endif #ifndef OLDROUTINENAMES #define OLDROUTINENAMES 0 #elif OLDROUTINENAMES #error OLDROUTINENAMES must be FALSE when compiling MoreIsBetter. #endif // // The next statement sets up the various TARGET_xxx // variables needed later in this file. // #include // // "TargetConditionals.h" on Mac OS X doesn't define // TARGET_API_MAC_CARBON, which is kinda annoying. So, // if we're building for Mach-O and it hasn't been set, // set it. All Mach-O builds are inherently Carbon builds. // // Note that we *have* to set TARGET_API_MAC_CARBON because // MoreIsBetter code tests it. However, we also want to set // the other values because otherwise GCC won't use its // precompiled header. I thought about fixing this by // including via , // but the whole goal of using was to // allow MoreIsBetter projects to have no dependencies on // frameworks beyond System.framework. // #if TARGET_RT_MAC_MACHO #define TARGET_API_MAC_OS8 0 #define TARGET_API_MAC_CARBON 1 #define TARGET_API_MAC_OSX 1 #endif // // We need a master conditional to determine whether to use // framework notation to reference include files. There is // no good way to determine whether the source tree // is using framework includes or not, so we make a guess and // say that Mach-O implies framework includes. However, // if you're building CFM with framework includes (which is // possible, although somewhat tricky), you'll have to // override this. // #if !defined(MORE_FRAMEWORK_INCLUDES) #if TARGET_RT_MAC_MACHO #define MORE_FRAMEWORK_INCLUDES 1 #else #define MORE_FRAMEWORK_INCLUDES 0 #endif #endif // // The following works around a problem in // in Mac OS X. CF is assuming that the CW Mach-O compiler // would not use framework includes, which is not the case for the // CWPro7 and later compilers. We only do this for the CW build // because otherwise the presence of the define prevents Project Builder // from using Carbon's precompiled header. // #if MORE_FRAMEWORK_INCLUDES #if defined(__MWERKS__) #if !defined(__CF_USE_FRAMEWORK_INCLUDES__) #define __CF_USE_FRAMEWORK_INCLUDES__ 1 #endif #endif #endif // // Previouly we would bring in at this point. // However, that's somewhat counter to the idea behind flat // includes, so I've eliminated it. // // // Now that we've included a Mac OS interface file, // we know that the Universal Interfaces environment // is set up. MoreIsBetter requires Universal Interfaces // 3.4 or higher. Check for it. Of course, "TargetConditionals.h" // on Mac OS X doesn't set UNIVERSAL_INTERFACES_VERSION, so // we only check this if we're not using framework includes. // #if !MORE_FRAMEWORK_INCLUDES #if !defined(UNIVERSAL_INTERFACES_VERSION) || UNIVERSAL_INTERFACES_VERSION < 0x0341 #error MoreIsBetter requires Universal Interfaces 3.4.1 or higher. #endif #endif // // We usually want assertions and other debugging code // turned on, but you can turn it all off if you like // by setting MORE_DEBUG to 0. Also, now that we use // the standard C assertion mechanism, we default to // have MORE_DEBUG off if NDEBUG is set. // #if !defined(MORE_DEBUG) #if defined(NDEBUG) #define MORE_DEBUG 0 #else #define MORE_DEBUG 1 #endif #endif // // We now use standard C assertions throughout MoreIsBetter. // Previously we would declare two custom assertion macros, // MoreAssert and MoreAssertQ. // // Our assertion macros compile down to nothing if // MORE_DEBUG is not true. MoreAssert produces a // value indicating whether the assertion succeeded // or failed. MoreAssertQ is Quinn's flavor of // MoreAssert which does not produce a value. // #include // // Chances are that if you're building CFM then you'd much // rather have assert triggered DebugStr that abort. The // following redefines assert that way. We don't do this // for Mach-O because you might be building a Mach-O tool that // doesn't have access to DebugStr. // #if TARGET_RT_MAC_CFM && !defined(NDEBUG) #undef assert #define assert(x) ((x) ? ((void) 0) : DebugStr("\pMoreIsBetter assertion failure: " #x)) #endif // // Finally, we define MoreAssertPCG, to accomodate some // older MoreIsBetter code that tests the result of its // assertions. This doesn't fit in with the standard C // assert model, so I've deprecated the approach. However // there's a bunch of existing code that works that way // and reworking it would be likely to generate errors. // Fortunately, all of the old code that uses this is // Carbon based, so I don't have to worry about not having // access to DebugStr. // #if MORE_DEBUG #define MoreAssertPCG(x) \ ((x) ? true : (DebugStr ("\pMoreIsBetter assertion failure: " #x), false)) #else #define MoreAssertPCG(x) (true) #endif \ No newline at end of file diff --git a/opal/mca/backtrace/darwin/backtrace_darwin.c b/opal/mca/backtrace/darwin/backtrace_darwin.c new file mode 100644 index 0000000000..e1b30f189a --- /dev/null +++ b/opal/mca/backtrace/darwin/backtrace_darwin.c @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana + * University Research and Technology + * Corporation. All rights reserved. + * Copyright (c) 2004-2005 The University of Tennessee and The University + * of Tennessee Research Foundation. All rights + * reserved. + * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, + * University of Stuttgart. All rights reserved. + * Copyright (c) 2004-2006 The Regents of the University of California. + * All rights reserved. + * $COPYRIGHT$ + * + * Additional copyrights may follow + * + * $HEADER$ + */ + +#include "opal_config.h" + +#include + +#include "opal/constants.h" +#include "opal/mca/backtrace/backtrace.h" +#include "opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreBacktrace.h" +#include "opal/mca/backtrace/darwin/MoreBacktrace/MoreDebugging/MoreAddrToSym.h" + +#define SIGNAL_SKIPFRAME 4 +#define ALWAYS_SKIPFRAME 2 +#define kFrameCount 32 + +void +opal_backtrace_print(FILE *file) +{ + int ret; + unsigned long frameCount; + unsigned long validFrames; + MoreBTFrame frames[kFrameCount]; + unsigned long frameIndex, skipframe = 0; + MoreAToSSymInfo symbol; + MoreAToSAddr address; + + frameCount = sizeof(frames) / sizeof(*frames); + ret = MoreBacktraceMachSelf(0, 0, frames, frameCount, &validFrames); + if (0 != ret) { + fprintf(file, "Stack corrupted and not printable\n"); + fflush(stderr); + return; + } + + if (validFrames > frameCount) { + validFrames = frameCount; + } + + if ((validFrames >= SIGNAL_SKIPFRAME) && + (frames[SIGNAL_SKIPFRAME-1].flags & kMoreBTSignalHandlerMask)) { + skipframe = SIGNAL_SKIPFRAME; + } else if (validFrames >= ALWAYS_SKIPFRAME) { + skipframe = ALWAYS_SKIPFRAME; + } + + for (frameIndex = skipframe; frameIndex < validFrames; frameIndex++) { + fprintf(stderr, "[%2ld] ", frameIndex - skipframe + 1); + + if (frames[frameIndex].flags & kMoreBTPCBadMask) { + address = 0; + } else { + address = (MoreAToSAddr) frames[frameIndex].pc; + } + + symbol.symbolName = NULL; + symbol.symbolType = kMoreAToSNoSymbol; + symbol.symbolOffset = 0; + + ret = MoreAToSCopySymbolNamesUsingDyld(1, &address, &symbol); + + if (symbol.symbolName) { + if (symbol.symbolName[0]) { + fprintf(file, "(%s + 0x%llx) ", + symbol.symbolName, symbol.symbolOffset); + free( (void *) symbol.symbolName); + } + } + + fprintf(file, "[0x%08llx, 0x%08llx] ", + frames[frameIndex].fp, + frames[frameIndex].pc); + + if (frames[frameIndex].flags) { + fprintf(file, "(%c%c%c)", + (frames[frameIndex].flags & kMoreBTFrameBadMask) ? 'F' : '-', + (frames[frameIndex].flags & kMoreBTPCBadMask) ? 'P' : '-', + (frames[frameIndex].flags & kMoreBTSignalHandlerMask) ? 'S' : '-'); + } + + fprintf(file, "\n"); + } +} + + +int +opal_backtrace_buffer(char ***message_out, int *len_out) +{ + return OPAL_SUCCESS; +} diff --git a/opal/mca/backtrace/darwin/backtrace_darwin_component.c b/opal/mca/backtrace/darwin/backtrace_darwin_component.c new file mode 100644 index 0000000000..211648df4c --- /dev/null +++ b/opal/mca/backtrace/darwin/backtrace_darwin_component.c @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana + * University Research and Technology + * Corporation. All rights reserved. + * Copyright (c) 2004-2005 The University of Tennessee and The University + * of Tennessee Research Foundation. All rights + * reserved. + * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, + * University of Stuttgart. All rights reserved. + * Copyright (c) 2004-2006 The Regents of the University of California. + * All rights reserved. + * $COPYRIGHT$ + * + * Additional copyrights may follow + * + * $HEADER$ + */ + +#include "opal_config.h" + +#include "opal/mca/backtrace/backtrace.h" + +const opal_backtrace_base_component_1_0_0_t mca_backtrace_darwin_component = { + /* First, the mca_component_t struct containing meta information + about the component itself */ + { + /* Indicate that we are a backtrace v1.0.0 component (which also + implies a specific MCA version) */ + OPAL_BACKTRACE_BASE_VERSION_1_0_0, + + /* Component name and version */ + "darwin", + OPAL_MAJOR_VERSION, + OPAL_MINOR_VERSION, + OPAL_RELEASE_VERSION, + + /* Component open and close functions */ + NULL, + NULL + }, + + /* Next the MCA v1.0.0 component meta data */ + { + /* Whether the component is checkpointable or not */ + true + }, +}; diff --git a/opal/mca/backtrace/darwin/configure.m4 b/opal/mca/backtrace/darwin/configure.m4 new file mode 100644 index 0000000000..2662c2f0c8 --- /dev/null +++ b/opal/mca/backtrace/darwin/configure.m4 @@ -0,0 +1,43 @@ +# -*- shell-script -*- +# +# Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana +# University Research and Technology +# Corporation. All rights reserved. +# Copyright (c) 2004-2005 The University of Tennessee and The University +# of Tennessee Research Foundation. All rights +# reserved. +# Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, +# University of Stuttgart. All rights reserved. +# Copyright (c) 2004-2005 The Regents of the University of California. +# All rights reserved. +# $COPYRIGHT$ +# +# Additional copyrights may follow +# +# $HEADER$ +# + +AC_DEFUN([MCA_backtrace_darwin_COMPILE_MODE], [ + AC_MSG_CHECKING([for MCA component $2:$3 compile mode]) + $4="static" + AC_MSG_RESULT([$$4]) +]) + + +# MCA_backtrace_darwin_CONFIG(action-if-can-compile, +# [action-if-cant-compile]) +# ------------------------------------------------ +AC_DEFUN([MCA_backtrace_darwin_CONFIG],[ + AC_CHECK_FUNCS([vm_read_overwrite], + [backtrace_darwin_happy="yes"], + [backtrace_darwin_happy="no"]) + + if test "$backtrace_darwin_happy" = "yes" ; then + if test "$OMPI_C_GCC_INLINE_ASSEMBLY" = "0" ; then + backtrace_darwin_happy="no" + fi + fi + + AS_IF([test "$backtrace_darwin_happy" = "yes"], + [$1], [$2]) +]) diff --git a/opal/mca/backtrace/darwin/configure.params b/opal/mca/backtrace/darwin/configure.params new file mode 100644 index 0000000000..79ed02a8e1 --- /dev/null +++ b/opal/mca/backtrace/darwin/configure.params @@ -0,0 +1,15 @@ +# -*- shell-script -*- +# +# Copyright (c) 2004-2006 The Regents of the University of California. +# All rights reserved. +# $COPYRIGHT$ +# +# Additional copyrights may follow +# +# $HEADER$ +# + +# Specific to this module + +PARAM_CONFIG_PRIORITY=30 +PARAM_CONFIG_FILES="Makefile" diff --git a/opal/mca/backtrace/execinfo/Makefile.am b/opal/mca/backtrace/execinfo/Makefile.am new file mode 100644 index 0000000000..0fae37c363 --- /dev/null +++ b/opal/mca/backtrace/execinfo/Makefile.am @@ -0,0 +1,23 @@ +# +# Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana +# University Research and Technology +# Corporation. All rights reserved. +# Copyright (c) 2004-2005 The University of Tennessee and The University +# of Tennessee Research Foundation. All rights +# reserved. +# Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, +# University of Stuttgart. All rights reserved. +# Copyright (c) 2004-2005 The Regents of the University of California. +# All rights reserved. +# $COPYRIGHT$ +# +# Additional copyrights may follow +# +# $HEADER$ +# + +noinst_LTLIBRARIES = libmca_backtrace_execinfo.la + +libmca_backtrace_execinfo_la_SOURCES = \ + backtrace_execinfo.c \ + backtrace_execinfo_component.c diff --git a/opal/mca/backtrace/execinfo/backtrace_execinfo.c b/opal/mca/backtrace/execinfo/backtrace_execinfo.c new file mode 100644 index 0000000000..faf41f97c6 --- /dev/null +++ b/opal/mca/backtrace/execinfo/backtrace_execinfo.c @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana + * University Research and Technology + * Corporation. All rights reserved. + * Copyright (c) 2004-2005 The University of Tennessee and The University + * of Tennessee Research Foundation. All rights + * reserved. + * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, + * University of Stuttgart. All rights reserved. + * Copyright (c) 2004-2006 The Regents of the University of California. + * All rights reserved. + * $COPYRIGHT$ + * + * Additional copyrights may follow + * + * $HEADER$ + */ + +#include "opal_config.h" + +#include +#include + +#include "opal/constants.h" +#include "opal/mca/backtrace/backtrace.h" + +void +opal_backtrace_print(FILE *file) +{ + int i; + int trace_size; + void * trace[32]; + char ** messages = (char **)NULL; + + trace_size = backtrace (trace, 32); + messages = backtrace_symbols (trace, trace_size); + + for (i = 0; i < trace_size; i++) { + fprintf(file, "[%d] func:%s\n", i, messages[i]); + fflush(file); + } + + free(messages); +} + + +int +opal_backtrace_buffer(char ***message_out, int *len_out) +{ + int trace_size; + void * trace[32]; + char ** funcs = (char **)NULL; + + trace_size = backtrace (trace, 32); + funcs = backtrace_symbols (trace, trace_size); + + *message_out = funcs; + *len_out = trace_size; + + return OPAL_SUCCESS; +} diff --git a/opal/mca/backtrace/execinfo/backtrace_execinfo_component.c b/opal/mca/backtrace/execinfo/backtrace_execinfo_component.c new file mode 100644 index 0000000000..3d0b942d4f --- /dev/null +++ b/opal/mca/backtrace/execinfo/backtrace_execinfo_component.c @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana + * University Research and Technology + * Corporation. All rights reserved. + * Copyright (c) 2004-2005 The University of Tennessee and The University + * of Tennessee Research Foundation. All rights + * reserved. + * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, + * University of Stuttgart. All rights reserved. + * Copyright (c) 2004-2006 The Regents of the University of California. + * All rights reserved. + * $COPYRIGHT$ + * + * Additional copyrights may follow + * + * $HEADER$ + */ + +#include "opal_config.h" + +#include "opal/mca/backtrace/backtrace.h" + +const opal_backtrace_base_component_1_0_0_t mca_backtrace_execinfo_component = { + /* First, the mca_component_t struct containing meta information + about the component itself */ + { + /* Indicate that we are a backtrace v1.0.0 component (which also + implies a specific MCA version) */ + OPAL_BACKTRACE_BASE_VERSION_1_0_0, + + /* Component name and version */ + "execinfo", + OPAL_MAJOR_VERSION, + OPAL_MINOR_VERSION, + OPAL_RELEASE_VERSION, + + /* Component open and close functions */ + NULL, + NULL + }, + + /* Next the MCA v1.0.0 component meta data */ + { + /* Whether the component is checkpointable or not */ + true + }, +}; diff --git a/opal/mca/backtrace/execinfo/configure.m4 b/opal/mca/backtrace/execinfo/configure.m4 new file mode 100644 index 0000000000..6b4a41b578 --- /dev/null +++ b/opal/mca/backtrace/execinfo/configure.m4 @@ -0,0 +1,39 @@ +# -*- shell-script -*- +# +# Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana +# University Research and Technology +# Corporation. All rights reserved. +# Copyright (c) 2004-2005 The University of Tennessee and The University +# of Tennessee Research Foundation. All rights +# reserved. +# Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, +# University of Stuttgart. All rights reserved. +# Copyright (c) 2004-2005 The Regents of the University of California. +# All rights reserved. +# $COPYRIGHT$ +# +# Additional copyrights may follow +# +# $HEADER$ +# + +AC_DEFUN([MCA_backtrace_execinfo_COMPILE_MODE], [ + AC_MSG_CHECKING([for MCA component $2:$3 compile mode]) + $4="static" + AC_MSG_RESULT([$$4]) +]) + + +# MCA_backtrace_execinfo_CONFIG(action-if-can-compile, +# [action-if-cant-compile]) +# ------------------------------------------------ +AC_DEFUN([MCA_backtrace_execinfo_CONFIG],[ + AC_CHECK_HEADERS([execinfo.h]) + # FreeBSD has backtrace in -lexecinfo, usually in libc + OMPI_CHECK_FUNC_LIB([backtrace], [execinfo], + [backtrace_execinfo_happy="yes"], + [backtrace_execinfo_happy="no"]) + + AS_IF([test "$backtrace_execinfo_happy" = "yes"], + [$1], [$2]) +]) diff --git a/opal/mca/backtrace/execinfo/configure.params b/opal/mca/backtrace/execinfo/configure.params new file mode 100644 index 0000000000..79ed02a8e1 --- /dev/null +++ b/opal/mca/backtrace/execinfo/configure.params @@ -0,0 +1,15 @@ +# -*- shell-script -*- +# +# Copyright (c) 2004-2006 The Regents of the University of California. +# All rights reserved. +# $COPYRIGHT$ +# +# Additional copyrights may follow +# +# $HEADER$ +# + +# Specific to this module + +PARAM_CONFIG_PRIORITY=30 +PARAM_CONFIG_FILES="Makefile" diff --git a/opal/mca/backtrace/none/Makefile.am b/opal/mca/backtrace/none/Makefile.am new file mode 100644 index 0000000000..5b899bee9d --- /dev/null +++ b/opal/mca/backtrace/none/Makefile.am @@ -0,0 +1,23 @@ +# +# Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana +# University Research and Technology +# Corporation. All rights reserved. +# Copyright (c) 2004-2005 The University of Tennessee and The University +# of Tennessee Research Foundation. All rights +# reserved. +# Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, +# University of Stuttgart. All rights reserved. +# Copyright (c) 2004-2005 The Regents of the University of California. +# All rights reserved. +# $COPYRIGHT$ +# +# Additional copyrights may follow +# +# $HEADER$ +# + +noinst_LTLIBRARIES = libmca_backtrace_none.la + +libmca_backtrace_none_la_SOURCES = \ + backtrace_none.c \ + backtrace_none_component.c diff --git a/opal/mca/backtrace/none/backtrace_none.c b/opal/mca/backtrace/none/backtrace_none.c new file mode 100644 index 0000000000..2f62519570 --- /dev/null +++ b/opal/mca/backtrace/none/backtrace_none.c @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana + * University Research and Technology + * Corporation. All rights reserved. + * Copyright (c) 2004-2005 The University of Tennessee and The University + * of Tennessee Research Foundation. All rights + * reserved. + * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, + * University of Stuttgart. All rights reserved. + * Copyright (c) 2004-2006 The Regents of the University of California. + * All rights reserved. + * $COPYRIGHT$ + * + * Additional copyrights may follow + * + * $HEADER$ + */ + + +void +opal_backtrace_print(FILE *file) +{ +} + + +int +opal_backtrace_buffer(char ***message_out, int *len_out); +{ + *messages_out = NULL; + *len_out = 0; + + return OMPI_ERR_NOT_IMPLEMENTED +} diff --git a/opal/mca/backtrace/none/backtrace_none_component.c b/opal/mca/backtrace/none/backtrace_none_component.c new file mode 100644 index 0000000000..d5cad610e6 --- /dev/null +++ b/opal/mca/backtrace/none/backtrace_none_component.c @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana + * University Research and Technology + * Corporation. All rights reserved. + * Copyright (c) 2004-2005 The University of Tennessee and The University + * of Tennessee Research Foundation. All rights + * reserved. + * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, + * University of Stuttgart. All rights reserved. + * Copyright (c) 2004-2006 The Regents of the University of California. + * All rights reserved. + * $COPYRIGHT$ + * + * Additional copyrights may follow + * + * $HEADER$ + */ + +#include "opal_config.h" + +#include "opal/mca/backtrace/backtrace.h" + +const opal_backtrace_base_component_1_0_0_t mca_backtrace_none_component = { + /* First, the mca_component_t struct containing meta information + about the component itself */ + { + /* Indicate that we are a backtrace v1.0.0 component (which also + implies a specific MCA version) */ + OPAL_BACKTRACE_BASE_VERSION_1_0_0, + + /* Component name and version */ + "none", + OPAL_MAJOR_VERSION, + OPAL_MINOR_VERSION, + OPAL_RELEASE_VERSION, + + /* Component open and close functions */ + NULL, + NULL + }, + + /* Next the MCA v1.0.0 component meta data */ + { + /* Whether the component is checkpointable or not */ + true + }, +}; diff --git a/opal/mca/backtrace/none/configure.m4 b/opal/mca/backtrace/none/configure.m4 new file mode 100644 index 0000000000..cec637d39f --- /dev/null +++ b/opal/mca/backtrace/none/configure.m4 @@ -0,0 +1,30 @@ +# -*- shell-script -*- +# +# Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana +# University Research and Technology +# Corporation. All rights reserved. +# Copyright (c) 2004-2005 The University of Tennessee and The University +# of Tennessee Research Foundation. All rights +# reserved. +# Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, +# University of Stuttgart. All rights reserved. +# Copyright (c) 2004-2005 The Regents of the University of California. +# All rights reserved. +# $COPYRIGHT$ +# +# Additional copyrights may follow +# +# $HEADER$ +# + +AC_DEFUN([MCA_backtrace_none_COMPILE_MODE], [ + AC_MSG_CHECKING([for MCA component $2:$3 compile mode]) + $4="static" + AC_MSG_RESULT([$$4]) +]) + + +# MCA_backtrace_none_CONFIG(action-if-can-compile, +# [action-if-cant-compile]) +# ------------------------------------------------ +AC_DEFUN([MCA_backtrace_none_CONFIG],[$1]) diff --git a/opal/mca/backtrace/none/configure.params b/opal/mca/backtrace/none/configure.params new file mode 100644 index 0000000000..4f3b69a4d0 --- /dev/null +++ b/opal/mca/backtrace/none/configure.params @@ -0,0 +1,15 @@ +# -*- shell-script -*- +# +# Copyright (c) 2004-2006 The Regents of the University of California. +# All rights reserved. +# $COPYRIGHT$ +# +# Additional copyrights may follow +# +# $HEADER$ +# + +# Specific to this module + +PARAM_CONFIG_PRIORITY=0 +PARAM_CONFIG_FILES="Makefile" diff --git a/opal/mca/backtrace/printstack/Makefile.am b/opal/mca/backtrace/printstack/Makefile.am new file mode 100644 index 0000000000..0db500da44 --- /dev/null +++ b/opal/mca/backtrace/printstack/Makefile.am @@ -0,0 +1,23 @@ +# +# Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana +# University Research and Technology +# Corporation. All rights reserved. +# Copyright (c) 2004-2005 The University of Tennessee and The University +# of Tennessee Research Foundation. All rights +# reserved. +# Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, +# University of Stuttgart. All rights reserved. +# Copyright (c) 2004-2005 The Regents of the University of California. +# All rights reserved. +# $COPYRIGHT$ +# +# Additional copyrights may follow +# +# $HEADER$ +# + +noinst_LTLIBRARIES = libmca_backtrace_printstack.la + +libmca_backtrace_printstack_la_SOURCES = \ + backtrace_printstack.c \ + backtrace_printstack_component.c diff --git a/opal/mca/backtrace/printstack/backtrace_printstack.c b/opal/mca/backtrace/printstack/backtrace_printstack.c new file mode 100644 index 0000000000..af31ff6e27 --- /dev/null +++ b/opal/mca/backtrace/printstack/backtrace_printstack.c @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana + * University Research and Technology + * Corporation. All rights reserved. + * Copyright (c) 2004-2005 The University of Tennessee and The University + * of Tennessee Research Foundation. All rights + * reserved. + * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, + * University of Stuttgart. All rights reserved. + * Copyright (c) 2004-2006 The Regents of the University of California. + * All rights reserved. + * $COPYRIGHT$ + * + * Additional copyrights may follow + * + * $HEADER$ + */ + + +void +opal_backtrace_print(FILE *file) +{ + printstack(fileno(file)); +} + + +int +opal_backtrace_buffer(char ***message_out, int *len_out); +{ + *messages_out = NULL; + *len_out = 0; + + /* BWB - I think we can implement this in a similar way that + printstack is implemented. I just don't have time right + now. */ + + return OMPI_ERR_NOT_IMPLEMENTED +} diff --git a/opal/mca/backtrace/printstack/backtrace_printstack_component.c b/opal/mca/backtrace/printstack/backtrace_printstack_component.c new file mode 100644 index 0000000000..f21b6e0784 --- /dev/null +++ b/opal/mca/backtrace/printstack/backtrace_printstack_component.c @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana + * University Research and Technology + * Corporation. All rights reserved. + * Copyright (c) 2004-2005 The University of Tennessee and The University + * of Tennessee Research Foundation. All rights + * reserved. + * Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, + * University of Stuttgart. All rights reserved. + * Copyright (c) 2004-2006 The Regents of the University of California. + * All rights reserved. + * $COPYRIGHT$ + * + * Additional copyrights may follow + * + * $HEADER$ + */ + +#include "opal_config.h" + +#include "opal/mca/backtrace/backtrace.h" + +const opal_backtrace_base_component_1_0_0_t mca_backtrace_printstack_component = { + /* First, the mca_component_t struct containing meta information + about the component itself */ + { + /* Indicate that we are a backtrace v1.0.0 component (which also + implies a specific MCA version) */ + OPAL_BACKTRACE_BASE_VERSION_1_0_0, + + /* Component name and version */ + "printstack", + OPAL_MAJOR_VERSION, + OPAL_MINOR_VERSION, + OPAL_RELEASE_VERSION, + + /* Component open and close functions */ + NULL, + NULL + }, + + /* Next the MCA v1.0.0 component meta data */ + { + /* Whether the component is checkpointable or not */ + true + }, +}; diff --git a/opal/mca/backtrace/printstack/configure.m4 b/opal/mca/backtrace/printstack/configure.m4 new file mode 100644 index 0000000000..39bd6e5bc2 --- /dev/null +++ b/opal/mca/backtrace/printstack/configure.m4 @@ -0,0 +1,39 @@ +# -*- shell-script -*- +# +# Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana +# University Research and Technology +# Corporation. All rights reserved. +# Copyright (c) 2004-2005 The University of Tennessee and The University +# of Tennessee Research Foundation. All rights +# reserved. +# Copyright (c) 2004-2005 High Performance Computing Center Stuttgart, +# University of Stuttgart. All rights reserved. +# Copyright (c) 2004-2005 The Regents of the University of California. +# All rights reserved. +# $COPYRIGHT$ +# +# Additional copyrights may follow +# +# $HEADER$ +# + +AC_DEFUN([MCA_backtrace_printstack_COMPILE_MODE], [ + AC_MSG_CHECKING([for MCA component $2:$3 compile mode]) + $4="static" + AC_MSG_RESULT([$$4]) +]) + + +# MCA_backtrace_printstack_CONFIG(action-if-can-compile, +# [action-if-cant-compile]) +# ------------------------------------------------ +AC_DEFUN([MCA_backtrace_printstack_CONFIG],[ + AC_CHECK_HEADERS([ucontext.h]) + # FreeBSD has backtrace in -lexecinfo, usually in libc + AC_CHECK_FUNCS([printstack], + [backtrace_printstack_happy="yes"], + [backtrace_printstack_happy="no"]) + + AS_IF([test "$backtrace_printstack_happy" = "yes"], + [$1], [$2]) +]) diff --git a/opal/mca/backtrace/printstack/configure.params b/opal/mca/backtrace/printstack/configure.params new file mode 100644 index 0000000000..79ed02a8e1 --- /dev/null +++ b/opal/mca/backtrace/printstack/configure.params @@ -0,0 +1,15 @@ +# -*- shell-script -*- +# +# Copyright (c) 2004-2006 The Regents of the University of California. +# All rights reserved. +# $COPYRIGHT$ +# +# Additional copyrights may follow +# +# $HEADER$ +# + +# Specific to this module + +PARAM_CONFIG_PRIORITY=30 +PARAM_CONFIG_FILES="Makefile" diff --git a/opal/util/stacktrace.c b/opal/util/stacktrace.c index 915e240316..993ae108f7 100644 --- a/opal/util/stacktrace.c +++ b/opal/util/stacktrace.c @@ -24,14 +24,6 @@ #include #endif -#ifdef HAVE_EXECINFO_H -#include -#endif - -#ifdef HAVE_UCONTEXT_H -#include -#endif - #ifdef HAVE_STRING_H #include #endif @@ -42,6 +34,7 @@ #include "opal/util/stacktrace.h" #include "opal/mca/base/mca_base_param.h" +#include "opal/mca/backtrace/backtrace.h" #include "opal/constants.h" #ifndef _NSIG @@ -67,12 +60,6 @@ #if OMPI_WANT_PRETTY_PRINT_STACKTRACE && ! defined(__WINDOWS__) static void opal_show_stackframe (int signo, siginfo_t * info, void * p) { -#ifdef HAVE_BACKTRACE - int i; - int trace_size; - void * trace[32]; - char ** messages = (char **)NULL; -#endif char print_buffer[1024]; char * tmp = print_buffer; int size = sizeof (print_buffer); @@ -295,17 +282,7 @@ static void opal_show_stackframe (int signo, siginfo_t * info, void * p) write(fileno(stderr), print_buffer, sizeof(print_buffer)-size); fflush(stderr); -#ifdef HAVE_BACKTRACE - trace_size = backtrace (trace, 32); - messages = backtrace_symbols (trace, trace_size); - - for (i = 0; i < trace_size; i++) { - fprintf(stderr, "[%d] func:%s\n", i, messages[i]); - fflush(stderr); - } -#elif defined(HAVE_PRINTSTACK) - printstack(fileno(stderr)); -#endif + opal_backtrace_print(stderr); write(fileno(stderr), eof_msg, sizeof(eof_msg)); fflush(stderr);