Questions about DefineClass and my attempted usage of it - c++

I'm trying to create a class/inject a class inside a java process through injecting a DLL into the process and using JNI to interface with java.
I came across a function called DefineClass but i can't quite get it work how i expected it to, so i have a few questions about the parameters the functions take:
In my case, what do i pass as class loader?
It accepts a byte array and its length as the "content" of the class, what would be the correct way of getting these bytes?
Which parts of the class is to be included in the array of bytes? Do i include everything or strip away parts?
Everything i have tried so far has resulted in the function returning null, so I'm not sure where to begin looking. If anyone would include some example usage or important notes about the usage that would be amazing!
jobject defined = jni->DefineClass("ChatFormatting", NULL, reach_buf, 4132);
if (defined == nullptr) {
std::cout << "Defined is NULL." << std::endl;
} else {
std::cout << "Success!" << std::endl;
}

You can get only class name and its' member entries addresses are incorrect.
Before inject, you must change addresses of entries by injectee module address.

Related

trying to use my custom class constructor without new [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
coming from java i would like to not have to deal with de-allocation when creating new custom or other library's objects.
today i was trying to create an instance of my entity object like:
entity cube = new entity("entityName")
because this is how entity's constructor is formatted
but i get the following error:
cannot convert from |entity *| to |entity|
i noticed there are no errors if i just remove the new keyword, and i was wondering two things.
what does the error while using new mean ? (i'm pretty confident with how pointers work but not completely as i started with java.)
is it ok for me to create objects like that without the new keyword or is an object even created? (because there are no errors.)
new entity("entityName")
means "create an instance of entity in the free store and return a pointer to that instance".
Since a pointer to an entity is not the same as an entity, you cannot initialise an entity with that value unless you have yet another constructor.
The way to do what you want is
entity cube("entityname");
And you need a good book on C++.
First, I suggest you to read a C++ tutorial. It has much more complexity than Java.
This is a very partial Java to C++ "how to convert" guide that I can give you:
Java code:
void sayHello(String name) {
system.out.println("Hello, " + name);
}
public static void main(String args[]) {
String name = "James"; // <-- This string is of course created in the dynamic memory
sayHello(name); // <-- "name" will be passed by reference to the "sayHello()" method
}
Equivalent in C++ - option 1:
void sayHello(const std::string &name) {
std::cout << "Hello, " << name << std::endl;
}
int main() {
std::string name("James"); // <-- Variable is created on the stack
sayHello(name); // <-- Although "name" is not a pointer, it will be passed by reference to "sayHello", as "name" is defiend there with "&", which means that it is a reference
}
A reference is a very "weird" type - it behaves like a local variable, although it actually points to an instance that does not have to be on the stack of the current function or on the stack at all.
C++ - option 2:
void sayHello(const std::string *name) {
std::cout << "Hello, " << *name << std::endl; // <-- dereferenceing "name" using a preceding star, as "cout" needs the variable itself and not its address
}
int main() {
std::string *name = new std::string("James"); // <-- Instance is created in the dynamic memory
sayHello(name); // <-- Sending the pointer "name" to the "sayHello" function
// You will need to free "name" somewhere in the code unless you don't care about memory leaks
}
There are more options, like passing the instance by value (not recommended in such case), or like creating it in the dynamic memory and deref
what does the error while using new mean ? (i'm pretty confident with how pointers work but not completely as i started with java.)
No. C++ is different about this, you don't use an allocation (new) to initialize cube:
entity cube("entityName");
is it ok for me to create objects like that without the new keyword or is an object even created? (because there are no errors.)
No. See above. ("because there are no errors." I doubt this, there should at least be compiler warnings if you assign entity from a pointer.)

Multiplatform way to determine if a dynamic library is present

I need to check if a dynamic library is present, so that later I can safely call functions that use this library.
Is there a multiplatform way to check this? I am targeting MS Windows 7 (VC++11) and Linux (g++).
To dynamically "use" a function from a shared library requires that the library isn't part of the executable file, so you will need to write code to load the library and then use the function. There may well be ways to to do that in a portable fashion, but I'm not aware of any code available to do that.
It isn't very hard code to write. As "steps", it involves the following:
Load the library given a name of a file (e.g. "xx", which is then translated to "xx.so" or "xx.dll" in the architecture specific code).
Find a function based on either index ("function number 1") or name ("function blah"), and return the address.
Repeat step 2 for all relevant functions.
When no longer needing the library, close it with the handle provided.
If step 1 fails, then your library isn't present (or otherwise "not going to work"), so you can't call functions in it...
Clearly, there are many ways to design an interface to provide this type of functionality, and exactly how you go about that would depend on what your actual problem setting is.
Edit:
To clarify the difference between using a DLL directly, and using one using dynamic loading from the code:
Imagine that this is our "shared.h", which defines the functions for the shared library
(There is probably some declspec(...) or exportsymbol or other such stuff in a real header, but I'll completely ignore that for now).
int func1();
char *func2(int x);
In a piece of code that directly uses the DLL, you'd just do:
#include <shared.h>
int main()
{
int x = func1();
char *str = func2(42);
cout << "x=" << x << " str=" << str << endl;
return 0;
}
Pretty straight forward, right?
When we use a shared library that is dynamically loaded by the code, it gets a fair bit more complex:
#include <shared.h>
typedef int (*ptrfunc1)();
typedef char * (*ptrfunc2)(int x);
int main()
{
SOMETYPE handle = loadlibrary("shared");
if (handle == ERROR_INDICATOR)
{
cerr << "Error: Couldn't load shared library 'shared'";
return 1;
}
ptrfunc1 pf1 = reinterpret_cast<ptrfunc1>(findfunc("func1"));
ptrfunc2 pf2 = reinterpret_cast<ptrfunc2>(findfunc("func2"));
int x = pf1();
char *str = pf2(42);
cout << "x=" << x << " str=" << str << endl;
return 0;
}
As you can see, the code suddenly got a lot more "messy". Never mind what hoops you have to jump through to find the constructor for a QObject, or worse, inherit from a QObject. In other words, if you are using Qt in your code, you are probably stuck with linking directly to "qt.lib" and your application WILL crash if a Qt environment isn't installed on the machine.
LoadLibrary calls should fail, then you can know if the dynamic library is present or not. Also with dynamic loading you get the function pointer from the dynamic library and if the pointer is null then the platform doesn't support that function on that platform.
On windows you have LoadLibrary API to load a dynamic lib. And GetProcAddress API to look up the desired function in that lib. If GetProcAddress returns NULL for that particular function that you are looking for that functionality is not present for that platform. You can log then and decide fallback.

Getting function pointers from specific files

I have a lot (perhaps hundreds) of different c++ files. Each one contains 10 functions, all of them taking in an int and a double and returning an int.
So the pointer to one of these functions in one of these files would look like this:
int (*foo)(int, double);
And then I have a class, which contains 10 of these function pointers.
Is it possible to have the constructor of this class take in a file name of one of these c++ files, put that file's functions into its pointers, and be able to use the functions later?
Preferably it would work so that even if two functions from different files had the same name it would still work (the idea is that multiple programmers could submit different files into the list, and they might use the same names for their 10 functions), but if that's not possible I could figure out something to avoid that.
From what I've searched, I can't seem to find anything that lets you differentiate between files when choosing functions, and even if I were to concatenate the functions into one file, there's still the problem of trying to designate which 10 functions to pick (as they all have the same arguments).
Is there any way to do this? Is there any better solution that I'm just not thinking of?
Is there any way to do this? Is there any better solution that I'm
just not thinking of?
You could just use different namespaces for them I think ? I mean each group of 10 functions in their own namespace; that way they won't conflict any more.
Other than that, you could try some dlsym + dlopen weirdness (or their win32 counterparts). It's not something I would do though.
I believe you are describing a dynamic linking library (aka shared object in Linux-land).
To achieve what you ask literally, you can turn each C++ file into a dynamic library and in the library constructor register the set of functions in some global map using FILE string as a key or declare them static, and make sure each file has some static variable whose initializer triggers functions' registration in the same global map.
To implement the same using plugin approach you can do it the way similar to what I have done it here (just download plugin.tgz, article is not yet ready). Contents:
app.cc - application, loads all plugins' libraries
module.cc - a plugin class implementing a business interface
module_ifc.h and a "loadable" interface bootstrap_ifc.h
client.cc - a plugin implementing bootstrap_ifc.h and using
method from module.cc resolved at runtime
Each of your C++ files having the same set of function would have a class implementing abstract business interface (useful part, all your functions) and bootstrap interface (unified initialization part, will be used by plugin loader). Each such class would be put into a separate shared library that declares class instance constructor and destructor methods.
A simple class to work with shared libraries on Linux:
#include <dlfcn.h>
class library {
void* _handle;
public:
library(char const* path);
~library();
template <typename F> F func(char const* name);
};
library::library(char const* path) {
_handle = dlopen(path, RTLD_NOW);
if (!_handle) throw std::runtime_error(dlerror());
std::clog << "opened library " << path << ", handle=" << std::hex << _handle << std::dec << "\n";
}
library::~library() {
if (_handle) dlclose(_handle);
std::clog << "closed library, handle=" << std::hex << _handle << std::dec << "\n";
}
template <typename F> F library::func(char const* name) {
dlerror();
F func = reinterpret_cast<F>(dlsym(_handle, name));
const char *dlsym_error = dlerror();
if (dlsym_error) throw std::runtime_error(dlsym_error);
std::clog << "loaded symbol " << name << ", ptr=" << std::hex << ((void*)func) << std::dec << "\n";
return func;
}

My static map is always empty

I declared a static unordered map in a header file as follows:
static boost::unordered_map<KeyAction, sf::Key::Code> WindowKeyMap;
in that same header file, i have a function that fills the map with some values:
static void Initialize(std::string &file)
{
WindowKeyMap[MoveLeft] = sf::Key::Code::Left;
WindowKeyMap[MoveRight] = sf::Key::Code::Right;
WindowKeyMap[MoveUp] = sf::Key::Code::Up;
WindowKeyMap[MoveDown] = sf::Key::Code::Down;
std::cout << std::endl << WindowKeyMap.size() << std::endl;
}
Later on in my program, inside a seperate class/function, i attempt to read one of the values:
std::cout << std::endl << WindowKeyMap.size() << std::endl;
auto test2 = WindowKeyMap[MoveRight];
but the map is always empty. The output to the console is always 4 from the initialize routine then 0 from the second cout. I thought static maps were persistent across the program, so I'm a little confused as to how my static map becaomes empty. Can anyone shed some light?
Thanks
When you declare your variable in the header like that each compilation unit (*.cpp) gets it's own local static copy. You have to declare it extern
extern boost::unordered_map<KeyAction, sf::Key::Code> WindowKeyMap;
and in one cpp put
boost::unordered_map<KeyAction, sf::Key::Code> WindowKeyMap;
Simple: just don't do it. While you can get rid of the initialization and scope as suggested by #Eelke, you will shoot yourself in the foot in the long term... Do you really want to have the hash table accessible by everybody and everywhere? Do you really accept the risk of uncontrollable access to the (apparently important) data? Do you really want to have an untestable global state all across your application? Do you really want to have all the dependencies introduced by <unordered_map> pulled into many translation units of your program? I could continue like that for a while but the point is: Wrap the logic and data into a class and provide the service via an interface. Create the instance of the interface via a factory or dependency container and manage the lifetime of that object explicitly.
Regards,
Paul

Segfault when calling a method c++

I am fairly new to c++ and I am a bit stumped by this problem. I am trying to assign a variable from a call to a method in another class but it always segfaults. My code compiles with no warnings and I have checked that all variables are correct in gdb but the function call itself seems to cause a segfault. The code I am using is roughly like the following:
class History{
public:
bool test_history();
};
bool History::test_history(){
std::cout<<"test"; //this line never gets executed
//more code goes in here
return true;
}
class Game{
private:
bool some_function();
public:
History game_actions_history;
};
bool Game::some_function(){
return game_actions_history.test_history();
}
Any tips or advice is greatly appreciated!
EDIT: I edited the code so there is no more local_variable and the value returns directly. But it still segfaults. As for posting the actual code, it's fairly large, what parts should I post?
From what I can see there's nothing wrong with the code you've displayed. However, segfaults often are a good indication that you've got corrupted memory. It's happening some place else besides what you've shown and only happens to impact the code here. I'd look any place you're dealing with arrays, pointers, or any manual memory interactions.
I have used valgrind succesfully with a lot of segfaults.
and have you tried to run gdb with the coredump caused by the segfault? from man gdb:
gdb program core
To create a coredump you might have to set:
ulimit -c unlimited
Shot in the dark. (Game*)this is NULL ?
The code is fine but the example is too incomplete to say what's wrong. Some things I'd suggest:
Add printouts to each class's destructor and constructor:
Game::Game() { cerr << this << " Game::Game" << endl; }
Game::Game(Game const&) { cerr << this << " Game::Game(Game const&)" << endl; }
Game::~Game() { cerr << this << " Game::~Game" << endl; }
bool Game::some_function() { cerr << this << " Game::some_function()" << endl; ... }
This will reveal:
Null object pointers.
Bad/deleted class pointers.
Second, for debugging, I'd strongly recommended sending printouts to cerr instead of cout. cout is usually buffered (for efficiency) before being output, cerr is not (at least, this used to be the case). If your program quits without executing its error handlers, at_exit, etc..., you are more likely to see the output if it is unbuffered and printed immediately.
Thirdly, if your class declarations live in a header, the class definitions, live in one cpp file and the code that uses the class in yet another, you may get this kind of crash if either of the cpp files were not recompiled after you changed the header.
Some other possibilities are:
stack overflow: you've allocated a lot of memory on the stack because of deep recursion or are allocating objects containing large arrays of data as local variables (i.e. not created or the heap with new or malloc))
corrupted class vtable (usually only possible due to dependency errors in your build tools),
corrupted object vtable pointer: possible through misuse of pointers: using pointers to deleted memory, or incorrectly writing to an in-use address. Not likely in your example because there are no virtual functions.
maintaining a pointer or reference to an object allocated on the stack that has been deleted: the printout code above will uncover this case.
I am wondering because you have defined some_function() in private of the Game class. So the code structure which you have mentioned above will also throw error for that.