How to fix EXCEPTION_ACCESS_VIOLATION when loading c++ dll file? - c++

The Problem
I am writing a simple Hello World program using the Java Native Interface (JNI). When I call System.loadLibrary("libsimple_JNI") to load the dll file containing the C++ hello world function, an EXCEPTION_ACCESS_VIOLATION (0xc0000005) occurs (I am compiling in Netbeans with 64 bit cygwin).
I have tried statically loading the library as well as loading it within the Java helper function which calls the C++ hello world function. I added the path to the cygwin1.dll in the system environment variables which resolved earlier problems with Java not being able to find the dependencies for my dll file.
Here is the exact error message
A fatal error has been detected by the Java Runtime Environment:
EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x0000000180128dd7, pid=19116, tid=0x0000000000003ea8
JRE version: Java(TM) SE Runtime Environment (8.0_131-b11) (build 1.8.0_131-b11)
Java VM: Java HotSpot(TM) 64-Bit Server VM (25.131-b11 mixed mode windows-amd64 compressed oops)
Problematic frame:
C [cygwin1.dll+0xe8dd7]
Failed to write core dump. Minidumps are not enabled by default on client versions of Windows
An error report file with more information is saved as:
C:\Users\Kogondo Admin\Desktop\JavaApplication7\hs_err_pid19116.log
Here is the Java Code
public static void main(String[] args) {
thingy my_thingy = new thingy();
my_thingy.hi();
}
public class thingy {
public thingy() {}
public void hi(){
System.loadLibrary("libsimple_JNI");
hello();
}
private native void hello();
}
Here is the C++ code
void JNICALL Java_javaapplication7_thingy_hello (JNIEnv * env, jobject object){
printf("hi from C");
}
When running properly, I expect the code to print "hi from C" to the output window in Netbeans.

Final Solution
7 and half hours I finally managed to find a solution. I followed van dench's advice to generate my dll file using the minGW compiler in Visual Studios instead of the cygwin compiler in Netbeans.
Here is a link to the video and the paper that I found which walk through how to do this. Note that the video is in Portuguese. That being said, the paper which it follows is in English and the video walkthrough shows step by step what commands and configurations you need to do.
I am willing to further elaborate on my solution if others would find that useful.
Good Luck!

Related

Unable to create DLLs: Getting DLL "is not a valid Win32 application"

As the title says, I can't create a simple DLL. I'm using VS 2017 Community Edition Version 15.8.0. Here is the .dll code:
#include "stdafx.h"
#include "InvWin32App.h"
#include "$StdHdr.h"
void Prc1()
{
printf("ran procedure 1\n");
}
Here is the code for the header, per the MS way to do things:
#ifdef INVWIN32APP_EXPORTS
#define INVWIN32APP_API __declspec(dllexport)
#else
#define INVWIN32APP_API __declspec(dllimport)
#endif
#ifdef __cplusplus
extern "C" {
#endif
INVWIN32APP_API void Prc1();
#ifdef __cplusplus
}
#endif
Here is the driver code: (Update: The driver program is an .exe program.)
#include "pch.h"
#include "InvWin32App.h"
int main()
{
Prc1();
}
It can't get any simpler than this. I get the following error message box when I try to run the code:
Unable to start program
program name.dll
program name.dll is not
a valid Win32 application
I can create .exe programs okay. I also got the error earlier this morning when I was running VS 2017 Version 15.7.5. Upgrading VS didn't do any good. I also tried to compile these as .c programs, but it didn't make any difference.
I had this problem on a couple occasions creating .exe programs using VS 2015. I don't recall what I did, but the problem disappeared. Any help would be appreciated.
TIA.
Right click the project in your solution explorer that is the project for the executable and click "Set as startup project."
Note that "is not a valid Win32 application" is not a compile error or a link error, it is the message you get when you tried to debug something that is not executable.
You can only start executables. Executables consume dlls. These should be two seperate projects with two sets of corresponding project settings.
I doubt that you are using a 32 bit dll. If you have your 64-bit Windows OS then you must have 64 bit version of this dll too. Sometimes, even you have 64-bit dll already then it could not run, so try the other version of this dll i.e. 32 bit version of this dll.
Along with this, make a small change in your unicurse.py file too.
PFB the code to add:
import ctypes
pdlib = ctypes.CDLL("pdcurses.dll")
though this line of code is somewhere inside some condition, but bringing on top will help you to check, if the dll has been loaded or not.
For any one joining the party at this time, I found that this error is caused when you try to run a 32bit dll using a 64bit python.
Now I won't go into the details as to why that won't work as above responses clearly describes that, but there are 2 solutions for this.
Install and 32bit python and use that to communicate with the dll.
Interprocess communication using the msl-loadlib library documentation
I used the second step which seemed more sustainable. The steps I am using below can be found in the documentation link above.
First is to create a server module that communicates with the 32 bit module
#server.py
from msl.loadlib import Server32
class Server(Server32):
# the init takes mandatory host and port as arguments
def __init__(self, host, port, **kwargs):
# using windll since this application is being run in windows, other options such as cdll exists
# this assumes that the dll file is in the same directory as this file
super(Server, self).__init__('tresdlib.dll', 'windll', host, port)
# define a function that is to be called with the required arguments
def fsl_command(self, com, doc):
#the server32 exposes the loaded dll as lib, which you can then use to call the dll functions and pass the required arguments
return self.lib.FSL_Command(com,doc)
Then we create a client module, that sends python requests to the server module
#client.py
from msl.loadlib import Client64
class Client(Client64):
def __init__(self):
# pass the server file we just created in module32=, the host am using is localhost, leave port as none for self assigning
super(Client, self).__init__(module32='server', host="127.0.0.1", port=None)
# define a function that calls the an existing server function and passes the args
def fsl_command(self, com, doc):
return self.request32('fsl_command', com, doc)
We are going to run this in a terminal but you can choose to call in another application
>>> from client import Client
>>> c = Client()
>>> c.fsl_command(arg1,arg2)

How to create empty working boost::python::dict?

I parse a C++ project which compiling as library.so for python. So I can`t debug it inside Qt creator IDE. For this purpose I created separate project with executable main():
int main()
{
boost::python::dict whiteList;
whiteList.has_key("blablabla");
...
return 0;
}
On release mode program compiling and work incorrectly. But on debugging mode program fails in has_key() method with error window:
The inferior stopped because it received a signal from the Operating System.
Signal name : SIGSEGV
Signal meaning : Segmentation fault
Probably the question is: How to correctly create and use boost::python::dict purely inside C++ program without involving python script?
Whenever you use the Python C API or Boost Python, you must initialize Python:
Py_Initialize();
Add that to the top of your main() et voila.

OCCI app crashes when running in debug mode in Visual Studio 2005

I'm attempting to get a development environment up and running for developing applications with Oracle C++ Call Interface (OCCI) in Visual Studio 2005.
My system specs are:
OS: Windows 7, 64-bit
Oracle: 11g release 11.2.0.2, 32-bit
Instant Client: BasicLite and SDK version 11.2.0.4 32-bit
Visual Studio 2005 Professional Edition version 8.0 with 32-bit tools enabled
I've followed this guide by Mark Williams and I got the example running but only in release mode. When I switch to debug mode the app will build, but when I run it I get the following error:
Problem signature:
Problem Event Name: APPCRASH
Application Name: OCCITest.exe
Application Version: 0.0.0.0
Application Timestamp: 53f5dfdd
Fault Module Name: KERNELBASE.dll
Fault Module Version: 6.1.7601.18229
The small example program that triggers this error is:
#include "employees.h"
using namespace std;
using namespace oracle::occi;
int main (void)
{
Employees *pEmployees = new Employees();
delete pEmployees;
return 0;
}
Employees::Employees()
{
user = "hr";
passwd = "hr";
db = "localhost:1521/service_name";
env = Environment::createEnvironment(Environment::DEFAULT);
try
{
con = env->createConnection(user, passwd, db);
}
catch (SQLException& ex)
{
cout << ex.getMessage();
exit(EXIT_FAILURE);
}
}
Employees::~Employees()
{
env->terminateConnection (con);
Environment::terminateEnvironment (env);
}
If I remove all calls to OCCI functionality the application doesn’t crash. That is, this program runs error-free:
#include "employees.h"
using namespace std;
using namespace oracle::occi;
int main (void)
{
Employees *pEmployees = new Employees();
delete pEmployees;
return 0;
}
Employees::Employees()
{
user = "hr";
passwd = "hr";
db = "localhost:1521/service_name";
cout<<"Look at me, I'm running"<<endl;
}
Employees::~Employees()
{}
In the guide Mark mentions that when running in debug mode, the linker should use the library file oraocci11d.lib. However, this file is not included in the Instant Client SDK version 11.2.0.4, so I’m using the input file oraocci11.lib for both the release and debug version.
I'm running out of ideas about how to proceed in solving this problem, and I would greatly appreciate any and all help.
If the Oracle DLL receives and/or passes objects such as std::string or any other object that either:
Manipulates the heap in any way, or
The objects could have differing internals between app and DLL,
then you have no choice but to use the correct library to link with. Otherwise you wind up with binary or heap incompatible objects being passed, which leads to what you're seeing now.
See here: http://docs.oracle.com/cd/E11882_01/appdev.112/e10764/install.htm#CBHGBBJI
The link above mentions both the debug import library and debug version of the DLL. Also this is stated at the link:
Applications that link to MSVCRTD.DLL, a debug version of Microsoft C-Runtime, /MDd compiler flag, should link with these specific OCCI libraries: oraocci11d.lib and oraocci11d.dll.
Since it took me quite some time to get the debug environment working I figured I'd answer my own question now that I did.
I got a variety of errors throughout the ordeal, but the error that I got most stuck on was an error saying:
'The application was unable to start correctly (0xc0150002).
Click OK to close the application.'
Also, I used http://www.dependencywalker.com which repeatedly told me that either oraocci11d.dll or a the following list of dll's could not be found.
API-MS-WIN-APPMODEL-RUNTIME-L1-1-0.DLL
API-MS-WIN-CORE-WINRT-ERROR-L1-1-0.DLL
API-MS-WIN-CORE-WINRT-L1-1-0.DLL
API-MS-WIN-CORE-WINRT-ROBUFFER-L1-1-0.DLL
API-MS-WIN-CORE-WINRT-STRING-L1-1-0.DLL
API-MS-WIN-SHCORE-SCALING-L1-1-1.DLL
DCOMP.DLL
IESHIMS.DLL
However, what was really missing was for the executable to be able to find oci.dll. I'm just mentioning the errors in case someone else runs into these.
Here is what was needed to make it work:
First of all, the Instant Client does not contain the oraocci11d.lib or oraocci11d.dll, so it is necessary to install the full Oracle Client.
Next, the following must be added to the PATH:
C:\Program Files\Oracle\11.2.0\OCI\lib\MSVC\vc8
C:\Program Files\Oracle\11.2.0\BIN
In Visual Studio, select Tools -> Options, unfold 'Projects and Solutions' and select VC++ Directories. In 'Show directories for' under:
Include Files add C:\Program Files\Oracle\11.2.0\OCI\include
Library files add C:\Program Files\Oracle\11.2.0\OCI\lib\MSVC\vc8
In the property page for your project under Configuration Properties -> Linker select Input and under Additional Dependencies add oraocci11d.lib (or oraocci11.lib for release mode). Then select debug/release mode in the Configuration Manager
I have a related problem in that I am successfully using oraocci12d.dll/msvcr100d.dll, but this in turn is using oci.dll/msvcr100.dll. ie, oci.dll is not using the debug version of msvcr100.
My program seems to run okay, but any memory leak reporting disappears on exit.

Win32 API stack walk with MinGW/MSYS?

i've to develop a stack trace walk to our win32 API plattform support to catch any exception with a behaviour of a JAVA stacktrace. Actually we got a full functional implementation for Linux plattforms.
First i've tried to implement a stackwalk using the win32 CaptureStackBackTrace API
mechanism. But this method is not integrated in the actually winbase header of mingw (using MSYS/MinGW 5.1.x) ...
So i decided tried use the dbgheader mechanism follwoing the instructions of this link :
http://sites.google.com/site/kenscode/prime-programs/boinc-with-mingw-on-win32
But i fail again and run into linker failures i could not solve. I think MinGW could not resolve the dbgheader library ....
DrMinGW is not an option for me, while it is a JIT Debugger, i've to implement a stack trace mechansim, for any exception occuring on runtime with a customizable log file tracebility like we know from JAVA ...
Has anyone get MSYS/MinGW runable with the win32 API in handshake? I will not change the compiler to the ugly MVC compiler instead of using MSYS/MinGW...
Thanks for any hint.
Best regards,
Christian
Check Mr. Edd's stack trace library at the following link. It will produce a nice stack frame listing and has specific code to support MinGW.
http://www.mr-edd.co.uk/code/stack_trace
His library uses dbghelp.dll, however, so you may get into some problems trying to compile it. As far as I know, MinGW doesn't include an import library for this DLL (see a old feature request here). I had success, however, creating one import library myself. You can do the same just using a .def file from the Wine project (check the previous link's attached files for one) and running the MingW utility dlltool:
dlltool -k -d dbghelp.def -l dbghelp.a
You can then include the resulting dbghelp.a file in your project. You won't probably like to have dependencies towards dbghelp.dll in your release builds, as the DLL itself is surely not redistributable.
Here is a method to walk the call stack using the Win32 API which you can call from MinGW.
http://www.codeproject.com/KB/threads/StackWalker.aspx
I got stack traces working in MingGW with Edd's dbg library, which is a successor to his minimal stack_trace library:
With msys2, this should get you a stack trace:
$ pacman -S mingw-w64-x86_64-edd-dbg
// main.cpp
#include <dbg/frames.hpp>
#include <dbg/symbols.hpp>
#include <iostream>
int main()
{
dbg::symdb db;
dbg::call_stack<64> traceback;
traceback.collect(0);
traceback.log(db, std::cout);
return 0;
}
$ g++ -ggdb main.cpp -ldbg
$ ./a.exe
0x0000000000402ee9: dbg::call_stack<64u>::collect(unsigned int) in C:\msys64\home\phil\stacktrace-example\a.exe
0x00000000004015f2: main in C:\msys64\home\phil\stacktrace-example\a.exe
0x00000000004013f8: __tmainCRTStartup in C:\msys64\home\phil\stacktrace-example\a.exe
0x000000000040151b: mainCRTStartup in C:\msys64\home\phil\stacktrace-example\a.exe
0x00007ffbb0838102: BaseThreadInitThunk in C:\WINDOWS\system32\KERNEL32.DLL
0x00007ffbb27cc5b4: RtlUserThreadStart in C:\WINDOWS\SYSTEM32\ntdll.dll
More about dbg can be found in the Wiki. The code is available here: https://bitbucket.org/edd/dbg/src

Is there a simpler Windows C++ Subversion API or an example .vcproj for minimal_client.c?

Following on the tails of my previous (answered) question...
SharpSvn makes calling the Subversion client API simple:
SvnClient client = new SvnClient();
client.Authentication.DefaultCredentials = new NetworkCredential(username, password);
client.CheckOut(new Uri("http://xxx.yyy.zzz.aaa/svn/repository"), workingCopyDir);
On the other hand, calling the client API from C/C++, as shown in minimal_client.c requires coding "closer to the metal", as it were, on Subversion.
Are there Windows libraries for C++ in Visual Studio 2003 that present a simpler interface than what minimal_client uses?
If there are not, is there a VS2003 C++ project (a .vcproj file) that demonstrates getting minimal_client to run? I'm able to compile minimal_client.c and link it using the following libraries:
libsvn_client-1.lib libsvn_delta-1.lib libsvn_diff-1.lib libsvn_fs-1.lib libsvn_fs_base-1.lib libsvn_fs_fs-1.lib libsvn_ra-1.lib libsvn_ra_local-1.lib libsvn_ra_svn-1.lib libsvn_repos-1.lib libsvn_subr-1.lib libsvn_wc-1.lib libapr-1.lib libaprutil-1.lib xml.lib libneon.lib
but when I run my application (in the debugger or start the release build without debugging), it runs for about 20 seconds without hitting the first line of main() and then throws this exception:
An unhandled exception of type
'System.TypeLoadException' occurred in
Unknown Module.
Additional information: Could not load
type apr_pool_t from assembly
minimal_client,
Version=1.0.3477.16033,
Culture=neutral, PublicKeyToken=null.
I've tried various combination of libsvn_.lib and svn_.lib to no avail.
Any thoughts on what I'm doing wrong?
EDIT: I started fresh with a "Win32 Console Project" (still in VS2003) and I am now able to debug the first few lines of my app. But now, on this line:
if (svn_cmdline_init ("minimal_client", stderr) != EXIT_SUCCESS)
I get a different exception (in the debugger or start the release build without debugging):
Unhandled exception at 0x7c91b21a in
Win32ConsoleProject_minimal_client.exe:
0xC0000005: Access violation writing
location 0x00000010.
EDIT: This thread explains that this error is a CRT mismatch between svn and stderr in my app. If I don't want to build Svn so they match (I don't want to), I can pass NULL instead of stderr (provided I'm willing to do without messages that would go to stderr) When I did this, my app ran all the way through correctly.
It seems that C++ wrappers are not overflowing the 'net. However, you may want to try SVNCPP, which can be yoinked from RapidSVN.
See http://rapidsvn.tigris.org/ for details (note: I've not tried it).
Can you upgrade to Visual C++ 2005 ? If so, you could just go using SharpSvn with C++/CLI.
Or even maybe stick to VC2003 and go SharpSvn with Managed C++ ? (not that I have any knowledge on the how od even the if)
edit: oh well, SharpSvn's homepage explicitely states that VC++ 2005 SP1 is required...