xref: /aosp_15_r20/external/perfetto/src/tracing/platform_windows.cc (revision 6dbdd20afdafa5e3ca9b8809fa73465d530080dc)
1 /*
2  * Copyright (C) 2021 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include "perfetto/base/build_config.h"
18 
19 #if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
20 
21 #include <Windows.h>
22 
23 #include "perfetto/ext/base/thread_task_runner.h"
24 #include "perfetto/tracing/internal/tracing_tls.h"
25 #include "perfetto/tracing/platform.h"
26 
27 // Thread Termination Callbacks.
28 // Windows doesn't support a per-thread destructor with its
29 // TLS primitives. So, we build it manually by inserting a
30 // function to be called on each thread's exit.
31 // This magic is from chromium's base/threading/thread_local_storage_win.cc
32 // which in turn is from http://www.codeproject.com/threads/tls.asp.
33 
34 #ifdef _WIN64
35 #pragma comment(linker, "/INCLUDE:_tls_used")
36 #pragma comment(linker, "/INCLUDE:perfetto_thread_callback_base")
37 #else
38 #pragma comment(linker, "/INCLUDE:__tls_used")
39 #pragma comment(linker, "/INCLUDE:_perfetto_thread_callback_base")
40 #endif
41 
42 namespace perfetto {
43 
44 namespace {
45 
46 class PlatformWindows : public Platform {
47  public:
48   static PlatformWindows* instance;
49   PlatformWindows();
50   ~PlatformWindows() override;
51 
52   ThreadLocalObject* GetOrCreateThreadLocalObject() override;
53   std::unique_ptr<base::TaskRunner> CreateTaskRunner(
54       const CreateTaskRunnerArgs&) override;
55   std::string GetCurrentProcessName() override;
56   void OnThreadExit();
57 
58  private:
59   DWORD tls_key_{};
60 };
61 
62 using ThreadLocalObject = Platform::ThreadLocalObject;
63 
64 // static
65 PlatformWindows* PlatformWindows::instance = nullptr;
66 
PlatformWindows()67 PlatformWindows::PlatformWindows() {
68   instance = this;
69   tls_key_ = ::TlsAlloc();
70   PERFETTO_CHECK(tls_key_ != TLS_OUT_OF_INDEXES);
71 }
72 
~PlatformWindows()73 PlatformWindows::~PlatformWindows() {
74   ::TlsFree(tls_key_);
75   instance = nullptr;
76 }
77 
OnThreadExit()78 void PlatformWindows::OnThreadExit() {
79   auto tls = static_cast<ThreadLocalObject*>(::TlsGetValue(tls_key_));
80   if (tls) {
81     // At this point we rely on the TLS object to be still set to the TracingTLS
82     // we are deleting. See comments in TracingTLS::~TracingTLS().
83     delete tls;
84   }
85 }
86 
GetOrCreateThreadLocalObject()87 ThreadLocalObject* PlatformWindows::GetOrCreateThreadLocalObject() {
88   void* tls_ptr = ::TlsGetValue(tls_key_);
89 
90   auto* tls = static_cast<ThreadLocalObject*>(tls_ptr);
91   if (!tls) {
92     tls = ThreadLocalObject::CreateInstance().release();
93     ::TlsSetValue(tls_key_, tls);
94   }
95   return tls;
96 }
97 
CreateTaskRunner(const CreateTaskRunnerArgs & args)98 std::unique_ptr<base::TaskRunner> PlatformWindows::CreateTaskRunner(
99     const CreateTaskRunnerArgs& args) {
100   return std::unique_ptr<base::TaskRunner>(new base::ThreadTaskRunner(
101       base::ThreadTaskRunner::CreateAndStart(args.name_for_debugging)));
102 }
103 
GetCurrentProcessName()104 std::string PlatformWindows::GetCurrentProcessName() {
105   char buf[MAX_PATH];
106   auto len = ::GetModuleFileNameA(nullptr /*current*/, buf, sizeof(buf));
107   std::string name(buf, static_cast<size_t>(len));
108   size_t sep = name.find_last_of('\\');
109   if (sep != std::string::npos)
110     name = name.substr(sep + 1);
111   return name;
112 }
113 
114 }  // namespace
115 
116 // static
GetDefaultPlatform()117 Platform* Platform::GetDefaultPlatform() {
118   static PlatformWindows* thread_safe_init_instance = new PlatformWindows();
119   return thread_safe_init_instance;
120 }
121 
122 }  // namespace perfetto
123 
124 // -----------------------
125 // Thread-local destructor
126 // -----------------------
127 
128 // .CRT$XLA to .CRT$XLZ is an array of PIMAGE_TLS_CALLBACK pointers that are
129 // called automatically by the OS loader code (not the CRT) when the module is
130 // loaded and on thread creation. They are NOT called if the module has been
131 // loaded by a LoadLibrary() call. It must have implicitly been loaded at
132 // process startup.
133 // See VC\crt\src\tlssup.c for reference.
134 
135 // extern "C" suppresses C++ name mangling so we know the symbol name for the
136 // linker /INCLUDE:symbol pragma above.
137 extern "C" {
138 // The linker must not discard perfetto_thread_callback_base. (We force a
139 // reference to this variable with a linker /INCLUDE:symbol pragma to ensure
140 // that.) If this variable is discarded, the OnThreadExit function will never be
141 // called.
142 
143 void NTAPI PerfettoOnThreadExit(PVOID, DWORD, PVOID);
PerfettoOnThreadExit(PVOID,DWORD reason,PVOID)144 void NTAPI PerfettoOnThreadExit(PVOID, DWORD reason, PVOID) {
145   if (reason == DLL_THREAD_DETACH || reason == DLL_PROCESS_DETACH) {
146     if (perfetto::PlatformWindows::instance)
147       perfetto::PlatformWindows::instance->OnThreadExit();
148   }
149 }
150 
151 #ifdef _WIN64
152 
153 // .CRT section is merged with .rdata on x64 so it must be constant data.
154 #pragma const_seg(".CRT$XLP")
155 
156 // When defining a const variable, it must have external linkage to be sure the
157 // linker doesn't discard it.
158 extern const PIMAGE_TLS_CALLBACK perfetto_thread_callback_base;
159 const PIMAGE_TLS_CALLBACK perfetto_thread_callback_base = PerfettoOnThreadExit;
160 
161 // Reset the default section.
162 #pragma const_seg()
163 
164 #else  // _WIN64
165 
166 #pragma data_seg(".CRT$XLP")
167 PIMAGE_TLS_CALLBACK perfetto_thread_callback_base = PerfettoOnThreadExit;
168 // Reset the default section.
169 #pragma data_seg()
170 
171 #endif  // _WIN64
172 
173 }  // extern "C"
174 
175 #endif  // OS_WIN
176