C++. How to trace memory allocation to .so module in linux - c++

We are in a situation that have a large application and now there is a situation that would need to know which .so module is allocating how much memory. I have no idea here, I was wondering a custom allocator overriding operator new, but that didn't help because I still cannot trace which module is doing to allocation. Replacing new by custom allocator would be terrible amount of work. Does anyone know how can I tell which module is doing how much allocations ?

You could make use of the LD_PRELOAD trick to hook malloc, realloc, free etc. That, combined with the info gleaned from boost.stacktrace would get you most (if not all) of what you need. Not trivial though.

It's not easy.
You can hook malloc, free, realloc globally in the application. Corresponding articles on Stackoverflow: How to use __malloc_hook?, An alternative for the deprecated __malloc_hook functionality of glibc.
You can retrieve a caller address from that hooks using __builtin_return_address and compare it with addresses of shared libraries. Maybe you have to examine a deeper frame address to get a proper address in a library, not an address of libc++. Read this Stackoverflow article __builtin_return_address returns null for index >0?.

Related

platform specific way (windows) to replace malloc (and other C allocation flavors)?

I know that while c++ ::operator new and associated flavors can be replaced/overridden, malloc (and calloc etc) can not.
However, is there still some (possibly platform specific) way to achieve the same (for example replace all malloc calls with an implementation that prints something to stdout on each allocation)? Using some linker magic maybe? In particular I want to replace the mallocs used by static libraries that I'm linking into my application (without altering those libraries code). I'm interested in solutions for windows, but if someone has a solution for another platform, that's certainly an interesting pointer as well.
Malloc can be overloaded or overridden. Check out this link to mi-malloc https://microsoft.github.io/mimalloc/overrides.html
If using MSVC instead of using a different allocator I suggest that you take a look at the debug CRT's reporting options (this is where leak reports can be generated for example, using _CrtSetDbgFlag). You can also send the report text to a file using __CrtSetReportMode and _CrtSetReportFile.
The existing debug allocator is already very capable.

Dynamic memory allocation in STD

Working a lot with microcontrollers and C++ it is important for me to know that I do not perform dynamic memory allocations. However I would like to get the most out of the STD lib. What would be the best strategy to determine if a function/class from STD uses dynamic memory allocation?
So far I come up with these options:
Read and understand the STD code. This is of course possible but lets be honest, it is not the easiest code to read and there is a lot of it.
A variation on reading the code could be to have a script search for memory allocation and highlight those parts to it make it easier to read. This still would require figuring out where functions allocating memory are used, and so forts.
Just testing what I would like to use and watch the memory with the debugger. So far I have been using this method but this is a reactive approach. I would like to know before hand when designing code what I can use from STD. Also what is there to say that there are some (edge) cases where memory is allocated. Those might not show up in this limited test.
Finally what could be done is regularly scan the generated assembler code for memory allocations. I suspect this could be scripted and included in the toolchain but again this is a reactive method.
If you see any other options or have experience doing something similar, please let me know.
p.s. I work mainly with ARM Cortex-Mx chips at this moment compiling with GCC.
You have some very good suggestions in the comments, but no actual answers, so I will attempt an answer.
In essence you are implying some difference between C and C++ that does not really exist. How do you know that stdlib functions don't allocate memory?
Some STL functions are allowed to allocate memory and they are supposed to use allocators. For example, vectors take an template parameter for an alternative allocator (for example pool allocators are common). There is even a standard function for discovering if a type uses memory
But... some types like std::function sometimes use memory allocation and sometimes do not, depending on the size of the parameter types, so your paranoia is not entirely unjustified.
C++ allocates via new/delete. New/Delete allocate via malloc/free.
So the real question is, can you override malloc/free? The answer is yes, see this answer https://stackoverflow.com/a/12173140/440558. This way you can track all allocations, and catch your error at run-time, which is not bad.
You can go better, if you are really hardcore. You can edit the standard "runtime C library" to rename malloc/free to something else. This is possible with "objcopy" which is part of the gcc tool chain. After renaming the malloc/free, to say ma11oc/fr33, any call to allocate/free memory will no longer link.
Link your executable with "-nostdlib" and "-nodefaultlibs" options to gcc, and instead link your own set of libs, which you generated with objcopy.
To be honest, I've only seen this done successfully once, and by a programmer you did not trust objcopy, so he just manually found the labels "malloc" "free" using a binary editor, and changed them. It definitely works though.
Edit:
As pointed out by Fureeish (see comments), it is not guaranteed by the C++ standard that new/delete use the C allocator functions.
It is however, a very common implementation, and your question does specifically mention GCC. In 30 years of development, I have never seen a C++ program that runs two heaps (one for C, and one for C++) just because the standard allows for it. There would simply be no advantage in it. That doesn't preclude the possibility that there may be an advantage in the future though.
Just to be clear, my answer assumes new USES malloc to allocate memory. This doesn't mean you can assume that every new call calls malloc though, as there may be caching involved, and the operator new may be overloaded to use anything at all at the global level. See here for GCC/C++ allocator schemes.
https://gcc.gnu.org/onlinedocs/libstdc++/manual/memory.html
Yet another edit:
If you want to get technical - it depends on the version of libstdc++ you are using. You can find operator new in new_op.cc, in the (what I assume is the official) source repository
(I will stop now)
The options you listed are pretty comprehensive, I think I would just add some practical color to a couple of them.
Option 1: if you have the source code for the specific standard library implementation you're using, you can "simplify" the process of reading it by generating a static call graph and reading that instead. In fact the llvm opt tool can do this for you, as demonstrated in this question. If you were to do this, in theory you could just look at a given method and see if goes to an allocation function of any kind. No source code reading required, purely visual.
Option 4: scripting this is easier than you think. Prerequisites: make sure you're building with -ffunction-sections, which allows the linker to completely discard functions which are never called. When you generate a release build, you can simply use nm and grep on the ELF file to see if for example malloc appears in the binary at all.
For example I have a bare metal cortex-M based embedded system which I know for a fact has no dynamic memory allocation, but links against a common standard library implementation. On the debug build I can do the following:
$ nm Debug/Project.axf | grep malloc
700172bc T malloc
$
Here malloc is found because dead code has not been stripped.
On the release build it looks like this:
$ nm Release/Project.axf | grep malloc
$
grep here will return "0" if a match was found and something other than "0" if it wasn't, so if you were to use this in a script it would be something like:
nm Debug/Project.axf | grep malloc > /dev/null
if [ "$?" == "0" ]; then
echo "error: something called malloc"
exit 1
fi
There's a mountain of disclaimers and caveats that come with any of these approaches. Keep in mind that embedded systems in particular use a wide variety of different standard library implementations, and each implementation is free to do pretty much whatever it wants with regard to memory management.
In fact they don't even have to call malloc and free, they could implement their own dynamic allocators. Granted this is somewhat unlikely, but it is possible, and thus grepping for malloc isn't actually sufficient unless you know for a fact that all memory management in your standard library implementation goes through malloc and free.
If you're serious about avoiding all forms of dynamic memory allocation, the only sure way I know of (and have used myself) is simply to remove the heap entirely. On most bare metal embedded systems I've worked with, the heap start address, end address, and size are almost always provided a symbols in the linker script. You should remove or rename these symbols. If anything is using the heap, you'll get a linker error, which is what you want.
To give a very concrete example, newlib is a very common libc implementation for embedded systems. Its malloc implementation requires that the common sbrk() function be present in the system. For bare metal systems, sbrk() is just implemented by incrementing a pointer that starts at the end symbol provided by the linker script.
If you were using newlib, and you didn't want to mess with the linker script, you could still replace sbrk() with a function that simply hard faults so you catch any attempt to allocate memory immediately. This in my opinion would still be much better than trying to stare at heap pointers on a running system.
Of course your actual system may be different, and you may have a different libc implementation that you're using. This question can really only answered to any reasonable satisfaction in the exact context of your system, so you'll probably have to do some of your own homework. Chances are it's pretty similar to what I've described here.
One of the great things about bare metal embedded systems is the amount of flexibility that they provide. Unfortunately this also means there are so many variables that it's almost impossible to answer questions directly unless you know all of the details, which we don't here. Hopefully this will give you a better starting point than staring at a debugger window.
To make sure you do NOT use dynamic memory allocation, you can override the global new operator so that it always throws an exception. Then run unit tests against all your use of the library functions you want to use.
You may need help from the linker to avoid use of malloc and free as technically you can't override them.
Note: This would be in the test environment. You are simply validating that your code does not use dynamic allocation. Once you have done that validation, you don't need the override anymore so it would not be in place in the production code.
Are you sure you want to avoid them?
Sure, you don't want to use dynamic memory management that is designed for generic systems. That would definitely be a bad idea.
BUT does the tool chain you use not come with an implementation that is specific to your hardware that does an intelligent job for that hardware? or have some special ways to compile that allows you to use only a known piece of memory that you have pre-sized and aligned for the data area.
Moving to containers. Most STL containers allow you to specialize them with an allocator. You can write your own allocator that does not use dynamic memory.
Generally you can check (suitably thorough) documentation to see whether the function (e.g., a constructor) can throw std::bad_alloc. (The inverse is often phrased as noexcept, since that exception is often the only one risked by an operation.) There is the exception of std::inplace_merge, which becomes slower rather than throwing if allocation fails.
The gcc linker supports a -Map option which will generate a link map with all the symbols in your executable. If anything in your application does dynamic memory allocation unintentionally, you will find a section with *alloc and free functions.
If you start with a program with no allocation, you can check the map after every compile to see if you have introduced one through the library function calls.
I used this method to identify an unexpected dynamic allocation introduced by using a VLA.

Finding memory leaks in MFC C++ release build without 3rd party tools/projects

I have a simple question:
How can I trace memory leaks in a VS 2010 MFC C++ project?
For debug builds there is the possibility described here.
What is the solution for release build without having to use 3rd party tools/projects?
The only solution is to override memory allocation operators (new and delete) yourself; these operators may log any memory allocation and deallocation to some kind of log, so you'll cal analyze this log later. You can see details here: Overriding memory allocation method standard libraries use?
However, this will affect speed terribly.
I am not sure it is possible to override free and malloc functions also. You can use #define to replace standard free and malloc in your own code, but I am not sure it is possible for your library dependencies, so your memory allocation/deallocation log may miss data allocated by library dependencies. Of course, you can rebuild all libraries with your own memory management functions.
I have tried to use MFC memory leak tools, but they only work in Debug. I have tried to use various tool apps like deleaker, but it is expensive. There are also free tools on GitHub, but the one I have tried was out of date (code unmaintained) which cost a bunch of time to configure and set up and just wasn't worth it.
Believe it or not, the best "tool" I have found is program component isolation through iterative compiling. Simply walk through your code, and disable/comment out code, from large to small. In other words, you comment out all the code, there is no leak, etc etc. Recompile and let the leak dump tell you if there is a leak or not. You can do this until the erring code jumps out at you. It is surprisingly effective. Sometimes the simplest solution is the best.
I assume you have a way of detecting leaks in Release mode, so this approach could work for that as well. I don't remember if Release MFC has leak dump or not. Maybe someone else knows this off the top of their head.

Overloading malloc to track memory usage of third party libraries [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Best strategy for profiling memory usage of my code (open source) and 3rd party code(closed source)
I am thinking of implementing a memory tracking tool to track malloc's in my code by having a library that I will link in at compile time to override malloc with a macro to add some additional debugging info that will print some stuff to a log. Is it possible to possibly do this with a third party library that I do not have source code, or possibly debug libraries available? Can you link in a library like I am talking about to a third party library and it will use the methods (or macros) defined in my library?
Thanks
I don't think you can do that, malloc is a system call.
The binary libraries aren't actually calling malloc(), they're loading a library stored on your machine into memory. Then executing the function at the correct memory address.
Redefining malloc() wont do anything except confuse things.
Use profiler: AQTime is a really good one for Visual Studio.
It depends on what platform / OS you are trying to do that on:
If you are using a RTOS on embedded device, you may be able to change the code directly in there too...
If you are on Linux, you may be able to find the code somewhere and change it there to recompile, but you may have a pretty serious performance impact on your platform.
For others, you can use a wrapper in your application, call it "os_malloc" or something like that and implement that function for any debugging or anything like that.
The last one is probably your safest bet no matter what...

How do you detect/avoid Memory leaks in your (Unmanaged) code? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
In unmanaged C/C++ code, what are the best practices to detect memory leaks? And coding guidelines to avoid? (As if it's that simple ;)
We have used a bit of a silly way in the past: having a counter increment for every memory allocation call and decrement while freeing. At the end of the program, the counter value should be zero.
I know this is not a great way and there are a few catches. (For instance, if you are freeing memory which was allocated by a platform API call, your allocation count will not exactly match your freeing count. Of course, then we incremented the counter when calling API calls that allocated memory.)
I am expecting your experiences, suggestions and maybe some references to tools which simplify this.
If your C/C++ code is portable to *nix, few things are better than Valgrind.
If you are using Visual Studio, Microsoft provides some useful functions for detecting and debugging memory leaks.
I would start with this article:
https://msdn.microsoft.com/en-us/library/x98tx3cf(v=vs.140).aspx
Here is the quick summary of those articles. First, include these headers:
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
Then you need to call this when your program exits:
_CrtDumpMemoryLeaks();
Alternatively, if your program does not exit in the same place every time, you can call this at the start of your program:
_CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF );
Now when the program exits all the allocations that were not free'd will be printed in the Output Window along with the file they were allocated in and the allocation occurrence.
This strategy works for most programs. However, it becomes difficult or impossible in certain cases. Using third party libraries that do some initialization on startup may cause other objects to appear in the memory dump and can make tracking down your leaks difficult. Also, if any of your classes have members with the same name as any of the memory allocation routines( such as malloc ), the CRT debug macros will cause problems.
There are other techniques explained in the MSDN link referenced above that could be used as well.
In C++: use RAII. Smart pointers like std::unique_ptr, std::shared_ptr, std::weak_ptr are your friends.
As a C++ Developer here's some simply guidelines:
Use pointers only when absolutely necessary
If you need a pointer, doublecheck if a SmartPointer is a possibility
Use the GRASP Creator pattern.
As for the detection of memory leaks personally I've always used Visual Leak Detector and find it to be very useful.
I've been using DevStudio for far too many years now and it always amazes me just how many programmers don't know about the memory analysis tools that are available in the debug run time libraries. Here's a few links to get started with:
Tracking Heap Allocation Requests - specifically the section on Unique Allocation Request Numbers
_CrtSetDbgFlag
_CrtSetBreakAlloc
Of course, if you're not using DevStudio then this won't be particularly helpful.
I’m amazed no one mentioned DebugDiag for Windows OS.
It works on release builds, and even at the customer site.
(You just need to keep your release version PDBs, and configure DebugDiag to use Microsoft public symbol server)
Visual Leak Detector is a very good tool, altough it does not supports the calls on VC9 runtimes (MSVCR90D.DLL for example).
Microsoft VC++ in debug mode shows memory leaks, although it doesn't show where your leaks are.
If you are using C++ you can always avoid using new explicitly: you have vector, string, auto_ptr (pre C++11; replaced by unique_ptr in C++11), unique_ptr (C++11) and shared_ptr (C++11) in your arsenal.
When new is unavoidable, try to hide it in a constructor (and hide delete in a destructor); the same works for 3rd party APIs.
There are various replacement "malloc" libraries out there that will allow you to call a function at the end and it will tell you about all the unfreed memory, and in many cases, who malloced (or new'ed) it in the first place.
If you're using MS VC++, I can highly recommend this free tool from the codeproject:
leakfinder by Jochen Kalmbach.
You simply add the class to your project, and call
InitAllocCheck(ACOutput_XML)
DeInitAllocCheck()
before and after the code you want to check for leaks.
Once you've build and run the code, Jochen provides a neat GUI tool where you can load the resulting .xmlleaks file, and navigate through the call stack where each leak was generated to hunt down the offending line of code.
Rational's (now owned by IBM) PurifyPlus illustrates leaks in a similar fashion, but I find the leakfinder tool actually easier to use, with the bonus of it not costing several thousand dollars!
Never used it myself, but my C friends tell me Purify.
If you're using Visual Studio it might be worth looking at Bounds Checker. It's not free, but it's been incredibly helpful in finding leaks in my code. It doesn't just do memory leaks either, but also GDI resource leaks, WinAPI usage errors, and other stuff. It'll even show you where the leaked memory was initialized, making it much easier to track down the leak.
I think that there is no easy answer to this question. How you might really approach this solution depends on your requirements. Do you need a cross platform solution? Are you using new/delete or malloc/free (or both)? Are you really looking for just "leaks" or do you want better protection, such as detecting buffer overruns (or underruns)?
If you are working on the windows side, the MS debug runtime libraries have some basic debug detection functionality, and as another has already pointed out, there are several wrappers that can be included in your source to help with leak detection. Finding a package that can work with both new/delete and malloc/free obviously gives you more flexibility.
I don't know enough about the unix side to provide help, although again, others have.
But beyond just leak detection, there is the notion of detecting memory corruption via buffer overruns (or underruns). This type of debug functionality is I think more difficult than plain leak detection. This type of system is also further complicated if you are working with C++ objects because polymorhpic classes can be deleted in varying ways causing trickiness in determining the true base pointer that is being deleted. I know of no good "free" system that does decent protection for overruns. we have written a system (cross platform) and found it to be pretty challenging.
I'd like to offer something I've used at times in the past: a rudimentary leak checker which is source level and fairly automatic.
I'm giving this away for three reasons:
You might find it useful.
Though it's a bit krufty, I don't let that embarass me.
Even though it's tied to some win32 hooks, that should be easy to alleviate.
There are things of which you must be careful when using it: don't do anything that needs to lean on new in the underlying code, beware of the warnings about cases it might miss at the top of leakcheck.cpp, realize that if you turn on (and fix any issues with) the code that does image dumps, you may generate a huge file.
The design is meant to allow you to turn the checker on and off without recompiling everything that includes its header. Include leakcheck.h where you want to track checking and rebuild once. Thereafter, compile leakcheck.cpp with or without LEAKCHECK #define'd and then relink to turn it on and off. Including unleakcheck.h will turn it off locally in a file. Two macros are provided: CLEARALLOCINFO() will avoid reporting the same file and line inappropriately when you traverse allocating code that didn't include leakcheck.h. ALLOCFENCE() just drops a line in the generated report without doing any allocation.
Again, please realize that I haven't used this in a while and you may have to work with it a bit. I'm dropping it in to illustrate the idea. If there turns out to be sufficient interest, I'd be willing to work up an example, updating the code in the process, and replace the contents of the following URL with something nicer that includes a decently syntax-colored listing.
You can find it here: http://www.cse.ucsd.edu/~tkammeye/leakcheck.html
For Linux:
Try Google Perftools
There are a lot of tools that do similar alloc/free counting, the pros of Goolge Perftools:
Quite fast (in comparison to valgrind: very fast)
Comes with nice graphical display of results
Has other useful capabilities: cpu-profiling, memory-usage profiling...
The best defense against leaks is a program structure which minimizes the use of malloc. This is not only good from a programming perspective, but also improves performance and maintainability. I'm not talking about using other things in place of malloc, but in terms of re-using objects and keeping very explicit tabs on all objects being passed around rather than allocating willy-nilly like one often gets used to in languages with garbage collectors like Java.
For example, a program I work on has a bunch of frame objects representing image data. Each frame object has sub-data, which the frame's destructor frees. The program keeps a list of all frames that are allocated, and when it needs a new one, checks a list of unused frame objects to see if it can re-use an existing one rather than allocate a new one. On shutdown, it just iterates through the list, freeing everything.
I would recommend using Memory Validator from software verify.
This tool proved itself to be of invaluable help to help me track down memory leaks and to improve the memory management of the applications i am working on.
A very complete and fast tool.
Are you counting the allocs and frees by interpolating your own syscall functions which record the calls and then pass the call to the real function?
This is the only way you can keep track of calls originating from code that you haven't written.
Have a look at the man page for ld.so. Or ld.so.1 on some systems.
Also do Google LD_PRELOAD and you'll find some interesting articles explaining the technique over on www.itworld.com.
At least for MS VC++, the C Runtime library has several functions that I've found helpful in the past. Check the MSDN help for the _Crt* functions.
Paul Nettle's mmgr is a long time favourite tool of mine. You include mmgr.h in your source files, define TEST_MEMORY, and it delivers a textfile full of memory problems that occurred during a run of your app.
General Coding Guideline:
Resources should be deallocated at the same "layer" (function/class/library) where they are allocated.
If this is not possible, try to use some automatic deallocation (boost shared pointer...)
Memory debugging tools are worth their weight in gold but over the years I've found that two simple ideas can be used to prevent most memory/resource leaks from being coded in the first place.
Write release code immediatly after writing the acquisition code for the resources you want to allocate. With this method its harder to "forget" and in some sense forces one to seriously think of the lifecycle of resources being used upfront instead of as an aside.
Use return as sparringly as possible. What is allocated should only be freed in one place if possible. The conditional path between acquisition of resource and release should be designed to be as simple and obvious as possible.
At the top of this list (when I read it) was valgrind. Valgrind is excellent if you are able to reproduce the leak on a test system. I've used it with great success.
What if you've just noticed that the production system is leaking right now and you have no idea how to reproduce it in test? Some evidence of what's wrong is captured in the state of that production system, and it might be enough to provide an insight on where the problem is so you can reproduce it.
That's where Monte Carlo sampling comes into the picture. Read Raymond Chen's blog article,
“The poor man's way of identifying memory leaks” and then check out my implementation (assumes Linux, tested only on x86 and x86-64)
http://github.com/tialaramex/leakdice/tree/master
Working on Motorola cell phones operating system, we hijacked memory allocation library to observe all memory allocations. It helped to find a lot of problems with memory allocations.
Since prevention is better then curing, I would recommend to use static analysis tool like Klockwork or PC-Lint
Valgrind is a nice option for Linux. Under MacOS X, you can enable the MallocDebug library which has several options for debugging memory allocation problems (see the malloc manpage, the "ENVIRONMENT" section has the relevant details). The OS X SDK also includes a tool called MallocDebug (usually installed in /Developer/Applications/Performance Tools/) that can help you to monitor usage and leaks.
Detect:
Debug CRT
Avoid:
Smart pointers, boehm GC
A nice malloc, calloc and reallloc replacement is rmdebug, it's pretty simple to use. It is much faster to then valgrind, so you can test your code extensively. Of course it has some downsides, once you found a leak you probably still need to use valgrind to find where the leak appears and you can only test mallocs that you do directly. If a lib leaks because you use it wrong, rmdebug won't find it.
http://www.hexco.de/rmdebug/
Most memory profilers slow my large complex Windows application to the point where the results are useless. There is one tool that works well for finding leaks in my application: UMDH - http://msdn.microsoft.com/en-us/library/ff560206%28VS.85%29.aspx
Mtrace appears to be the standard built-in one for linux. The steps are :
set up the environment variable MALLOC_TRACE in bash
MALLOC_TRACE=/tmp/mtrace.dat
export MALLOC_TRACE;
Add #include <mcheck.h> to the top of you main source file
Add mtrace(); at the start of main and muntrace(); at the bottom (before the return statement)
compile your program with the -g switch for debug information
run your program
display leak info with mtrace your_prog_exe_name /tmp/mtrace.dat
(I had to install the mtrace perl script first on my fedora system with yum install glibc_utils )