aboutsummaryrefslogtreecommitdiff
path: root/Ryujinx.HLE/OsHle/Diagnostics/Demangler.cs
blob: 6646dede6eaffacb2cbf2d37a736e4e5482f3757 (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
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
using System;
using System.Collections.Generic;
using System.Linq;

namespace Ryujinx.HLE.OsHle.Diagnostics
{
    static class Demangler
    {
        private static readonly Dictionary<string, string> BuiltinTypes = new Dictionary<string, string>
        {
            { "v", "void" },
            { "w", "wchar_t" },
            { "b", "bool" },
            { "c", "char" },
            { "a", "signed char" },
            { "h", "unsigned char" },
            { "s", "short" },
            { "t", "unsigned short" },
            { "i", "int" },
            { "j", "unsigned int" },
            { "l", "long" },
            { "m", "unsigned long" },
            { "x", "long long" },
            { "y", "unsigned long long" },
            { "n", "__int128" },
            { "o", "unsigned __int128" },
            { "f", "float" },
            { "d", "double" },
            { "e", "long double" },
            { "g", "__float128" },
            { "z", "..." },
            { "Dd", "__iec559_double" },
            { "De", "__iec559_float128" },
            { "Df", "__iec559_float" },
            { "Dh", "__iec559_float16" },
            { "Di", "char32_t" },
            { "Ds", "char16_t" },
            { "Da", "decltype(auto)" },
            { "Dn", "std::nullptr_t" },
        };

        private static readonly Dictionary<string, string> SubstitutionExtra = new Dictionary<string, string>
        {
            {"Sa", "std::allocator"},
            {"Sb", "std::basic_string"},
            {"Ss", "std::basic_string<char, ::std::char_traits<char>, ::std::allocator<char>>"},
            {"Si", "std::basic_istream<char, ::std::char_traits<char>>"},
            {"So", "std::basic_ostream<char, ::std::char_traits<char>>"},
            {"Sd", "std::basic_iostream<char, ::std::char_traits<char>>"}
        };

        private static int FromBase36(string encoded)
        {
            string base36 = "0123456789abcdefghijklmnopqrstuvwxyz";
            char[] reversedEncoded = encoded.ToLower().ToCharArray().Reverse().ToArray();
            int result = 0;
            for (int i = 0; i < reversedEncoded.Length; i++)
            {
                char c = reversedEncoded[i];
                int value = base36.IndexOf(c);
                if (value == -1)
                    return -1;
                result += value * (int)Math.Pow(36, i);
            }
            return result;
        }

        private static string GetCompressedValue(string compression, List<string> compressionData, out int pos)
        {
            string res = null;
            bool canHaveUnqualifiedName = false;
            pos = -1;
            if (compressionData.Count == 0 || !compression.StartsWith("S"))
                return null;

            if (compression.Length >= 2 && SubstitutionExtra.TryGetValue(compression.Substring(0, 2), out string substitutionValue))
            {
                pos = 1;
                res = substitutionValue;
                compression = compression.Substring(2);
            }
            else if (compression.StartsWith("St"))
            {
                pos = 1;
                canHaveUnqualifiedName = true;
                res = "std";
                compression = compression.Substring(2);
            }
            else if (compression.StartsWith("S_"))
            {
                pos = 1;
                res = compressionData[0];
                canHaveUnqualifiedName = true;
                compression = compression.Substring(2);
            }
            else
            {
                int id = -1;
                int underscorePos = compression.IndexOf('_');
                if (underscorePos == -1)
                    return null;
                string partialId = compression.Substring(1, underscorePos - 1);

                id = FromBase36(partialId);
                if (id == -1 || compressionData.Count <= (id + 1))
                {
                    return null;
                }
                res = compressionData[id + 1];
                pos = partialId.Length + 1;
                canHaveUnqualifiedName= true;
                compression = compression.Substring(pos);
            }
            if (res != null)
            {
                if (canHaveUnqualifiedName)
                {
                    List<string> type = ReadName(compression, compressionData, out int endOfNameType);
                    if (endOfNameType != -1 && type != null)
                    {
                        pos  += endOfNameType;
                        res = res + "::" + type[type.Count - 1];
                    }
                }
            }
            return res;
        }

        private static List<string> ReadName(string mangled, List<string> compressionData, out int pos, bool isNested = true)
        {
            List<string> res = new List<string>();
            string charCountString = null;
            int charCount = 0;
            int i;

            pos = -1;
            for (i = 0; i < mangled.Length; i++)
            {
                char chr = mangled[i];
                if (charCountString == null)
                {
                    if (ReadCVQualifiers(chr) != null)
                    {
                        continue;
                    }
                    if (chr == 'S')
                    {
                        string data = GetCompressedValue(mangled.Substring(i), compressionData, out pos);
                        if (pos == -1)
                        {
                            return null;
                        }
                        if (res.Count == 0)
                            res.Add(data);
                        else
                            res.Add(res[res.Count - 1] + "::" + data);
                        i += pos;
                        if (i < mangled.Length && mangled[i] == 'E')
                        {
                            break;
                        }
                        continue;
                    }
                    else if (chr == 'E')
                    {
                        break;
                    }
                }
                if (Char.IsDigit(chr))
                {
                    charCountString += chr;
                }
                else
                {
                    if (!int.TryParse(charCountString, out charCount))
                    {
                        return null;
                    }
                    string demangledPart = mangled.Substring(i, charCount);
                    if (res.Count == 0)
                        res.Add(demangledPart);
                    else
                        res.Add(res[res.Count - 1] + "::" + demangledPart);
                    i = i + charCount - 1;
                    charCount = 0;
                    charCountString = null;
                    if (!isNested)
                        break;
                }
            }
            if (res.Count == 0)
            {
                return null;
            }
            pos = i;
            return res;
        }

        private static string ReadBuiltinType(string mangledType, out int pos)
        {
            string res = null;
            string possibleBuiltinType;
            pos = -1;
            possibleBuiltinType = mangledType[0].ToString();
            if (!BuiltinTypes.TryGetValue(possibleBuiltinType, out res))
            {
                if (mangledType.Length >= 2)
                {
                    // Try to match the first 2 chars if the first call failed
                    possibleBuiltinType = mangledType.Substring(0, 2);
                    BuiltinTypes.TryGetValue(possibleBuiltinType, out res);
                }
            }
            if (res != null)
                pos = possibleBuiltinType.Length;
            return res;
        }

        private static string ReadCVQualifiers(char qualifier)
        {
            if (qualifier == 'r')
                return "restricted";
            else if (qualifier == 'V')
                return "volatile";
            else if (qualifier == 'K')
                return "const";
            return null;
        }

        private static string ReadRefQualifiers(char qualifier)
        {
            if (qualifier == 'R')
                return "&";
            else if (qualifier == 'O')
                return "&&";
            return null;
        }

        private static string ReadSpecialQualifiers(char qualifier)
        {
            if (qualifier == 'P')
                return "*";
            else if (qualifier == 'C')
                return "complex";
            else if (qualifier == 'G')
                return "imaginary";
            return null;
        }

        private static List<string> ReadParameters(string mangledParams, List<string> compressionData, out int pos)
        {
            List<string> res = new List<string>();
            List<string> refQualifiers = new List<string>();
            string parsedTypePart = null;
            string currentRefQualifiers = null;
            string currentBuiltinType = null;
            string currentSpecialQualifiers = null;
            string currentCompressedValue = null;
            int i = 0;
            pos = -1;

            for (i = 0; i < mangledParams.Length; i++)
            {
                if (currentBuiltinType != null)
                {
                    string currentCVQualifier = String.Join(" ", refQualifiers);
                    // Try to mimic the compression indexing
                    if (currentRefQualifiers != null)
                    {
                        compressionData.Add(currentBuiltinType + currentRefQualifiers);
                    }
                    if (refQualifiers.Count != 0)
                    {
                        compressionData.Add(currentBuiltinType + " " + currentCVQualifier + currentRefQualifiers);
                    }
                    if (currentSpecialQualifiers != null)
                    {
                        compressionData.Add(currentBuiltinType + " " + currentCVQualifier + currentRefQualifiers + currentSpecialQualifiers);
                    }
                    if (currentRefQualifiers == null && currentCVQualifier == null && currentSpecialQualifiers == null)
                    {
                        compressionData.Add(currentBuiltinType);
                    }
                    currentBuiltinType = null;
                    currentCompressedValue = null;
                    currentCVQualifier = null;
                    currentRefQualifiers = null;
                    refQualifiers.Clear();
                    currentSpecialQualifiers = null;
                }
                char chr = mangledParams[i];
                string part = mangledParams.Substring(i);

                // Try to read qualifiers
                parsedTypePart = ReadCVQualifiers(chr);
                if (parsedTypePart != null)
                {
                    refQualifiers.Add(parsedTypePart);

                    // need more data
                    continue;
                }

                parsedTypePart = ReadRefQualifiers(chr);
                if (parsedTypePart != null)
                {
                    currentRefQualifiers = parsedTypePart;

                    // need more data
                    continue;
                }

                parsedTypePart = ReadSpecialQualifiers(chr);
                if (parsedTypePart != null)
                {
                    currentSpecialQualifiers = parsedTypePart;

                    // need more data
                    continue;
                }

                // TODO: extended-qualifier?

                if (part.StartsWith("S"))
                {
                    parsedTypePart = GetCompressedValue(part, compressionData, out pos);
                    if (pos != -1 && parsedTypePart != null)
                    {
                        currentCompressedValue = parsedTypePart;
                        i += pos;
                        res.Add(currentCompressedValue + " " + String.Join(" ", refQualifiers) + currentRefQualifiers + currentSpecialQualifiers);
                        currentBuiltinType = null;
                        currentCompressedValue = null;
                        currentRefQualifiers = null;
                        refQualifiers.Clear();
                        currentSpecialQualifiers = null;
                        continue;
                    }
                    pos = -1;
                    return null;
                }
                else if (part.StartsWith("N"))
                {
                    part = part.Substring(1);
                    List<string> name = ReadName(part, compressionData, out pos);
                    if (pos != -1 && name != null)
                    {
                        i += pos + 1;
                        res.Add(name[name.Count - 1]  + " " + String.Join(" ", refQualifiers) + currentRefQualifiers + currentSpecialQualifiers);
                        currentBuiltinType = null;
                        currentCompressedValue = null;
                        currentRefQualifiers = null;
                        refQualifiers.Clear();
                        currentSpecialQualifiers = null;
                        continue;
                    }
                }

                // Try builting
                parsedTypePart = ReadBuiltinType(part, out pos);
                if (pos == -1)
                {
                    return null;
                }
                currentBuiltinType = parsedTypePart;
                res.Add(currentBuiltinType + " " + String.Join(" ", refQualifiers) + currentRefQualifiers + currentSpecialQualifiers);
                i = i + pos -1;
            }
            pos = i;
            return res;
        }

        private static string ParseFunctionName(string mangled)
        {
            List<string> compressionData = new List<string>();
            int pos = 0;
            string res;
            bool isNested = mangled.StartsWith("N");

            // If it's start with "N" it must be a nested function name
            if (isNested)
                mangled = mangled.Substring(1);
            compressionData = ReadName(mangled, compressionData, out pos, isNested);
            if (pos == -1)
                return null;
            res = compressionData[compressionData.Count - 1];
            compressionData.Remove(res);
            mangled = mangled.Substring(pos + 1);

            // more data? maybe not a data name so...
            if (mangled != String.Empty)
            {
                List<string> parameters = ReadParameters(mangled, compressionData, out pos);
                // parameters parsing error, we return the original data to avoid information loss.
                if (pos == -1)
                    return null;
                parameters = parameters.Select(outer => outer.Trim()).ToList();
                res += "(" + String.Join(", ", parameters) + ")";
            }
            return res;
        }

        public static string Parse(string originalMangled)
        {
            if (originalMangled.StartsWith("_Z"))
            {
                // We assume that we have a name (TOOD: support special names)
                string res = ParseFunctionName(originalMangled.Substring(2));
                if (res == null)
                    return originalMangled;
                return res;
            }
            return originalMangled;
        }
    }
}