Crash in windows XP with very simple gtk+cairo program - c++

I am developing a Gtk application using gtkmm on Windows Vista with Visual Studio 2005. The application works fine on the development machine but I have received crash reports after it has been run on Windows XP machines (both Service Pack 2 and 3). I distribute the app with the directory structure described in http://live.gnome.org/gtkmm/MSWindows and it had given me no problems so far.
The crash gives no error messages except for Windows asking whether I want to report the error.
In order to solve the problem, I tried to compile the program against different versions of gtkmm (a recent stable version gtkmm-win32-devel-2.16.0-4 and an older version gtkmm-win32-devel-2.10.11-1) but the problem persisted.
I hunted down the problem to a call to window->create_cairo_context() inside the on_expose_event of a Gtk::DrawingArea. When I commented out this call, the problem would disappear. So I wrote the following minimal program, which still crashes:
#include <gtkmm.h>
#include <iostream>
class MyWindow : public Gtk::Window {
bool on_expose_event(GdkEventExpose* event) {
std::cout << "expose" << std::endl;
Glib::RefPtr<Gdk::Window> window = get_window();
if(window) {
std::cout << "win" << std::endl;
std::cout << "Get cairo" << std::endl;
Cairo::RefPtr<Cairo::Context> cr = window->create_cairo_context();
std::cout << "Get cairo done" << std::endl;
} else {
std::cout << "no win" << std::endl;
}
return true;
}
};
int main (int argc, char *argv[]) {
Gtk::Main m(argc,argv);
MyWindow w;
m.run(w);
return 0;
}
This minimal app may run and display the window without problem, but if I move the window off the screen limits or if I minimize/maximize it enough times (thus triggering calls to on_expose_event), it will eventually crash. It may also be the case that it won't crash the first time, but it will crash after restarting the app and triggering multiple calls to on_expose_event as described above. One thing I've noticed is that the app crashes after printing "Get cairo done". When I comment out the call to create_cairo_context, the problem dissapears, so I'm pretty sure there is something wrong with this line.
The error happens on clean installed Windows XP machines. I have tested both apps (original and minimal) on a colleague's notebook, which also has Windows XP, but it doesn't crash there. I suppose there is some dependency that is available/up to date in our computers but not in the computers where the application crashes. I have updated DirectX and installed Visual Studio C++ 2005 Redistributable on one of the problematic machines, but the problem persists.
The original app, which draws a graph on the DrawingArea, doesn't necessarily crash the first time either. It may work fine the first time after rebooting, but is more prone to fail the second time.
I am thinking about compiling and testing with MinGW to see if that solves the problem. I'll also try to compile a debug version and try to use a debugger. I have suspected the version of gdi32.dll might have something to do, seeing that libcairo-2.dll depends on this dll according to Dependency Walker, but until now it's just an speculation. Other than that, I'm out of ideas.
I'll be trying these ideas for the time being. Hopefully someone has more suggestions or knows what is going on with the code above.

Related

Syntax for BluetoothLEDevice::RequestPreferredConnectionParameters()

Using C++/WinRT, Win10, VS2019, SDK 10.0.22621.0, NuGet CppWinRT 2.0.220608.4
I'm trying to get the RequestPreferredConnectionParameters to work. At this point I am wondering if maybe I have the syntax wrong or maybe something else about it that I am not aware of. The MS docs for the function are here and the link to the various parameters are here.
The command line, as I have it, with pubDevice being the BLE device object, is:
BluetoothLEPreferredConnectionParametersRequest rcoConnect = pubDevice.RequestPreferredConnectionParameters(BluetoothLEPreferredConnectionParameters::ThroughputOptimized());
Just to mention, I am able to run
auto statusTest = co_await pubDevice.RequestAccessAsync();
before the RequestPreferredConnectionParameters without problems so, obviously, the device object is good and can be connected to.
What is happening is this. I have a function, OpenDevice(), that opens the device based on the address. If, after getting the device object, I issue the command above while still in the OpenDevice function, the code will not crash but it will immediately jump to the end of the OpenDevice() function bypassing all other lines of code below it and there will be no connection at all after that.
If I run the RequestPreferredConnectionParameters outside of the OpenDevice() function it errors out with a
An unhandled exception was encountered during a user callback and the line referenced is in base.h line 4942 if (result == impl::error_changed_state)
I had assumed that the callback refered to was the Rx Characteristic ValueChanged Callback that is set in OpenDevice(). So I tested by first revoking that callback with
pubRxCharacteristic.ValueChanged(etValueChangeToken);
and then running the RequestPreferredConnectionParameters but I still got the An unhandled exception error.
The only other callback that I have is the BluetoothLEAdvertisementWatcher advert received callback but that was stopped after the device was found.
Can anyone verify that my syntax seems correct and/or have any clue as to what is causing my problems?
EDIT to show more code in a console app------------
#IInspectable
Again for the record:
Using C++/WinRT, Win10, VS2019 - Console App, SDK 10.0.22621.0, NuGet CppWinRT 2.0.220608.4
Pertinent includes in the pch.h file:
// 2022/9/10 -- for WHCAR and apparently GUID
#include <Windows.h>
#include <tchar.h>
#include <winrt\Windows.Foundation.h>
#include <winrt\Windows.Storage.Streams.h>
#include <winrt\Windows.Devices.Bluetooth.h>
#include <winrt\Windows.Devices.Bluetooth.Advertisement.h>
#include <winrt\Windows.Devices.Bluetooth.GenericAttributeProfile.h>
// 2022/9/10
#include <winrt\Windows.Devices.Enumeration.h>
#include <winrt/Windows.Foundation.Collections.h>
Pertinent name spaces at top of Main.cpp:
using namespace winrt;
using namespace Windows::Foundation;
using namespace winrt::Windows::Foundation;
using namespace Windows::Storage::Streams;
using namespace Windows::Devices::Bluetooth;
using namespace Windows::Foundation::Collections;
using namespace Windows::Devices::Bluetooth::Advertisement;
using namespace Windows::Devices::Bluetooth::GenericAttributeProfile;
// 2022/9/10 for RequestConnectionAsync
using namespace Windows::Devices::Enumeration;
I assume that the code to watch for and find the device is not pertinent here. Needless to say the device is found and the address is passed to OpenDevice to create the device object.
Here is the top portion of OpenDevice:
IAsyncAction OpenDevice(unsigned long long deviceAddress)
{
auto device = co_await BluetoothLEDevice::FromBluetoothAddressAsync(deviceAddress);
// 2022/9/10 test code
auto statusTest = co_await device.RequestAccessAsync();
// Allowed, DeniedBySystem, Unspecified
if (statusTest != DeviceAccessStatus::Allowed) {
std::cout << "Access to device is not allowed...." << std::endl;
}
else {
std::cout << "Access to device is allowed...." << std::endl;
}
// Next line ends without error but immediately goes to the end of OpenDevice()
std::cout << "Asking for ThroughputOptimized...." << std::endl;
auto statusConnection = device.RequestPreferredConnectionParameters(BluetoothLEPreferredConnectionParameters::ThroughputOptimized());
std::cout << "Line after Request ThroughputOptimized...." << std::endl;
Beep(500, 500);<br/> // function never gets to this cout or Beep<br/>
// More code follows to get Rx and TxCharacteristics etc.<br/>
} // end OpenDevice
Here is the console output:
Notice the last cout is the line Asking for ThroughputOptimized.
No cout for Line after Request ThroughputOptimized and no Beep.
Trying to locate the TENS device: Waiting for device:
AdvertisementReceived:
LocalName: []
AdvertisementType: [ConnectableUndirected]
BluetoothAddress: [0x300000e59630]
RawSignalStrengthInDBm: [-60] ServiceUUID: [0000fff0-0000-1000-8000-00805f9b34fb] Found TENS Device Main
Service.... TENS device found. Access to device is
allowed.... Asking for ThroughputOptimized....
WinRTBle.exe (process 15576) exited with code -1073740791. Press
any key to close this window .
Barring a problem in syntax or a missing header. the only other thing that I can think of is that it needs Win11. The docs for RequestPreferredConnectionParameters Method say
Windows requirements Device family Windows 11 (introduced in
10.0.22000.0)
Does that mean that regardless of the SDK it needs Win11?
#IInspectable As much as I was dreading this, apparently the answer is that it needs Win11. The console app code mentioned above in the edit to the original question was compiled into an exe. I have Win11 on a VM VirtualBox and I ran that exe on that Win11 and the code continued past the ThroughputOptimized() line in question and finished the rest of the app as expected. So that's ashamed. I don't have Win11 on a real box yet (call me paranoid) but I guess I could bracket the code for the Win11 OS and only run it when a user happens to be running Win11
Always something.......
EDIT 2 ...............................
And the "Always something" comes up immediately. As far as I can tell from what I have been able to find, there is no way to tell if the OS is Win10 or Win11. It was recommended to use RtlGetVersion but that returned 10 for both Win10 and Win11. Another poster suggested to use the File version of the System32 kernal32.dll file but they also both reported major number 10 and minor number 0. The MS docs for adding a version manifest had the UUIDs for both OSs as the same.
This is ridiculous that MS would come up with a function that only runs in Win11 and then not have to ability to tell you which OS you are running in....Jeeeeeeze.....
EDIT 3.........................
Spoke too soon. I was messing around with the console app and forgot that in my MFC app I use the WMI IWbemClassObject Caption property to get the OS.
For Windows 10 I get
Microsoft Windows 10 Pro
and for Win11 I get
Microsoft Windows 11 Home
So apparently that is really the only way to do it.

c++ (on Clion) for loop stops in the middle with no errors (exit code 0) [duplicate]

When using CLion I have found the output sometimes cuts off.
For example when running the code:
main.cpp
#include <stdio.h>
int main() {
int i;
for (i = 0; i < 1000; i++) {
printf("%d\n", i);
}
fflush(stdout); // Shouldn't be needed as each line ends with "\n"
return 0;
}
Expected Output
The expected output is obviously the numbers 0-999 on each on a new line
Actual Output
After executing the code multiple times within CLion, the output often changes:
Sometimes it executes perfectly and shows all the numbers 0-999
Sometimes it cuts off at different points (e.g. 0-840)
Sometimes it doesn't output anything
The return code is always 0!
Screenshot
Running the code in a terminal (i.e. not in CLion itself)
However, the code outputs the numbers 0-999 perfectly when compiling and running the code using the terminal.
I have spent so much time on this thinking it was a problem with my code and a memory issue until I finally realised that this was just an issue with CLion.
OS: Ubuntu 14.04 LTS
Version: 2016.1
Build: #CL-145.258
Update
A suitable workaround is to run the code in debug mode (thanks to #olaf).
The consensus is that this is an IDE issue. Therefore, I have reported the bug.
A suitable workaround is to execute the code in debug mode (no breakpoint required).
I will update this question, as soon as this bug is fixed.
Update 1
WARNING: You should not change information in registry unless you have been asked specifically by JetBrains. Registry is not in the main menu for a reason! Use the following solution at your own risk!!!
JetBrains have contacted me and provided a suitable solution:
Go to the Find Action Dialog box (CTRL+SHIFT+A)
Search for "Registry..."
Untick run.processes.with.pty
Should then work fine!
Update 2
The bug has been added here:
https://youtrack.jetbrains.com/issue/CPP-6254
Feel free to upvote it!

Qlist<QCameraInfo> causes access violation in QList destructor

I am writing a video grabbing application in c++ using Qt5. I am following their example code and looking at the documentation for getting the camera info:
http://doc.qt.io/qt-5/qcamerainfo.html
The problem I have is that after I use the prescribed technique for getting camera data (which works perfectly):
QList<QCameraInfo>cameraInfos = QCameraInfo::availableCameras();
I get an Access violation error whenever cameraInfos goes out of scope.
For example, if I do:
void readDeviceInfo(void) {
// Camera devices:
QList<QCameraInfo>cameraInfos = QCameraInfo::availableCameras()
for (QList<QCameraInfo>::Iterator it = cameraInfos.begin();
it != cameraInfos.end(); ++it)
std::cout << it->description().toStdString().c_str() << std::endl;
}
The crash occurs on the return of this function. If I do:
foreach(const QCameraInfo &ci, QCameraInfo::availableCameras());
The crash occurs in the evaluation of the foreach loop. Likewise, if I declare QList<QCameraInfo> cameraInfos as a field in a class, the crash happens when the class is destroyed. This is verified by the output of my call stack:
ntdll.dll!000000007750eef1() Unknown
kernel32.dll!00000000773c1a0a() Unknown
> VideoCapture.exe!free(void * pBlock) Line 51 C
VideoCapture.exe!QCameraInfo::`scalar deleting destructor'(unsigned int) C++
VideoCapture.exe!QList<QCameraInfo>::node_destruct(QList<QCameraInfo>::Node * from, QList<QCameraInfo>::Node * to) Line 484 C++
VideoCapture.exe!QList<QCameraInfo>::dealloc(QListData::Data * data) Line 857 C++
VideoCapture.exe!QList<QCameraInfo>::~QList<QCameraInfo>() Line 817 C++
I am using Visual Studio 2013 (windows obviously).
You need to compile Qt yourself, then run your test case under a debugger and see where it crashes. You also need a minimal, self-contained test case for this - and that must be the part of the question (SSCCE). As it is, it's more likely that you're corrupting memory elsewhere and the failure you're seeing is the outcome of a corrupted heap, not a Qt bug.
Sidebar: You need to be proficient in running small examples in Qt Creator. Arguably, the templates Qt Creator comes with aren't very good for that. You can use this template, available as Other Projects->Simple qmake, to make quick prototypes.
The following works fine for me with 1 camera on current Qt on both OS X 10.9 and Windows 10/VS 2015. The std::cout you're using is red herring, you can use qDebug() as well.
// https://github.com/KubaO/stackoverflown/tree/master/questions/camlist-37603946
#include <QtWidgets>
#include <QtMultimedia>
int main(int argc, char ** argv) {
QApplication app{argc, argv};
QComboBox combo;
QObject::connect(&combo, &QComboBox::currentTextChanged, [&]{
std::cout << combo.currentText().toStdString() << std::endl;
});
for (auto const & info : QCameraInfo::availableCameras())
combo.addItem(info.description());
combo.show();
return app.exec();
}
So after following Kuba's advice and running his test program in my environment with a freshly built Qt library, I got the same errors. Then I had the bright idea to run it in release mode rather than debug. Lo and behold, it worked perfectly, with both the freshly built Qt5 (x86, as it happened) and the pre-built binaries (64 bit) gotten from Qt's downloads page.
It seems that linking to the qt debug libraries was causing this behavior. I'm now linking to the non-debug libraries in debug mode and am nice and happy -- for the most part -- I am still a little annoyed that the qt libs suffixed with 'd' don't seem to work properly on my system. Nevertheless, I can move on with developing this project.
Thanks to all that commented and answered!

C++ Very Sleepy strange results

I'm currently programming an SDL Network Game, everything is perfect ... But my game only runs at 30fps, so I ran a Very Sleepy analysis.
First strange effect, very sleepy increase the perfs of my Game to 60Fps ... ( Why ? )
And secondly, there is a lot of SDL_LogCritical calls ( you can get the report here : http://puu.sh/gauEi/9a852462e6.png ). And nothing is shown in the console.
( I also use SDLNet, with TCP protocol, there is no packet loose ).
Moreover, I overwritten the output for SDL Logs :
void log(void* userdata, int category, SDL_LogPriority priority, const char* message) {
std::cout << "Log : " << message << std::endl;
}
int main(int argc, char **argv) {
SDL_Init(SDL_INIT_EVERYTHING);
SDLNet_Init();
SDL_LogSetOutputFunction(log, NULL);
SDL_LogCritical(1, "TEST LOG");
}
And I can see the "TEST LOG" in the console. So the SDL_LogCritical which consumme 30% doesn't output everything .
I don't know what's wrong, but frequent calls to a logging function indicate that something is wrong and SDL tries to tell you about it. However, the lack of output might be caused by you explicitely or implicitely disable logging to the console. Your use of Network might indicate your not looking at the right console to see these warnings. It's all a bit hard to diagnose with the lack of information given.
Performance increase due to debugging is strange, but can often be explained by the fact that the debugger doesn't use exactly the same environment as you do when running normally.
OK, so you're not seeing output when something else calls SDL's log functionality. This points to the messages being logged somehow being below necessary priority. Compare SDL's source code to find out how that could be happening. Maybe you should, at this point, use a debugger to set breakpoints.

Make main() "uncrashable"

I want to program a daemon-manager that takes care that all daemons are running, like so (simplified pseudocode):
void watchMe(filename)
{
while (true)
{
system(filename); //freezes as long as filename runs
//oh, filename must be crashed. Nevermind, will be restarted
}
}
int main()
{
_beginThread(watchMe, "foo.exe");
_beginThread(watchMe, "bar.exe");
}
This part is already working - but now I am facing the problem that when an observed application - say foo.exe - crashes, the corresponding system-call freezes until I confirm this beautiful message box:
This makes the daemon useless.
What I think might be a solution is to make the main() of the observed programs (which I control) "uncrashable" so they are shutting down gracefully without showing this ugly message box.
Like so:
try
{
char *p = NULL;
*p = 123; //nice null pointer exception
}
catch (...)
{
cout << "Caught Exception. Terminating gracefully" << endl;
return 0;
}
But this doesn't work as it still produces this error message:
("Untreated exception ... Write access violation ...")
I've tried SetUnhandledExceptionFilter and all other stuff, but without effect.
Any help would be highly appreciated.
Greets
This seems more like a SEH exception than a C++ exception, and needs to be handled differently, try the following code:
__try
{
char *p = NULL;
*p = 123; //nice null pointer exception
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ?
EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
{
cout << "Caught Exception. Terminating gracefully" << endl;
return 0;
}
But thats a remedy and not a cure, you might have better luck running the processes within a sandbox.
You can change the /EHsc to /EHa flag in your compiler command line (Properties/ C/C++ / Code Generation/ Enable C++ exceptions).
See this for a similar question on SO.
You can run the watched process a-synchronously, and use kernel objects to communicate with it. For instance, you can:
Create a named event.
Start the target process.
Wait on the created event
In the target process, when the crash is encountered, open the named event, and set it.
This way, your monitor will continue to run as soon as the crash is encountered in the watched process, even if the watched process has not ended yet.
BTW, you might be able to control the appearance of the first error message using drwtsn32 (or whatever is used in Win7), and I'm not sure, but the second error message might only appear in debug builds. Building in release mode might make it easier for you, though the most important thing, IMHO, is solving the cause of the crashes in the first place - which will be easier in debug builds.
I did this a long time ago (in the 90s, on NT4). I don't expect the principles to have changed.
The basic approach is once you have started the process to inject a DLL that duplicates the functionality of UnhandledExceptionFilter() from KERNEL32.DLL. Rummaging around my old code, I see that I patched GetProcAddress, LoadLibraryA, LoadLibraryW, LoadLibraryExA, LoadLibraryExW and UnhandledExceptionFilter.
The hooking of the LoadLibrary* functions dealt with making sure the patching was present for all modules. The revised GetProcAddress had provide addresses of the patched versions of the functions rather than the KERNEL32.DLL versions.
And, of course, the UnhandledExceptionFilter() replacement does what you want. For example, start a just in time debugger to take a process dump (core dumps are implemented in user mode on NT and successors) and then kill the process.
My implementation had the patched functions implemented with __declspec(naked), and dealt with all the registered by hand because the compiler can destroy the contents of some registers that callers from assembly might not expect to be destroyed.
Of course there was a bunch more detail, but that is the essential outline.