How to wrap functions with the `--wrap` option correctly? - c++

The man page of gcc 6.3 says:
--wrap=symbol
Use a wrapper function for symbol. Any undefined reference to
symbol will be resolved to "__wrap_symbol". Any undefined
reference to "__real_symbol" will be resolved to symbol.
...
If you link other code with this file using --wrap malloc, then all
calls to "malloc" will call the function "__wrap_malloc" instead.
The call to "__real_malloc" in "__wrap_malloc" will call the real
"malloc" function.
So I created a simple example:
#include <stdio.h>
int foo() {
printf("foo\n");
return 0;
}
int __wrap_foo() {
printf("wrap foo\n");
return 0;
}
int main () {
printf("foo:");foo();
printf("wrapfoo:");__wrap_foo();
printf("realfoo:");__real_foo();
return 0;
}
And compiled it with:
gcc main.c -Wl,--wrap=foo -o main
This gave me a warning:
main.c:18:21: warning: implicit declaration of function ‘__real_foo’ [-Wimplicit-function-declaration]
printf("realfoo:");__real_foo();
^~~~~~~~~~
Well going on. Now I would suggest an output like this:
foo:wrap foo
wrapfoo:wrap foo
realfoo:foo
Instead I get this:
foo:foo
wrapfoo:wrap foo
realfoo:foo
I hope the thing is clear. I am confused about the warning. Normally the __real function should be linked by the linker to foo(). Furthermore a call to foo() should be linked to __wrap_foo. But the output showes, that foo() is being executed instead.
How to use --wrap correctly?

As StoryTeller told me, I ignored the "undefined reference" requirement which I already posted above:
... Any undefined reference to symbol will be resolved to "__wrap_symbol". Any undefined reference to "__real_symbol" will be resolved to symbol.
To use the --wrap option I rearranged my code example like this:
main.c:
#include <stdio.h>
extern int foo();
extern int __real_foo();
int __wrap_foo() {
printf("wrap foo\n");
return 0;
}
int main () {
printf("foo:");foo();
printf("wrapfoo:");__wrap_foo();
printf("realfoo:");__real_foo();
return 0;
}
foo.c:
#include <stdio.h>
int foo() {
printf("foo\n");
return 0;
}
Then compile:
gcc main.c foo.c -Wl,--wrap=foo -o main
And the the amazing output after running ./main:
foo:wrap foo
wrapfoo:wrap foo
realfoo:foo
The trick is (correct me if I am wrong) that the reference of foo() and __real_foo() is not defined at compile time. I. E. they have **undefined references" which is the requierement for the linker to link foo() to __wrap_foo() and __real_foo() to foo().

Related

Where is the syntax with class as a parameter in main needed?

This question states that main can be implementation defined with some restrictions.
So, I wrote the following C++ code to try out the following signature of main:
main.h
class MyClass {
private:
int i;
public:
MyClass();
inline int geti() {
return i;
}
inline void seti(int i) {
this->i = i;
}
~MyClass();
};
MyClass::MyClass() {
this->i = 2;
}
MyClass::~MyClass() {
}
main.c++
#include <iostream>
#include "main.h"
int main(MyClass myClass) {
std::cout << myClass.geti() << std::endl;
return 0;
}
Which Gives the following results:
The command g++ -o main main.c++ -O3 compiles successfully with warnings:
main.c++:5:5: warning: first argument of ‘int main(MyClass)’ should be ‘int’ [-Wmain]
5 | int main(MyClass myClass) {
| ^~~~
main.c++:5:5: warning: ‘int main(MyClass)’ takes only zero or two arguments [-Wmain]
The command clang++ -o main main.c++ -std=c++14 gives the error:
main.c++:5:5: error: first parameter of 'main' (argument count) must be of type 'int'
int main(MyClass myClass) {
^
1 error generated.
the main file generated by g++ gives SIGSEGV (why though?)
So, if main can be implementation defined, why does clang give an error while g++ generated file give SIGSEGV?
I also went further and created a different code so that I will be able to pass a MyClass object to main.c++ as follows:
#include <iostream>
#include "main.h"
#include <unistd.h>
int main() {
MyClass myClass;
execve("./main",myClass,NULL);
return 0;
}
However, as execve takes the second parameter to be a char* const *, it does not compile. How do I pass the myClass object to the main file generated by g++?
The command g++ -o main main.c++ -O3 compiles successfully with warnings
This is not successful compilation. You should always use -Werror. If you fail to do so and then decide to ignore the warning and proceed with running the program, it's your own responsibility. You better know full well what you are doing. See this for more information.
the main file generated by g++ gives SIGSEGV (why though?)
The compiler has warned you. It is in your best interest to listen to it. If things go boom, chances are, that's because you have ignored warnings.
why does clang give an error while g++ generated file give SIGSEGV?
The program is not a valid C++ program. There is no meaningful difference between a warning and an error.
How do I pass the myClass object to the main file generated by g++?
You cannot. main must have a form equivalent to one of these two:
int main()
int main(int argc, char* argv[])
(Optional reading in italics) Other forms of main are implementation-defined. This means your implementation needs to support them in a documented way. Unless you have read documentation for your implementation and found that it supports the form of main you want, there's no way to do that.
Other than having an implementation-defined main, the only way a program can get hold of an object of a class type is by constructing that object.
You are close. You have identified your primary issue attempting to pass as a parameter to main() -- that won't work. The declaration for main() is defined by the standard and you are limited to passing string values (nul-terminated character arrays... C-Strings) in as arguments.
In your case you need to create an instance of your class within main(), e.g.
#include <iostream>
#include "main.h"
int main() {
MyClass myClass;
std::cout << myClass.geti() << std::endl;
return 0;
}
Your main.h header has a variable shadowing problem where at line 10:
inline void seti(int i) {
int i shadows a prior declaration at line 3, e.g. int i; (though the consequence would be unlikely to matter). Just replace the variable name in the second declaration with j (or whatever you like). Your code will compile without warning, e.g.
class MyClass {
private:
int i;
public:
MyClass();
inline int geti() {
return i;
}
inline void seti(int j) {
this->i = j;
}
~MyClass();
};
MyClass::MyClass() {
this->i = 2;
}
MyClass::~MyClass() {
}
Example Use/Output
$ ./bin/main
2
You can also call your seti() function to update the private variable in your class, e.g.
myClass.seti(5);
std::cout << myClass.geti() << std::endl;
Which would now output 5.
Let me know if you have further questions.

inline assembly in C++ function with return statement

Consider this code:
#include <cstdio>
int get_value() { asm("movl $254, %eax"); }
int main() { printf("%d\n", get_value()); }
Now if one compiles this code with g++ main.cpp, one gets a compiler warning (but the code still compiles):
main.cpp: In function ‘int get_value()’:
main.cpp:3:43: warning: no return statement in function returning non-void [-Wreturn-type]
3 | int get_value() { asm("movl $254, %eax"); }
|
As this answer says that if a compiler generates a binary with the above code, all bets are off. (no return statement from a function with return type int)
Indeed, when one compiles this code with optimization turned on g++ -O3 main.cpp, this program immediately segfaults.
So my question is how can one return from inline assembly within a c++ function that is conformant with C++, and one doesn't get this warning, and the code works fine.
I believe what you have to do is declare a dummy variable, and use the gcc extended syntax to output that variable, and then you can return that variable. The optimiser should strip both assignents out.
It is sort-of explained in https://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html#s5, and might look like this:
#include <cstdio>
int get_value() {
int b;
asm("movl $254, %0;"
: "=r"(b)
);
return b;
}
int main() {
printf("%d\n", get_value());
}

"Undefined Refrence to Foo" while compiling with G++

I have three files:
my.cpp
#include "my.h"
#include <iostream>
void print_foo() {
cout << foo << '\n';
}
void print(int i) {
cout << i << '\n';
}
my.h
extern int foo;
void print_foo();
void print(int);
use.cpp
#include "my.h"
int main(int argc, char *argv[]) {
foo = 7;
print_foo();
print(99);
return 0;
}
Now when I run g++ my.cpp use.cpp I get the error
/usr/bin/ld: /tmp/ccUKJUlZ.o: in function `print_foo()':
my.cpp:(.text+0x6): undefined reference to `foo'
/usr/bin/ld: /tmp/ccN0mIhY.o: in function `main':
use.cpp:(.text+0x11): undefined reference to `foo'
collect2: error: ld returned 1 exit status
Additionally, if I run g++ -c my.cpp everything goes alright, but, if I then run g++ my.o use.cpp I get the same error.
You never actually define a variable foo - in both use.cpp and my.cpp, you use foo, and in my.h you declare it as an extern.
See the beginning of this response for more information on declaring vs. defining. You may think that your problem would be solved if you added a type in front of your foo = 7 line in use.cpp; however, what you also need to do is make foo a global variable instead of a local one (which it is when you declare it simply within main), as extern will only "find" variables that have global scope. You can make a variable global by declaring it outside of any function (side note - you should only use global variables when you absolutely have to).
Therefore, you could solve your problem by changing your use.cpp to the following:
#include "my.h"
int foo = 7;
int main(int argc, char *argv[]) {
print_foo();
print(99);
return 0;
}

Inserting function calls in the gimple

I'm having problems figuring out how to do the next thing.
I have the following code:
test.cpp
#include <stdio.h>
void
function(void) {printf("Hellow ");}
int main(void) {
printf("World\n");
return 0;
}
And I want to transform it into the next one:
#include <stdio.h>
void
function(void) {printf("Hellow ");}
int main(void) {
function();
printf("World\n");
return 0;
}
with a gcc plugin.
The code that doesn't work in my plugin is this one:
...
tree function_fn;
tree function_fn_type;
function_fn_type=build_function_type_list(void_type_node, void_type_node, NULL_TREE);
function_fn = build_fn_decl ("function", function_fn_type);
gimple call = gimple_build_call (funcion_fn, 0);
gsi_insert_before (&gsi, call, GSI_NEW_STMT);
...
Then when I compile test.cpp with the plugin i have the next error message:
/tmp/cc2VRszt.o: In function main':
test.cpp:(.text+0x60): Undefined reference tofunction'
Anyone can help me?
You're building a function declaration, and inserting a call to a function based on the declaration, but unless you've defined that function in another translation unit you link to, it will be unresolved. If you want a plugin to insert a definition in the same translation unit like in your example, this guide for front-end developers would be a good start:
http://www.tldp.org/HOWTO/GCC-Frontend-HOWTO-7.html

C++: Linking files with GCC compiler

I have three files : myh.h; my.cpp; use.cpp. Here are the contents of the files:
myh.h
extern int foo;
void print_foo();
void print(int);
my.cpp
#include "myh.h"
#include <iostream>
void print_foo()
{
std::cout<<foo<<std::endl;
}
void print(int i)
{
std::cout<<i<<std::endl;
}
use.cpp
#include "myh.h"
int main()
{
foo=7;
print_foo();
print(99);
return 0;
}
GCC spews out the following error:
my.o:my.cpp:(.text+0x7): undefined reference to `foo'
use.o:use.cpp:(.text+0x10): undefined reference to `foo'
collect2: ld returned 1 exit status
I compile the files using the -c command and it doesn't give errors. I link using the following command:
g++ -o final my.o use.o
What is the problem here, I read other topics with similar problems, and the case here is just strange .....
For the curious this is an exercise drill from Stroustrup's book Programming principles of using C++
Edit: I did as dasblinkenlight said, and in use.cpp I added an int in front of foo (so now foo is defined), but I still get this error:
my.o:my.cpp:(.text+0x7): undefined reference to `foo'
collect2: ld returned 1 exit status
Which tells me that it is not defined in my.cpp also? If I have to define it everywhere what is the point of including it in the header file, or how should this be approached more appropriately?
You get a linker error because you declared foo, but you never defined it.
extern int foo is only a declaration; it does not cause allocation of memory for the foo variable, only promises that you will do it at some other place. To fix it, you need to add this line to one of the cpp files, like this:
#include "myh.h"
int foo;
int main()
{
foo=7;
print_foo();
print(99);
return 0;
}
The problem is that foo is declared but not defined. You need to define foo in exactly one of the translation units, e.g.:
int foo = 0;