aboutsummaryrefslogtreecommitdiff
path: root/src/ARMeilleure/Diagnostics/Symbols.cs
blob: d857c079f5cc02aa1b4eba504775a0270d5c3327 (plain) (blame)
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;

namespace ARMeilleure.Diagnostics
{
    static class Symbols
    {
        private readonly struct RangedSymbol
        {
            public readonly ulong Start;
            public readonly ulong End;
            public readonly ulong ElementSize;
            public readonly string Name;

            public RangedSymbol(ulong start, ulong end, ulong elemSize, string name)
            {
                Start = start;
                End = end;
                ElementSize = elemSize;
                Name = name;
            }
        }

        private static readonly ConcurrentDictionary<ulong, string> _symbols;
        private static readonly List<RangedSymbol> _rangedSymbols;

        static Symbols()
        {
            _symbols = new ConcurrentDictionary<ulong, string>();
            _rangedSymbols = new List<RangedSymbol>();
        }

        public static string Get(ulong address)
        {
            if (_symbols.TryGetValue(address, out string result))
            {
                return result;
            }

            lock (_rangedSymbols)
            {
                foreach (RangedSymbol symbol in _rangedSymbols)
                {
                    if (address >= symbol.Start && address <= symbol.End)
                    {
                        ulong diff = address - symbol.Start;
                        ulong rem = diff % symbol.ElementSize;

                        StringBuilder resultBuilder = new();
                        resultBuilder.Append($"{symbol.Name}_{diff / symbol.ElementSize}");

                        if (rem != 0)
                        {
                            resultBuilder.Append($"+{rem}");
                        }

                        result = resultBuilder.ToString();
                        _symbols.TryAdd(address, result);

                        return result;
                    }
                }
            }

            return null;
        }

        [Conditional("M_DEBUG")]
        public static void Add(ulong address, string name)
        {
            _symbols.TryAdd(address, name);
        }

        [Conditional("M_DEBUG")]
        public static void Add(ulong address, ulong size, ulong elemSize, string name)
        {
            lock (_rangedSymbols)
            {
                _rangedSymbols.Add(new RangedSymbol(address, address + size, elemSize, name));
            }
        }
    }
}