How would someone get the actual location/address of result function 1002DDCC3 through offset in IDA PRO?
Specifically the "a1 + 0x2E0" part.
It calls a new function obviously sub_100xxxxx;
Let's say
a1 == 942691698;
int (__stdcall *__stdcall QueryInterface(unsigned int a1))(int)
{
if ( a1 == 942691698 )
return (int (__stdcall *)(int))sub_1002DDC3;
}
int __stdcall sub_1002DDC3(int a1, int a2)
{
int result; // eax#2
if ( a1 )
result = (*(int (__stdcall **)(_DWORD))(*(_DWORD *)a1 + 0x2E0))(a2);
else
result = -1;
return result;
}
Raw Assembly of the function 1002DDC3 is http://img.techpowerup.org/121010/Capture.png
Your wording is very unclear. Assuming that QueryInterface() really does have something to do with IUnknown::QueryInterface():
If you're asking "what is the meaning of the return value of sub_1002DDC3()", it's probably an HRESULT. The most important values here are zero (S_OK), -1 (general error), and non-zero (specific errors).
Or are you asking "what is the address of sub_1002DDC3()?"
It would actually be easier to understand this if you could post the raw disassembly.
Edited to add
The address of the interface method is determined at runtime. The disassembler doesn't know the addresses in advance and so can't tell you which method is being called.
Yes, you need to disassemble the COM object separately.
It depends on the value of the 'a1' argument. Since this function can be called with different values of 'a1', it is impossible to tell by just looking at the listing. You will have to run it under a debugger or check the callers.
Related
I am learning C++ using C++ Primer 5th edition. In particular, i read about void*. There it is written that:
We cannot use a void* to operate on the object it addresses—we don’t know that object’s type, and the type determines what operations we can perform on that object.
void*: Pointer type that can point to any nonconst type. Such pointers may not
be dereferenced.
My question is that if we're not allowed to use a void* to operate on the object it addressess then why do we need a void*. Also, i am not sure if the above quoted statement from C++ Primer is technically correct because i am not able to understand what it is conveying. Maybe some examples can help me understand what the author meant when he said that "we cannot use a void* to operate on the object it addresses". So can someone please provide some example to clarify what the author meant and whether he is correct or incorrect in saying the above statement.
My question is that if we're not allowed to use a void* to operate on the object it addressess then why do we need a void*
It's indeed quite rare to need void* in C++. It's more common in C.
But where it's useful is type-erasure. For example, try to store an object of any type in a variable, determining the type at runtime. You'll find that hiding the type becomes essential to achieve that task.
What you may be missing is that it is possible to convert the void* back to the typed pointer afterwards (or in special cases, you can reinterpret as another pointer type), which allows you to operate on the object.
Maybe some examples can help me understand what the author meant when he said that "we cannot use a void* to operate on the object it addresses"
Example:
int i;
int* int_ptr = &i;
void* void_ptr = &i;
*int_ptr = 42; // OK
*void_ptr = 42; // ill-formed
As the example demonstrates, we cannot modify the pointed int object through the pointer to void.
so since a void* has no size(as written in the answer by PMF)
Their answer is misleading or you've misunderstood. The pointer has a size. But since there is no information about the type of the pointed object, the size of the pointed object is unknown. In a way, that's part of why it can point to an object of any size.
so how can a int* on the right hand side be implicitly converted to a void*
All pointers to objects can implicitly be converted to void* because the language rules say so.
Yes, the author is right.
A pointer of type void* cannot be dereferenced, because it has no size1. The compiler would not know how much data he needs to get from that address if you try to access it:
void* myData = std::malloc(1000); // Allocate some memory (note that the return type of malloc() is void*)
int value = *myData; // Error, can't dereference
int field = myData->myField; // Error, a void pointer obviously has no fields
The first example fails because the compiler doesn't know how much data to get. We need to tell it the size of the data to get:
int value = *(int*)myData; // Now fine, we have casted the pointer to int*
int value = *(char*)myData; // Fine too, but NOT the same as above!
or, to be more in the C++-world:
int value = *static_cast<int*>(myData);
int value = *static_cast<char*>(myData);
The two examples return a different result, because the first gets an integer (32 bit on most systems) from the target address, while the second only gets a single byte and then moves that to a larger variable.
The reason why the use of void* is sometimes still useful is when the type of data doesn't matter much, like when just copying stuff around. Methods such as memset or memcpy take void* parameters, since they don't care about the actual structure of the data (but they need to be given the size explicitly). When working in C++ (as opposed to C) you'll not use these very often, though.
1 "No size" applies to the size of the destination object, not the size of the variable containing the pointer. sizeof(void*) is perfectly valid and returns, the size of a pointer variable. This is always equal to any other pointer size, so sizeof(void*)==sizeof(int*)==sizeof(MyClass*) is always true (for 99% of today's compilers at least). The type of the pointer however defines the size of the element it points to. And that is required for the compiler so he knows how much data he needs to get, or, when used with + or -, how much to add or subtract to get the address of the next or previous elements.
void * is basically a catch-all type. Any pointer type can be implicitly cast to void * without getting any errors. As such, it is mostly used in low level data manipulations, where all that matters is the data that some memory block contains, rather than what the data represents. On the flip side, when you have a void * pointer, it is impossible to determine directly which type it was originally. That's why you can't operate on the object it addresses.
if we try something like
typedef struct foo {
int key;
int value;
} t_foo;
void try_fill_with_zero(void *destination) {
destination->key = 0;
destination->value = 0;
}
int main() {
t_foo *foo_instance = malloc(sizeof(t_foo));
try_fill_with_zero(foo_instance, sizeof(t_foo));
}
we will get a compilation error because it is impossible to determine what type void *destination was, as soon as the address gets into try_fill_with_zero. That's an example of being unable to "use a void* to operate on the object it addresses"
Typically you will see something like this:
typedef struct foo {
int key;
int value;
} t_foo;
void init_with_zero(void *destination, size_t bytes) {
unsigned char *to_fill = (unsigned char *)destination;
for (int i = 0; i < bytes; i++) {
to_fill[i] = 0;
}
}
int main() {
t_foo *foo_instance = malloc(sizeof(t_foo));
int test_int;
init_with_zero(foo_instance, sizeof(t_foo));
init_with_zero(&test_int, sizeof(int));
}
Here we can operate on the memory that we pass to init_with_zero represented as bytes.
You can think of void * as representing missing knowledge about the associated type of the data at this address. You may still cast it to something else and then dereference it, if you know what is behind it. Example:
int n = 5;
void * p = (void *) &n;
At this point, p we have lost the type information for p and thus, the compiler does not know what to do with it. But if you know this p is an address to an integer, then you can use that information:
int * q = (int *) p;
int m = *q;
And m will be equal to n.
void is not a type like any other. There is no object of type void. Hence, there exists no way of operating on such pointers.
This is one of my favourite kind of questions because at first I was also so confused about void pointers.
Like the rest of the Answers above void * refers to a generic type of data.
Being a void pointer you must understand that it only holds the address of some kind of data or object.
No other information about the object itself, at first you are asking yourself why do you even need this if it's only able to hold an address. That's because you can still cast your pointer to a more specific kind of data, and that's the real power.
Making generic functions that works with all kind of data.
And to be more clear let's say you want to implement generic sorting algorithm.
The sorting algorithm has basically 2 steps:
The algorithm itself.
The comparation between the objects.
Here we will also talk about pointer functions.
Let's take for example qsort built in function
void qsort(void *base, size_t nitems, size_t size, int (*compar)(const void *, const void*))
We see that it takes the next parameters:
base − This is the pointer to the first element of the array to be sorted.
nitems − This is the number of elements in the array pointed by base.
size − This is the size in bytes of each element in the array.
compar − This is the function that compares two elements.
And based on the article that I referenced above we can do something like this:
int values[] = { 88, 56, 100, 2, 25 };
int cmpfunc (const void * a, const void * b) {
return ( *(int*)a - *(int*)b );
}
int main () {
int n;
printf("Before sorting the list is: \n");
for( n = 0 ; n < 5; n++ ) {
printf("%d ", values[n]);
}
qsort(values, 5, sizeof(int), cmpfunc);
printf("\nAfter sorting the list is: \n");
for( n = 0 ; n < 5; n++ ) {
printf("%d ", values[n]);
}
return(0);
}
Where you can define your own custom compare function that can match any kind of data, there can be even a more complex data structure like a class instance of some kind of object you just define. Let's say a Person class, that has a field age and you want to sort all Persons by age.
And that's one example where you can use void * , you can abstract this and create other use cases based on this example.
It is true that is a C example, but I think, being something that appeared in C can make more sense of the real usage of void *. If you can understand what you can do with void * you are good to go.
For C++ you can also check templates, templates can let you achieve a generic type for your functions / objects.
I'm trying to edit an arduino library, it's
int hour() { // the hour now
return hour(now());
}
I tried
int hour() { // the hour now
char s[25];
return sprintf(s,"%02d", hour(now));
}
But it's returning annoying results, I don't know how to program in C++, I just need to print a "0" if the number is lower than 10. Thanks, Heitor.
You don't say what the annoying results are, but based on what you have shown I'm going to take a punt and say you get a compilation error related to mismatched return type in hour(), or that you are accessing invalid memory.
If you want the hour() function to return a 0-prefixed number, you'll need to change the return type. However, changing it to char* would see you return a pointer to memory allocated on the stack. Memory that becomes invalid as soon as you return.
What you'd need to do is to set aside a memory buffer in the code that calls hour(), not in hour() itself. Then you pass that to hour(), along with the size of the buffer.
Your calling code would look something like this:
char s[25]; // 25 still seems excessive, I suggest 3, so you can fit two digits plus zero termination.
hour( s, 25 );
and your hour() function would be:
void hour( char* pBuffer, size_t size ) {
snprintf( pBuffer, size, "%02d", hour( now() ) );
}
As everyone mentioned your question is vague.But from your title and content I think I might help you.
I think you need to print a 0 infront of every digit (hour) that is less than 10. that is if hour is 1 then print 01 etc.
If that's what you need then you made a few mistakes in your sketch.First of all you are returning a char array from the function not int. Then hour(now()) is required instead of hour(now).
char * hour() { // the hour now
static char s[25]; //might be 5 is enough and more
sprintf(s,"%02d", hour(now()));
return s;
}
PS : As the return type is char array if you were storing it to an integer variable at caller , as if say int hr = hour();,it wont be possible now.So you need to print it directly as Serial.println (hour ());
If you wanted to return the result without having to allocate data every time you could use something like this.
Note: This only works for values -99 to 999
typedef union
{
char str[4];
int i;
} CharInt;
CharInt hour()
{
CharInt ci = {0};
sprintf(ci.str,"%02d", hour(now()));
return ci;
}
int main()
{
printf("%s", hour().str);
}
Since s is local to the hour() function, when you return it goes out of scope and ceases to exist. So the processor is free to overwrite that with something else. When the caller tries to access the array it gets whatever was written over it instead of what it was inside that function. You should never try to return a pointer to a local variable from a function.
Given these typedefs and the value below:
typedef void GTVOID;
typedef GTVOID *PARAM_VALUE;
typedef unsigned long UDGT32
typedef UDGT32 PARAM_CONST;
typedef signed long DGT32;
typedef DGT32 RESULT_FUNC;
DWORD value = 1; // given from a define
How I can convert it to satisfy the needs of that device SDK function in C++?
RESULT_FUN RSetParam( PARAM_CONST DeviceParameter, PARAM_VALUE value);
The C reference code in samples is:
RSetParam( R_SOME_PARAM_CONST, (PARAM_VALUE)value );
I tried it below, but it's just weird. It compiles ok, works all day long and by some
creepy luck, starts throwing access violations out of blue:
RSetParam(R_SOME_PARAM_CONST, reinterpret_cast<void*> (value));
What I'm doing wrong?
You have tried to reinterpret the value 1 as an address. Depending on what the function RSetParam is doing with this address (value), the program may seg-fault. Especially, if it tries to write to this address.
I think, the function RSetParam awaits an address to a variable as second argument. The type of the variable might depend on something else, that is, why the adress must be passed as void *.
So, if you want to pass number 1 as DWORD you have to allocate a variable on the stack first and then pass its address:
DWORD tmp = 1; // given from define
RSetParam( R_SOME_PARAM_CONST, (PARAM_VALUE) &tmp ); // note the '&' !
I had this code as part of a C++ project
unsigned int fn() {
//do some computations
int value = ....
if(value <= 0)
return 0;
return (unsigned int)value;
}
I don't get the need to use the cast at the last return statement since all negative numbers will be caught in the if statement(hence returning 0).
And moreover this function fn is called from another function (whose return type is int) that simply returns the value returned by fn.
Thanks..
The purpose is to silence the compiler warning that could otherwise be issued.
I think that it really changes nothing
I personally run the same code for different scenarios and it appears the last cast can be done away with.
I am reading this tutorial about function pointers which said that function pointers can replace a switch statement
http://www.newty.de/fpt/intro.html .
Can anyone clarify?
We have a switch statement like this:
// The four arithmetic operations ... one of these functions is selected
// at runtime with a swicth or a function pointer
float Plus (float a, float b) { return a+b; }
float Minus (float a, float b) { return a-b; }
float Multiply(float a, float b) { return a*b; }
float Divide (float a, float b) { return a/b; }
// Solution with a switch-statement - <opCode> specifies which operation to execute
void Switch(float a, float b, char opCode)
{
float result;
// execute operation
switch(opCode)
{
case '+' : result = Plus (a, b); break;
case '-' : result = Minus (a, b); break;
case '*' : result = Multiply (a, b); break;
case '/' : result = Divide (a, b); break;
}
cout << "Switch: 2+5=" << result << endl; // display result
}
// Solution with a function pointer - <pt2Func> is a function pointer and points to
// a function which takes two floats and returns a float. The function pointer
// "specifies" which operation shall be executed.
void Switch_With_Function_Pointer(float a, float b, float (*pt2Func)(float, float))
{
float result = pt2Func(a, b); // call using function pointer
cout << "Switch replaced by function pointer: 2-5="; // display result
cout << result << endl;
}
// Execute example code
void Replace_A_Switch()
{
cout << endl << "Executing function 'Replace_A_Switch'" << endl;
Switch(2, 5, /* '+' specifies function 'Plus' to be executed */ '+');
Switch_With_Function_Pointer(2, 5, /* pointer to function 'Minus' */ &Minus);
}
As you can see, the Replace_A_Switch() function as an example is very unclear. Supposed we need to point the function pointer to one of 4 arithmetic functions(Plus,Mins,Multiply,Divide). how can we know which one we need to point to? We have to use the switch statement again to point the function pointer to the arithmetic functions , right?
It will be like this one**(please the comment in the code)**:
void Replace_A_Switch()
{
.....................
..........
//How can we know this will point to the &Minus function if we don't use the switch statement outside?
Switch_With_Function_Pointer(2, 5, /* pointer to function 'Minus' */ &Minus);
}
So in summary, what is the advantages of function pointer, it always said that the function pointer a late-binding mechanism , but in this tutorial i dont see any advantage of the function pointer for late binding.
Any help are very appreciated. Thanks.
What you're saying is pretty well true, you still need to decide somewhere what function pointer to use.
What you're looking at though is a pretty simple, contrived example for explanation purpose. It shows how you can leverage a function pointer. In this case it might be pointlessly complicated but a real case would probably be too complicated to use to instruct in this basic concept.
The difference becomes much clearer when you've got a lot of functions that have the same switch, or a switch with subsets of the same set. The difference is all the same though (this is also important). In that case, why rewrite it a bunch of times?
It also opens your code for a change in how the decision is made. Maybe you want to invert '+' and '-' for whatever reason. Change the point where you make the pointer and all the client code catches up.
Finally, what if you don't even need to make the decision? Instead of replacing the switch for example, what if you just wanted to do the addition version? Obviously addition is too simple a task for this level of design, but again it's just an example.
All this is true whether you're using function pointers or a class hierarchy. Someone has to decide what the input will be. What these constructs do is provide you a method to compose different bits into a running program. It also separates the part that is responsible for deciding which version of things to use from the using of those things. There are a lot of different ways to approach that creation (see creational design patterns for some).
As the tutorial states there are no advantages and the basic calculator is simply an example. The main use of function pointers is to allow the API-dev to define a function, which does something that is not known at the time the API is created.
A better example is probably qsort, which takes a comparison function. Thanks to this function-pointer argument it is possible to implement the sort in a generic way. Since you could not possibly know what kind of data needs to be sorted you can't know how the <,=,> operators have to be implemented. Thus you expect the caller to provide a function that implements the comparison thereby avoiding this dilemma.
In general, function pointers are often useful if you want to program something in a generic way. Its use is that of function-arguments in other languages. If someone asked you to implement a simple reduce function for example, you could come up with something like this:
void reduce(void *data, size_t nmemb, size_t size,
void (*op)(void *, void *), void *res){
int i;
for (i = 0; i < nmemb; ++i){
op(data, res);
data = (void *)((unsigned char*)data + size);
}
}
Clearly it is very advantageous over rewriting this for operations like multiply, add, and more complex ones all over again with the respective function replacing op.
I can see how you can convert your '+', '-' etc into an enum, and store the 4 func pointers into an array ordered by the enum order. After that arr[op] is the function you want, just execute that.
Alternatively a std::map<String, FuncType> map from + -> &Plus.
as from what i see..
the pt2Func is a name defined for pointer which references a function
you can see how it works in the main where it is being called
(removed the comment to make it more readable)
Switch_With_Function_Pointer(2, 5, &Minus);
&Minus here is a pointer that references to your function Minus
this is stupid as you are calling a function to reference another function by using a pointer.
There is no benefit and it does nothing special.. its just another more complicated way to call the Minus function
the Switch function however is just a normal switch encapsulated in a function for reusability