summaryrefslogtreecommitdiff
path: root/Userland/Libraries/LibELF/Hashes.h
blob: ae172e4b47bd0fb4cb5adcb2bba69fc963612190 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/*
 * Copyright (c) 2019-2020, Andrew Kaster <akaster@serenityos.org>
 * Copyright (c) 2020, Itamar S. <itamar8910@gmail.com>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#pragma once

#include <AK/StringView.h>

namespace ELF {

constexpr u32 compute_sysv_hash(const StringView& name)
{
    // SYSV ELF hash algorithm
    // Note that the GNU HASH algorithm has less collisions

    u32 hash = 0;

    for (auto ch : name) {
        hash = hash << 4;
        hash += ch;

        const u32 top_nibble_of_hash = hash & 0xf0000000u;
        hash ^= top_nibble_of_hash >> 24;
        hash &= ~top_nibble_of_hash;
    }

    return hash;
}

constexpr u32 compute_gnu_hash(const StringView& name)
{
    // GNU ELF hash algorithm
    u32 hash = 5381;

    for (auto ch : name)
        hash = hash * 33 + ch;

    return hash;
}

}