Re: [PATCH v2] objtool: fix .cold. functions parent symbols search

From: Josh Poimboeuf
Date: Fri Nov 09 2018 - 12:23:15 EST


On Wed, Nov 07, 2018 at 10:45:15PM +0100, Artem Savkov wrote:
> Because find_symbol_by_name() traverses the same lists as read_symbols()
> changing sym->name in place without copying it affects the result of
> find_symbol_by_name() and, in case when ".cold" function precedes it's
> parent in sec->symbol_list, can result in function being considered a
> parent of itself. This leads to function length being set to 0 and other
> consequent side-effects including a segfault in add_switch_table().
> The effects of this bug are only visible when building with
> -ffunction-sections in KCFLAGS.
>
> Fix by copying the search string instead of modifying it in place.
>
> Signed-off-by: Artem Savkov <asavkov@xxxxxxxxxx>

This needs a "Fixes" tag to identify the patch which introduced the bug.

> ---
> tools/objtool/elf.c | 7 ++++---
> 1 file changed, 4 insertions(+), 3 deletions(-)
>
> diff --git a/tools/objtool/elf.c b/tools/objtool/elf.c
> index 6dbb9fae0f9d..781c8afb29b9 100644
> --- a/tools/objtool/elf.c
> +++ b/tools/objtool/elf.c
> @@ -298,6 +298,7 @@ static int read_symbols(struct elf *elf)
> /* Create parent/child links for any cold subfunctions */
> list_for_each_entry(sec, &elf->sections, list) {
> list_for_each_entry(sym, &sec->symbol_list, list) {
> + char *pname;
> if (sym->type != STT_FUNC)
> continue;
> sym->pfunc = sym->cfunc = sym;
> @@ -305,9 +306,9 @@ static int read_symbols(struct elf *elf)
> if (!coldstr)
> continue;
>
> - coldstr[0] = '\0';
> - pfunc = find_symbol_by_name(elf, sym->name);
> - coldstr[0] = '.';
> + pname = strndup(sym->name, coldstr - sym->name);
> + pfunc = find_symbol_by_name(elf, pname);
> + free(pname);
>
> if (!pfunc) {
> WARN("%s(): can't find parent function",

strndup()'s return code needs to be checked.

Also, for such a short-lived allocation, I think a stack-allocated
string would be better.

--
Josh