Unhandled Exception at KernelBase.dll when Invoking my CLR Project - c++

I get this exception:
Unhandled exception at 0x75374B32 (KernelBase.dll) in
LogLoaderUnmanaged.exe: 0xE0434352 (parameters: 0x80070002,
0x00000000, 0x00000000, 0x00000000, 0x74040000).
When I call my CLR project using this code (part of an Application .exe type project):
int _tmain(int argc, _TCHAR* argv[])
{
_tprintf_s(_T("Press enter to start logging messages."));
_getch();
std::string app("Application");
std::string domain("Domain");
std::string message("Message");
UnmanagedLoggerClient::LogError(Debug, app.c_str(), domain.c_str(), message.c_str());
_tprintf_s(_T("Done."));
}
The error is at the call to LogError, which is defined in my CLR DLL's header as follows:
#ifdef UNMANAGEDLOGGERCLIENT_EXPORTS
#define WIN32PROJECT_API __declspec(dllexport)
#else
#define WIN32PROJECT_API __declspec(dllimport)
#endif
enum UnmanagedLogLevel
{
Debug = 0,
Error = 1
};
static class WIN32PROJECT_API UnmanagedLoggerClient
{
public:
static void LogError (UnmanagedLogLevel level, const char* app, const char* domain, const char* message);
};
In the implementation the method is pretty straightforward:
void UnmanagedLoggerClient::LogError(UnmanagedLogLevel level, const char* app, const char* domain, const char* message)
{
LoggerClient::LogLevel logLevel = static_cast<LoggerClient::LogLevel>(level);
LoggerClient::Logger::LogError(logLevel, gcnew String(app), gcnew String(domain), gcnew String(message), DateTime::Now);
}
Any ideas why this happens? I'm not really much of a C++ guy and I haven't found any useful information searching for this problem online. Many thanks for any input!

You are using a very brittle way to get the CLR initialized, diagnostics are therefore poor. There's a "File not found" error code visible in your exception diagnostic, error code 0x80070002.
You managed to start the CLR, the exception code is a managed exception, but it could not find a file. Make sure all executables are present in the same directory as your EXE. Use SysInternals' ProcMon if that doesn't help, you'll see it searching for a file and not finding it.

Related

C++ bit7z : Exception thrown at ... in ... Microsoft C++ exception: bit7z::BitException at memory location 0x001AF440 & paths of directory and files

I'm trying to create a program that, on execution, zips a given directory. Most of my errors have been resolved and I am hopefully getting to the end of this, but I still have the issue of an exception being thrown and a question regarding the program. I code in C++20 and on Visual Studio 2019.
I've come across this exact error when debugging the program:
Exception thrown at 0x76820B42 in aixLogger.exe: Microsoft C++ exception: bit7z::BitException at memory location 0x001AF440.
I already checked with a breakpoint what code is giving me this error:
catch (const BitException& ex) {
ex.what(); //<-
}
The code runs otherwise and isn't giving me any error messages, the breakpoint activates on the line I marked with an arrow (not actually part of my code).
To eliminate further possible edits I will add the rest of my code as well:
main.cpp
#include <QCoreApplication>
#include <string>
#include <iostream>
#include <filesystem>
#include <bit7z.hpp>
#include "main.h"
#include <bitcompressor.hpp>
namespace fs = std::filesystem;
using namespace bit7z;
using namespace std;
int main(int argc, char* argv[])
{
QCoreApplication a(argc, argv);
try {
Bit7zLibrary lib{ L"7z.dll" };
BitCompressor compressor{ lib, BitFormat::Zip };
//vector< wstring > files = { L"aretz/Downloads/test" };
wstring dir = { L"D: / local / aretz / Programmierung / git - workplace / aixLogger / test /" } ;
wstring zip = { L"zippedtest.zip" };
compressor.compressDirectory(dir, zip);
}
catch (const BitException& ex) {
ex.what();
}
return a.exec();
}
void AIXLogger::CompressDir() {
/*try {
Bit7zLibrary lib{ L"7z.dll" };
BitCompressor compressor{ lib, BitFormat::Zip };
vector< wstring > files = { L"C:/Users/aretz/Downloads/test" };
wstring zip = { L"zippedtest.zip" };
compressor.compressFiles(files, zip);
}
catch (const BitException& ex) {
ex;
}*/
}
main.h
#pragma once
#include <qwidget.h>
#include <qobject.h>
#include <bit7z.hpp>
class AIXLogger : public QWidget
{
Q_OBJECT
public slots:
public:
void CompressDir();
};
I've currently commented out the function CompressDir() as I can't call it in my main since it gives me either a syntax error or tells me the identifier is undefined.
Syntax Error:
AIXLogger.CompressDir(); the dot is marked as the error
identifier is undefined:
CompressDir();
I don't know what exactly is causing the catch to thrown an exception. From other posts I suspected that my paths for the files and directories are at fault, but changing them or moving my test directory didn't help at all. Removing the try and catch lines from my codeblock only adds the same error message where Exception Thrown is being replaced by Unhandled Exception. Thanks to anyone who can help.
I already checked with a breakpoint what code is giving me this error:
catch (const BitException& ex) {
ex.what(); //<-
}
The code runs otherwise and isn't giving me any error messages
The code isn't giving you any error message since you're not doing anything with the information provided by the thrown exception.
You're simply calling ex.what() without, for example, printing the error message string it returns, e.g., via std::cout.
the breakpoint activates on the line I marked with an arrow (not actually
part of my code).
I don't know what exactly is causing the catch to thrown an exception. From other posts I suspected that my paths for the files and directories are at fault, but changing them or moving my test directory didn't help at all.
The ex.what() error message should give you more details about the actual issue you're having.
By the way, I'm the author of the bit7z library, and from my experience and looking at the code you posted, I can think of some possible causes (the most common ones):
The program could not find the 7z.dll library.
Please ensure that the DLL is in the same directory as the executable or in one of the default DLL search paths of Windows.
The program could not find the directory path to be compressed.
As before, make sure that the path exists.

Debug Assertion Failed Expression __acrt_first_block == header

I have been trying to figure out why this is happening and maybe it is just due to inexperience at this point but could really use some help.
When I run my code, which is compiled into a DLL using C++20, I get that a debug assertion has failed with the expression being __acrt_first_block == header.
I narrowed down where the code is failing, but the weird part is that it runs just fine when I change the Init(std::string filePath function signature to not contain the parameter. The code is below and hope someone can help.
Logger.h
#pragma once
#include "../Core.h"
#include <memory>
#include <string>
#include "spdlog/spdlog.h"
namespace Ruby
{
class RUBY_API Logger
{
public:
static void Init(std::string filePath);
inline static std::shared_ptr<spdlog::logger>& GetCoreLogger() { return coreLogger; }
inline static std::shared_ptr<spdlog::logger>& GetClientLogger() { return clientLogger; }
private:
static std::shared_ptr<spdlog::logger> coreLogger;
static std::shared_ptr<spdlog::logger> clientLogger;
};
}
Logger.cpp
namespace Ruby
{
std::shared_ptr<spdlog::logger> Logger::coreLogger;
std::shared_ptr<spdlog::logger> Logger::clientLogger;
void Logger::Init(std::string filePath)
{
std::string pattern{ "%^[%r][%n][%l]: %v%$" };
auto fileSink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(filePath, true);
// Setup the console and file sinks
std::vector<spdlog::sink_ptr> coreSinks;
coreSinks.push_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>());
coreSinks.push_back(fileSink);
// Bind the sinks to the core logger.
coreLogger = std::make_shared<spdlog::logger>("RUBY", begin(coreSinks), end(coreSinks));
// Set the Patterns for the sinks
coreLogger->sinks()[0]->set_pattern(pattern);
coreLogger->sinks()[1]->set_pattern(pattern);
// Tell spdlog to flush the file loggers on trace or worse message (can be changed if necessary).
coreLogger->flush_on(spdlog::level::trace);
// Set the default level of the logger
coreLogger->set_level(spdlog::level::trace);
// Do the same for the client logger
std::vector<spdlog::sink_ptr> clientSinks;
clientSinks.push_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>());
clientSinks.push_back(fileSink);
clientLogger = std::make_shared<spdlog::logger>("APP", begin(clientSinks), end(clientSinks));
clientLogger->sinks()[0]->set_pattern(pattern);
clientLogger->sinks()[1]->set_pattern(pattern);
clientLogger->flush_on(spdlog::level::trace);
clientLogger->set_level(spdlog::level::trace);
}
}
Entrypoint.h
#pragma once
#ifdef RB_PLATFORM_WINDOWS
extern Ruby::Application* Ruby::CreateApplication();
int main(int argc, char** argv)
{
Ruby::Logger::Init("../Logs/Recent_Run.txt");
RB_CORE_INFO("Initialized the logger.");
auto app = Ruby::CreateApplication();
app->Run();
delete app;
return 0;
}
#else
#error Ruby only supports windows
#endif // RB_PLATFORM_WINDOWS
For anyone else who runs into a similar problem, here is how I fixed it.
Essentially the function signature for the Init() function was the problem. The std::string parameter was causing the debug assertion to fire, my best guess as of right now was because of move semantics but that part I am still not sure on. So there are a couple of ways that I found to fix this.
Method 1:
Make the parameter a const char*. I don't quite like this approach as it then relies on C style strings and if you are trying to write a program in modern C++, this is a huge step backwards.
Method 2:
Make the parameter a const std::string&. Making it a const reference to a string prevents the move semantics (again as far as I know) and the assertion no longer fires. I prefer this fix as it keeps the program in modern C++.
I hope this helps anyone who has similar issues, and be careful with statics and move semantics.

Loading dynamcally a DLL inside another DLL

I'm trying to convert the functionality of our old code to a DLL.
One of the function wants to export from our old code use a dynamically linked DLL (that I'm gonna call other)
std::wstring otherDLL = L"C:\\PATH\\TO\\OTHER\\DLL"
if (!(libOther = LoadLibraryW(otherDLL.c_str()))){
return;
}
In our old code, this portion of code works just fine.
So I added in my new DLL the following code:
extern "C++" std::wstring test_load(void){
std::wstring otherDLL = L"C:\\PATH\\TO\\OTHER\\DLL"
if (!(libOther = LoadLibraryW(otherDLL.c_str()))){
return L"Not Loaded";
}
return L"Loaded";
}
(this function is not launched during DLLMain). If I try to launch test_load from my DLL in another exe
#include "MyNewDLL.h"
int main()
{
std::wcout << test_load();
}
I get following error
Unhandled exception at 0x7BDE20f3 (ucrtbased.dll) in Test.exe: 0xC00000005: Access violation reading location 0x00000000
What's strange is that if I try to load the OtherDLL from the main that is not inside MyNewDLL, there is no error and I can use it just fine.
Any Idea where my problem could come from ?

Need help correcting Access Violation with FFmpeg DLL

I'm trying to use the FFmpeg dll's using Visual Studio 2012 and I'm getting a run time access violation when I call avcodec_find_encoder. Here is the code:
// TestFFmpeg.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
extern "C" {
#include "libavcodec\avcodec.h"
#include "libavformat\avformat.h"
}
#define INBUF_SIZE 4096
int _tmain(int argc, _TCHAR* argv[])
{
AVCodec *codec;
const char *videoFilename = "C:\\Users\\Public\\Videos\\Sample Videos\\Wildlife.wmv";
av_register_all(); // This works; however, no parameters or return values.
codec = avcodec_find_encoder(CODEC_ID_WMV3); // Run time Access Violation HERE
if (!codec) {
fprintf(stderr, "Codec not found\n");
exit(1);
}
return 0;
}
Here is the error message:
Unhandled exception at 0x75C18B60 (msvcrt.dll) in TestFFmpeg.exe: 0xC0000005: Access violation reading location 0x00000049.
The stack trace is:
msvcrt.dll!_strcmp() Unknown
avcodec-54.dll!6a56caac() Unknown
[Frames below may be incorrect and/or missing, no symbols loaded for avcodec-54.dll]
> TestFFmpeg.exe!wmain(int argc, wchar_t * * argv) Line 23 C++
TestFFmpeg.exe!__tmainCRTStartup() Line 533 C
TestFFmpeg.exe!wmainCRTStartup() Line 377 C
kernel32.dll!#BaseThreadInitThunk#12() Unknown
ntdll.dll!___RtlUserThreadStart#8() Unknown
ntdll.dll!__RtlUserThreadStart#8() Unknown
I'm guessing there's a problem with returning the codec pointer, but I'm new to C++ and have no idea how to correct it. I tried the cdecl, stdcall, and fastcall calling conventions -- none corrected the issue. I'm using the latest 32-bit DLL from Zeranoe. Any suggestions?
EDIT:
I've called other functions in the DLL and they work. For example, avformat_open_input works properly. I can pass parameters and the function returns a successful return value (0) and populates the format context structure. av_find_stream_info works as well. I still can't figure out why avcodec_find_decoder creates an access violation.
Finally, fixed it. I did two steps and I'm not sure which one worked (heh):
Added the '.lib' files as linker input dependencies
I picked up the Sept 7 build and made sure I have all the same build-date for the dll's, libraries, and include files.
Everything appears to work fine now.

Testing exceptions with BOOST

I'm using boost test framework 1.47 and I'm having difficulties testing my exceptions
Here is my exception class
class VideoCaptureException : public std::exception
{
std::string m_Description;
public:
VideoCaptureException(const char* description)
{
m_Description = std::string(description);
}
VideoCaptureException(const std::string& description)
{
m_Description = description;
}
virtual ~VideoCaptureException() throw() {}
virtual const char* what() const throw()
{
return m_Description.c_str();
}
}
I'm trying to test code that simply throws this exception
BOOST_CHECK_THROW( source.StopCapture(), VideoCaptureException )
For some reason it doesn't work.
unknown location(0): fatal error in "testVideoCaptureSource": unknown type
testVideoCaptureSource.cpp(28): last checkpoint
What is it that I'm doing wrong?
After encountering this error myself, I have tracked it down to a silly, but easy-to-make mistake:
throw new VideoCaptureException( "uh-oh" );
will fail with that error message, while:
throw VideoCaptureException( "uh-oh" );
will succeed.
The new variant causes a pointer to an exception to be caught, rather than the exception itself. The boost library doesn't know what to do with this, so it just says "unknown type".
It would be nice if the library explained the situation properly, but hopefully anybody else hitting "fatal error: unknown type" will find this page and see how to fix it!