I'm trying to find the address of the SetProcessDEPPolicy function of the Windows API in kernel32 (see my problem here and the first answer I got).
I've never written a Windows C++ program before so I'm a bit lost but I have this so far:
#include <windows.h>
#include <iostream>
int main(int argc, char* argv[])
{
HANDLE kernel32 = GetModuleHandle("kernel32");
FARPROC* funcAddr = (FARPROC *) GetProcAddress(kernel32, "SetProcessDEPPolicy");
std::cout << "# ";
}
I'm getting the following error on line 7:
C:\Documents and Settings\John\Desktop>c++ finddep.cpp -o finddep.exe finddep.cpp: In function 'int main(int, char**)': finddep.cpp:7:79: error: invalid conversion from 'HANDLE {aka void*}' to 'HINSTA NCE' [-fpermissive] FARPROC funcAddr = (FARPROC *) GetProcAddress(kernel32, "SetProcessDEPPolicy") ;
^
In file included from c:\mingw\include\windows.h:50:0,
from finddep.cpp:1: c:\mingw\include\winbase.h:1675:27: error: initializing argument 1 of 'int (__ attribute__((__stdcall__)) * GetProcAddress(HINSTANCE, LPCSTR))()' [-fpermissive ] WINBASEAPI FARPROC WINAPI GetProcAddress(HINSTANCE,LPCSTR);
^ finddep.cpp:7:79: error: cannot convert 'int (__attribute__((__stdcall__)) **)() ' to 'FARPROC {aka int (__attribute__((__stdcall__)) *)()}' in initialization FARPROC funcAddr = (FARPROC *) GetProcAddress(kernel32, "SetProcessDEPPolicy") ;
I couldn't find any good ideas on how to solve this from Google.
(Once I get this to compile, how can I print the address in the pointer?)
EDIT: Added Cyclone's suggestion from the comment, getting same error Invalid conversion from HANDLE to HINSTANCE
This is how you should do it:
#include <windows.h>
#include <iostream>
int main(int argc, char* argv[])
{
HMODULE kernel32 = GetModuleHandleA("kernel32");
FARPROC *funcAddr = (FARPROC *)GetProcAddress(kernel32, "SetProcessDEPPolicy");
std::cout << "#" << funcAddr;
}
Related
Here is Minimal example :-
#include <stdio.h>
#include <Windows.h>
using namespace std;
void myFunc(TCHAR Path)
{
printf("pathLen : %lu\n", sizeof(Path));
printf("character size : %lu\n", sizeof(*Path));
printf("pathLenInBytes : %lu\n", sizeof(Path) * sizeof(*Path));
}
int main()
{
TCHAR selfPath[MAX_PATH];
if (GetModuleFileName(NULL, selfPath, MAX_PATH) == 0) // Getting exe File Location
printf("Error : %lu\n", GetLastError());
printf("Self Path : %s\n", selfPath);
myFunc(selfPath);
return 0;
}
Here is Error Output from MinGW-W64 Compiler :-
g++ -Os -s -o goga.exe tesst.cpp
tesst.cpp: In function 'void myFunc(LPCSTR, TCHAR)':
tesst.cpp:9:43: error: invalid type argument of unary '*' (have 'TCHAR' {aka 'char'})
9 | printf("character size : %lu\n", sizeof(*Path));
| ^~~~
tesst.cpp:10:35: error: 'pathLen' was not declared in this scope
10 | printf("pathLenInBytes : %lu\n", pathLen * sizeof(*Path));
| ^~~~~~~
tesst.cpp:10:53: error: invalid type argument of unary '*' (have 'TCHAR' {aka 'char'})
10 | printf("pathLenInBytes : %lu\n", pathLen * sizeof(*Path));
| ^~~~
tesst.cpp: In function 'int main()':
tesst.cpp:23:22: error: invalid conversion from 'TCHAR*' {aka 'char*'} to 'TCHAR' {aka 'char'} [-fpermissive]
23 | myFunc("AppBroker", selfPath);
| ^~~~~~~~
| |
| TCHAR* {aka char*}
tesst.cpp:6:32: note: initializing argument 2 of 'void myFunc(LPCSTR, TCHAR)'
6 | void myFunc(LPCSTR Name, TCHAR Path)
| ~~~~~~^~~~
But If I put the GetModuleFineName() directy inside myFunc() then it works :-
#include <stdio.h>
#include <Windows.h>
using namespace std;
void myFunc()
{
TCHAR selfPath[MAX_PATH];
if (GetModuleFileName(NULL, selfPath, MAX_PATH) == 0) // Getting exe File Location
printf("Error : %lu\n", GetLastError());
printf("Self Path : %s\n", selfPath);
printf("pathLen : %lu\n", sizeof(selfPath));
printf("character size : %lu\n", sizeof(*selfPath));
printf("pathLenInBytes : %lu\n", sizeof(selfPath) * sizeof(*selfPath));
}
int main()
{
myFunc();
return 0;
}
But I dont need it this way. How can i solve this error ?
EDIT : Tried replacing myFunc(TCHAR Path) with myFunc(TCHAR *Path) & also with myFunc(TCHAR Path[]). Both Work and program compiles successfully but the output is different that expected output now !
Expected Output :-
Self Path : C:\Users\username\Desktop\Coding\PETS\muse\goga.exe
pathLen : 260
character size : 1
pathLenInBytes : 260
Output that I Get:-
Self Path : C:\Users\username\Desktop\Coding\PETS\muse\goga.exe
pathLen : 8
character size : 1
pathLenInBytes : 8
I make an attempt to answer
In your first version, your prototype must be
myFunc(TCHAR *Path) or myFunc(TCHAR Path[]) because a path is an array of TCHAR, thus a TCHAR*
(a starting documentation can be found here or here)
What you obtained from the first code that compiles is only what you have asked.
Let us see:
printf("pathLen : %lu\n", sizeof(Path));
printf("character size : %lu\n", sizeof(*Path));
printf("pathLenInBytes : %lu\n", sizeof(Path) * sizeof(*Path));
First remark: you should not use sizeof (thanks # Remy LEABEAU for review) with TCHAR* but _tcslen() or lstrlen
In the first line, you asked to display the size of path which is a pointer (a TCHAR*). The size
of a pointer can be 4 bytes or 8 bytes depending on your system(ref). So 8 is correct.
In an array, its name is also the adress of the first element in it. Thus if you try to printf
sizeof(*Path), you ask to print the size of the first character pointed by the pointer, thus 1.
The two previous lines also explain what the thrid line gives you: 1*8 = 8.
If pathLenis the size in byte of the path, you may use _tcslen() or lstrlen() to compute the length of the path and then use sizeof(TCHAR) as found here
Proposition to obtain what your needed output:
printf("pathLen : %lu\n", _tcslen(Path));
printf("TCHAR size : %lu\n", sizeof(TCHAR));
printf("pathLenInBytes : %lu\n", _tcslen(Path)* sizeof(*Path));
I have c++ file like below one,
#include <iostream>
using namespace std;
extern "C" {
#include "sample_publish.c"
}
int main()
{
int antenna_id = 123;
send_message_to_mqtt(&antenna_id);
}
I have included a c file in c++ file and I need to pass the variable antenna_id to the function send_message_to_mqtt and the same is in c file like below one.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"
void send_message_to_mqtt(int *antenna_id) {
MQTTClient client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_deliveryToken token;
int rc;
MQTTClient_create(&client, "tcp://mqtt1.mindlogic.com:1883", "ExampleClientPub",
MQTTCLIENT_PERSISTENCE_NONE, NULL);
conn_opts.keepAliveInterval = 20;
conn_opts.cleansession = 1;
if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
{
printf("Failed to connect, return code %d\n", rc);
exit(EXIT_FAILURE);
}
printf("DATA FROM C++:::%d\n", *antenna_id);
char payload_data[] = "hi";
//pubmsg.payload = payload_data;
pubmsg.payload = *antenna_id
pubmsg.payloadlen = (int)strlen(*antenna_id);
pubmsg.qos = 1;
pubmsg.retained = 0;
MQTTClient_publishMessage(client, "MQTT-Examples", &pubmsg, &token);
printf("Waiting for up to %d seconds for publication of %s\n""on topic %s for client with ClientID: %s\n",(int)(10000L/1000), "Hello World!", "MQTT-Examples", "ExampleClientPub");
rc = MQTTClient_waitForCompletion(client, token, 10000L);
printf("Message with delivery token %d delivered\n", token);
MQTTClient_disconnect(client, 10000);
MQTTClient_destroy(&client);
// return rc;
}
When I execute a c++ file, the antenna_id variable is doesnt accessible in c file which in turn not allowing me to map against pubmsg.payload and this is due to the below error,
dell#dell-Inspiron-5379:~/workspace_folder$ g++ sample.cpp -o sample -lpaho-mqtt3c
In file included from sample.cpp:5:0:
sample_publish.c: In function ‘void send_message_to_mqtt(int*)’:
sample_publish.c:30:22: error: invalid conversion from ‘int’ to ‘void*’ [-fpermissive]
pubmsg.payload = *antenna_id
^~~~~~~~~~~
sample_publish.c:31:5: error: expected ‘;’ before ‘pubmsg’
pubmsg.payloadlen = (int)strlen(*antenna_id);
^~~~~~
How to overcome this one?
A guess on the problem, it's most likely this line:
pubmsg.payload = *antenna_id
Besides missing the semicolon, the payload is a pointer to the first byte of the data to be sent. That is, you should not dereference the pointer:
pubmsg.payload = antenna_id;
On a related note, this line is also very wrong:
pubmsg.payloadlen = (int)strlen(*antenna_id);
The strlen function is to get the length if a null-terminate byte string.
The length of an int can be gotten with the sizeof operator:
pubmsg.payloadlen = sizeof *antenna_id;
Note that here you must use the dereference operator, otherwise you get the size of the pointer itself.
I found this code for injecting dll files and call functions from them. I got an exe and the source code. The exe is working but when i try to compile the source code i get this error:
LoadDll.cpp: In Funktion »bool ExecuteRemoteThread(HANDLE, BOOL, BOOL, wchar_t*, wchar_t*)«:
LoadDll.cpp:313:62: Fehler: ungültige Umwandlung von »DWORD (__attribute__((__stdcall__)) *)(RemoteThreadBlock*) {aka long unsigned int (__attribute__((__stdcall__)) *)(RemoteThreadBlock*)}« in »LPCVOID {aka const void*}« [-fpermissive]
In file included from c:\mingw\bin\../lib/gcc/mingw32/4.7.2/../../../../include/windows.h:50:0,
from LoadDll.cpp:16:
c:\mingw\bin\../lib/gcc/mingw32/4.7.2/../../../../include/winbase.h:2215:24: Fehler: Argument 3 von »BOOL WriteProcessMemory(HANDLE, LPVOID, LPCVOID, SIZE_T, SIZE_T*)« wird initialisiert [-fpermissive]
The source code can be found at: https://pastebin.com/AuZpy57U
It seems like the error is in line 313
if ( ! WriteProcessMemory( hProcess, p, &RemoteThread, 0, 0 ) )
I hope you can help me compiling this.
if ( ! WriteProcessMemory( hProcess, p, &RemoteThread, 0, 0 ) )
You have to cast the third parameter:
if ( !WriteProcessMemory( hProcess, p, reinterpret_cast<LPCVOID>(&RemoteThread), 0, 0 ) )
Update:
To get rid of undefined reference to 'WinMain#16' you should use
int main()
{
int argc;
wchar_t **argv = CommandLineToArgvW(GetCommandLineW(), &argc);
// ...
instead of
int wmain(int argc, wchar_t *argv[])
{
// ...
I've follow the next tutorial:
https://msdn.microsoft.com/en-us/library/64tkc9y5(v=vs.80).aspx
It is working fine for me. But I need to printf the response of the callbackfunctions:
printf(uReturnVal);
I get the error: cannot convert argument 1 from 'UINT' to 'const char *const '
I've tried another options:
printf(Convert.ToString(uReturnVal)); //ERROR :'Convert': undeclared identifier [
And:
printf(uReturnVal->ToString()); //ERROR: '->ToString' must point to class/struct/union/generic
And:
printf(uReturnVal.ToString());//error: /ERROR: '->ToString' must point to class/struct/union/generic
This is the code of the tutorial:
typedef UINT (CALLBACK* LPFNDLLFUNC1)(DWORD,UINT);
HINSTANCE hDLL; // Handle to DLL
LPFNDLLFUNC1 lpfnDllFunc1; // Function pointer
DWORD dwParam1;
UINT uParam2, uReturnVal;
hDLL = LoadLibrary("MyDLL");
if (hDLL != NULL)
{
lpfnDllFunc1 = (LPFNDLLFUNC1)GetProcAddress(hDLL,
"DLLFunc1");
if (!lpfnDllFunc1)
{
// handle the error
FreeLibrary(hDLL);
return true;
}
else
{
// call the function
uReturnVal = lpfnDllFunc1(dwParam1, uParam2);
}
}
Many thanks in advance.
First argument to printf functions is always format specifier. In your case printf("%u\n",uReturnVal) should work. See Format Specification Syntax: printf and wprintf Functions.
To Expand:
The code above is pure C.
You can also do it in C++ style, even more elegant:
#include <iostream>
...
uReturnVal = lpfnDllFunc1(dwParam1, uParam2);
std::cout << "Result is: " << uReturnVal << std::endl;
I found this code for reading data from my USB peripheral:
#include "stdafx.h"
#define IWEARDRV_EXPLICIT
#include <windows.h>
#include <iweardrv.h>
int _tmain(int argc, _TCHAR* argv[])
{
// Load functions dynamically (in case they don't have a VR920)
HINSTANCE iweardll = LoadLibraryA("iweardrv.dll");
if (!iweardll) {
printf("VR920 drivers are not installed, you probably don't have a VR920.");
return 2;
}
IWROpenTracker = (PIWROPENTRACKER) GetProcAddress(iweardll, "IWROpenTracker");
IWRCloseTracker = (PIWRCLOSETRACKER) GetProcAddress(iweardll, "IWRCloseTracker");
IWRZeroSet = (PIWRZEROSET) GetProcAddress(iweardll, "IWRZeroSet");
IWRGetTracking = (PIWRGETTRACKING) GetProcAddress(iweardll, "IWRGetTracking");
IWRGetVersion = (PIWRGETVERSION) GetProcAddress(iweardll, "IWRGetVersion");
// Try to connect to the VR920 tracker
if (IWROpenTracker()) {
printf("VR920 is not connected.");
return 1;
}
// Read 20 samples
for (int i=1; i<=20; i++) {
LONG y, p, r;
double yaw, pitch, roll;
if (!IWRGetTracking(&y,&p,&r)) {
yaw = y*(180.0/32768.0);
pitch = p*(180.0/32768.0);
roll = r*(180.0/32768.0);
printf("Yaw=%lf degrees, Pitch=%lf degrees, Roll=%lf degrees", yaw, pitch, roll);
} else {
printf("Unable to read tracking.");
}
Sleep(500);
}
// Tidy up
IWRCloseTracker();
FreeLibrary(iweardll);
return 0;
}
Where I've setted additional include directory for include file iweardrv.h. It returns me these errors:
IntelliSense: argument of type "const char *" is incompatible with parameter of type "LPCWSTR"
IntelliSense: identifier "printf" is undefined
How do I avoid the errors? First error refers to LoadLibrary argument "iweardrv.dll" (a dynamic Library related to iweardrv.h) and second error refers to all printf calling lines.
EDIT: I corrected the first error using LoadLibraryA() because it takes a const char* but I cannot correct the second error.
The first error is because you are compiling with UNICODE defined and LoadLibrary expects a wide string. Use the L prefix to specify a wide literal:
LoadLibrary(L"iweardrv.dll");
The second error is due to a missing #include. You need to include stdio.h to define printf:
#include <stdio.h>
For C++ it would be more normal to use std::cout rather than printf.