1

I have a binary executable mytest, created with Clang and bfd/lld, and in order for it to work correctly I have to pass the environment variable ASAN_OPTIONS="use_sigaltstack=1" to it, but I want to avoid having to manually type that in every time I want to run the executable from the command line.

I could create a wrapper script, of course, but that adds more complexity.

Is there a way, when creating the binary, to attach the environment variable and its value to the binary so that it is automatically set when execution begins?

It is too late to set the environment variable in my code, because Asan reads the environment variable before my code starts running.

newmacuser
  • 51
  • 4
  • No, there's no such thing. Why not just set the environment variable in your `.profile`? – Barmar Oct 01 '19 at 01:34
  • Another option changing the code, no? (Using `putenv`: http://man7.org/linux/man-pages/man3/putenv.3.html ) – tmrlvi Oct 01 '19 at 01:35
  • 3
    @tmrlvi The variable might need to be set before `main()` runs, since it's controlling a runtime library. – Barmar Oct 01 '19 at 01:36
  • The answer to this question greatly depends on whether you ask specifically about `ASAN_OPTIONS` or arbitrary environment variable. – yugr Oct 01 '19 at 03:14

2 Answers2

3

First thing first: for Asan the recommended approach is to implement __asan_default_options (as explained in Asan wiki).

In general, you could reset environment variable by calling setenv/putenv at program start. But this would not help if variable is used in initialization code (as is the case with Asan).

You could also provide a custom hacky implementation of getenv which would return desired value for "ASAN_OPTIONS" and forward to normal Glibc implementation (obtained via dlsym) otherwise. But that would not help with Asan either because it obtains environment variables by reading /proc/self/environ.

Yet another hacky approach is to setenv and then restart the executable via exec syscall. This may change program semantics so is not recommended. Asan uses this approach on OSX due to lack of better solutions.

yugr
  • 19,769
  • 3
  • 51
  • 96
0

I want to avoid having to manually type that in every time I want to run the executable from the command line.

One way to achieve this is to re-execv the binary if it finds that ASAN_OPTIONS is missing. That is: in main check whether ASAN_OPTIONS is set via getenv. If not, call setenv(ASAN_OPTIONS, ...) and execv(argv[0], argv).

Beware: this makes the binary hard(er) to debug.

Employed Russian
  • 199,314
  • 34
  • 295
  • 362