Re: [patch V6 00/37] x86/entry: Rework leftovers and merge plan

From: Lai Jiangshan
Date: Fri May 22 2020 - 22:52:38 EST


On Tue, May 19, 2020 at 5:04 PM Peter Zijlstra <peterz@xxxxxxxxxxxxx> wrote:

> +#ifdef CONFIG_DEBUG_ENTRY
> /* Begin/end of an instrumentation safe region */
> -#define instrumentation_begin() ({ \
> +#define instrumentation_begin() ({ \
> asm volatile("%c0:\n\t" \
> ".pushsection .discard.instr_begin\n\t" \
> ".long %c0b - .\n\t" \
> ".popsection\n\t" : : "i" (__COUNTER__)); \
> })
>
> -#define instrumentation_end() ({ \
> - asm volatile("%c0:\n\t" \
> +/*
> + * Because instrumentation_{begin,end}() can nest, objtool validation considers
> + * _begin() a +1 and _end() a -1 and computes a sum over the instructions.
> + * When the value is greater than 0, we consider instrumentation allowed.
> + *
> + * There is a problem with code like:
> + *
> + * noinstr void foo()
> + * {
> + * instrumentation_begin();
> + * ...
> + * if (cond) {
> + * instrumentation_begin();
> + * ...
> + * instrumentation_end();
> + * }
> + * bar();
> + * instrumentation_end();
> + * }
> + *
> + * If instrumentation_end() would be an empty label, like all the other
> + * annotations, the inner _end(), which is at the end of a conditional block,
> + * would land on the instruction after the block.
> + *
> + * If we then consider the sum of the !cond path, we'll see that the call to
> + * bar() is with a 0-value, even though, we meant it to happen with a positive
> + * value.
> + *
> + * To avoid this, have _end() be a NOP instruction, this ensures it will be
> + * part of the condition block and does not escape.
> + */
> +#define instrumentation_end() ({ \
> + asm volatile("%c0: nop\n\t" \
> ".pushsection .discard.instr_end\n\t" \
> ".long %c0b - .\n\t" \
> ".popsection\n\t" : : "i" (__COUNTER__)); \
> })

Hello,

I, who don't know how does the objtool handle it, am just curious.
_begin() and _end() are symmetrical, which means if _end() (without nop)
can escape, so can _begin() in a reverse way. For example:

noinstr void foo()
{
instrumentation_begin();
do {
instrumentation_begin();
...
instrumentation_end();
} while (cond);
bar();
instrumentation_end();
}

Here, the first _begin() can be "dragged" into the do-while block.
Expectedly, objtool validation should not complain here.

But objtool validation's not complaining means it can handle it
magically correctly (by distinguishing how many _begin()s should
be taken around the jmp target when jmp in a specific path), or
handle it by not checking if all paths have the same count onto
a jmp target (a little nervous to me), or other possible ways.

Sorry for my curiosity.
Thanks
Lai.