Passing structure through Pointer param in JNA(Found solution by myself) [closed] - jna

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
Found solution, leaving post, in case someone will find it useful.
Now it seems so oblivious... but when you pass the structure by its Pointer in some native function, it simply does not know that it need to reread itself from native memory.
Everything you need to do, in cases like mine, is to call structures method autoRead() after native method returns, and structure will reread itself from native memory.
Here is some example:
// Original C code
typedef struct _SomeStructure {
int x, y;
} SomeStructure;
void DoSomesthing(BYTE* data, int param); //returns lots of data types,
//including SomeStructure
// Equivalent JNA mapping
class SomeStructure extends Structure { public int x, y; }
void DoSomesthing(Pointer data, int param);
...
SomeStructure st = new SomeStructure();
DoSomesthing(st.getPointer(), 100);
st.autoRead(); //structure will be filled
This trick will work only if you need to get some structure from native function. _______________________________________________________________________________
Currently I`m working on exstension of JNA, so it could use MSCAPI, and I faced a little problem.
MSCAPI functions designed in quite specific way, so the work completely different way with different params. In particularly
BOOL WINAPI CryptGetProvParam(
__in HCRYPTPROV hProv,
__in DWORD dwParam,
__out BYTE *pbData,
__inout DWORD *pdwDataLen,
__in DWORD dwFlags
);
function returns PROV_ENUMALGS structure in pbData param, when PROV_ENUMALGS flag is set, but in other cases it could return handles, 0t-strings and lots of other stuff.
So I mapped it with:
boolean CryptGetProvParam(
HCRYPTPROV hProv,
int dwParam,
Pointer pbData,
IntByReference pdwDataLen,
int dwFlags
);
But, when Im tried to call it with PROV_ENUMALGS.getPointer() (as pbData param) structure was not filling, so I ended up with having overloaded function with pdData type PROV_ENUMALGS. Its working, but feeling, that there is some better way to do it, then having overloaded function, does not leave me for a week...
So, guys, any suggestions?
PS Sorry for my bad English, and formatting skills.
Perhaps i wasn`t very clear first time, here is some more code:
HCRYPTPROV hProv = JMSCAPIUtil.contextVerify(null, 420);
PROV_ENUMALGS algs = new PROV_ENUMALGS();
if(Advapi32.INSTANCE.CryptGetProvParam(hProv,
Advapi32.PP_ENUMALGS,
algs,//.getPointer(),
new IntByReference(algs.size()),
Advapi32.CRYPT_FIRST)){
System.out.println(algs.aiAlgid+"\t"+algs.dwBitLen+"\t"
+ new String(algs.szName,0,algs.dwNameLen.intValue()));
}else{
int err=Kernel32.INSTANCE.GetLastError();
System.out.println(err);
}
JMSCAPIUtil.contextRelease(hProv);
Here is result:
26154 256 GOST 28147
Obviously, it calls
boolean CryptGetProvParam(
HCRYPTPROV hProv,
int dwParam,
PROV_ENUMALGS pbData,
IntByReference pdwDataLen,
int dwFlags
);
mapping.
If ,// deleted, it calls
boolean CryptGetProvParam(
HCRYPTPROV hProv,
int dwParam,
Pointer pbData,
IntByReference pdwDataLen,
int dwFlags
);
mapping, and result will be:
0 0
Apparently, structure does not fills, when passed by pointer.

Related

starting a process with exactly the same address structure as previous openning

Is it possible to start a process in windows with exactly the same address structure as the previous opening of the process?
To clarify the goal of this question I should mention that I use cheatengine (http://www.cheatengine.org/) to cheat some games! It includes several iterations to find a parameter (e.g. ammunition) and freeze it. However, each time I restart the game, since the memory structure of the game changes, I need to go through the time-consuming iterations again. So, if there were a method bring up the game exactly with the same memory structure as before, I wouldn't need going through iterations.
Not to say it's impossible, but this is essentially too much work due to the dynamic memory allocation routines the process will be using including the new operator and malloc(). Additionally when the DLL's imported by the executable are loaded into memory they have a preferred imagebase but if that address is already used, the OS will load it into a different memory location. Additionally Address Space Layout Randomization (ASLR) can be enabled on the process which is a security measure that randomizes the memory address of code sections.
The solution to your problem is much easier then what you're asking. To defeat the dynamic memory allocation described above you can still resolve the correct address of a variable by utilizing:
Relative offsets from module bases
Multi-level pointers
Pattern Scanning
Cheat Engine has all 3 of these built into it. When you save an address to your table is often saves it as a module + relative offset. You can pointer scan for the address and save it as a multilevel pointer or reverse the pointer yourself and manually place it in the table. Pattern scanning is achieved by using a CE Script, which you can put right in the Cheat Table.
In this case the ammo variable, may be a "static address" which means it's relative to the base address of the module. you may see it listed in Cheat Engine as "client.dll + 0xDEADCODE". You simply get the base address of the module at runtime and add the relative offset.
If you're looking to make an external hack in C++ you can get started like this.
In an external hack you do this by walking a ToolHelp32Snapshot:
uintptr_t GetModuleBase(const wchar_t * ModuleName, DWORD ProcessId) {
// This structure contains lots of goodies about a module
MODULEENTRY32 ModuleEntry = { 0 };
// Grab a snapshot of all the modules in the specified process
HANDLE SnapShot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, ProcessId);
if (!SnapShot)
return NULL;
// You have to initialize the size, otherwise it will not work
ModuleEntry.dwSize = sizeof(ModuleEntry);
// Get the first module in the process
if (!Module32First(SnapShot, &ModuleEntry))
return NULL;
do {
// Check if the module name matches the one we're looking for
if (!wcscmp(ModuleEntry.szModule, ModuleName)) {
// If it does, close the snapshot handle and return the base address
CloseHandle(SnapShot);
return (DWORD)ModuleEntry.modBaseAddr;
}
// Grab the next module in the snapshot
} while (Module32Next(SnapShot, &ModuleEntry));
// We couldn't find the specified module, so return NULL
CloseHandle(SnapShot);
return NULL;
}
To get the Process ID you would do:
bool GetPid(const wchar_t* targetProcess, DWORD* procID)
{
HANDLE snap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (snap && snap != INVALID_HANDLE_VALUE)
{
PROCESSENTRY32 pe;
pe.dwSize = sizeof(pe);
if (Process32First(snap, &pe))
{
do
{
if (!wcscmp(pe.szExeFile, targetProcess))
{
CloseHandle(snap);
*procID = pe.th32ProcessID;
return true;
}
} while (Process32Next(snap, &pe));
}
}
return false;
}
Using my example you would combine these functions and do:
DWORD procId;
GetPid(L"game.exe", &procId);
uintptr_t modBaseAddr = GetModuleBase(L"client.dll", procId);
uintptr_t ammoAddr = modBaseAddr + 0xDEADCODE;
If the address is not "static" you can find a pointer to it, the base address of the pointer must be static and then you just follow the above guide, and dereference each level of the pointer and add an offset.
Of course I have a function for that too :)
uintptr_t FindDmaAddy(HANDLE hProcHandle, uintptr_t BaseAddress, uintptr_t Offsets[], int PointerLevel)
{
uintptr_t pointer = BaseAddress;
uintptr_t pTemp;
uintptr_t pointerAddr;
for (int i = 0; i < PointerLevel; i++)
{
if (i == 0)
{
ReadProcessMemory(hProcHandle, (LPCVOID)pointer, &pTemp, sizeof(pTemp), NULL);
}
pointerAddr = pTemp + Offsets[i];
ReadProcessMemory(hProcHandle, (LPCVOID)pointerAddr, &pTemp, sizeof(pTemp), NULL);
}
return pointerAddr;
}
I would highly recommend watching some Youtube tutorials to see how it's done, much better explained in video format.

Choosing unique names for luaL_newmetatable

I'm writing a Lua library which registers some metatables using luaL_newmetatable(). Since other libraries might do that as well, I'd like to ask what is a good strategy to avoid having the same name used twice. I was thinking about using a reverse DNS name like com.mydomain.mylibrary which should be pretty safe I guess. However, I'd like to ask if there maybe is a better or standard way of choosing unique names for libraries using luaL_newmetatable().
I like use lightuserdata with pointer to string.
#define LCURL_EASY_NAME LCURL_PREFIX" Easy"
static const char *LCURL_EASY = LCURL_EASY_NAME;
It just requires simple functions to use it.
int lutil_newmetatablep (lua_State *L, const void *p) {
lua_rawgetp(L, LUA_REGISTRYINDEX, p);
if (!lua_isnil(L, -1))
return 0;
lua_pop(L, 1);
lua_newtable(L); /* create metatable */
lua_pushvalue(L, -1); /* duplicate metatable to set*/
lua_rawsetp(L, LUA_REGISTRYINDEX, p);
return 1;
}
Similar for get/set. Checkout e.g. my Lua-cURL library.
I would use a string that describes what is in the "object" as this string is output in Lua error message eventually:
e.g. if the metatable is named "database connection":
stdin:1: bad argument #1 to 'status' (database connection expected, got no value)
If you use a UUID, nobody can make sense of the output.

Luabind calling convention issues

I am having an issue with Luabind that I am unsure of how to fix without some over-simplified solution.
Luabind appears to only allow binding to functions using the __cdecl calling convention. In my current project all of the functionality exposed to extensions/plugins is exposed using __stdcall. This leaves me unable to bind the exposed objects directly and instead I have to make wrappers for the objects exposed. This would be fine but there are a lot of objects that would need to be wrapped.
For example, an object can look like this:
struct IObject
{
void __stdcall SomeFunc1( void );
void __stdcall SomeFunc2( const char* );
};
struct IObjectContainer
{
IObject* __stdcall GetObject( int );
IObject* __stdcall GetObject( const char* );
};
struct IObjectCore
{
IObjectContainer* __stdcall GetObjectContainer();
};
I don't have the option of changing the entire projects calling convention currently so I am seeing if someone has a solution to perhaps patch Luabind to work with __stdcall functions. I am not the best with templates and with boost things, so I'm personally unsure where to even start trying to add the ability to use __stdcall functions.
For reference, I am using:
Lua 5.1.4
Luabind 0.9.1
VS2010
Both Lua and Luabind are stock latest versions of their rev. (Not using Lua 5.2 for project restriction reasons, but if there is a __stdcall fix for 5.2/Luabind I will gladly take that as well.)
I could only find a fix for a very old version of Luabind to do this but the patch floating on the net still for that does not line up with the current Luabind code at all.
If there is any other information needed feel free to ask.
Sadly due to inactivity and no further answers from more searching I spoke with the project developer and have gotten the entire project stripped of __stdcall. So the bindings all work fine now via __cdecl. Not the route I wanted to take but things are working as planned now.
I faced the exact same problem when binding OpenGL (with GLEW functions) to Lua, and solved it using variadic templates.
Now if the function is global and you know its address in compile time, you can be good with something like this:
template<typename Signature>
struct wrap_known;
template<typename Ret, typename... Args>
struct wrap_known<Ret __stdcall (Args...)> {
template <Ret __stdcall functor(Args...)>
static Ret invoke(Args... arguments) {
return functor(arguments...);
}
};
// I know using macro is generally a bad idea but it's just shorter
#define wrap(f) wrap_known<decltype(f)>::invoke<f>
and then, when binding, use the macro like this:
luabind::def("Clear", wrap(glClear)),
luabind::def("Vertex4f", wrap(glVertex4f))
However, in your case, we have a bunch of member functions and not globals like above.
Here is the code for wrapping member functions with __stdcall calling convention:
template<typename Signature>
struct wrap_mem;
template<typename Sub, typename Ret, typename... Args>
struct wrap_mem<Ret(__stdcall Sub::*) (Args...)> {
template <Ret(__stdcall Sub::*functor) (Args...)>
static Ret invoke(Sub* subject, Args... arguments) {
return (subject->*functor)(arguments...);
}
};
#define wrap_member(f) wrap_mem<decltype(f)>::invoke<f>
Use it like this:
struct A {
int __stdcall my_method(double b) {
return 2;
}
};
// ...
luabind::class_<A>("A")
.def("my_method", wrap_member(&A::my_method))
Sometimes, however, you are not that lucky to know the function's address in compile time, and this happens with GLEW for example. For functions like glUniform*f, glGetUniformLocation, the "wrap" macro will not work, so I made another version for wrapping functions known at runtime:
template<typename Signature>
struct wrap_unknown;
template<typename Ret, typename... Args>
struct wrap_unknown<Ret (__stdcall*) (Args...)> {
template <Ret (__stdcall** functor)(Args...)>
static Ret invoke(Args... arguments) {
return (**functor)(arguments...);
}
};
#define wrap_ptr(f) wrap_unknown<decltype(f)>::invoke<&f>
(if above code scares you, it is actually a good sign)
Now you can bind GLEW functions like this:
luabind::def("Uniform4f", wrap_ptr(glUniform4f)),
luabind::def("GetUniformLocation", wrap_ptr(glGetUniformLocation))
Just don't ask me to write another version for binding pointers to members known at runtime :)
If you don't want to use C++11 for some reason, here you can find out how to pass function arguments and return value as template parameters in C++03.

confusion passing data to pthread_create()... how it works?

Please take a look to the pthread_create() prototype we have:
int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
void *(*start_routine) (void *), void *arg);
to the last argument is a void pointer. But taking a look in some code in the internet I see developers doing:
long t;
pthread_create( &thread, NULL, function, (void*)t);
and it works!!! I mean they are not doing:
pthread_create( &thread, NULL, function, (void*)&t);
in other words, the reference of "t" is not being used.
However, if I change the datatype to "int" instead "long".. does not work.
I believe the reference should be considered always but do you have idea why long is working with no references?
Thank you guys!
The parameter being passed to the thread function is a void*. In the general case, that pointer can point to some block of data the function can use.
However, remember that the pointer itself is a value. It's common to simply use that value as the data for the thread function if the amount of data you're passing is small enough to fit in a void* - namely if all you need to pass to the function is a integer value. That's what's happening the case:
long t;
t = /* some value to pass to the thread */;
pthread_create( &thread, NULL, function, (void*)t);
One advantage to this is that you don't have lifetime issues to deal with on the thread data.

Lua to 'C' calling convention issues

I don't really want to go down the metatables etc. route as it seems rather complicated.
To crudely access 'C' structs in Lua I do:
void execute_lua_script(char *name)
{
lua_pushstring (L,name);
lua_gettable (L, LUA_GLOBALSINDEX);
lua_pushstring(L,"junk");
lua_pushinteger(L,7);
lua_pushlightuserdata(L, avatar_obj);
lua_pcall (L, 3, 2, 0);
}
The registered C func is:
int get_obj_struct(lua_State *L)
{
const char *str;
OBJECT_DEF *obj;
int stack;
obj=(OBJECT_DEF *)lua_touserdata(L,1);
str=lua_tostring(L,2);
//printf("\nIN OBJ:%d %s",obj,str);
if (!strcmp(str,"body->p.x"))
lua_pushnumber(L,obj->body->p.x);
if (!strcmp(str,"collided_with"))
lua_pushlightuserdata(L, obj->collided_with);
if (!strcmp(str,"type"))
lua_pushnumber(L,obj->type);
stack=lua_gettop(L);
//printf("\n%d",stack);
if (stack<3)
report_error("Unknown structure request ",(char *)str);
return 1;
}
Although crude; it works! :-)
The problem is when I request "collided_with" (a pointer); I need to return that back to my script; but for reasons I don't understand 'obj' ends up as nil.
My lua script:
function test(a,b,obj)
--print("\nLUA! test:",a,b);
b=b+1;
c=get_obj_struct(obj,"body->p.x");
--print("x:",c);
collided_with=get_obj_struct(obj,"collided_with");
type=get_obj_struct(collided_with,"type");
print("type:",type);
return a,b;
end
I am expecting 'collided_with' to be a pointer that I can then pass back into get_obj_struct and look for type.
I know it's something to do with me mis-using pushlightuserdata and also reading for the obj.
So an explanation would be great!. Also if someone wishes to give a version that uses 'tables' (as I assume that would be much more efficient) then I would be grateful for the help.
The online "Programming In Lua" book provides a good description of how to implement Lua types in C. In my opinion, your best bet would be to follow the examples provided in Chapter 28 to "do it right" and create a complete Lua wrapper for your object. In addition to being easier to maintain, it will almost certainly be more faster than a strcmp based implementation.

Resources