Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C test if variable is in read-only section

Tags:

c

gcc

macros

I'd like to write a low-level logging function that would look like:

DO_DBG("some string", val1, val2)

What I want it to do, is to store the pointer to the string rather than a copy of the string, for performance reasons. This assumes that the string is a read-only literal. To prevent people having to debug the debugger, it would be nice if the compiler could complain if the first parameter of DO_DBG was in a writable section of code vs text, etc. I'm wondering if a mechanism to do that exists. (I'm using gcc 4.9.1, ld 2.24).

like image 634
John Avatar asked Jan 29 '16 20:01

John


2 Answers

You could use the automatic literal string concatenation to your advantage:

#define DO_DBG(s, a, b) _DO_DBG("" s, a, b)

And implement your real macro as _DO_DBG.

like image 98
Amit Avatar answered Oct 19 '22 20:10

Amit


You can set up a SIGSEGV handler, and then try to do:

s[0] = s[0];

If the handler is triggered, it means that the variable is in a read-only segment, so you can save the pointer. If not, you can complain (or just make a copy of the string).

You'll need to declare the string volatile so the compiler doesn't optimize the assignment away.

like image 23
Barmar Avatar answered Oct 19 '22 20:10

Barmar