I want to call MessageBox() function in such way:
1). load needed library
2). get the function address
3). call it
So, for such aim as I understand, I should define new type with all types of arguments in MessageBox function.
It returnes INT and accepts: HWND, LPCSTR, LPCSTR, UNIT.
So I registred new type:
typedef int(__stdcall *msgbox)(HWND, LPCSTR, LPCSTR, UINT);
I have problems with calling such function. Does such way work for all functions or only for exported?
How can I call MessageBox exactly in such way?
Full code:
#include <iostream>
#include <windows.h>
using namespace std;
typedef int(__stdcall *msgbox)(HWND, LPCSTR, LPCSTR, UINT);
int main(void)
{
HINSTANCE__ *hModule = LoadLibrary(L"\\Windows\\System32\\User32.dll");
msgbox *me = 0;
if(hModule != 0)
{
me = (msgbox*)GetProcAddress(hModule, "MessageBox");
}
return 0;
}
Why are you declaring everything as a pointer?
LoadLibrary returns an HMODULE, not an HINSTANCE__ * (it will work with the latter but it's always better to adhere to the documentation).
Similarly, msgbox is typedef'd to a function pointer type, so me is a msgbox, not a msgbox *.
The reason why GetProcAddress fails is because user32.dll exports 2 functions, MessageBoxA and MessageBoxW. When you simply call MessageBox in your code, macros defined in Windows.h replace it with one of the 2 actual function names depending on whether you're compiling for UNICODE or not. But when you're trying to directly access the exported function as you are doing, you need to explicitly specify which one you're trying to get a pointer to.
#include <iostream>
#include <windows.h>
typedef int(__stdcall *msgbox)(HWND, LPCSTR, LPCSTR, UINT);
int main(void)
{
HMODULE hModule = ::LoadLibrary(L"User32.dll");
msgbox me = NULL;
if( hModule != NULL ) {
me = reinterpret_cast<msgbox>( ::GetProcAddress(hModule, "MessageBoxA") );
}
if( me != NULL ) {
(*me)( NULL, "I'm a MessageBox", "Hello", MB_OK );
}
if( hModule != NULL ) {
::FreeLibrary( hModule );
}
}
Related
I want to experiment with the programs that write programs in C code, and i want to use construction like following:
int main() {
char* srcCode="int f(int x) { return x+42; }";
int (*compiledFun)(int) = compile(srcCode);
printf("result=%d", (*compiledFun)(123));
return 0;
}
Desired output should be printed "result=165".
My question is about compile() function. I may try to put srcCode in a file, then invoke external compiler, like gcc, then try to read produced binary, probably fix some addresses, and so to fill the compiledFun memory. But I feel like that would be a very inefficient stub. Is there any way to compile a program from within a program, directly from memory to memory? Maybe some library or a subset that can be ripped off gcc sources, responsible for producting binary code from source text?
That may be important addition, all source code that should be compiled is a function that takes arguments and returns. It will not call any external libraries and function like printf, but only do some calculations and return.
Use libtcc an in-memory C compiler from TinyC.
A complete example from here https://github.com/TinyCC/tinycc/blob/mob/tests/libtcc_test.c
/*
* Simple Test program for libtcc
*
* libtcc can be useful to use tcc as a "backend" for a code generator.
*/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "libtcc.h"
/* this function is called by the generated code */
int add(int a, int b)
{
return a + b;
}
/* this strinc is referenced by the generated code */
const char hello[] = "Hello World!";
char my_program[] =
"#include <tcclib.h>\n" /* include the "Simple libc header for TCC" */
"extern int add(int a, int b);\n"
"#ifdef _WIN32\n" /* dynamically linked data needs 'dllimport' */
" __attribute__((dllimport))\n"
"#endif\n"
"extern const char hello[];\n"
"int fib(int n)\n"
"{\n"
" if (n <= 2)\n"
" return 1;\n"
" else\n"
" return fib(n-1) + fib(n-2);\n"
"}\n"
"\n"
"int foo(int n)\n"
"{\n"
" printf(\"%s\\n\", hello);\n"
" printf(\"fib(%d) = %d\\n\", n, fib(n));\n"
" printf(\"add(%d, %d) = %d\\n\", n, 2 * n, add(n, 2 * n));\n"
" return 0;\n"
"}\n";
int main(int argc, char **argv)
{
TCCState *s;
int i;
int (*func)(int);
s = tcc_new();
if (!s) {
fprintf(stderr, "Could not create tcc state\n");
exit(1);
}
/* if tcclib.h and libtcc1.a are not installed, where can we find them */
for (i = 1; i < argc; ++i) {
char *a = argv[i];
if (a[0] == '-') {
if (a[1] == 'B')
tcc_set_lib_path(s, a+2);
else if (a[1] == 'I')
tcc_add_include_path(s, a+2);
else if (a[1] == 'L')
tcc_add_library_path(s, a+2);
}
}
/* MUST BE CALLED before any compilation */
tcc_set_output_type(s, TCC_OUTPUT_MEMORY);
if (tcc_compile_string(s, my_program) == -1)
return 1;
/* as a test, we add symbols that the compiled program can use.
You may also open a dll with tcc_add_dll() and use symbols from that */
tcc_add_symbol(s, "add", add);
tcc_add_symbol(s, "hello", hello);
/* relocate the code */
if (tcc_relocate(s, TCC_RELOCATE_AUTO) < 0)
return 1;
/* get entry symbol */
func = tcc_get_symbol(s, "foo");
if (!func)
return 1;
/* run the code */
func(32);
/* delete the state */
tcc_delete(s);
return 0;
}
I am using Thrust 1.8 and I get two compiler errors when I try to compile the below code :
#include <thrust/device_vector.h>
#include <thrust/functional.h>
int main(int argc, char* argv[])
{
thrust::device_vector<bool> condition(100);
thrust::device_vector<int> input(100);
thrust::device_vector<float> result(100);
float mean = 10.4f;
thrust::transform(condition.begin(),condition.end(),input.begin(),result.begin(), ( (thrust::placeholders::_1 ) ? ( thrust::placeholders::_2) : (mean) ) );
}
When I try to compile, I get the following compiler time errors :
(for placeholders::_1)
Error : Expression must be of bool type (or convertible to bool)
(for placeholders::_2)
Error : operand types are incompatible ("const thrust::detail::functional::actor < thrust::detail::functional::argument<1U>>" and "float")
How to correct this?
You cannot use the placeholders like you tried to, i.e. in combination with a ternary operator.
Instead, you could create your own functor:
struct my_fun : public thrust::binary_function<bool,float,float>
{
float mean;
my_fun(float mean) : mean(mean) {}
__host__ __device__
float operator()(bool condition, float input) const
{
float result = mean;
if (condition)
{
result = input;
}
return result;
}
};
...
thrust::transform(condition.begin(),
condition.end(),
input.begin(),
result.begin(),
my_fun(mean));
I have a constructor where as first 2 parameteres I would like to pass:
ID3D11ShaderResourceView* as a steady downloaded texture OR
const CHAR* as a filename to downlowd this texture and assign it to a class ID3D11ShaderResourceView* member (with following release on demand), but I can not understand the way I should do it correctly. it looks this way:
class {button
public
button() {};
button(data1 (or texture or filname), data2 (or texture or filname), rest data....);
...
~button();
}
so I tried:
templates but failed, may be cause of knowledge lack, templates
define one type while I need a choice of 2. Varradic templates, or I didnt get them right but they mean undetermined amount of variables when I need to differ only 2 first.
Unions but it had conflict with class variable set - said could not match const char [amount] with const char* and unions do not work with std::string.
tried void* with typeid.name() but it always showed me "void *"
I don't want to overload constructors, becuase this will create 4+ of them barely differing one from another. Do you think boost::variant helps me in this case? Is there any smooth and effective way to build that kind of constructor? My c++ knowledge is on beginning level, sorry if its a duplicate topic, read all it suggested to me while creating it but didn't seem to find out anything closely similar, thanks:)
Update:
Applied boost::any, got next results:
class button : public frame {
public:
button() {};
button(boost::any _texture,
boost::any _hover_texture,
...
};
if (_texture.type() == typeid(ID3D11ShaderResourceView*)) texture = boost::any_cast<ID3D11ShaderResourceView*>(_texture);
if (_texture.type() == typeid(const char*))
{
if ( FAILED(D3DX11CreateShaderResourceViewFromFile(gvDevice,boost::any_cast<const char*>(_texture), NULL, NULL, &texture, NULL )) )
mboxout( "loading texture failed.", "UI texture load error", true );
};
if (_hover_texture.type() == typeid(ID3D11ShaderResourceView*)) hover_texture = boost::any_cast<ID3D11ShaderResourceView*>(_hover_texture);
if (_hover_texture.type() == typeid(const char*))
{
if ( FAILED(D3DX11CreateShaderResourceViewFromFile(gvDevice, boost::any_cast<const char*>(_hover_texture), NULL, NULL, &hover_texture, NULL )) )
mboxout( "loading texture failed.", "UI texture load error", true );
};
Is it the only possible decision because this one seems akward for me? Thanks :)
As always, when you have combinatoric explosion/tedious repetition, refactor your code into reusable units.
In this case, your constructor could be just
template <typename T1, typename T2>
button(T1 const& texture, T2 const& hover_texture)
: _texture(load(texture)),
_hover_texture(load(hover_texture))
{
};
And all the loading logic would be inside... you guess it the load function. A sample implementation of that:
static ID3D11ShaderResourceView* load(ID3D11ShaderResourceView* v){
return v; // just return the resources passed in
}
static ID3D11ShaderResourceView* load(char const* fname) {
ID3D11ShaderResourceView* p = NULL;
if (FAILED(D3DX11CreateShaderResourceViewFromFile(gvDevice, fname, NULL, NULL, &p, NULL)))
throw std::runtime_error(std::string("loading texture failed (") + fname + ")");
return p;
}
Note: while we were at it we separated UI from business logic. You do not want to display messageboxes from inside constructors. Ever. You just want to notify the caller of the problem and the caller decides what to do (use another resource, try a different path, retry a download, write a warning message to the log, shut down etc.)
Full Demo
Live On Coliru
#include <iostream>
#include <stdexcept>
///////////////////////////////////////////////////////
// mocking ID3D*
struct ID3D11ShaderResourceView;
enum ERROR_CODE { ERR_OK };
#define FAILED(e) (ERR_OK != (e))
static int gvDevice = 42;
ERROR_CODE D3DX11CreateShaderResourceViewFromFile(int, char const* fname, void*, void*, ID3D11ShaderResourceView**, void*) {
std::cout << "Loaded from " << fname << "\n";
return ERR_OK;
}
//
///////////////////////////////////////////////////////
struct frame{ virtual ~frame() = default; };
class button : public frame {
public:
button() {};
template <typename T1, typename T2>
button(T1 const& texture, T2 const& hover_texture)
: _texture(load(texture)),
_hover_texture(load(hover_texture))
{
};
private:
// TODO Rule-Of-Three constructor/destructorl
// SUGGEST: Rule-Of-Zero using shared pointers instead
ID3D11ShaderResourceView* _texture;
ID3D11ShaderResourceView* _hover_texture;
static ID3D11ShaderResourceView* load(ID3D11ShaderResourceView* v) { return v; }
static ID3D11ShaderResourceView* load(char const* fname) {
ID3D11ShaderResourceView* p = NULL;
if (FAILED(D3DX11CreateShaderResourceViewFromFile(gvDevice, fname, NULL, NULL, &p, NULL)))
throw std::runtime_error(std::string("loading texture failed (") + fname + ")");
return p;
}
};
#include <cassert>
int main() {
ID3D11ShaderResourceView* default_texture = NULL;
assert(!FAILED( D3DX11CreateShaderResourceViewFromFile(gvDevice, "default_texture.bin", NULL, NULL, &default_texture, NULL)));
try {
button button1("t1.bin", "hover1.bin");
button button2(default_texture, "hover2.bin");
button button3("t3.bin", default_texture);
button button4(default_texture, default_texture);
} catch(std::exception const& e) {
std::cout << "Oops: " << e.what() << "\n";
}
}
Prints:
Loaded from default_texture.bin
Loaded from t1.bin
Loaded from hover1.bin
Loaded from hover2.bin
Loaded from t3.bin
There's still a lot to be improved (see the comments, e.g.) but this is a start.
My aim is to call some function via its address. How can I do it?
I have done the next work for such aim, but at first(1) - I've got access violation ( don't know why ) and with the second I have some problems with calling function is ASM with ESP value...
The first (the problem with access violation):
#include <iostream>
#include <Windows.h>
const DWORD_PTR offset = 0x00001a90;
typedef void (__stdcall *uef)(int);
int main(void)
{
HMODULE hModule = LoadLibrary(L"C:\\Windows\\system32\\OpenAL32.dll");
DWORD_PTR addr = (DWORD_PTR)hModule + offset;
uef func = (uef)offset;
func(0);
return 0;
}
The second (problems at runtime with ESP value):
#include <iostream>
#include <Windows.h>
typedef void (__stdcall *uef)(int);
int main(void)
{
HMODULE hModule = LoadLibrary(L"C:\\Windows\\system32\\OpenAL32.dll");
uef obj = NULL;
if(hModule != NULL)
{
obj = reinterpret_cast<uef>(GetProcAddress(hModule, "alEnable"));
}
if(obj != NULL)
{
(*obj)(0);
}
if(hModule != NULL)
{
FreeLibrary(hModule);
}
return 0;
}
How could I solve this problem?
PS
And the another main question is:
How can I dynamically calculate the function address in runtime for next calling?
Thanks,
Best Regards!
First, there is a major issue (hence the access violation) with the hardcoded address offset (const DWORD_PTR offset = 0x00001a90). Don't do that! How can you know that the offsett will not be changed because of ASLR?
I am having a hard time compiling this C code.
Basically what happens is:
it does compile but when I run it (on Terminal) it prints me:Illegal instruction
I tried to debug it and on Xcode and when it attempts to execute (*fraction).print() it says: EXC_BAD_ACCESS
if I delete the (*fraction).print() line everything works fine (same happens if I only delete the next line)
GNU99 and -fnested-functions flag is enabled
I do not want to change the main function just the other stuff
This code drove me crazy for a whole afternoon so a little help would be really appreciated.
Thankyou
#include <stdlib.h>
#include "string.h"
#include "stdio.h"
typedef struct
{
int numerator;
int denominator;
void (*print)(); // prints on screen "numerator/denominator"
float (*convertToNum)(); //returns value of numerator/denominator
void (*setNumerator)(int n);
void (*setDenominator)(int d);
} Fraction;
Fraction* allocFraction(Fraction* fraction); //creates an uninitialized fraction
void deleteFraction(Fraction *fraction);
Fraction* allocFraction(Fraction* fraction)
{
void print()
{
int a= 10;
printf("%i/%i", (*fraction).numerator, (*fraction).denominator);
a--;
}
float convertToNum()
{
return (float)(*fraction).numerator/(float)(*fraction).denominator;
}
void setNumerator (int n)
{
(*fraction).numerator= n;
}
void setDenominator (int d)
{
(*fraction).denominator= d;
}
if(fraction== NULL)
fraction= (Fraction*) malloc(sizeof(Fraction));
if(fraction)
{
(*fraction).convertToNum= convertToNum;
(*fraction).print= print;
(*fraction).setNumerator= setNumerator;
(*fraction).setDenominator= setDenominator;
}
return fraction;
}
void deleteFraction(Fraction *fraction)
{
free(fraction);
}
int main (int argc, const char * argv[])
{
Fraction *fraction= allocFraction(fraction);
(*fraction).setNumerator(4);
(*fraction).setDenominator(7);
(*fraction).print(); //EXC_BAD_ACCESS on debug. Illegal instruction in Terminal
printf("%f", (*fraction).convertToNum());
(*fraction).print();
deleteFraction(fraction);
return 0;
}
You can't write C in the same way you write Javascript.
Specifically, it appears that print() is a nested function inside allocFraction() (which is itself not standard C but a gcc extension). You can't call a nested function through a function pointer from outside the scope of where it's defined. This is true even if you don't access anything in the outer scope from the nested scope.
Your code appears to be attempting to do object-oriented programming in C. Have you considered C++?