blob: 5a55f29d2966460f2f6f0037ddab364089d18ba7 [file] [log] [blame]
Austin Schuh36244a12019-09-21 17:52:38 -07001// Copyright 2018 The Abseil Authors.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15// See "Retrieving Symbol Information by Address":
16// https://msdn.microsoft.com/en-us/library/windows/desktop/ms680578(v=vs.85).aspx
17
18#include <windows.h>
19
20// MSVC header DbgHelp.h has a warning for an ignored typedef.
21#pragma warning(push)
22#pragma warning(disable:4091)
23#include <DbgHelp.h>
24#pragma warning(pop)
25
26#pragma comment(lib, "dbghelp.lib")
27
28#include <algorithm>
29#include <cstring>
30
31#include "absl/base/internal/raw_logging.h"
32
33namespace absl {
34
35static HANDLE process = NULL;
36
37void InitializeSymbolizer(const char *argv0) {
38 if (process != nullptr) {
39 return;
40 }
41 process = GetCurrentProcess();
42
43 // Symbols are not loaded until a reference is made requiring the
44 // symbols be loaded. This is the fastest, most efficient way to use
45 // the symbol handler.
46 SymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_UNDNAME);
47 if (!SymInitialize(process, nullptr, true)) {
48 // GetLastError() returns a Win32 DWORD, but we assign to
49 // unsigned long long to simplify the ABSL_RAW_LOG case below. The uniform
50 // initialization guarantees this is not a narrowing conversion.
51 const unsigned long long error{GetLastError()}; // NOLINT(runtime/int)
52 ABSL_RAW_LOG(FATAL, "SymInitialize() failed: %llu", error);
53 }
54}
55
56bool Symbolize(const void *pc, char *out, int out_size) {
57 if (out_size <= 0) {
58 return false;
59 }
60 std::aligned_storage<sizeof(SYMBOL_INFO) + MAX_SYM_NAME,
61 alignof(SYMBOL_INFO)>::type buf;
62 SYMBOL_INFO *symbol = reinterpret_cast<SYMBOL_INFO *>(&buf);
63 symbol->SizeOfStruct = sizeof(SYMBOL_INFO);
64 symbol->MaxNameLen = MAX_SYM_NAME;
65 if (!SymFromAddr(process, reinterpret_cast<DWORD64>(pc), nullptr, symbol)) {
66 return false;
67 }
68 strncpy(out, symbol->Name, out_size);
69 if (out[out_size - 1] != '\0') {
70 // strncpy() does not '\0' terminate when it truncates.
71 static constexpr char kEllipsis[] = "...";
72 int ellipsis_size =
73 std::min<int>(sizeof(kEllipsis) - 1, out_size - 1);
74 memcpy(out + out_size - ellipsis_size - 1, kEllipsis, ellipsis_size);
75 out[out_size - 1] = '\0';
76 }
77 return true;
78}
79
80} // namespace absl