5

I have a legacy C Linux application that I need to reuse . This application uses a lot of global variables. I want to reuse this application's main method and invoke that in a loop. I have found that when I call the main method( renamed to callableMain) in a loop , the application behavior is not consistent as the values of global variables set in previous iteration impact the program flow in the new iteration.

What I would like to do is to reset all the global variables to the default value before the execution of the the new iteration.

for example , the original program is like this

OriginalMain.C

#include <stdio.h>

int global = 3; /* This is the global variable. */

void doSomething(){     
         global++; /* Reference to global variable in a function. */    
}    

     // i want to rename this main method to callableMain() and
     // invoke  it in a loop 
     int main(void){    
       if(global==3) {    
       printf(" All  Is Well \n");    

       doSomething() ;  
     }
     else{

       printf(" Noooo\n");  

       doNothing() ;

     }
     return 0;
}

I want to change this program as follows:

I changed the above file to rename the main() to callableMain()

And my new main methods is as follows:

int main(){  

     for(int i=0;i<20;i++){  

         callableMain();

         // this is where I need to reset the value of global vaiables
        // otherwise the execution flow  changes
     }    
}   

Is this possible to reset all the global variables to the values before main() was invoked ?

The short answer is that there is no magical api call that would reset global variables. The global variables would have to be cached and reused.

4
  • 1
    No automagical method of doing so. Consider automated code scanning to detect all globals. Also, function-level statics can also contribute to the global state. Also the state of the RTL (open handles and such). Sep 13, 2010 at 22:28
  • Judging by all responses below, you are right that I need automated code scanning to detect all globals. Would you be able to recommend any such tool ( Linux based) that could detect all globals as well as function level statics.
    – user193116
    Sep 13, 2010 at 22:41
  • 1
    If you want everything to be reset back to its original state, what is wrong with simply running the executable 20 times?
    – dreamlax
    Sep 14, 2010 at 5:08
  • dreamlax: Performance, typically.
    – Ken
    Sep 14, 2010 at 16:55

8 Answers 8

8

I would invoke it as a subprocess, modifying its input and output as needed. Let the operating system do the dirty work for you.

The idea is to isolate the legacy program from your new program by relegating it to its own process. Then you have a clean separation between the two. Also, the legacy program is reset to a clean state every time you run it.

First, modify the program so that it reads the input data from a file, and writes its output in a machine-readable format to another file, with the files being given on the command line.

You can then create named pipes (using the mkfifo call) and invoke the legacy program using system, passing it the named pipes on the command line. Then you feed it its input and read back its output.

I am not an expert on these matters; there is probably a better way of doing the IPC. Others here have mentioned fork. However, the basic idea of separating out the legacy code and invoking it as a subprocess is probably the best approach here.

1
  • This sounds promising. I was looking to use a OS level API cal to do the job for me. Would you be able to elaborate a bit more on your approach ?
    – user193116
    Sep 14, 2010 at 3:01
5

fork() early?

You could fork(2) at some early point when you think the globals are in a good state, and then have the child wait on a pipe or something for some work to do. This would require writing any changed state or at least the results back to the parent process but would decouple your worker from your primary control process.

In fact, it might make sense to fork() at least twice, once to set up a worker controller and save the initialized (but not too initialized :-) global state, and then have this worker controller fork() again for each loop you need run.

A simpler variation might be to just modify the code so that the process can start in a "worker mode", and then use fork() or system() to start the application at the top, but with an argument that puts it in to the slave mode.

1
  • Or similarly, exec, if available and if you know how to identify the executable. Sep 13, 2010 at 23:33
3

There is a way to do this on certain platforms / compilers, you'd basically be performing the same initialization your compiler performs before calling main().

I have done this for a TI DSP, in that case I had the section with globals mapped to a specific section of memory and there were linker directives available that declared variables pointing to the start and end of this section (so you can memset() the whole area to zero before starting initialization). Then, the compiler provided a list of records, each of which comprised of an address, data length and the actual data to be copied into the address location. So you'd just loop through the records and do memcpy() into the target address to initialize all globals.

Very compiler specific, so hopefully the compiler you're using allows you to do something similar.

1
  • 1
    :-D Yes, dangerous indeed. But where's the fun in writing C if you're not living on the edge (especially in a bootloader project)!
    – Praetorian
    Sep 13, 2010 at 23:34
1

In short, no. What I would do in this instance is create definitions, constants if you will, and then use those to reset the global variables with.

Basically

#define var1 10
int vara = 10

etc... basic C right? You can then go ahead and wrap the reinitialization in a handy function =)

1

Assuming we are dealing with ELF on Linux, then the following function to reset the variables works

// these extern variables come from glibc
// https://github.com/ysbaddaden/gc/blob/master/include/config.h
extern char __data_start[];
extern char __bss_start[];
extern char _end[];
#define DATA_START ((char *)&__data_start)
#define DATA_END ((char *)&__bss_start)
#define BSS_START ((char *)&__bss_start)
#define BSS_END ((char *)&_end)

/// first call saves globals, subsequent calls restore
void reset_static_data();
// variable for quick check
static int pepa = 42;

// writes to memory between global variables are reported as buffer overflows by asan
ATTRIBUTE_NO_SANITIZE_ADDRESS
void reset_static_data()
{
    // global variable, ok to leak it
    static char * x;

    size_t s = BSS_END - DATA_START;

    // memcpy is always sanitized, so access memory as chars in a loop

    if (x == NULL) {  // store current static variables
        x = (char *) malloc(s);
        for (size_t i = 0; i < s; i++) {
            *(x+i) = *(DATA_START + i);
        }
    } else {  // restore previously saved static variables
        for (size_t i = 0; i < s; i++) {
            *(DATA_START + i) = *(x+i);
        }
    }

    // quick check, see that pepa does not grow in stderr output
    fprintf(stderr, "pepa: %d\n", pepa++);
}

The general approach is based on answer in How to get the data and bss address space in run time (In Unix C program), see the linked ysbaddaden/gc GitHub repo for macOS version of the macros.

To test the above code, just call it a few times and note that the incremented global variable pepa still keeps the value of 42.

reset_static_data();
reset_static_data();
reset_static_data();

Saving current state of the globals is convenient in that it does not require rerunning __attribute__((constructor)) functions which would be necessary if I set everything in .bss to zero (which is easy) and everything in .data to the initial values (which is not so easy). For example, if you load libpython3.so in your program, it does do run-time initialization which is lost by zeroing .bss. Calling into Python then crashes.

Sanitizers

Writing into areas of memory immediately before or after a static variable will trigger buffer-overflow warning from Address Sanitizer. To prevent this, use the ATTRIBUTE_NO_SANITIZE_ADDRESS macro the way the code above does. The macro is defined in sanitizer/asan_interface.h.

Code coverage

Code coverage counters are implemented as global variables. Therefore, resetting globals will cause coverage information to be forgotten. To solve this, always dump the coverage-to-date before restoring the globals. There does not seem to be a macro to detect whether code coverage is enabled or not in the compiler, so use your build system (CMake, ...) to define suitable macro yourself, such as QD_COVERAGE below.

// The __gcov_dump function writes the coverage counters to gcda files
// and the __gcov_reset function resets them to zero.
// The interface is defined at https://github.com/gcc-mirror/gcc/blob/7501eec65c60701f72621d04eeb5342bad2fe4fb/libgcc/libgcov-interface.c
extern "C" void __gcov_reset();
extern "C" void __gcov_dump();

void flush_coverage() {
#if defined(QD_COVERAGE)
    __gcov_dump();
    __gcov_reset();
#endif
}
1
0

I think you must change the way you see the problem.

Declare all the variables used by callableMain() inside callableMain()'s body, so they are not global anymore and are destroyed after the function is executed and created once again with the default values when you call callableMain() on the next iteration.

EDIT:

Ok, here's what you could do if you have the source code for callableMain(): in the beginning of the function, add a check to verify if its the first time the function its being called. Inside this check you will copy the values of all global variables used to another set of static variables (name them as you like). Then, on the function's body replace all occurences of the global variables by the static variables you created.

This way you will preserve the initial values of all the global variables and use them on every iteration of callableMain(). Does it makes sense to you?

void callableMain()
{
  static bool first_iter = true;

  if (first_iter)
  {  
    first_iter = false;
    static int my_global_var1 = global_var1;
    static float my_global_var2 = global_var2;
    ..
  }

  // perform operations on my_global_var1 and my_global_var2, 
  // which store the default values of the original global variables.

}
3
  • This is not feasible, as the global variables are being accessed by different function in different modules. Doing so causes too many compiler errors.
    – user193116
    Sep 13, 2010 at 22:33
  • If the variables are no longer global, they will not be accessible by functions outside of callableMain() such as the doSomething() function in the question.
    – semaj
    Sep 13, 2010 at 22:35
  • He doesn't want to rewrite this entire program; that's the point of the question.
    – David M.
    Sep 13, 2010 at 22:52
0
for (int i = 0; i < 20; i++) {
    int saved_var1 = global_var1;
    char saved_var2 = global_var2;
    double saved_var3 = global_var3;

    callableMain();

    global_var1 = saved_var1;
    global_var2 = saved_var2;
    global_var3 = saved_var2;
}

Or maybe you can find out where global variables start memcpy them. But I would always cringe when starting a loop ...

for (int i = 0; i < 20; i++) {
    static unsigned char global_copy[SIZEOFGLOBALDATA];
    memcpy(global_copy, STARTOFGLOBALDATA, SIZEOFGLOBALDATA);

    callableMain();

    memcpy(STARTOFGLOBALDATA, global_copy, SIZEOFGLOBALDATA);
}

0

If you don't want to refactor the code and encapsulate these global variables, I think the best you can do is define a reset function and then call it within the loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.