Skip to content

Commit

Permalink
genksyms: fix memory leak when the same symbol is read from *.symref …
Browse files Browse the repository at this point in the history
…file

When a symbol that is already registered is read again from *.symref
file, __add_symbol() removes the previous one from the hash table without
freeing it.

[Test Case]

  $ cat foo.c
  #include <linux/export.h>
  void foo(void);
  void foo(void) {}
  EXPORT_SYMBOL(foo);

  $ cat foo.symref
  foo void foo ( void )
  foo void foo ( void )

When a symbol is removed from the hash table, it must be freed along
with its ->name and ->defn members. However, sym->name cannot be freed
because it is sometimes shared with node->string, but not always. If
sym->name and node->string share the same memory, free(sym->name) could
lead to a double-free bug.

To resolve this issue, always assign a strdup'ed string to sym->name.

Fixes: 64e6c1e ("genksyms: track symbol checksum changes")
Signed-off-by: Masahiro Yamada <masahiroy@kernel.org>
  • Loading branch information
masahir0y committed Jan 10, 2025
1 parent 45c9c41 commit be2fa44
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 5 deletions.
8 changes: 6 additions & 2 deletions scripts/genksyms/genksyms.c
Original file line number Diff line number Diff line change
Expand Up @@ -272,11 +272,15 @@ static struct symbol *__add_symbol(const char *name, enum symbol_type type,
break;
}
}

free_list(sym->defn, NULL);
free(sym->name);
free(sym);
--nsyms;
}

sym = xmalloc(sizeof(*sym));
sym->name = name;
sym->name = xstrdup(name);
sym->type = type;
sym->defn = defn;
sym->expansion_trail = NULL;
Expand Down Expand Up @@ -483,7 +487,7 @@ static void read_reference(FILE *f)
defn = def;
def = read_node(f);
}
subsym = add_reference_symbol(xstrdup(sym->string), sym->tag,
subsym = add_reference_symbol(sym->string, sym->tag,
defn, is_extern);
subsym->is_override = is_override;
free_node(sym);
Expand Down
2 changes: 1 addition & 1 deletion scripts/genksyms/genksyms.h
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ struct string_list {

struct symbol {
struct symbol *hash_next;
const char *name;
char *name;
enum symbol_type type;
struct string_list *defn;
struct symbol *expansion_trail;
Expand Down
4 changes: 2 additions & 2 deletions scripts/genksyms/parse.y
Original file line number Diff line number Diff line change
Expand Up @@ -482,12 +482,12 @@ enumerator_list:
enumerator:
IDENT
{
const char *name = strdup((*$1)->string);
const char *name = (*$1)->string;
add_symbol(name, SYM_ENUM_CONST, NULL, 0);
}
| IDENT '=' EXPRESSION_PHRASE
{
const char *name = strdup((*$1)->string);
const char *name = (*$1)->string;
struct string_list *expr = copy_list_range(*$3, *$2);
add_symbol(name, SYM_ENUM_CONST, expr, 0);
}
Expand Down

0 comments on commit be2fa44

Please sign in to comment.