Category: Dumpstack in c

A backtrace is a list of the function calls that are currently active in a thread. The usual way to inspect a backtrace of a program is to use an external debugger such as gdb. However, sometimes it is useful to obtain a backtrace programmatically from within a program, e.

The header file execinfo. The backtrace function obtains a backtrace for the current thread, as a list of pointers, and places the information into buffer. The return value is the actual number of entries of buffer that are obtained, and is at most size. The pointers placed in buffer are actually return addresses obtained by inspecting the stack, one return address per stack frame. Note that certain compiler optimizations may interfere with obtaining a valid backtrace.

Function inlining causes the inlined function to not have a stack frame; tail call optimization replaces one stack frame with another; frame pointer elimination will stop backtrace from interpreting the stack contents correctly.

The argument buffer should be a pointer to an array of addresses obtained via the backtrace function, and size is the number of entries in that array the return value of backtrace. The return value is a pointer to an array of strings, which has size entries just like the array buffer. Each string contains a printable representation of the corresponding element of buffer.

What is the purpose of using a dumpStack() method in Java?

It includes the function name if this can be determinedan offset into the function, and the actual return address in hexadecimal. Currently, the function name and offset can only be obtained on systems that use the ELF binary format for programs and libraries. On other systems, only the hexadecimal return address will be present. Also, you may need to pass additional flags to the linker to make the function names available to the program.

For example, on systems using GNU ld, you must pass -rdynamic. Note that only the return value need be freed, not the individual strings. Instead of returning the strings to the caller, it writes the strings to the file descriptor fdone per line. It does not use the malloc function, and can therefore be used in situations where that function might fail.How to begin Get the book.

Practice problems Quizzes. But finding problems with pointers is easier than you'd think. Those segfaults often turn out to be among the easiest bugs to find, and using special tools such as Valgrind, even finding buffer overflows is simplified. This tutorial assumes that you have a basic knowledge of pointers such as can be acquired by reading a pointer tutorial.

Stack Program in C

It would help to be running a system that has a debugger such as GDB, or to at least have sufficient familiarity with GDB-like debuggers to understand the examples presented. Finally, for finding buffer overflows and other invalid uses of memory, you will fare best with Valgrindthough none of the examples will use it.

What is a segmentation fault? When your program runs, it has access to certain portions of memory. First, you have local variables in each of your functions; these are stored in the stack. Your program is only allowed to touch memory that belongs to it -- the memory previously mentioned.

Any access outside that area will cause a segmentation fault. Segmentation faults are commonly referred to as segfaults.

A fifth way of causing a segfault is a recursive function that uses all of the stack space. On some systems, this will cause a "stack overflow" report, and on others, it will merely appear as another type of segmentation fault.

The strategy for debugging all of these problems is the same: load the core file into GDB, do a backtrace, move into the scope of your code, and list the lines of code that caused the segmentation fault. The core file contains all the information needed by GDB to reconstruct the state of execution when the invalid operation caused a segmentation fault.

Program terminated with signal 11, Segmentation fault. Some information about loading symbols 0 0xc in foo at t. This is a goldmine of information: we already know exactly where the problem happened and which pointer was involved. The pointer x is initialized to 0, equivalent to NULL in fact, NULL is a stand-in for 0and we know that it's a no-no to then try to access that pointer.

But what if it weren't so obvious? Simply printing the value of the pointer can often lead to the solution. The address 0x0 is invalid -- in fact, it's NULL. If you dereference a pointer that stores the location 0x0 then you'll definitely get a segmentation fault, just as we did. If we'd gotten something more complicated, such as execution crashing inside a system call or library function perhaps because we passed an uninitialized pointer to fgetswe'd need to figure out where we called the library function and what might have happened to cause a segfault within it.

Does this mean the library function did something wrong? It means that we probably passed a bad value to the function. To debug this, we need to see what we passed into strcat.

So let's see what function call we made that led to the segfault. Each function is directly above the function that called it. So foo was called by main in this case. The numbers on the side 0, 1, 2 also indicate the order of calls, from most recent to longest ago. To move from viewing the state within each function encapsulated in the idea of a stack framewe can use the up and down commands.

Right now, we know we're in the strcat stack frame, which contains all of the local variables of strcat, because it's the top function on the stack.

We want to move "up" toward the higher numbers ; this is the opposite of how the stack is printed.

dumpstack in c

We should probably lookup the strcat function at this point to make sure that we got the order of arguments correct. Since we did, the problem must be with x. The strcat function must be derefencing a NULL pointer that we gave it, and even though it's a library function, it doesn't do anything magical.If you usually work with non-trivial C sources, you may have wondered which execution path that is, which sequence of function calls brought you to a certain point in your program.

Also, it would be even more useful if you could have that piece of information whenever your beautiful, bug-free program suddenly crashes, and you have no debugger at hand. What is needed is a stack backtrace and, thanks to a little known feature of the GNU C library, obtaining it is a fairly easy task. Before diving into the article, let's briefly go over how function calls and parameters pass work in C.

In order to prepare for the function call, parameters are pushed on the stack in reverse order. Afterwards, the caller's return address also is pushed on the stack and the function is called. Finally, the called function's entry code creates some more space on the stack for storage of automatic variables.

This layout commonly is called a stack frame for that particular instance of the function call. When more function calls are nested, the whole procedure is repeated, causing the stack to keep growing downwards and building a chain of stack frames see Figure 1. Thus, at any given point in a program it theoretically is possible to backtrace the sequence of stack frames to the originating calling point, up to the main function to be exact, up to the libc function, which calls main when the process starts up.

Getting the stack backtrace with GDB or an equivalent graphical front end for a program that crashed while running is straightforward: you simply issue the bt command, which returns the list of functions called up to the point of the crash. As this is a standard practice, we do not provide any more details here; have a look at the GDB info page if you need specifics info gdb stack gets you there. If for some reason you're not running inside a debugger, two options are available for tracing what the program is doing.

The first method is to disseminate it with print and log messages in order to pinpoint the execution path. In a complex program, this option can become cumbersome and tedious even if, with the help of some GCC-specific macros, it can be simplified a bit. Consider, for example, a debug macro such as. You can propagate this macro quickly throughout your program by cutting and pasting it.

When you do not need it anymore, switch it off simply by defining it to no-op. A nicer way to get a stack backtrace, however, is to use some of the specific support functions provided by glibc. The key one is backtracewhich navigates the stack frames from the calling point to the beginning of the program and provides an array of return addresses.

You then can map each address to the body of a particular function in your code by having a look at the object file with the nm command. This function transforms a list of return addresses, as returned by backtraceinto a list of strings, each containing the function name offset within the function and the return address. The list of strings is allocated from your heap space as if you called mallocso you should free it as soon as you are done with it.

This prints the strings directly to the given file descriptor and does not allocate new memory for strings storage. It is a safer choice in those cases where memory heap potentially is corrupted. In order to convert an address to a function name, the last two functions rely on symbol information to be available inside the program itself.

To enable this feature, compile your program with the -rdynamic option see man dlopen for more details. Listing 1.

How to Use the Backtrace Functions. Listing 1 demonstrates how to use these functions.In this post, I am going to not disappoint and show you some more cool things that the windows debugger can do for you with public symbols for a latch timeout issue.

If there are further occurrences of the same latch timeout, then that is reported as an error message in the SQL Errorlog. Buffer latch timeouts are typically reported using Error: and The common reasons for such errors are documented in a KB Article.

For a non-buffer latch timeout, you will get the an error. Continuing to wait. This is what you will see in the SQL Errorlog when a latch timeout occurs. I have only pasted the relevant portion from the Errorlog for brevity. As I have outlined in my previous blog posts on similar topics, that there is a large opportunity for due diligence that can be done with the help of the Windows Event Logs and the SQL Server Errorlogs before you start spawning off windows debugger to analyze the memory dump on your system.

The timeout occurred while waiting for a buffer latch on a page Page ID is available in the message above. Latch timeouts are typically victims of either a system related issue hardware or drivers or operating system or a previous error encountered by SQL Server.

So the next obvious action item would be to look into the SQL Errorlogs and find out if there were any additional errors prior to the latch timeout issue. This is usually a temporary condition and the SQL Server will keep retrying the operation. If the condition persists then immediate action must be taken to correct it. Additionally, I see prior and post within minutes the latch timeout issue, multiple other SPIDs reporting the same error message for different offsets but again on the same file.

I also see the latch timeout message being reported after every ms for the same page and the database. Notice the waittime above, it has increased from to !! These are relevant posts related to the above issue.

As of now, it is quite clear that the issue is related to a possible sparse file issue related to file fragmentation.

Now it is time for me to check if there are other threads in the dump waiting on SyncWritePreemptive calls. Use the location provided in the Errorlog snippet reporting the Latch Timeout message to locate the mini-dump for the issue in this case SQLDump This dump file has an exception of interest stored in it. The above tells you that this is a mini-dump for a Latch Timeout condition and the location from where you loaded the dump. Then I use the command to set my symbol path and direct the symbols downloaded from the Microsoft symbol server to a local symbol file cache on my machine.

Then I issue a reload command to load the symbols for sqlservr. The only difference here is that the all the public symbols for all loaded modules in the dump will be downloaded from the Microsoft Symbol Server which are available. Next thing is to verify that the symbols were correctly loaded using the lmvm sqlservr command.

If the symbols were loaded correctly, you should see the following output. Note the text in green. I will use the! Thread1 frame s match Thread1 frame s match Thread1 frame s match Thread1 frame s match Thread1 frame s match Thread1 frame s match Thread1 frame s match Thread1 frame s match Thread1 frame s match Thread1 frame s match Thread1 frame s match Thread1 frame s match Thread1 frame s match Thread1 frame s match Thread1 frame s match Thread1 frame s match Thread1 frame s match.

ZwDelayExecution kernel32! SleepEx sqlservr!By using our site, you acknowledge that you have read and understand our Cookie PolicyPrivacy Policyand our Terms of Service. The dark mode beta is finally here. Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

I want to dump the stacks of the threads in a file. How can I do that in linux? How can I find the starting address of the stack and its size?

dumpstack in c

Note that I want to do this progammatically from the same process not using ptrace, gdb or something like that. Do you want to get some application checkpointing? If you want it, there are some libraries implementing it, even imperfectly, but usefully in practice.

The point is, that even if you manage to dump your threads' stacks in a file, I'm not sure you'll be able to do somehing useful with that file. I heard there is also some linux libraries which force a running process to dump a core file that you could examine with gdb later without aborting that process.

If you just want to inspect your call stack, look into Ian Taylor's libbacktrace. Notice that several checkpointing infrastructures including SBCL 's save-lisp-and-die are not capable of restoring any other threads than the main one. That says something about the difficulty of managing pthread -s stacks. Learn more. How to dump thread stacks Ask Question. Asked 8 years, 5 months ago. Active 1 year, 1 month ago. Viewed 3k times.

MetallicPriest MetallicPriest Have you considered using a debugger? I want to do it programmatically, not using a debugger. Do you want to get the callstack, or just a dump of all of the stack? Pileborg, just dump the stack. Active Oldest Votes. Chris Chris 4 4 silver badges 11 11 bronze badges. Brett Hale Brett Hale This won't do the job. MetallicPriest That would work I suppose, but it is by definition non-portable That may not matter, depending on the OP's need. I think it's the same on Solaris, and probably other Unixen.The crash dump stack is configured through various settings in the registry.

dumpstack in c

The kernel function IoConfigureCrashDumpwhich is called explicitly during the crash dump stack pre-initialization phase during kernel initialization and implicitly whenever NtSetSystemInformationPoBroadcastSystemState or PoShutdownBugCheck is called, reads the crash dump settings from the registry and stores this information in a global data structure.

The completed global data structure is used during pre-initialization of the crash dump stack. After Windows Vista, the registry-reading code is located in crashdmp. The table below captures all registry settings, as of Windows 8, that control hibernation and crash, as found through reversing relevant components. Keys and value names that are not user-driven but rather are generated by an operating system component are also included for purposes of thoroughness. The default values for some variables can change based on values supplied in the registry.

The table below attempts to capture this mapping. Dump type definitions are shown below. Note that only 4, 5 and 6 are the only usable dump types. The dump context structure has a flags field, some of whose bits are controllable from the registry settings outlined above. The bit layout is shown below. The driver maintains a global buffer to store telemetry data and registers a bugcheck callback routine CrashdmpDriveTelemetryCallback.

Exploring the Microsoft Windows crash dump stack. Skip to content. Configuration The crash dump stack is configured through various settings in the registry. MinidumpDir Valid path Smss.

WLST Command and Variable Reference

MinidumpsCount Number Smss. Overwrite 0 or 1 Smss. DedicatedDumpFile Valid file crashdmp. The value cannot be longer than characters. DumpFileSize Valid size crashdmp. DumpFilters String crashdmp. CrashDumpEnabled crashdmp. Purpose not exactly known. See this page for details.

SimulateError Any value! The value passed from the registry is stored unchecked in the dump context structure and referenced later. SimulateNotReady Any value crashdmp. See the table below for possible values of the Flags member.

Flags Bitmask crashdmp.By using our site, you acknowledge that you have read and understand our Cookie PolicyPrivacy Policyand our Terms of Service. The dark mode beta is finally here. Change your preferences any time. Stack Overflow for Teams is a private, secure spot for you and your coworkers to find and share information.

I want to have a way to report the stack trace to the user if an exception is thrown. What is the best way to do this? Does it take huge amounts of extra code? I'd like it to be portable if possible. I want information to pop up, so the user can copy the stack trace and email it to me if an error comes up. On GCC it's pretty trivial, see this post for more details. You'll have to figure out the best way to integrate this functionality into your app, but the amount of code you need to write should be minimal.

Andrew Grant's answer does not help getting a stack trace of the throwing function, at least not with GCC, because a throw statement does not save the current stack trace on its own, and the catch handler won't have access to the stack trace at that point any more. The only way - using GCC - to solve this is to make sure to generate a stack trace at the point of the throw instruction, and save that with the exception object.

This method requires, of course, that every code that throws an exception uses that particular Exception class. If you are using Boost 1. Unix: backtrace. Mac: backtrace. Windows: CaptureBackTrace.

I would like to add a standard library option i.

Subscribe to RSS

This won't give you a stack unwind, but in my opinion the next best thing. It is described on StackOverflow here and herehow you can get a backtrace on your exceptions inside your code without need for a debugger or cumbersome logging, by simply writing a proper exception handler which will rethrow nested exceptions. Since you can do this with any derived exception class, you can add a lot of information to such a backtrace!

On Windows, check out BugTrap. Its not longer at the original link, but its still available on CodeProject. I have a similar problem, and though I like portability, I only need gcc support. In gcc, execinfo. To demangle the function names, Mr. Bingmann has a nice piece of code. To dump a backtrace on an exception, I create an exception that prints the backtrace in the constructor. Compiling and running this with gcc 4.

thoughts on “Dumpstack in c

Leave a Reply

Your email address will not be published. Required fields are marked *