Open a dll (get handle) in c++ - c++

I'm looking to load a dll library in c++, visual studio.
When I do I get error code 193, this is:
ERROR_BAD_EXE_FORMAT
193 (0xC1)
%1 is not a valid Win32 application.
The code is below
using namespace std;
int main(){
HINSTANCE dllhandle =
LoadLibrary(L"C:\\LKG5000_DLL_ver1_10\\English\\64bit\\LKIF2.dll");
cout << dllhandle << endl;
if (dllhandle != 0)
{
cout << "Created Handle" << endl;
}
else
{
cout << ":(" << endl;
}
cout << GetLastError() << endl;
getchar(); //Lazy way to keep cmd window open
return 0;
}
Any suggestions? Thanks

Given the DLL path it looks like it's a 64-bit (WIN64) DLL.
Make sure your program that is trying to load that DLL is compiled for 64-bit target as well.
You can't load a 64-bit DLL in a 32-bit application or the other way around.
Read here for more details.

Related

Loading a DLL with LoadLibraryA(path_to_dll) is changing the inherit handle flag (HANDLE_FLAG_INHERIT) from 1 to 0 for file descriptors 0, 1, and 2

We have written some functions in golang and a c wrapper on top of that to invoke those functions. We first build golang code to create an archive file and then we build the wrapper code in c to be consumed as a DLL.
After loading this DLL using LoadLibraryA(path_to_dll) in my program I am seeing that the inherit flags for fd 0, 1, and 2 are getting changed from 1 to 0. This does not happen immediately after loading the DLL though. I had added sleep in my code after the load library call and seems like it takes a few milliseconds after loading the library to change the flag values.
I am using GetHandleInformation((HANDLE) sock, &flags) to get the inherit flag value.
Any idea/pointers on what could be causing this? Thanks!
Updates:
I was able to find out the exact line in the go code that is flipping the inherit flag values. The global variable reqHandler in below k8sService.go code is causing this. Any idea why the use of this global variable is flipping the inherit flag values?
my-lib/k8sService.go (go code)
package main
import "C"
import (
"my-lib/pkg/cmd"
)
func main() {
}
var reqHandler []*cmd.K8sRequest
my-lib/pkg/cmd/execute.go
import (
"my-lib/pkg/dto"
)
type K8sRequest struct {
K8sDetails dto.K8sDetails
}
my-lib/pkg/dto/structs.go
package dto
// K8sDetails contains all the necessary information about talking to the cluster. Below struct has few more variables.
type K8sDetails struct {
// HostName of the cluster's API server
HostName string `json:"hostname"`
// Port on which the API server listens on to
Port int `json:"port"`
}
We have a C wrapper on top of the above k8sService.go. We first build golang code to create an archive file and then with this archive file and wrapper code in C we build the target DLL. Below is the sample program which loads this DLL and also prints the inherit flag values before and after loading the DLL.
#include <windows.h>
#include <iostream>
#include <io.h>
#include "wrapper/cWrapper.h"
void printInheritVals() {
typedef SOCKET my_socket_t;
my_socket_t fd0 = _get_osfhandle(0);
my_socket_t fd1 = _get_osfhandle(1);
my_socket_t fd2 = _get_osfhandle(2);
std::cout << "fd0: " << fd0 << std::endl;
std::cout << "fd1: " << fd1 << std::endl;
std::cout << "fd2: " << fd2 << std::endl;
DWORD flags;
int inherit_flag_0 = -1;
int inherit_flag_1 = -1;
int inherit_flag_2 = -1;
if (!GetHandleInformation((HANDLE) fd0, &flags)) {
std::cout << "GetHandleInformation failed" << std::endl;
} else {
inherit_flag_0 = (flags & HANDLE_FLAG_INHERIT);
}
if (!GetHandleInformation((HANDLE) fd1, &flags)) {
std::cout << "GetHandleInformation failed" << std::endl;
} else {
inherit_flag_1 = (flags & HANDLE_FLAG_INHERIT);
}
if (!GetHandleInformation((HANDLE) fd2, &flags)) {
std::cout << "GetHandleInformation failed" << std::endl;
} else {
inherit_flag_2 = (flags & HANDLE_FLAG_INHERIT);
}
std::cout << "inherit_flag_0: " << inherit_flag_0 << std::endl;
std::cout << "inherit_flag_1: " << inherit_flag_1 << std::endl;
std::cout << "inherit_flag_2: " << inherit_flag_2 << std::endl;
}
int main()
{
printInheritVals(); // In output all flag values are 1
HINSTANCE hGetProcIDDLL = LoadLibraryA(PATH_TO_DLL);
if (!hGetProcIDDLL) {
std::cout << "could not load the dynamic library" << std::endl;
return EXIT_FAILURE;
}
std::cout << "Library loaded" << std::endl;
printInheritVals(); // In output all flag values are 1
Sleep(1000);
printInheritVals(); // In output all flag values are 0
return EXIT_SUCCESS;
}
This is a bug in the golang.org/x/sys/windows package. The same issue used to be in the built-in syscall package as well, but it was fixed in Go 1.17.
Something in your project must be importing the golang.org/x version of the package instead of the built-in one, and so the following code executes to initialize the Stdin, Stdout, and Stderr variables:
var (
Stdin = getStdHandle(STD_INPUT_HANDLE)
Stdout = getStdHandle(STD_OUTPUT_HANDLE)
Stderr = getStdHandle(STD_ERROR_HANDLE)
)
func getStdHandle(stdhandle uint32) (fd Handle) {
r, _ := GetStdHandle(stdhandle)
CloseOnExec(r)
return r
}
The fix for that code would be to remove the CloseOnExec call, which is what clears HANDLE_FLAG_INHERIT on the given file handle.
How to solve that in your project is less clear. I think you can vendor golang.org/x/sys module in your project, perhaps with a replace directive in your go.mod. Apply the fix in your local copy.
Meanwhile, I encourage you to also report the bug. The documentation instructs you to report the issue on the main Go project at GitHub, prefixing the title with x/sys.

Why can't I open DLL file? Every time it returns NULL

So, I'm trying to use a function from DLL file and for some reason I can't open the DLL file: when I'm using the LoadLibrary function it returns as NULL
I'm freaking out that I can't find this bug
typedef unsigned int (WINAPI* AvVersion)(void);
void secret()
{
HMODULE dll = LoadLibrary("Secret.dll");
if (dll == NULL)
{
std::cout << "coudlnt open ""secret.dll""\nError Code:" << GetLastError() << std::endl;
return;
}
AvVersion function = (AvVersion)GetProcAddress(dll, "TheAnswerToLifeTheUniverseAndEverything");
std::cout << "result:" << function() << std::endl;
}
The code number is 126
and the name of the function is TheAnswerToLifeTheUniverseAndEverything

Function pointer obtained from GetProcAddress crashes the program if it uses the stdlib

I'm trying to dynamically load a dll and call a function from it at runtime. I have succeeded in getting a working pointer with GetProcAddress, but the program crashes if the function from the dll uses the stdlib. Here's the code from the executable that loads the dll:
#include <iostream>
#include <windows.h>
typedef int (*myFunc_t)(int);
int main(void) {
using namespace std;
HINSTANCE dll = LoadLibrary("demo.dll");
if (!dll) {
cerr << "Could not load dll 'demo.dll'" << endl;
return 1;
}
myFunc_t myFunc = (myFunc_t) GetProcAddress(dll, "myFunc");
if (!myFunc) {
FreeLibrary(dll);
cerr << "Could not find function 'myFunc'" << endl;
return 1;
}
cout << "Successfully loaded myFunc!" << endl;
cout << myFunc(3) << endl;
cout << myFunc(7) << endl;
cout << myFunc(42) << endl;
cout << "Successfully called myFunc!" << endl;
FreeLibrary(dll);
return 0;
}
Here's code for the dll that actually works:
#include <iostream>
extern "C" {
__declspec(dllexport) int myFunc(int demo) {
//std::cout << "myFunc(" << demo << ")" << std::endl;
return demo * demo;
}
}
int main(void) {
return 0;
}
(Note that the main method in the dll code is just to appease the compiler)
If I uncomment the line with std::cout however, then the program crashes after the cout << "Sucessfully loaded myFunc!" << endl; line but before anything else gets printed. I know there must be some way to do what I want; what do I need to change for it to work?
As discussed in the comments, it turns out that the compiler's demands for a main function were hints that I was inadvertently making a an exe that decptively used the file extension dll, not an actual dll (because I didn't quite understand the compiler options I was using), which in some way messed up the dynamic loading of that assembly.

C++/Cheat Engine, Writing to memory in Google Chrome - WriteProcessMemory & ReadProcessMemory

In efforts to learn more C++, I have chosen - you know - something fun to do and that is writing to random application's memory. The code I have written seems to work on all applications but I am having difficulties getting it to work with Google Chrome tabs.
What I am trying to do is simply change my score on Slope (on y8.com) for which I have the memory address with the help of cheat engine. The problem seems to be retrieving the Process ID of the tab. Using Chrome's Task Manager, I translated the tab's address to hex, opened the process in cheat engine and found the score address.
Here the problem comes. Whenever I use GetWindowThreadProcessId(window, &processID); cout << processID, it doesn't print the ID which can be seen in chrome's task manager for the game's tab. In fact, it prints the ID of chrome as a whole (which I know because in chrome's task manager, "chrome" has that ID). And the score cannot be written to or read from chrome's processID. If I ignore this problem, buffer seems to always print as 0.. no changes.
I am very new to this, and expect myself not to know what I am talking about. If you test the game yourself, you'll have to find the address that your chrome is using at the time. But here's the code (I have commented out the WriteProcessMemory and put Read just so I get it working before I write anything):
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
int main() {
int buffer = 0;
LPVOID address = (LPVOID)0x15E7E1B0FB8/*(0x000000000192DFA0 + 0x0000291D8FE04000 + 0x18)*/;
cout << "Begin playing the game and wait for the 0 score to appear" << endl;
HWND window = FindWindow(NULL, "Slope Game - Play online at Y8.com");
if (window) {
cout << "Game found running! You ready to hax?" << endl;
DWORD processID = 11180;
GetWindowThreadProcessId(window, &processID);
HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, false, processID);
if (handle) {
/*string hackedScoreInput = "0";
cout << "Desired Score: " << flush; getline(cin, hackedScoreInput);
int hackedScore = stoi(hackedScoreInput);
int suc = WriteProcessMemory(handle, address, &hackedScore, sizeof(hackedScore), NULL);
if (suc > 0) {
cout << "HAXED!" << endl;
CloseHandle(handle);
}
else {
cerr << GetLastError() << endl;
cerr << hackedScore << " of size: " << sizeof(hackedScore) << endl;
return 3;
}*/
while (true) {
ReadProcessMemory(handle, address, &buffer, sizeof(buffer), NULL);
cout << buffer << " at adress: " << processID << endl;
Sleep(100);
system("CLS");
}
}
else {
cerr << "Could not open the process" << endl;
return 2;
}
}
else {
cerr << "Error! Could not find window!" << endl;
Sleep(3000);
return 1;
}
return 0;
}
What's wrong with the code?
Modern browsers use multiple processes and there is no rule that says that a browser tab HWND has to be owned by the process where the web page "runs".
Some browser implementations might have one main process that hosts the UI including all tabs but the actual web page content might be rendered to a shared bitmap/memory in a different process where it is safe to run scripts etc.
Chrome is open source so you could take a look and see if there is a way to find out which render process renders a certain tab by looking at the child processes command line arguments.

Values returned from a DLL differ between straight g++ and qt using g++

I have written a dll that uses an abstract interface to allow access to the c++ class inside. When I load the library dynamically at run-time using the LoadLibrary() function using a simple console created in eclipse using g++ and call a function from within the dll I get the correct values returned. However when writing the same console program using qt-creator qt5 with the g++ compiler I get completely different results that are not correct.
All of this was written under Windows 7 64-bit but using the x86 side of it for the programs.
The code that calls the dll from eclipse looks as follows:
HMODULE hMod = ::LoadLibrary("libTestDll.dll");
if (hMod) {
cout << "Library Loaded" << endl;
CreateITestType create = (CreateITestType) GetProcAddress(hMod,
"GetNewITest");
ITest* test = create();
std::cout << test->Sub(20, 5) << std::endl;
std::cout << test->Sub(20, 3) << std::endl;
std::cout << test->Add(20, 5) << std::endl;
std::cout << test->Add(13, 4) << std::endl;
DeleteITestType del = (DeleteITestType) GetProcAddress(hMod,
"DeleteITest");
del(test);
test = NULL;
FreeLibrary(hMod);
}
This returns:
Library Loaded
15
17
25
17
The code that calls the dll from qt looks as follows:
HMODULE hMod = LoadLibrary(TEXT("libTestDll.dll"));
if(hMod)
{
CreateITestType create = (CreateITestType)GetProcAddress(hMod, "GetNewITest");
DeleteITestType destroy = (DeleteITestType)GetProcAddress(hMod, "DeleteITest");
ITest* test = create();
std::cout << test->Sub(20, 5) << std::endl;
std::cout << test->Sub(20, 3) << std::endl;
std::cout << test->Add(20, 5) << std::endl;
std::cout << test->Add(13, 4) << std::endl;
destroy(test);
test = NULL;
FreeLibrary(hMod);
}
And This returns:
1
-17
25
24
Both programs have the imports:
#include <windows.h>
#include <iostream>
#include "TestDll.h"
And finally the functions are implemented as follows:
int Test::Add(int a, int b)
{
return (a+b);
}
int Test::Sub(int a, int b)
{
return (a-b);
}
My question is where is the difference coming from seeing as the two programs are identical in both code and compiler, and how can this be fixed?
Did you also rebuild the DLL with qt-creator qt5 with the g++ compiler? If not, then what you've discovered is that if you don't use the exact same compiler, compiler options and settings, defines, and pretty much every other aspect of the build system, C++ interfaces are not typically ABI compatible.