C++, pre-processor statement - c++

Can someone explain what does this statement do?
#define CONST_SIG (void (*) () ) 1

This statement defines CONST_SIG to be 1 cast into a pointer to a function that gets no parameters and returns void. This may be useful if you have a pointer to a function and you perhaps test it for truthness, then CONST_SIG will be true.
You can try the cdecl program, which is available in many linux distributions, for "English translation" of C declarations. Example output in this instance:
cdecl> explain (void (*) () )
cast unknown_name into pointer to function returning void
Side-note: The reason it says "unknown_name" is because our pointer has no name. To name it, for example, "p", would look like this: (void (*p) () ).

You can pass CONST_SIG to a function which expects a function pointer and treats a value of 1 as a special value for this function pointer.

Related

Is void *function() a pointer to function or a function returning a void*?

I'm confused about the meaning of void *function().
Is it a pointer to function or a function returning void*? I've always used it on data structures as a recursive function returning a pointer, but when i saw a code in multithreading (pthread) there is a same function declaration. Now I'm confused what's the difference between them.
The function has the return type void *.
void *function();
So I always prefer in such cases to separate the symbol * from the function name like
void * function();
And as Jarod42 pointed to in a comment you can rewrite the function declaration in C++ using the trailing return type like
auto function() -> void *;
If you want to declare a pointer to function then you should write
void ( *function )();
where the return type is void Or
void * ( *function )();
where the return type void *.
Or a pointer to function that returns pointer to function
void * ( *( *function )() )();
Whenever I'm unsure about C syntax issues, I like to use the cdecl utility (online version) to interpret for me. It translates between C syntax and English.
For example, I input your example of void *foo() and it returned
declare foo as function returning pointer to void
To see what the other syntax would look like, I input declare foo as pointer to function returning void and it returned
void (*foo)()
This gets particularly useful when you have multiple levels of typecasts, stars, or brackets in a single expression.
It is a function returning a pointer to void.
Think of your declaration this way:
void *(function());
This would be a function returning void (or nothing):
void (*function2)();
Think of the above declaration this way:
void ((*function2)());
A much easier way to write these is to use typedefs:
typedef void *function_returning_void_pointer();
typedef void function_returning_nothing();
function_returning_void_pointer function;
function_returning_nothing *function2;
This generally eliminates the confusion around function pointers and is much easier to read.
Declarations in C/C++ are read from the identifier outwards following operator precedence.
A quick look at the C/C++ operator precedence table in wikipedia reveals that the function call operator () has a higher precedence than the indirection operator *. So, your function declarations reads like this:
Start at the identifier: function is
function() a function that takes no arguments
void* function() and returns a void*.
This general principle also holds with array declarations ([] also has higher precedence than *) and combinations of the two. So
int *(*arr[42])();
is read as
arr is
arr[42] an array of 42 elements which are
*arr[42] pointers to
(*arr[42])() functions that take no arguments and
int *(*arr[42])() return an int*.
It takes a bit to get used to this, but once you've understood the principle, it's easy to read those declarations unambiguously.

What does void(*)() mean in code

I saw this code today in some fb profile, and was not able to understand what is and how this is working:-
(*(void(*)()) shellcode)()
Can someone please explain me, what does above code mean ?
Full Code Snippet Below :-
#include <stdio.h>
#include <string.h>
char *shellcode = "\x31\xc0\x50\x68\x2f\x2f\x73\x68\x68\x2f\x62\x69"
"\x6e\x89\xe3\x50\x53\x89\xe1\xb0\x0b\xcd\x80";
int main(void)
{
fprintf(stdout,"Length: %d\n",strlen(shellcode));
(*(void(*)()) shellcode)();
return 0;
}
It is a cast to a function pointer (with no returned result and no arguments). I prefer using typedef to define signature of such functions:
typedef void plainsig_t(void);
then simply code
(*(plainsig_t*)shellcode) ();
For function pointers, you don't need to dereference them, so it is shorter to just code:
((plainsig_t*) shellcode) ();
which basically calls the function whose machine code is located inside shellcode memory zone.
BTW, this is not strictly portable C. In principle, there is no guarantee that you can cast a data pointer to a function pointer. (On some weird processors -e.g. embedded microcontrollers, DSP, 1970s era computers-, code and data sit in different address spaces, or have different pointer sizes, etc....). But most common processors and ABI (x86-64/Linux, ARM/Android, ....) have the same address space for code and for data and accept casting function pointers to data pointers and vice versa.
This is one place that C and C++ differ.
In C it means a pointer to a function returning void and taking an unspecified number of arguments of unspecified types.
In C++ it means a pointer to a function returning void and taking no argument.
The expression as a whole takes the address of shellcode, casts it to a pointer to function type, then invokes the function -- i.e., executes the op-codes in that string.
void(*)() means "a pointer to a void function that takes no arguments." The line
(*(void(*)()) shellcode)();
is casting shellcode to such a function pointer, dereferencing the pointer (not actually necessary), and then calling the function.
It's a function pointer. Type specifiers match declarations; so a function void f() has type void(); and a pointer to a function void (*pf)() has type void(*)().
Note that, as with function declarations, it has slightly different meanings in C and C++. In C, the empty parentheses mean it has an unspecified number of parameters, while in C++ it means it has no parameters. However, that doesn't affect the meaning of the code.
This code reinterprets an array as a function and attempts to call it. Presumably, the array contains machine code to print a message, or format your hard drive, or something. On most modern platforms, this will cause a protection fault since the static data is (hopefully) not executable by default.
In C a variable is declared as int foo;
, to declare a function we use int foo( ); It means that the return type of the function is int. To declare a pointer we use *foo.
In the expression (*(void(*)())0)() we can see that
Assuming that the variable fp is a function pointer, we can use (*fp)( ); to call the function, because fp is a function pointer, and *fp is the function pointed to by the pointer, so (*fp)( ); can call the function.
Suppose fp is a pointer to a non-return value type, then the way to call it is void (*fp)( ), then the type of the fp variable is void (*)( ).
If we were to cast this type to a constant shellcode, then we use ( void (*)() ) shellcode.
Now that the shellcode is cast to the type, in order to call the shellcode we use
( ( void (*)() ) shellcode )();
Note: We can use typedef to replace the type name of the above expression
For example: typedef void (*ff)( ); Therefore, the way to call a function can be written as:
(*(ff) shellcode ) ( );
from : https://www.codetd.com/en/article/14043929

C++ :: double colon marks and (void *) [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What does (char *) x or (void *) z mean?
I am working with a c++ file and have encountered the following line:
tmp.sort(Hash::pairval, printPair, (void *)(tmp.bitSize()));
I am most unsure of what (void *) means. bitsize() is a function, and I have heard the term passing a function pointer before. Is that what this is?
I know the :: is normally the scope resolution operator, which I have seen in .cpp/.h object type files. I believe it is serving the same purpose here, to state that pairval is found in Hash.
Thanks
The (void *) is simply casting the return value of tmp.bitSize() to a void pointer type. Casting is a very common operation in C++ and c as well.
Hash::pair
Is most probably a call to a static member of class Hash.
The (void*) part is a cast to void pointer of tmp.bitSize() which most probably returns some kind of value. So there is no function pointer.
I am most unsure of what (void *) means. bitsize() is a function, and I have heard the term passing a function pointer before. Is that what this is?
Nope. Note the parentheses, tmp.bitSize() is a function call expression that is called and returns a value. Hence - no function pointers involved here.
The return value is then cast to the pointer-to-void type (i.e. the catch-all "pointer to something" type) in order to be passed to a function which expects such pointer.
Why on Earth would someone convert a bit size (which looks like a number) into a pointer, I have no idea. This is somewhere between dubious and incorrect.
Read up on casting in C++. C-style casts are discouraged and casting to void* is seldomly useful and often dangerous because of the strict aliasing rule.
know the :: is normally the scope resolution operator, which I have seen in .cpp/.h object type files. I believe it is serving the same purpose here, to state that pairval is found in Hash.
That's correct.

What does the macro ((void(*)())0)() mean?

The outcome of the following macro is clear:
#define CRASH() do {\
*(int *)(uintptr_t)0xbbadbeef = 0;\
((void(*)())0)();\
} while (false)
My question is, what does the line
((void(*)())0)();
break down to, in English? For example, "this is a function that returns a pointer to a...."
It looks like it casts 0 as a function pointer (with the signature that it takes not parameters and has void return type) and then invokes it.
( ( void(*)() ) 0 ) ();
/* cast..*/ /* fn pointer signature */ /*..cast 0 */ /* invocation */
Which is another way to say that it's trying to invoke (call) a function that's expected to be located in memory at address 0x00000000 - which is guaranteed to be an invalid address.
Cast 0 to a pointer to a void function that takes can be called with no parameters (the (void(*)())0 part of the expression)
Call that function through a pointer with an empty parameter list (the () part after it).
EDIT 1: Edited in response to Cristoph's comment.
It casts a NULL pointer to a method taking no parameters and returning void, and attempts to call this method.
Needless to say, it crashes, so the name CRASH suits it very well.
It casts 0 to a function pointer, where the function takes no argument and returns void, then tries to call this function. It basically dereferences a null pointer.
It casts 0 to a pointer to a function, then attempts to call that function. Which will cause a segfault and crash.
Edit: way too much competition for these questions. Upvotes all round, and I'm going to bed :)
It means “treating NULL pointer as pointer to void function(), call function()”.
It takes the value zero, and casts it to a function pointer that doesn't return anything (void).
Presumably, the purpose is that when you call this "function", it calls address zero, which should indeed crash the application.
For me it is simpler to translate to a different C++, rather than directly to english:
typedef void (void_func_t)(); // type of a function taking no arguments
// and returning void
typedef void_fnct_t* void_func_ptr; // pointer to such a function
static_cast<void_func_ptr>(0)(); // call that function
// ((void_func_ptr)0)(); // pure C equivalent cast
if fp is a pointer to a function, *fp is the function itself, so(fp)()is the way to invoke it. ANSI C permits this to be abbreviated as fp(), bu keep in mind that it is only an abbreviation. -------C traps an pitfalls.
( ( void()() )0 ) () is the avvreviation of ( ( void()() )0 )()

How to read this kind of pointer in c++?

CUnknown* (*)( LPUNKNOWN pUnk, HRESULT* phr );
Seems I've always been in trouble reading such complicated pointers..
How do you read it? what if the expression even longer?
Everyone has said what it is, but you asked how to read it.
Function pointer syntax is as follows:
RETURN_VALUE (*POINTER_NAME) (ARGUMENT LIST)
So
foo (*bar) (baz)
is a pointer to a function taking baz and returning foo, and the pointer is called bar.
In the case that you only want to write the type of a function pointer, rather than declare one, you just leave out the name, e.g.
RETURN_VALUE (*) (ARGUMENT_LIST)
as you see here.
For parsing hard-to-understand C declarations, there's a nice program called cdecl available on most Linux and Unix-like systems, as well as available as a web app: http://cdecl.org/
What I learned from books and Uni was to start at the middle and proceed outwards back and forth. The trick is only to do it slowly, and know where the middle actually is.
You have a
CUnknown* (*)( LPUNKNOWN pUnk, HRESULT* phr );
that's a pointer (*)
Now we go right: it's a pointer to a function because the next thing is a (
The arguments of the function are a LPUNKNOWN and a pointer to HRESULT, and that's it.
Now we go left: the function returns a pointer to CUnknown.
So, as stated by everyone, it's a pointer to a function that takes two arguments -a LPUNKNOWN and a pointer to a HRESULT- and returns a pointer to CUnknown.
Link beauties: this and this.
The Clockwise Spiral Rule helps me understand things like this. From the site:
Starting with the unknown element, move in a spiral/clockwise direction; when ecountering the following elements replace them with the corresponding english statements:
Keep doing this in a spiral/clockwise direction until all tokens have been covered.
Always resolve anything in parenthesis first!
[X] or []
=> Array X size of... or Array undefined size of...
(type1, type2)
=> function passing type1 and type2 returning...
*
=> pointer(s) to...
It's a pointer to a function taking the arguments 'LPUNKNOWN pUnk, HRESULT* phr' and it returns a pointer to a CUnknown.
it's a function pointer with two arguments that returns a CUnknown*
I think this is pointer to a function taking LPUNKNOWN and pointer to HRESULT, returning pointer to CUnknown
For some function:
int f(int a, int& b, int* c);
The type of the expression:
&f
Or, equivalently:
f
Is:
int(*)(int, int&, int*)
And an easy way to remember this is that a function pointer type specifier is just like a function declaration, except with the name replaced with (*). You can also perform a typedef:
typedef int(*ftype)(int, int&, int*);
And now you can write:
ftype func = f;
Rather than:
int(*func)(int, int&, int*) = f;