Jens
Jens

Reputation: 9130

Can I intercept global pointer initialization in C?

Suppose I have a small program like this one:

int i = 0;
int *pi = &i;
int **ppi = π

int main(int argc, char *argv[]) {
  return i + *pi + **ppi;
}

Is there a way to intercept the initialization of pi and ppi when they are set during program load/setup? I'd like to hook into their initialization so that I may rewrite the pointer values and stick a few of my own bits in, if possible before main() runs. All this should be transparent and automated.

I have looked into the LD Audit interface (link) but that provided only callbacks for functions.

Upvotes: 0

Views: 136

Answers (2)

QJGui
QJGui

Reputation: 967

All c program will be compiled and linked by the compiler such as GCC. Each compiler may give you these features such as function invoke hooks and so on.

As I know the Function invoke analysis can use these features. If you know the chinese , you can look the detail of this document.

But I do not find a way to hook the global variables. These variables can be initialized by the compiler in linking data-area step.

Upvotes: 0

Lee Daniel Crocker
Lee Daniel Crocker

Reputation: 13171

This is an implementation detail, not part of the language. There might be a way to do it, but then you'd no longer be writing in C.

And why would you want to? If you need to do something before main(), why not just convert something like this:

int main(int argc, char *argv[]) {
    // Do stuff
}

to something like:

int old_main(int argc, char *argv[]) {
    // Do stuff
}

int main(int argc, char *argv[]) {
    // Do earlier stuff
    return old_main(argc, argv);
}

And why bother intercepting initializers? Just let the values be initialized, then change them to what you want.

Any time you try to work around the language instead of working with it, you're asking for bugs and unpredictable behavior.

Upvotes: 2

Related Questions