How to emulate constructor or static block in C - c

I am enhancing a tool.
Please note that this tool will be linked to test program, which will have main( ) function, so my tool can't have main. What this tool has is a number of functions which the test program will use.
Now additionally, i want to add a timer to this tool. The idea is: when the test program is linked to this tool and starts, the timer should automatically start.
If this was C++, i would have created a class with a constructor, so that whenever the class is loaded, the constructor is called first, and i can initialize my timer inside the constructor.
If this was Java, i would have simply created a global static block, and put the timer code inside the static block.
But my tool is purely in C in Linux, so how can i achieve this goal?
Please help me.

This looks like your case also:
How do I get the GCC __attribute__ ((constructor)) to work under OSX?
From GCC docs:
constructor
destructor
constructor (priority)
destructor (priority)
The constructor attribute causes the
function to be called automatically
before execution enters main ().
Similarly, the destructor attribute
causes the function to be called
automatically after main () has
completed or exit () has been called.
Functions with these attributes are
useful for initializing data that will
be used implicitly during the
execution of the program.

Write your own replacement for the crt*.o object file that calls main(), and link to it when building.

Related

Best way to abstract away an init function?

I am making a low level library that requires initialization to work properly which I implemented with a init function. I am wondering if there is a way to make the init call be called once the user calls a library function ideally without:
Any overhead
No repeated calls
No exposed global variables. (my current solution does this, which I don't quite like)
my current solution as per comment request:
bool isinit = 0;
void init()
{
isinit = 1;
// init code
}
void lib_function()
{
if(!isinit) init();
// function code
}
The compiler seems to be smart enough (using -0fast on gcc) to not make that comparison each time a lib_function is called, but this still exposes a global variable which I don't like.
Best way to abstract away an init function?
Surely your library has some state. Typically, a library exposes functions that work on a specific structure. Do not use global variables - do not write spaghetti code. Expose the structure that holds the state of your library, and make all functions of your library take a pointer to the structure as an argument. Use a namespace - prepend all exported symbols with a prefix. An init function is just like int lib_init(struct lib_the_struct *t); - it will be self-understandable that users need to initialize the structure with that function before use. For example: fopen(), pthread_create.
Write an init function in your library. Write clear documentation stating, that the user of your library has to call the function once before calling any other function. For example: https://curl.se/libcurl/c/curl_global_init.html .
If you're happy with a solution that is a common extension rather than part of the C standard, you can mark your init function with the constructor attribute, which ensures it will be called automatically during program initialization (or during shared library load if you eventually end up using that).
I would fix this with assert so that the if will dissappear in release build and if you forget to call the init_function somewhere you get the error while developing.
Also turn isinit into a static so every library can have its own variable with the same name.
#include <assert.h>
#ifndef NDEBUG
static int isinit = 0;
#endif
void lib_function()
{
assert(isinit && "library: init not called");
}
There will be overhead if you run if(!isinit) init(); each time you call a function. At least an extra branch.
As for removing global variables, do in your example but static bool isinit = 0;. This reduces the scope of the variable to the local translation unit (.c file and all .h files it includes). It's no longer "global". Note that this isn't ideal in multi-threaded scenarios - you will have to protect the variable with a mutex then.
Overall though, what you are trying to do isn't a good idea. It is very common convention for C libraries to have an init function and the user of the library is expected to call it before calling anything else or they are to blame, not your library. Naturally you have to make this clear to them with source code documentation. It is common to have a list of prerequisites in source code comments together with every function declaration placed in the header file of the library.

How xtaskcreat creates task without function body in FREERTOS

I am new to RTOS and I was going through some demo code in freeRTOS, I came across xtaskcreate function.I know that when a function is called it should have its function body some where in the code.When I referred the the task.c file and did not found any xtaskcreate function body. So can some one explain me where the xtaskcreat function body is present else if not then how it is executed.
It's defined in file Source/tasks.c near line 595 (FreeRTOS v9.0.0rc2).
But if SUPPORT_DYNAMIC_ALLOCACTION is not defined, xTaskCreate won't be defined too.
It depends which FreeRTOS version you are using.
The latest V9.0.0rc2 has both xTaskCreate() and xTaskCreateStatic() as separate functions in tasks.c. Some versions will have both calls defined as macros that each calls xTaskGenericCreate() with parameters set appropriately for the required behavior (hiding the complexity from the end user).
In both cases its easy to find out. The 'Task' on the front of the function name tells you the prototype is in tasks.h - so just search that file for xTaskCreate() and see if it is a direct function call or a macro that calls another function - which you can then find in tasks.c.

Is function invocation at translation time valid?

I'm trying to achive a function to be called only one time. But I want to save the if (firstTime) check.
What I'm thinking about was:
while (1)
{
foo();
}
foo()
{
static int test = 1, srand (test);
test++;
}
But I couldn't find anything in the standard what is covering this.
So I'm not sure about, this is undefined. And if not so, will srand be invoked as expected? If not so, is it (as the main question is) even possible to invoke functioncalls on translationtime (what would more be, behave as if), as I'm doing here?
As an option to a first time flag, you could use a pointer to function that is initially set to the first time function, which in turn would set the pointer to function to the actual function. There's a level of indirection, but it eliminates a conditional branch.
A more general version of this idea is to use the pointer to function as a "state machine", where each function "advances" (sets) the pointer to the next state (the next function as part of a series of functions). This can be handy for event or interrupt driven code. I've used this method for device drivers and embedded code.
Your idea is probably that using a function call as an initializer for a static variable would call that function only once a program startup.
No, this is not possible in C, only constants are allowed in that context. In C++ this would be possible, and the compiler applies some secret wisdom to know in which order such initializations are effected.

Re-initialize library variables in C program

I am trying to write a program where I have to call some functions through a (shared) library (its source is available). The C code for the library has several global variables, and many functions change the values of these global variables. What I have to do in my program requires that each function call that I make gets to work with a fresh set of variables.
For example, let this function be a part of the library:
int x = 1;
int foo()
{
int a = 0;
//do somethings to 'a'
//...
x++;
return a;
}
Now every time I invoke foo() from my program, the value of x gets update from 1 to 2 then 3 then 4 and so on... I am try to construct a program so that every time foo() is invoked, it sees x = 1.
I am sorry to say that my knowledge of how C/linux treat these variable spaces is insufficient, so this question may seem vague. The above is just a small example; in reality, there are so many variables that is practically impossible to reset their values manually.
What may be the best way to compile that library and/or use it my program so as to refresh the variables?
(On a side note, what I am also trying to do is to parallelize calls to foo(), but because of the shared variables, I cannot do that.)
EDIT:
When working on some web dev projects, I used to encapsulate some code in webservices and then invoke those services from the main program. Does a similar framework exist in C/Linux? Please note that functions are returning data.
You have discovered one of the main reasons that global variables (or global state in general) are a really bad idea.
Since you have access to the source, I would suggest investing some time to refactor the source code.
You can achieve the ability to parallelize calls to foo with the following strategy:
Gather up all of the global variables into a single struct. Call it something like Context.
Change each function that acts on a global variable to take a pointer to a Context, and change the function to update the variables in the Context instead of updating global variables.
Now each thread that wants to use the library can create a new Context and pass that into foo and related functions.
If it's not feasible to make such a change to the source code, you can use more than one CPU core by starting child processes. Each child process has it's own memory space. That option is not nearly as efficient as using multiple threads.
I have no answer in details. But you can try one of the following:
unload and load library
try to clear library's .bss and fill .data section with values from the library (ref dl_iterate_phdr() call).

Overriding _init function in C , how safe is it?

I am building a debugging memory tool in a form of a shared library which I link against an executable at run time(includes overrided methods of malloc family). To handle initializations of my data structures I simple use a condition variable. Every time my malloc is called I check if the variable is not set and then I call a function responsible for initializing my structures. Now this works fine for programs running a single thread of execution but problems arise if a program includes more than 1 thread.
The only way (I can think of) to be sure that initialization happens before the user spawns any threads is to override _init as shown in this link.
Now this small example runs right but when I try to override _init on my own shared libary I get this error when trying to link it :
memory2.o: In function `_init':
memory2.c(.text+0x0): multiple definition of `_init'
/usr/lib/gcc/i686-linux-gnu/4.4.5/../../../../lib/crti.o(.init+0x0):
first defined here
collect2: ld returned 1 exit status
I use exactly the same steps as in the example from the link, it's just that my shared library also includes a set of global variables and overrided versions of malloc/free etc.
Anyone can give me a pointer of what's going wrong? Furthermore , is there anything else to take into consideration when overriding _init ( I am guessing it's not a very normal thing to do).
Thank you
Take a look at the following FAQ page:
http://www.faqs.org/docs/Linux-HOWTO/Program-Library-HOWTO.html#INIT-AND-CLEANUP
It describes _init/_fini as dangerous and obsolete, and recommends that __attribute__ ((constructor)) and __attribute__ ((destructor)) are used instead.
From the gcc manual:
constructor (priority)
destructor (priority)
The
constructor attribute causes the
function to be called automatically
before execution enters main().
Similarly, the destructor attribute
causes the function to be called
automatically after main() has
completed or exit() has been called.
Functions with these attributes are
useful for initializing data that will
be used implicitly during the
execution of the program. You may
provide an optional integer priority
to control the order in which
constructor and destructor functions
are run. A constructor with a smaller
priority number runs before a
constructor with a larger priority
number; the opposite relationship
holds for destructors. So, if you have
a constructor that allocates a
resource and a destructor that
deallocates the same resource, both
functions typically have the same
priority. The priorities for
constructor and destructor functions
are the same as those specified for
namespace-scope C++ objects (see C++
Attributes).
These attributes are not currently
implemented for Objective-C.
1) You can write your own _init or main:
GNU GCC allows you to define your own function of the same name as an existing symbol. When linking, you provide an argument of -Xlinker --wrap=<symName>. Pretending you did this to main, you can call the real main via __real_main(...):
int main(int argc, void *argv)
{
// any code you want here
return __real_main(argc,argv);
}
2) You can write your own dynamic linker. If you do this then set the .interp section to point to the shared object containing your dynamic linker/loader.
To overcome that error compile the code as gcc -nostartfiles memory2.c -o memory2, here we are skipping the constructor and destructor.
But it is not recommended to override these.

Resources