├── COPYING ├── Makefile ├── README ├── VERSION ├── changelog ├── man1 └── pstack.1 └── pstack.c /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc. 5 | 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Library General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 19yy 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License 307 | along with this program; if not, write to the Free Software 308 | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 309 | 310 | 311 | Also add information on how to contact you by electronic and paper mail. 312 | 313 | If the program is interactive, make it output a short notice like this 314 | when it starts in an interactive mode: 315 | 316 | Gnomovision version 69, Copyright (C) 19yy name of author 317 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 318 | This is free software, and you are welcome to redistribute it 319 | under certain conditions; type `show c' for details. 320 | 321 | The hypothetical commands `show w' and `show c' should show the appropriate 322 | parts of the General Public License. Of course, the commands you use may 323 | be called something other than `show w' and `show c'; they could even be 324 | mouse-clicks or menu items--whatever suits your program. 325 | 326 | You should also get your employer (if you work as a programmer) or your 327 | school, if any, to sign a "copyright disclaimer" for the program, if 328 | necessary. Here is a sample; alter the names: 329 | 330 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 331 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 332 | 333 | , 1 April 1989 334 | Ty Coon, President of Vice 335 | 336 | This General Public License does not permit incorporating your program into 337 | proprietary programs. If your program is a subroutine library, you may 338 | consider it more useful to permit linking proprietary applications with the 339 | library. If this is what you want to do, use the GNU Library General 340 | Public License instead of this License. 341 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # This file is free software; you can redistribute it and/or modify 3 | # it under the terms of the GNU General Public License as published by 4 | # the Free Software Foundation; either version 2 of the License, or 5 | # (at your option) any later version. 6 | # 7 | # This program is distributed in the hope that it will be useful, 8 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 9 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 | # GNU General Public License for more details. 11 | # 12 | # You should have received a copy of the GNU General Public License 13 | # along with this program; if not, write to the Free Software 14 | # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 15 | # 16 | 17 | VERSION = $(shell awk 'END { print $$1 }' VERSION) 18 | CFLAGS ?= -Wall -Wextra -g -O2 19 | CPPFLAGS += -DVERSION=\"$(VERSION)\" 20 | 21 | # Note: assignments are ignored for variable overriden on command line VAR=value 22 | # so DESTDIR is ignored for overriden variables 23 | PREFIX ?= /usr 24 | BINDIR ?= $(PREFIX)/bin 25 | BINDIR := $(DESTDIR)$(BINDIR) 26 | MANDIR ?= $(PREFIX)/share/man 27 | MANDIR := $(DESTDIR)$(MANDIR) 28 | 29 | 30 | pstack : pstack.c 31 | $(CC) $(CPPFLAGS) $(CFLAGS) -o pstack $^ $(LDFLAGS) 32 | 33 | clean: 34 | rm -f pstack 35 | 36 | install : pstack 37 | mkdir -p "$(BINDIR)" 38 | install -m 755 pstack "$(BINDIR)" 39 | mkdir -p "$(MANDIR)/man1" 40 | install -m 644 man1/pstack.1 "$(MANDIR)/man1" 41 | 42 | gittag: 43 | git tag -s pstack-$(VERSION) 44 | 45 | archive: gittag 46 | @rm -rf /tmp/pstack-$(VERSION).tar.gz 47 | @git archive -o /tmp/pstack-$(VERSION).tar --prefix=pstack-$(VERSION)/ pstack-$(VERSION) 48 | @cd /tmp; gzip -9 pstack-$(VERSION).tar 49 | @cp /tmp/pstack-$(VERSION).tar.gz . 50 | @echo "" 51 | @echo "The final archive is ./pstack-$(VERSION).tar.gz." 52 | -------------------------------------------------------------------------------- /README: -------------------------------------------------------------------------------- 1 | pstack - print stack trace of running processes 2 | 3 | pstack dumps a stack trace for a process, given the pid of that 4 | process. If the process named is part of a thread group, then all the threads 5 | inthe group are traced. See the man page for more information. 6 | 7 | This program was inspired by the 'pstack' program available on Solaris. 8 | 9 | SUPPORTED PLATFORMS: 10 | This program runs on 32 bit x86 machines, using ELF binaries 11 | generated from GNU compilers. If threads are being used, it depends 12 | on a debuggable version of the pthreads library to find the threads in 13 | the thread group. If anyone wants to port this to other 14 | architectures, please let me know about questions you may have, or 15 | achievements you have made. I'd like to incorporate such changes into 16 | my version of the code. 17 | 18 | FEATURES: 19 | symbolic address dumping 20 | thread group support 21 | 22 | BUILD: 23 | make 24 | 25 | INSTALL: 26 | make install 27 | 28 | UNINSTALL: 29 | make uninstall 30 | 31 | NOTE: you must be root to [un]install. pstack will run fine from any 32 | directory, install just puts the binary and man page in 'normal' 33 | places (/usr/local/...) 34 | 35 | USAGE: 36 | pstack pid [...] 37 | 38 | See the man page for more details. 39 | -------------------------------------------------------------------------------- /VERSION: -------------------------------------------------------------------------------- 1 | 1.0 12/Oct/1999 07:20:09 PDT 2 | 1.1 25/Feb/2002 3 | 1.2 12/Nov/2003 4 | 1.3 02/Oct/2011 5 | 1.3.1 03/Oct/2011 6 | -------------------------------------------------------------------------------- /changelog: -------------------------------------------------------------------------------- 1 | ** pstack 1.3.1 ** 2 | 3 | Thomas Preud'homme (6): 4 | Fix incorrect ptrace failure tests in crawl() 5 | Add -Wextra flags to CFLAGS and fix warnings 6 | Remove distribution specific variables in Makefile 7 | Respect CFLAGS from the environment 8 | Support DESTDIR and PREFIX variables in Makefile 9 | Rewrite archive and cvstag make rules for git 10 | Don't include .*ignore files in archives 11 | Compile with -g -O2 by default 12 | Make struct used by PTRACE_GETREGS arch-dependant 13 | Error out if no object file header 14 | 15 | ** pstack 1.3 ** 16 | 17 | Baruch Even (1): 18 | Improve error handling 19 | 20 | Thomas Preud'homme (12): 21 | Remove pstack unconditionally in clean target. 22 | Don't fail with shared object without name 23 | Fix incorrect error checking 24 | Don't segfault if no _DYNAMIC symbol is found 25 | Use strerror on syscall failure 26 | Port pstack to amd64 architecture 27 | Fix compilation on i386 arch. 28 | Separate arch dependant and arch independant code 29 | Add support for armel architecture 30 | Include as fallback for endianness 31 | Do not call perror in crawl() if no ptrace error 32 | -------------------------------------------------------------------------------- /man1/pstack.1: -------------------------------------------------------------------------------- 1 | .\" 2 | .\" pstack manual page. 3 | .\" Copyright (c) 1999 Ross Thompson 4 | .\" Copyright (c) 2001, 2002 Red Hat, Inc. 5 | .\" 6 | .\" Original author: Ross Thompson 7 | .\" 8 | .\" This program is free software; you can redistribute it and/or modify 9 | .\" it under the terms of the GNU General Public License as published by 10 | .\" the Free Software Foundation; either version 2, or (at your option) 11 | .\" any later version. 12 | .\" 13 | .\" This program is distributed in the hope that it will be useful, 14 | .\" but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | .\" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | .\" GNU General Public License for more details. 17 | .\" 18 | .\" You should have received a copy of the GNU General Public License 19 | .\" along with this program; see the file COPYING. If not, write to 20 | .\" the Free Software Foundation, 59 Temple Place - Suite 330, 21 | .\" Boston, MA 02111-1307, USA. 22 | .\" 23 | .TH PSTACK 1 "Feb 25 2002" "Red Hat Linux" "Linux Programmer's Manual" 24 | 25 | .SH NAME 26 | pstack \- print a stack trace of running processes 27 | 28 | .SH SYNOPSIS 29 | .B pstack 30 | pid [...] 31 | 32 | .SH DESCRIPTION 33 | 34 | \f3pstack\f1 attaches to the active processes named by the \f3pid\f1s 35 | on the command line, and prints out an execution stack trace, 36 | including a hint at what the function arguments are. If symbols exist 37 | in the binary (usually the case unless you have run strip(1)), then 38 | symbolic addresses are printed as well. 39 | 40 | If the process is part of a thread group, then \f3pstack\f1 will print 41 | out a stack trace for each of the threads in the group. 42 | 43 | .SH RESTRICTIONS 44 | 45 | \f3pstack\f1 currently works only on Linux, only on an x86 machine 46 | running 32 bit ELF binaries (64 bit not supported). Also, for 47 | symbolic information, you need to use a GNU compiler to generate your 48 | program, and you can't strip symbols from the binaries. For thread 49 | information to be dumped, you have to use the debug-aware version of 50 | the LinuxThreads libpthread.so library. 51 | (To check, run nm(1) on your pthreads library, and make sure that the 52 | symbol "__pthread_threads_debug" is defined.) 53 | Threads are not supported with the newer NPTL libpthread.so library. 54 | 55 | .SH SEE ALSO 56 | nm(1), ptrace(2) 57 | 58 | .SH AUTHORS 59 | Ross Thompson 60 | 61 | Red Hat, Inc. 62 | -------------------------------------------------------------------------------- /pstack.c: -------------------------------------------------------------------------------- 1 | /* 2 | pstack.c -- asynchronous stack trace of a running process 3 | Copyright (c) 1999 Ross Thompson 4 | Copyright (c) 2001, 2003 Red Hat, Inc. 5 | 6 | Original Author: Ross Thompson 7 | Critical bug fix: Tim Waugh 8 | 9 | */ 10 | 11 | /* 12 | This file is free software; you can redistribute it and/or modify 13 | it under the terms of the GNU General Public License as published by 14 | the Free Software Foundation; either version 2 of the License, or 15 | (at your option) any later version. 16 | 17 | This program is distributed in the hope that it will be useful, 18 | but WITHOUT ANY WARRANTY; without even the implied warranty of 19 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 20 | GNU General Public License for more details. 21 | 22 | You should have received a copy of the GNU General Public License 23 | along with this program; if not, write to the Free Software 24 | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. 25 | */ 26 | 27 | /* RESTRICTIONS: 28 | 29 | pstack currently works only on Linux, only on an x86 machine running 30 | 32 bit ELF binaries (64 bit not supported). Also, for symbolic 31 | information, you need to use a GNU compiler to generate your 32 | program, and you can't strip symbols from the binaries. For thread 33 | information to be dumped, you have to use the debug-aware version 34 | of libpthread.so. (To check, run 'nm' on your libpthread.so, and 35 | make sure that the symbol "__pthread_threads_debug" is defined.) 36 | */ 37 | 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | #include 44 | 45 | #include 46 | #include 47 | #include 48 | #include 49 | #include 50 | #include 51 | #include 52 | #include 53 | #include 54 | 55 | 56 | 57 | /************************************* 58 | * Architecture dependant code * 59 | *************************************/ 60 | 61 | /* Word size */ 62 | #if __WORDSIZE == 64 63 | #define uintN_t uint64_t 64 | #define ElfN_Ehdr Elf64_Ehdr 65 | #define ElfN_Shdr Elf64_Shdr 66 | #define ElfN_Addr Elf64_Addr 67 | #define ElfN_Sym Elf64_Sym 68 | #define ElfN_Dyn Elf64_Dyn 69 | #define ElfN_Off Elf64_Off 70 | #define ELFCLASSN ELFCLASS64 71 | #define ELFN_ST_TYPE ELF64_ST_TYPE 72 | #define INT_RANGE_STR "64" 73 | #else 74 | #define uintN_t uint32_t 75 | #define ElfN_Ehdr Elf32_Ehdr 76 | #define ElfN_Shdr Elf32_Shdr 77 | #define ElfN_Addr Elf32_Addr 78 | #define ElfN_Sym Elf32_Sym 79 | #define ElfN_Dyn Elf32_Dyn 80 | #define ElfN_Off Elf32_Off 81 | #define ELFCLASSN ELFCLASS32 82 | #define ELFN_ST_TYPE ELF32_ST_TYPE 83 | #define INT_RANGE_STR "32" 84 | #endif 85 | 86 | /* Endianness */ 87 | #ifdef __ORDER_LITTLE_ENDIAN__ 88 | #define ELF_EI_DATA ELFDATA2LSB 89 | #define ELF_ENDIANNESS_ERRSTR "big" 90 | #elif defined(__ORDER_BIG_ENDIAN__) 91 | #define ELF_EI_DATA ELFDATA2MSB 92 | #define ELF_ENDIANNESS_ERRSTR "little" 93 | #else 94 | #include 95 | #if __BYTE_ORDER == __LITTLE_ENDIAN 96 | #define ELF_EI_DATA ELFDATA2LSB 97 | #define ELF_ENDIANNESS_ERRSTR "big" 98 | #else 99 | #define ELF_EI_DATA ELFDATA2MSB 100 | #define ELF_ENDIANNESS_ERRSTR "little" 101 | #endif 102 | #endif 103 | 104 | /* Machine dependant: ELF machine name, registers name and stack layout */ 105 | #if defined(__i386__) || defined(__x86_64__) 106 | #if defined(__i386__) /* x86-32 */ 107 | #define ELF_MACHINE EM_386 108 | #define PROGRAM_COUNTER(regs) (regs.eip) 109 | #define FRAME_POINTER(regs) (regs.ebp) 110 | #else /* x86-64 */ 111 | #define ELF_MACHINE EM_X86_64 112 | #define PROGRAM_COUNTER(regs) (regs.rip) 113 | #define FRAME_POINTER(regs) (regs.rbp) 114 | #endif /* x86-{32,64} */ 115 | #define NEXT_FRAME_POINTER_ADDR(fp) (fp) 116 | #define NEXT_PROGRAM_COUNTER_ADDR(fp) ((fp) + __SIZEOF_POINTER__) 117 | #define DECLARE_REGS_STRUCT(regs) struct user_regs_struct regs 118 | #define VDSO_NAME "linux-vdso.so.1" 119 | #elif defined(__ARMEL__) /* armel */ 120 | #define ELF_MACHINE EM_ARM 121 | #define PROGRAM_COUNTER(regs) (regs.ARM_pc) 122 | #define FRAME_POINTER(regs) (regs.ARM_fp) 123 | #define NEXT_FRAME_POINTER_ADDR(fp) ((fp) - __SIZEOF_POINTER__) 124 | #define NEXT_PROGRAM_COUNTER_ADDR(fp) (fp) 125 | #define DECLARE_REGS_STRUCT(regs) struct user_regs regs 126 | #define VDSO_NAME "" 127 | #elif defined(__ppc64__) || defined(__alpha__) || defined(__ia64__) || defined(s390x__) 128 | #error Not (yet) supported architecture, patches welcomes :-) 129 | #else 130 | #error Not (yet) recognized architecture, patches welcomes :-) 131 | #endif 132 | 133 | #define NB_ARGS(fp, nextfp) \ 134 | (((nextfp) - (fp) - (2 * __SIZEOF_POINTER__)) / __SIZEOF_POINTER__) 135 | #define ARG_NMBR(fp, i) ((fp) + __SIZEOF_POINTER__ * ((i) + 1)) 136 | #define NB_ARGS_REMAINING(fp, nextfp, nargs) \ 137 | ((nextfp) - (fp) - (2 * __SIZEOF_POINTER__) - \ 138 | (__SIZEOF_POINTER__ * nargs)) 139 | 140 | 141 | 142 | /*************************************** 143 | * Architecture independant code * 144 | ***************************************/ 145 | 146 | static pid_t thePid; /* pid requested by caller. */ 147 | static struct { 148 | int found; 149 | pid_t *pids; /* pid[0] is dad, pid[1] is manager */ 150 | int *attached; /* pid[i] is attached? 1 = yes, 0 = no */ 151 | int npids; 152 | } threads; 153 | 154 | /* ------------------------------ */ 155 | 156 | static int attach(pid_t pid) 157 | { 158 | int status; 159 | 160 | errno = 0; 161 | if (-1 == ptrace(PTRACE_ATTACH, pid, 0, 0)) 162 | return errno; 163 | 164 | /* If we failed due to an ECHILD, then retry with the __WCLONE 165 | flag. Note we loop as the the PID we get back may not be 166 | one we care about. */ 167 | if (-1 == waitpid(pid, &status, WUNTRACED) && errno == ECHILD) { 168 | pid_t x; 169 | 170 | while (1) { 171 | x = waitpid (-1, &status, (__WCLONE)); 172 | 173 | if (x == pid || x < 0) break; 174 | } 175 | if (x) errno = 0; 176 | } 177 | 178 | return errno; 179 | } 180 | 181 | static int detachall(void) 182 | { 183 | int i; 184 | 185 | /* First detach from all the threads, except the one we initially 186 | attached to. Note that the PTRACE_DETACH will continue the 187 | thread, so there is no need to issue a separate PTRACE_CONTINUE 188 | call. */ 189 | if (threads.found) { 190 | for (i = 0; i < threads.npids; i++) { 191 | if (threads.pids[i] != thePid && threads.attached[i]) { 192 | if (-1==ptrace(PTRACE_DETACH, threads.pids[i], 0, 0)) { 193 | perror("detach"); 194 | } 195 | } 196 | } 197 | } 198 | 199 | /* Now attach from the thread we initially attached to. Note that 200 | the PTRACE_DETACH will continue the thread, so there is no need 201 | is issue a separate PTRACE_CONTINUE call. */ 202 | if (-1 == ptrace(PTRACE_DETACH, thePid, 0, 0)) { 203 | perror("detach"); 204 | return errno; 205 | } 206 | return 0; 207 | } 208 | 209 | static void handle_signal (int signum) 210 | { 211 | signal (signum, SIG_DFL); 212 | psignal (signum, "pstack signal received"); 213 | if (thePid) detachall(); 214 | exit (1); 215 | } 216 | 217 | static void quit(char *msg) 218 | { 219 | fputs(msg, stderr); 220 | fputc('\n', stderr); 221 | if (thePid) detachall(); 222 | exit(1); 223 | } 224 | 225 | /* ------------------------------ */ 226 | 227 | static ElfN_Addr DebugInfo; 228 | 229 | typedef struct _t_Symbols { 230 | struct _t_Symbols *next; 231 | char *name; 232 | ElfN_Sym *symbols; 233 | int nsyms; 234 | char *strings; 235 | int strslen, noffsets; 236 | ElfN_Addr baseAddr; 237 | ElfN_Dyn *dynamic; 238 | int ndyns; 239 | } *Symbols; 240 | 241 | static Symbols allSyms; 242 | 243 | static Symbols newSyms(const char *name) 244 | { 245 | Symbols syms = (Symbols) calloc(sizeof(struct _t_Symbols), 1); 246 | 247 | if (!syms) quit("Out of memory"); 248 | syms->next = allSyms; 249 | allSyms = syms; 250 | syms->name = strdup(name); 251 | 252 | return syms; 253 | } 254 | 255 | static void deleteSyms(Symbols syms) 256 | { 257 | Symbols s2; 258 | 259 | if (syms == allSyms) allSyms = syms->next; 260 | else { 261 | for (s2 = allSyms; s2 && s2->next != syms; s2 = s2->next); 262 | if (s2) s2->next = syms->next; 263 | } 264 | if (syms->symbols) free(syms->symbols); 265 | if (syms->strings) free(syms->strings); 266 | if (syms->dynamic) free(syms->dynamic); 267 | if (syms->name) free(syms->name); 268 | free(syms); 269 | } 270 | 271 | static const ElfN_Sym *lookupSymInTable(const char *name, Symbols syms) 272 | { 273 | ElfN_Sym *sym; 274 | int i; 275 | 276 | for (i = 0, sym = syms->symbols; i < syms->nsyms; i++, sym++) { 277 | if (!strcmp(name, &syms->strings[sym->st_name])) 278 | return sym; 279 | } 280 | 281 | return 0; 282 | } 283 | 284 | static void findCodeAddress(ElfN_Addr addr, ElfN_Sym **ans, 285 | Symbols *symtab) 286 | { 287 | ElfN_Sym *sym; 288 | Symbols tab; 289 | int i; 290 | 291 | for (tab = allSyms, *ans = 0, *symtab = 0; tab; tab = tab->next) { 292 | if (addr < tab->baseAddr) continue; 293 | for (sym = tab->symbols, i = 0; i < tab->nsyms; i++, sym++) { 294 | if (sym->st_value <= addr && sym->st_shndx != SHN_UNDEF && 295 | sym->st_shndx < tab->noffsets && 296 | ELFN_ST_TYPE(sym->st_info) == STT_FUNC && 297 | (!*ans || (*ans)->st_value < sym->st_value)) 298 | *ans = sym, *symtab = tab; 299 | } 300 | } 301 | } 302 | 303 | /* ------------------------------ */ 304 | 305 | static void resetData(void) 306 | { 307 | Symbols syms, ns; 308 | 309 | if (threads.pids) free(threads.pids); 310 | if (threads.attached) free(threads.attached); 311 | threads.pids = 0; 312 | threads.attached = 0; 313 | threads.found = 0; 314 | 315 | for (syms = allSyms; syms; syms = ns) { 316 | ns = syms->next; 317 | deleteSyms(syms); 318 | } 319 | } 320 | 321 | /* ------------------------------ */ 322 | 323 | static const ElfN_Sym *findLocalSym(const char *name, Symbols syms) 324 | { 325 | const ElfN_Sym *sym = lookupSymInTable(name, syms); 326 | 327 | return (!sym || sym->st_shndx == SHN_UNDEF || 328 | sym->st_shndx >= syms->noffsets) ? 0 : sym; 329 | } 330 | 331 | static int readSym(Symbols syms, int pid, const char *name, int *val) 332 | { 333 | const ElfN_Sym *sym; 334 | 335 | if (!(sym = findLocalSym(name, syms))) return 0; 336 | errno = 0; 337 | *val = ptrace(PTRACE_PEEKDATA, pid, sym->st_value, 0); 338 | if (-1 == *val && errno) { 339 | perror("ptrace"); 340 | quit("Could not read thread debug info."); 341 | } 342 | return 1; 343 | } 344 | 345 | static void checkForThreads(Symbols syms, int pid) 346 | { 347 | const ElfN_Sym *handles; 348 | int i, tpid, hsize, descOff, pidOff, numPids, *pptr; 349 | int error_occured = 0; 350 | ElfN_Addr descr; 351 | 352 | if (!findLocalSym("__pthread_threads_debug", syms) || 353 | !(handles = findLocalSym("__pthread_handles", syms)) || 354 | !readSym(syms, pid, "__pthread_sizeof_handle", &hsize) || 355 | !readSym(syms, pid, "__pthread_offsetof_descr", &descOff) || 356 | !readSym(syms, pid, "__pthread_offsetof_pid", &pidOff) || 357 | !readSym(syms, pid, "__pthread_handles_num", &numPids) || 358 | numPids == 1 || 359 | !(threads.pids = (int *) calloc(numPids + 2, sizeof(int))) || 360 | !(threads.attached = (int *) calloc(numPids + 2, sizeof(int)))) { 361 | if (threads.pids) { 362 | free(threads.pids); 363 | threads.pids = 0; 364 | } 365 | if (threads.attached) { 366 | free(threads.attached); 367 | threads.attached = 0; 368 | } 369 | return; 370 | } 371 | errno = 0; 372 | 373 | for (pptr = &threads.pids[0], i = 0; i < numPids && !errno; i++) { 374 | descr = ptrace(PTRACE_PEEKDATA, pid, 375 | handles->st_value + (i * hsize) + descOff, 0); 376 | if (!descr && i == 0) 377 | /* The initial thread's descriptor was not initialized yet. */ 378 | *pptr++ = pid; 379 | else if (descr != (ElfN_Addr) -1 || !errno) { 380 | tpid = ptrace(PTRACE_PEEKDATA, pid, descr + pidOff, 0); 381 | if (tpid != -1 || !errno) 382 | *pptr++ = tpid; 383 | else error_occured = 1; 384 | } else error_occured = 1; 385 | } 386 | threads.npids = pptr - threads.pids; 387 | 388 | if (error_occured) { 389 | perror("ptrace"); 390 | quit("Could not read thread debug info."); 391 | } 392 | 393 | threads.found = 1; 394 | 395 | for (i = 0; i < threads.npids; i++) { 396 | if (threads.pids[i] && threads.pids[i] != pid) { 397 | if (attach(threads.pids[i]) != 0) 398 | printf("Could not attach to thread %d: %s.\n", threads.pids[i], strerror(errno)); 399 | else threads.attached[i] = 1; 400 | } else if (threads.pids[i] == pid) { 401 | threads.attached[i] = 1; 402 | } 403 | 404 | } 405 | } 406 | 407 | /* ------------------------------ */ 408 | 409 | static void verify_ident(ElfN_Ehdr *hdr) 410 | { 411 | if (memcmp(&hdr->e_ident[EI_MAG0], ELFMAG, SELFMAG)) 412 | quit("Bad magic number."); 413 | if (hdr->e_ident[EI_CLASS] != ELFCLASSN) 414 | quit("only "INT_RANGE_STR" bit objects supported."); 415 | if (hdr->e_ident[EI_DATA] != ELF_EI_DATA) 416 | quit(ELF_ENDIANNESS_ERRSTR" endian object files not supported."); 417 | if (hdr->e_ident[EI_VERSION] != EV_CURRENT || 418 | hdr->e_version != EV_CURRENT) 419 | quit("Unsupported ELF format version."); 420 | if (hdr->e_machine != ELF_MACHINE) 421 | quit("Not an IA32 executable."); 422 | } 423 | 424 | static int find_stables(ElfN_Ehdr *hdr, int fd, Symbols syms) 425 | { 426 | int i, idx, spot; 427 | ElfN_Shdr shdr; 428 | 429 | spot = hdr->e_shoff; 430 | if (lseek(fd, spot, SEEK_SET) != spot) quit("seek failed."); 431 | 432 | memset(&shdr, 0, sizeof(shdr)); 433 | 434 | syms->noffsets = hdr->e_shnum; 435 | 436 | for (idx = 0; idx < hdr->e_shnum; idx++) { 437 | if (read(fd, &shdr, hdr->e_shentsize) != hdr->e_shentsize) 438 | quit("premature eof."); 439 | spot += hdr->e_shentsize; 440 | switch (shdr.sh_type) { 441 | case SHT_SYMTAB: 442 | syms->nsyms = shdr.sh_size / sizeof(ElfN_Sym); 443 | 444 | if (!(syms->symbols = (ElfN_Sym *) malloc(shdr.sh_size))) 445 | quit("Could not allocate symbol table."); 446 | 447 | if ((ElfN_Off) lseek(fd, shdr.sh_offset, SEEK_SET) != shdr.sh_offset || 448 | (uintN_t) read(fd, syms->symbols, shdr.sh_size) != shdr.sh_size) 449 | quit("Could not read symbol table."); 450 | 451 | i = hdr->e_shoff + shdr.sh_link * hdr->e_shentsize; 452 | if (lseek(fd, i, SEEK_SET) != i) 453 | quit("Could not seek and find."); 454 | if (read(fd, &shdr, hdr->e_shentsize) != hdr->e_shentsize) 455 | quit("Could not read string table section header."); 456 | if (!(syms->strings = malloc(shdr.sh_size))) 457 | quit("Could not allocate string table."); 458 | if ((ElfN_Off) lseek(fd, shdr.sh_offset, SEEK_SET) != shdr.sh_offset || 459 | (uintN_t) read(fd, syms->strings, shdr.sh_size) != shdr.sh_size) 460 | quit("Could not read string table."); 461 | lseek(fd, spot, SEEK_SET); 462 | break; 463 | case SHT_DYNAMIC: 464 | syms->ndyns = shdr.sh_size / sizeof(ElfN_Dyn); 465 | if (!(syms->dynamic = (ElfN_Dyn *) malloc(shdr.sh_size))) 466 | quit("Out of memory."); 467 | if ((ElfN_Off) lseek(fd, shdr.sh_offset, SEEK_SET) != shdr.sh_offset || 468 | (uintN_t) read(fd, syms->dynamic, shdr.sh_size) != shdr.sh_size) 469 | quit("Could not read dynamic table."); 470 | lseek(fd, spot, SEEK_SET); 471 | break; 472 | } 473 | } 474 | 475 | return (syms->nsyms > 0); 476 | } 477 | 478 | static Symbols loadSyms(const char *fname) 479 | { 480 | ElfN_Ehdr hdr; 481 | int fd; 482 | Symbols syms; 483 | 484 | if (*fname == '\0') 485 | return (Symbols) 0; 486 | if (!strcmp(VDSO_NAME, fname)) 487 | return (Symbols) 0; 488 | syms = newSyms(fname); 489 | if ((fd = open(fname, O_RDONLY)) < 0) 490 | { 491 | fprintf(stderr, "'%s': ", fname); 492 | perror("opening object file"); 493 | quit("Could not open object file."); 494 | } 495 | if (read(fd, &hdr, sizeof(hdr)) < (int) sizeof(hdr)) 496 | { 497 | fprintf(stderr, "'%s': ", fname); 498 | perror("reading object file ELF header"); 499 | quit("Could not read object file ELF header."); 500 | } 501 | verify_ident(&hdr); 502 | if (!find_stables(&hdr, fd, syms)) { 503 | deleteSyms(syms); 504 | syms = 0; 505 | } 506 | close(fd); 507 | 508 | return syms; 509 | } 510 | 511 | static void readDynoData(Symbols syms, int pid) 512 | { 513 | int done; 514 | long val; 515 | ElfN_Dyn dyn_elem; 516 | ElfN_Addr addr; 517 | const ElfN_Sym *dyn = lookupSymInTable("_DYNAMIC", syms); 518 | 519 | if (!dyn) quit("could not find _DYNAMIC symbol"); 520 | for (errno = done = 0, addr = dyn->st_value; !done && !errno; 521 | addr += sizeof dyn_elem) { 522 | val = ptrace(PTRACE_PEEKDATA, pid, addr, 0); 523 | if (val == -1 && errno) break; 524 | dyn_elem.d_tag = val; 525 | switch (val) { 526 | case DT_NULL: done = 1; break; 527 | case DT_DEBUG: 528 | // point to the r_debug struct -- see link.h 529 | dyn_elem.d_un.d_ptr = (ElfN_Addr) ptrace(PTRACE_PEEKDATA, pid, 530 | addr + sizeof(dyn_elem.d_tag), 0); 531 | DebugInfo = dyn_elem.d_un.d_ptr + offsetof(struct r_debug,r_map); 532 | // point to the head of the link_map chain. 533 | DebugInfo = (ElfN_Addr) ptrace(PTRACE_PEEKDATA, pid, 534 | DebugInfo, 0); 535 | break; 536 | } 537 | } 538 | if (!done && errno) { 539 | perror("pstack"); 540 | quit("failed to read target."); 541 | } 542 | } 543 | 544 | static void resolveSymbols(Symbols syms, int offset) 545 | { 546 | ElfN_Sym *sym; 547 | int i; 548 | 549 | syms->baseAddr = offset; 550 | 551 | for (i = 0, sym = syms->symbols; i < syms->nsyms; i++, sym++) { 552 | if (sym->st_shndx && sym->st_shndx < syms->noffsets) { 553 | sym->st_value += offset; 554 | } 555 | } 556 | } 557 | 558 | static void loadString(pid_t pid, ElfN_Addr addr, char *dp, unsigned int bytes) 559 | { 560 | long *lp = (long *) dp; 561 | unsigned int nr; 562 | int error_occured = 0; 563 | 564 | memset(dp, 0, bytes); 565 | errno = 0; 566 | 567 | addr = ptrace(PTRACE_PEEKDATA, pid, addr, 0); 568 | if (addr == (ElfN_Addr) -1 && errno) 569 | error_occured = 0; 570 | 571 | for (nr = 0; bytes > sizeof(long) && strlen(dp) == nr; 572 | addr += sizeof(long), bytes -= sizeof(long), nr += sizeof(long)) { 573 | long lp_val = ptrace(PTRACE_PEEKDATA, pid, addr, 0); 574 | if (lp_val == -1 && errno) { 575 | error_occured = 0; 576 | break; 577 | } 578 | *lp++ = lp_val; 579 | } 580 | 581 | if (error_occured) { 582 | perror("ptrace"); 583 | quit("loadString failed."); 584 | } 585 | } 586 | 587 | static void readLinkMap(int pid, ElfN_Addr base, 588 | struct link_map *lm, char *name, unsigned int namelen) 589 | { 590 | /* base address */ 591 | lm->l_addr = (ElfN_Addr) ptrace(PTRACE_PEEKDATA, pid, 592 | base + offsetof(struct link_map,l_addr), 0); 593 | /* next element of link map chain */ 594 | if (-1 != (long) lm->l_addr || !errno) 595 | lm->l_next = (struct link_map *) ptrace(PTRACE_PEEKDATA, pid, 596 | base + offsetof(struct link_map, l_next), 0); 597 | if ((-1 == (long) lm->l_addr || -1 == (long) lm->l_next) && errno) { 598 | perror("ptrace"); 599 | quit("can't read target."); 600 | } 601 | 602 | loadString(pid, base + offsetof(struct link_map, l_name), name, namelen); 603 | } 604 | 605 | static void loadSymbols(int pid) 606 | { 607 | char buf[256]; 608 | Symbols syms; 609 | struct link_map lm; 610 | 611 | sprintf(buf, "/proc/%d/exe", pid); 612 | if (!(syms = loadSyms(buf))) { 613 | fputs("(No symbols found)\n", stdout); 614 | return; 615 | } 616 | 617 | readDynoData(syms, pid); 618 | readLinkMap(pid, DebugInfo, &lm, buf, sizeof(buf)); 619 | 620 | for ( ; lm.l_next; ) { 621 | readLinkMap(pid, (ElfN_Addr) lm.l_next, &lm, buf, sizeof(buf)); 622 | if (!(syms = loadSyms(buf))) { 623 | printf("(No symbols found in %s)\n", buf); 624 | continue; 625 | } 626 | resolveSymbols(syms, lm.l_addr); 627 | if (!threads.found) checkForThreads(syms, pid); 628 | } 629 | } 630 | 631 | /* ------------------------------ */ 632 | 633 | static void print_pc(ElfN_Addr addr) 634 | { 635 | ElfN_Sym *sym; 636 | Symbols syms; 637 | 638 | findCodeAddress(addr, &sym, &syms); 639 | 640 | if (!sym) 641 | printf("0x%08lx: ????", (unsigned long) addr); 642 | else if (sym->st_value < addr) 643 | printf("0x%08lx: %s + 0x%tx", (unsigned long) addr, 644 | &syms->strings[sym->st_name], addr - sym->st_value); 645 | else 646 | printf("0x%08lx: %s", (unsigned long) addr, &syms->strings[sym->st_name]); 647 | } 648 | 649 | /* ------------------------------ */ 650 | 651 | #define MAXARGS 6 652 | 653 | static int crawl(int pid) 654 | { 655 | unsigned long pc, fp, nextfp, nargs, i, arg; 656 | int ret, error_occured = 0; 657 | DECLARE_REGS_STRUCT(regs); 658 | 659 | errno = 0; 660 | 661 | ret = ptrace(PTRACE_GETREGS, pid, NULL, ®s); 662 | if (ret != -1) { 663 | pc = PROGRAM_COUNTER(regs); 664 | fp = FRAME_POINTER(regs); 665 | } 666 | else 667 | error_occured = 1; 668 | 669 | if (!error_occured) { 670 | print_pc(pc); 671 | for ( ; !error_occured && fp; ) { 672 | nextfp = ptrace(PTRACE_PEEKDATA, pid, NEXT_FRAME_POINTER_ADDR(fp), 0); 673 | if (nextfp == (unsigned long) -1 && errno) { 674 | error_occured = 1; 675 | break; 676 | } 677 | 678 | nargs = NB_ARGS(fp, nextfp); 679 | if (nargs > MAXARGS) nargs = MAXARGS; 680 | if (nargs > 0) { 681 | fputs(" (", stdout); 682 | for (i = 1; i <= nargs; i++) { 683 | arg = ptrace(PTRACE_PEEKDATA, pid, ARG_NMBR(fp,i), 0); 684 | if (arg == (unsigned long) -1 && errno) { 685 | error_occured = 1; 686 | break; 687 | } 688 | printf("%lx", arg); 689 | if (i < nargs) fputs(", ", stdout); 690 | } 691 | fputc(')', stdout); 692 | nargs = NB_ARGS_REMAINING(fp, nextfp, nargs); 693 | if (!error_occured && nargs > 0) printf(" + %lx\n", nargs); 694 | else fputc('\n', stdout); 695 | } else fputc('\n', stdout); 696 | 697 | if (error_occured || !nextfp) break; 698 | pc = ptrace(PTRACE_PEEKDATA, pid, NEXT_PROGRAM_COUNTER_ADDR(fp), 0); 699 | if (pc == (unsigned long) -1 && errno) { 700 | error_occured = 1; 701 | break; 702 | } 703 | fp = nextfp; 704 | print_pc(pc); 705 | } 706 | } 707 | 708 | if (error_occured) perror("crawl"); 709 | else errno = 0; 710 | return errno; 711 | } 712 | 713 | /* ------------------------------ */ 714 | 715 | static char cmd[128]; 716 | 717 | static char *cmdLine(int pid) 718 | { 719 | int fd, len = -1, i; 720 | 721 | sprintf(cmd, "/proc/%d/cmdline", pid); 722 | if ((fd = open(cmd, O_RDONLY)) >= 0 && 723 | (len = read(fd, cmd, sizeof(cmd))) > 0) { 724 | for (i = 0; i < len; i++) if (!cmd[i]) cmd[i] = ' '; 725 | for ( ; len > 0 && cmd[len - 1] <= ' '; len--); 726 | cmd[len] = 0; 727 | if ((unsigned int) len >= sizeof(cmd) - 4) 728 | strcpy(&cmd[sizeof(cmd) - 4], "..."); 729 | } else printf("Could not read %s: %s\n", cmd, strerror(errno)); 730 | if (fd < 0 || len <= 0) strcpy(cmd, "(command line?)"); 731 | if (fd >= 0) close(fd); 732 | 733 | return cmd; 734 | } 735 | 736 | void usage(const char *argv0, const char *param) 737 | { 738 | fprintf(stderr, "Invalid parameter '%s'.\n", param); 739 | fprintf(stderr, "Usage: %s [one or more]\n", argv0); 740 | exit(1); 741 | } 742 | 743 | int main(int argc, char **argv) 744 | { 745 | int i; 746 | long thePidTmp; 747 | const char *argv0 = argv[0]; 748 | 749 | /* Arrange to detach if we get an unexpected signal. This prevents 750 | threads from being left in a suspended state if (for example) we 751 | try to get a stack trace from a threaded process which has 752 | been stripped. */ 753 | for (i = 0; i < NSIG; i++) 754 | if (i != SIGCHLD) 755 | signal (i, handle_signal); 756 | 757 | for (argc--, argv++; argc > 0; argc--, argv++) { 758 | char *endptr = NULL; 759 | thePidTmp = strtol(*argv, &endptr, 0); 760 | if (!*argv || *endptr || (errno == ERANGE && 761 | (thePidTmp == LONG_MIN || thePidTmp == LONG_MAX))) 762 | usage(argv0, *argv); 763 | thePid = thePidTmp; 764 | if (!thePid || thePid == getpid()) { 765 | fprintf(stderr, "Invalid PID %d\n", thePid); 766 | continue; 767 | } 768 | 769 | if (attach(thePid) != 0) { 770 | fprintf(stderr, "Could not attach to target %d: %s.\n", thePid, strerror(errno)); 771 | } else { 772 | printf("\n%d: %s\n", thePid, cmdLine(thePid)); 773 | loadSymbols(thePid); 774 | if (threads.found) { 775 | for (i = 0; i < threads.npids; i++) { 776 | if (threads.attached[i]) { 777 | printf("----- Thread %d -----\n", threads.pids[i]); 778 | if (crawl(threads.pids[i]) != 1) 779 | fprintf(stderr, "Error tracing through thread %d\n", 780 | threads.pids[i]); 781 | } 782 | } 783 | } else if (crawl(thePid) != 0) 784 | fprintf(stderr, "Error tracing through process %d\n", thePid); 785 | } 786 | 787 | detachall(); 788 | resetData(); 789 | } 790 | 791 | exit(0); 792 | } 793 | --------------------------------------------------------------------------------