macro: add READ_NOW() macro for force reading of memory, making a copy

When accessing journal files we generally are fine when values change
beneath our feet, while we are looking at them, as long as they change
from something valid to zero. This is required since we nowadays
forcibly unallocate journal files on vacuuming, to ensure they are
actually released.

However, we need to make sure that the validity checks we enforce are
done on suitable copies of the fields in the file. Thus provide a macro
that forces a copy, and disallows the compiler from merging our copy
with the actually memory where it is from.
This commit is contained in:
Lennart Poettering 2020-04-23 10:42:01 +02:00
parent a5f0f46f1a
commit ed50f18c4d

View file

@ -585,4 +585,17 @@ static inline int __coverity_check_and_return__(int condition) {
DEFINE_PUBLIC_TRIVIAL_REF_FUNC(type, name); \
DEFINE_PUBLIC_TRIVIAL_UNREF_FUNC(type, name, free_func);
/* A macro to force copying of a variable from memory. This is useful whenever we want to read something from
* memory and want to make sure the compiler won't optimize away the destination variable for us. It's not
* supposed to be a full CPU memory barrier, i.e. CPU is still allowed to reorder the reads, but it is not
* allowed to remove our local copies of the variables. We want this to work for unaligned memory, hence
* memcpy() is great for our purposes. */
#define READ_NOW(x) \
({ \
typeof(x) _copy; \
memcpy(&_copy, &(x), sizeof(_copy)); \
asm volatile ("" : : : "memory"); \
_copy; \
})
#include "log.h"