module handle through base address - c++

Im' trying to get the module handle of a module in C++ on windows.
My problem is that I have only the base address and File handle of the module but GetModuleHandle receives only its name as a parameter.
Is there a way in c++ on windows to obtain a module handle without knwoing the module's name?

Have you tried using GetModuleHandleEx (GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCTSTR)lpBaseAddress, &module)?

Use GetModuleHandleEx if you use WindowsXP or later. For previous Windows versions like Windows2000 this function is not available, but there is alternate solution, check comments at the bottom of this page: http://msdn.microsoft.com/en-us/library/ms683200(v=VS.85).aspx

Related

Can't find COM object from C++, although Guid it's registered

First of all happy new year to everyone, hope you're doing well!
I'm working on a C++ project in which I need to call a C# DLL I created following the first answer of this post. Once I have the DLL, I need to call it from Qt, so by using dumpcpp and the .tlb file generated by regasm, I managed to get the .cpp and .h files to use my classes. Just as a reference, the namespace of the classes is Wrapper, and the main class is Device with guid {DD4A4896-C105-4C60-839B-B18C99C8FE15}.
Once I have the generated files to use the DLL, if I try to create a Wrapper:: Device instance on Qt, I get the following error:
QAxBase::setControl: requested control {dd4a4896-c105-4c60-839b-b18c99c8fe15} could not be instantiated
QAxBase::qt_metacall: Object is not initialized, or initialization failed
It doesn't give any more information, so I tried to check if the guid was stored on the system registry (I used the regasm command explained on the previously quoted post, and It said that it was successful, but you never know). Opening Registry editor and searching for the Guid revealed that it's present at: Computer\HKEY_CLASSES_ROOT\WOW6432Node\CLSID\{DD4A4896-C105-4C60-839B-B18C99C8FE15}, which, as far as I know, is the right route for these guids, and it points to the right DLL.
I though It may be due to some kind ActiveQt problem, and as the previously quoted post explained how to use that DLL from VS C++, I decided to give it a try, using this as an another reference. I've finished with this code, which is supposed to create an instance of my Device object
#include <iostream>
#include <atlstr.h>
#import "C:\Users\javie\Documents\Wrapper\Wrapper\bin\x86\Release\netstandard2.0\Wrapper.tlb" named_guids raw_interfaces_only
inline void TESTHR(HRESULT x) { if FAILED(x) _com_issue_error(x); };
int main()
{
try
{
TESTHR(CoInitialize(0));
Wrapper::IDevicePtr devPtr = nullptr;
TESTHR(devPtr.CreateInstance("{DD4A4896-C105-4c60-839B-B18C99C8FE15}"));
}
catch (const _com_error& e)
{
CStringW out;
out.Format(L"Exception occurred. HR = %lx, error = %s", e.Error(), e.ErrorMessage());
MessageBoxW(NULL, out, L"Error", MB_OK);
}
CoUninitialize();// Uninitialize COM
std::cout << "Hello World!\n";
}
However, this doesn't work either, the createInstance method throws an exception of Class not registered and HR=80040154. Again, according to Registry editor, the class is registered, so I don't understand the error. I've also tried with devPtr.CreateInstance("Wrapper.Device"), devPtr.CreateInstance("Wrapper::Device") or `devPtr.CreateInstance("Wrapper::CLSID_Device") as the links I posted suggest, but in those cases I get another exception with HR=800401f3 and message Invalid class string.
It doesn't matter whether VS or Qt Creator are opened as administrator or not, I get the exact same error.
I have run out of ideas, and I really need to be able to use that DLL from Qt using the files generated by dumpcpp.
Does any one know what could be happening? It feels quite strange to me.
If your C++ application is 64-bit, that's the answer right there, because your C# component is 32-bit (or MSIL but registered to the 32-bit hive). In situations like these, a simple test using VBScript is always useful.
Write a simple VB Script (test.vbs)
Dim obj
Set obj = CreateObject("Wrapper.Device") ' or whatever your ProgID is
MsgBox TypeName(obj)
Now, run this macro 2 ways: with 32-bit and 64-bit versions of VBScript:
32-bit > c:\windows\SysWow64\cscript.exe test.vbs
64-bit > c:\windows\system32\cscript.exe test.vbs
This is assuming your C# component is dispatch compatible. If it's not, then it will still give you differing results that you can use to debug.
Assuming automation/IDispatch compatible, one will work and one won't if you have registered your component correctly.
Have you registered correctly? When I use regasm, I always use the the switches /tlb /codebase when registering the C# component for COM.
Ok, in case someone find the same error, I'll explain the solution I found.
The problem was that in my case, the C# class I developed depended on another 32 bits dll which was not registered on my PC. Once I registered the other dll, everything worked fine.
I don't know why VS kept telling me that the class was not registered when my class itselft was registered, it was one of its dependencies that wasn't registered.
Anyway, I discovered this thanks to Joseph's comments, so thanks a lot for your help.

Which module called my DLL exported function?

Background
I'm developing a C++ windows DLL module that exports a single function
__declspec(dllexport) void Run()
Motivation
I would like to implement some sort of accessing rights to my function. I wish to prevent unauthorized modules from activating my DLL proc.
I don't need a robust/bullet proof mechanism. I only like to "defend" this proc from other modules running under my own app.
Approach
Get the calling module name and decide based on the name if access is granted.
Question
Would this approach suffice?
if so, how do I get the name of the calling module?
if so, how do I get the name of the calling module?
get return address by call _ReturnAddress
get base address of the image that contains this return address -
RtlPcToFileHeader
finally call GetModuleFileName function
so code can be like this
HMODULE hmod;
if (RtlPcToFileHeader(_ReturnAddress(), (void**)&hmod))
{
WCHAR sz[MAX_PATH];
if (GetModuleFileName(hmod, sz, MAX_PATH))
{
DbgPrint("%p %S\n", hmod, sz);
}
}
about - are this work in XP ? yes, but with one note. _ReturnAddress is CL intrinsic - so not depended from os version (for say gcc exist __builtin_return_address (0) ) GetModuleFileName also very old api function and exist in win2000, xp, everywhere. about RtlPcToFileHeader
- it exported (and implemented) in ntdll.dll in all windows versions from xp to latest. also begin from win2003 it also exported from kernel32.dll but implementation here - simply jump to ntdll.RtlPcToFileHeader - so if want use this on xp also - link with ntdll.lib and place it before kernel32.lib in libs order or can get it it runtime by GetProcAddress(GetModuleHandle(L"ntdll"), "RtlPcToFileHeader");
or even if somebody afraid that RtlPcToFileHeader will be removed from ntdll (this is of course no) can use this
GetProcAddress(GetModuleHandle(g_xp ? L"ntdll" : L"kernel32"), "RtlPcToFileHeader");

Convert URI to path

I am working on a Windows C++ App, where I get a URI similar to file:///C:/test 1/file.foo. Now I want to e.g. open that URI with ifstream.
Is there any C/C++ API available on Windows to convert such a path?
My Google Foo seems to be weak today.
There are multiple file URI "versions" so you should not parse it yourself, some of the APIs are broken as well.
If you just want a Windows style path, call PathCreateFromUrl.
If you don't want to convert the path then you must use CreateURLMonikerEx or SHParseDisplayName (with a bind context) but then you end up with a Windows IStream instead.
There is PathCreateFromUrl() :
https://msdn.microsoft.com/en-us/library/bb773581(v=vs.85).aspx

IESetProtectedModeCookie function not found in Iepmapi.h

IESetProtectedModeCookie function not found in Iepmapi.h
But when i call function using LoadLibrary technique with Ieframe.dll then it create entry in LOW folder of cookies but get GP after creating entry.
How?
If you look at the documentation for IESetProtectedModeCookie, you can see that it is only supported in IE8 and above.
Try defining _WIN32_IE=_WIN32_IE_IE80 and call the function normally instead of using LoadLibrary.

Get fd or handle from socket object

I want to create a native (c++) module for node.js which is able to send sockets to another node process, which is completely unrelated to the current process. To do so, I tought of using the ancillary library, which has a really, really easy API for this. The problem I have to solve now is how I can get the fd or the handle of a socket object of node.js.
There's a TCPWrap class in tcp_wrap.cc & tcp_wrap.h, which has a property called handle_, which holds a uv_tcp_t object from libuv, but that property is private. Also I can't #include because it's just a module of node.js an not directly in node.js itself. I don't know if it's a good idea to copy the source files to my module just to get the that class...
Have you any ides how I could do it?
I doesn't have to run on winows, tough.
Thanks!
I finally found a way to do it. You can find the node module here:
https://github.com/VanCoding/node-ancillary
I've just taken the headers "tcp_wrap.h","stream_wrap.h" and "handle_wrap.h" and then included "tcp_wrap.h".
I could then get the object the following way:
TCPWrap* wrap = static_cast<TCPWrap*>(args[0]->ToObject()->GetPointerFromInternalField(0));
StreamWrap* s = (StreamWrap*)wrap;
The following code then gives access to the file descriptor
s->GetStream()->fd