DevShark
DevShark

Reputation: 9122

How does __builtin___clear_cache work?

Going through the gcc documentation, I stumbled into the builtin function __builtin___clear_cache.

— Built-in Function: void __builtin___clear_cache (char *begin, char *end) This function is used to flush the processor's instruction cache for the region of memory between begin inclusive and end exclusive. Some targets require that the instruction cache be flushed, after modifying memory containing code, in order to obtain deterministic behavior.

If the target does not require instruction cache flushes, __builtin___clear_cache has no effect. Otherwise either instructions are emitted in-line to clear the instruction cache or a call to the __clear_cache function in libgcc is made.

I find this interesting, but surprising. In many cases, a large number of the instructions for the current stack is stored in the L1 cache (instruction cache). So it would seem at first glance that this builtin could corrupt significantly the flow of our program, by making it wipe out the next instructions on the stack.

Does this instruction also repopulates the part of the stack that was in the L1 cache?

This seems unlikely. If it does not, then I suppose the onus is on the user to use the right begin and end arguments, so as to not corrupt our process. In practice, how could one find what the right begin and end to use?

Upvotes: 6

Views: 13570

Answers (2)

Changbin Du
Changbin Du

Reputation: 800

On x86, the __builtin___clear_cache() does nothing. (but note it's not declared as a pure function)

On aarch64, the __builtin___clear_cache() will be finally expanded as a function call to __aarch64_sync_cache_range() in libgcc. You can view the GCC code below to understand how it is implemented.

https://github.com/gcc-mirror/gcc/blob/master/libgcc/config/aarch64/sync-cache.c#L31

And for Clang it is here:

https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/builtins/clear_cache.c#L123

Upvotes: 1

It is just emitting some weird machine instruction[s] on target processors requiring them (x86 don't need that).

Think of __builtin___clear_cache as a "portable" (to GCC and compatible compilers) way to flush the instruction cache (e.g. in some JIT library).

In practice, how could one find what the right begin and end to use?

To be safe, I would use that on some page range (e.g. obtained with sysconf(_SC_PAGESIZE)....), so usually a 4Kbyte aligned memory range (multiple of 4Kbyte). Otherwise, you want some target specific trick to find the cache line width...

On Linux, you might read /proc/cpuinfo and use the cache_alignment & cache_size lines to get a more precise cache line size and alignment.

BTW, a code using __builtin__clear_cache is very likely to be (for other reasons) target machine specific, so it has or knows some machine parameters (and that should include cache size & alignment).

Upvotes: 6

Related Questions