Bug Summary

File:src/gnu/usr.bin/clang/liblldbCore/../../../llvm/lldb/source/Core/FormatEntity.cpp
Warning:line 1700, column 37
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name FormatEntity.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model static -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/liblldbCore/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/liblldbCore/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/liblldbCore/../include -I /usr/src/gnu/usr.bin/clang/liblldbCore/obj -I /usr/src/gnu/usr.bin/clang/liblldbCore/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -I /usr/src/gnu/usr.bin/clang/liblldbCore/../../../llvm/lldb/include -I /usr/src/gnu/usr.bin/clang/liblldbCore/../../../llvm/lldb/source -I /usr/src/gnu/usr.bin/clang/liblldbCore/../../../llvm/clang/include -I /usr/src/gnu/usr.bin/clang/liblldbCore/obj/../include/lldb/Core -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/liblldbCore/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -stack-protector 2 -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/liblldbCore/../../../llvm/lldb/source/Core/FormatEntity.cpp

/usr/src/gnu/usr.bin/clang/liblldbCore/../../../llvm/lldb/source/Core/FormatEntity.cpp

1//===-- FormatEntity.cpp --------------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "lldb/Core/FormatEntity.h"
10
11#include "lldb/Core/Address.h"
12#include "lldb/Core/AddressRange.h"
13#include "lldb/Core/Debugger.h"
14#include "lldb/Core/DumpRegisterValue.h"
15#include "lldb/Core/Module.h"
16#include "lldb/Core/ValueObject.h"
17#include "lldb/Core/ValueObjectVariable.h"
18#include "lldb/DataFormatters/DataVisualization.h"
19#include "lldb/DataFormatters/FormatClasses.h"
20#include "lldb/DataFormatters/FormatManager.h"
21#include "lldb/DataFormatters/TypeSummary.h"
22#include "lldb/Expression/ExpressionVariable.h"
23#include "lldb/Interpreter/CommandInterpreter.h"
24#include "lldb/Symbol/Block.h"
25#include "lldb/Symbol/CompileUnit.h"
26#include "lldb/Symbol/CompilerType.h"
27#include "lldb/Symbol/Function.h"
28#include "lldb/Symbol/LineEntry.h"
29#include "lldb/Symbol/Symbol.h"
30#include "lldb/Symbol/SymbolContext.h"
31#include "lldb/Symbol/VariableList.h"
32#include "lldb/Target/ExecutionContext.h"
33#include "lldb/Target/ExecutionContextScope.h"
34#include "lldb/Target/Language.h"
35#include "lldb/Target/Process.h"
36#include "lldb/Target/RegisterContext.h"
37#include "lldb/Target/SectionLoadList.h"
38#include "lldb/Target/StackFrame.h"
39#include "lldb/Target/StopInfo.h"
40#include "lldb/Target/Target.h"
41#include "lldb/Target/Thread.h"
42#include "lldb/Utility/AnsiTerminal.h"
43#include "lldb/Utility/ArchSpec.h"
44#include "lldb/Utility/CompletionRequest.h"
45#include "lldb/Utility/ConstString.h"
46#include "lldb/Utility/FileSpec.h"
47#include "lldb/Utility/Log.h"
48#include "lldb/Utility/Logging.h"
49#include "lldb/Utility/RegisterValue.h"
50#include "lldb/Utility/Status.h"
51#include "lldb/Utility/Stream.h"
52#include "lldb/Utility/StreamString.h"
53#include "lldb/Utility/StringList.h"
54#include "lldb/Utility/StructuredData.h"
55#include "lldb/lldb-defines.h"
56#include "lldb/lldb-forward.h"
57#include "llvm/ADT/STLExtras.h"
58#include "llvm/ADT/StringRef.h"
59#include "llvm/ADT/Triple.h"
60#include "llvm/Support/Compiler.h"
61
62#include <cctype>
63#include <cinttypes>
64#include <cstdio>
65#include <cstdlib>
66#include <cstring>
67#include <memory>
68#include <type_traits>
69#include <utility>
70
71namespace lldb_private {
72class ScriptInterpreter;
73}
74namespace lldb_private {
75struct RegisterInfo;
76}
77
78using namespace lldb;
79using namespace lldb_private;
80
81using Definition = lldb_private::FormatEntity::Entry::Definition;
82using Entry = FormatEntity::Entry;
83using EntryType = FormatEntity::Entry::Type;
84
85enum FileKind { FileError = 0, Basename, Dirname, Fullpath };
86
87constexpr Definition g_string_entry[] = {
88 Definition("*", EntryType::ParentString)};
89
90constexpr Definition g_addr_entries[] = {
91 Definition("load", EntryType::AddressLoad),
92 Definition("file", EntryType::AddressFile)};
93
94constexpr Definition g_file_child_entries[] = {
95 Definition("basename", EntryType::ParentNumber, FileKind::Basename),
96 Definition("dirname", EntryType::ParentNumber, FileKind::Dirname),
97 Definition("fullpath", EntryType::ParentNumber, FileKind::Fullpath)};
98
99constexpr Definition g_frame_child_entries[] = {
100 Definition("index", EntryType::FrameIndex),
101 Definition("pc", EntryType::FrameRegisterPC),
102 Definition("fp", EntryType::FrameRegisterFP),
103 Definition("sp", EntryType::FrameRegisterSP),
104 Definition("flags", EntryType::FrameRegisterFlags),
105 Definition("no-debug", EntryType::FrameNoDebug),
106 Entry::DefinitionWithChildren("reg", EntryType::FrameRegisterByName,
107 g_string_entry),
108 Definition("is-artificial", EntryType::FrameIsArtificial),
109};
110
111constexpr Definition g_function_child_entries[] = {
112 Definition("id", EntryType::FunctionID),
113 Definition("name", EntryType::FunctionName),
114 Definition("name-without-args", EntryType::FunctionNameNoArgs),
115 Definition("name-with-args", EntryType::FunctionNameWithArgs),
116 Definition("mangled-name", EntryType::FunctionMangledName),
117 Definition("addr-offset", EntryType::FunctionAddrOffset),
118 Definition("concrete-only-addr-offset-no-padding",
119 EntryType::FunctionAddrOffsetConcrete),
120 Definition("line-offset", EntryType::FunctionLineOffset),
121 Definition("pc-offset", EntryType::FunctionPCOffset),
122 Definition("initial-function", EntryType::FunctionInitial),
123 Definition("changed", EntryType::FunctionChanged),
124 Definition("is-optimized", EntryType::FunctionIsOptimized)};
125
126constexpr Definition g_line_child_entries[] = {
127 Entry::DefinitionWithChildren("file", EntryType::LineEntryFile,
128 g_file_child_entries),
129 Definition("number", EntryType::LineEntryLineNumber),
130 Definition("column", EntryType::LineEntryColumn),
131 Definition("start-addr", EntryType::LineEntryStartAddress),
132 Definition("end-addr", EntryType::LineEntryEndAddress),
133};
134
135constexpr Definition g_module_child_entries[] = {Entry::DefinitionWithChildren(
136 "file", EntryType::ModuleFile, g_file_child_entries)};
137
138constexpr Definition g_process_child_entries[] = {
139 Definition("id", EntryType::ProcessID),
140 Definition("name", EntryType::ProcessFile, FileKind::Basename),
141 Entry::DefinitionWithChildren("file", EntryType::ProcessFile,
142 g_file_child_entries)};
143
144constexpr Definition g_svar_child_entries[] = {
145 Definition("*", EntryType::ParentString)};
146
147constexpr Definition g_var_child_entries[] = {
148 Definition("*", EntryType::ParentString)};
149
150constexpr Definition g_thread_child_entries[] = {
151 Definition("id", EntryType::ThreadID),
152 Definition("protocol_id", EntryType::ThreadProtocolID),
153 Definition("index", EntryType::ThreadIndexID),
154 Entry::DefinitionWithChildren("info", EntryType::ThreadInfo,
155 g_string_entry),
156 Definition("queue", EntryType::ThreadQueue),
157 Definition("name", EntryType::ThreadName),
158 Definition("stop-reason", EntryType::ThreadStopReason),
159 Definition("stop-reason-raw", EntryType::ThreadStopReasonRaw),
160 Definition("return-value", EntryType::ThreadReturnValue),
161 Definition("completed-expression", EntryType::ThreadCompletedExpression)};
162
163constexpr Definition g_target_child_entries[] = {
164 Definition("arch", EntryType::TargetArch)};
165
166#define _TO_STR2(_val)"_val" #_val
167#define _TO_STR(_val)"_val" _TO_STR2(_val)"_val"
168
169constexpr Definition g_ansi_fg_entries[] = {
170 Definition("black",
171 ANSI_ESC_START"\033[" _TO_STR(ANSI_FG_COLOR_BLACK)"30" ANSI_ESC_END"m"),
172 Definition("red", ANSI_ESC_START"\033[" _TO_STR(ANSI_FG_COLOR_RED)"31" ANSI_ESC_END"m"),
173 Definition("green",
174 ANSI_ESC_START"\033[" _TO_STR(ANSI_FG_COLOR_GREEN)"32" ANSI_ESC_END"m"),
175 Definition("yellow",
176 ANSI_ESC_START"\033[" _TO_STR(ANSI_FG_COLOR_YELLOW)"33" ANSI_ESC_END"m"),
177 Definition("blue", ANSI_ESC_START"\033[" _TO_STR(ANSI_FG_COLOR_BLUE)"34" ANSI_ESC_END"m"),
178 Definition("purple",
179 ANSI_ESC_START"\033[" _TO_STR(ANSI_FG_COLOR_PURPLE)"35" ANSI_ESC_END"m"),
180 Definition("cyan", ANSI_ESC_START"\033[" _TO_STR(ANSI_FG_COLOR_CYAN)"36" ANSI_ESC_END"m"),
181 Definition("white",
182 ANSI_ESC_START"\033[" _TO_STR(ANSI_FG_COLOR_WHITE)"37" ANSI_ESC_END"m"),
183};
184
185constexpr Definition g_ansi_bg_entries[] = {
186 Definition("black",
187 ANSI_ESC_START"\033[" _TO_STR(ANSI_BG_COLOR_BLACK)"40" ANSI_ESC_END"m"),
188 Definition("red", ANSI_ESC_START"\033[" _TO_STR(ANSI_BG_COLOR_RED)"41" ANSI_ESC_END"m"),
189 Definition("green",
190 ANSI_ESC_START"\033[" _TO_STR(ANSI_BG_COLOR_GREEN)"42" ANSI_ESC_END"m"),
191 Definition("yellow",
192 ANSI_ESC_START"\033[" _TO_STR(ANSI_BG_COLOR_YELLOW)"43" ANSI_ESC_END"m"),
193 Definition("blue", ANSI_ESC_START"\033[" _TO_STR(ANSI_BG_COLOR_BLUE)"44" ANSI_ESC_END"m"),
194 Definition("purple",
195 ANSI_ESC_START"\033[" _TO_STR(ANSI_BG_COLOR_PURPLE)"45" ANSI_ESC_END"m"),
196 Definition("cyan", ANSI_ESC_START"\033[" _TO_STR(ANSI_BG_COLOR_CYAN)"46" ANSI_ESC_END"m"),
197 Definition("white",
198 ANSI_ESC_START"\033[" _TO_STR(ANSI_BG_COLOR_WHITE)"47" ANSI_ESC_END"m"),
199};
200
201constexpr Definition g_ansi_entries[] = {
202 Entry::DefinitionWithChildren("fg", EntryType::Invalid, g_ansi_fg_entries),
203 Entry::DefinitionWithChildren("bg", EntryType::Invalid, g_ansi_bg_entries),
204 Definition("normal", ANSI_ESC_START"\033[" _TO_STR(ANSI_CTRL_NORMAL)"0" ANSI_ESC_END"m"),
205 Definition("bold", ANSI_ESC_START"\033[" _TO_STR(ANSI_CTRL_BOLD)"1" ANSI_ESC_END"m"),
206 Definition("faint", ANSI_ESC_START"\033[" _TO_STR(ANSI_CTRL_FAINT)"2" ANSI_ESC_END"m"),
207 Definition("italic", ANSI_ESC_START"\033[" _TO_STR(ANSI_CTRL_ITALIC)"3" ANSI_ESC_END"m"),
208 Definition("underline",
209 ANSI_ESC_START"\033[" _TO_STR(ANSI_CTRL_UNDERLINE)"4" ANSI_ESC_END"m"),
210 Definition("slow-blink",
211 ANSI_ESC_START"\033[" _TO_STR(ANSI_CTRL_SLOW_BLINK)"5" ANSI_ESC_END"m"),
212 Definition("fast-blink",
213 ANSI_ESC_START"\033[" _TO_STR(ANSI_CTRL_FAST_BLINK)"6" ANSI_ESC_END"m"),
214 Definition("negative",
215 ANSI_ESC_START"\033[" _TO_STR(ANSI_CTRL_IMAGE_NEGATIVE)"7" ANSI_ESC_END"m"),
216 Definition("conceal",
217 ANSI_ESC_START"\033[" _TO_STR(ANSI_CTRL_CONCEAL)"8" ANSI_ESC_END"m"),
218 Definition("crossed-out",
219 ANSI_ESC_START"\033[" _TO_STR(ANSI_CTRL_CROSSED_OUT)"9" ANSI_ESC_END"m"),
220};
221
222constexpr Definition g_script_child_entries[] = {
223 Definition("frame", EntryType::ScriptFrame),
224 Definition("process", EntryType::ScriptProcess),
225 Definition("target", EntryType::ScriptTarget),
226 Definition("thread", EntryType::ScriptThread),
227 Definition("var", EntryType::ScriptVariable),
228 Definition("svar", EntryType::ScriptVariableSynthetic),
229 Definition("thread", EntryType::ScriptThread)};
230
231constexpr Definition g_top_level_entries[] = {
232 Entry::DefinitionWithChildren("addr", EntryType::AddressLoadOrFile,
233 g_addr_entries),
234 Definition("addr-file-or-load", EntryType::AddressLoadOrFile),
235 Entry::DefinitionWithChildren("ansi", EntryType::Invalid, g_ansi_entries),
236 Definition("current-pc-arrow", EntryType::CurrentPCArrow),
237 Entry::DefinitionWithChildren("file", EntryType::File,
238 g_file_child_entries),
239 Definition("language", EntryType::Lang),
240 Entry::DefinitionWithChildren("frame", EntryType::Invalid,
241 g_frame_child_entries),
242 Entry::DefinitionWithChildren("function", EntryType::Invalid,
243 g_function_child_entries),
244 Entry::DefinitionWithChildren("line", EntryType::Invalid,
245 g_line_child_entries),
246 Entry::DefinitionWithChildren("module", EntryType::Invalid,
247 g_module_child_entries),
248 Entry::DefinitionWithChildren("process", EntryType::Invalid,
249 g_process_child_entries),
250 Entry::DefinitionWithChildren("script", EntryType::Invalid,
251 g_script_child_entries),
252 Entry::DefinitionWithChildren("svar", EntryType::VariableSynthetic,
253 g_svar_child_entries, true),
254 Entry::DefinitionWithChildren("thread", EntryType::Invalid,
255 g_thread_child_entries),
256 Entry::DefinitionWithChildren("target", EntryType::Invalid,
257 g_target_child_entries),
258 Entry::DefinitionWithChildren("var", EntryType::Variable,
259 g_var_child_entries, true)};
260
261constexpr Definition g_root = Entry::DefinitionWithChildren(
262 "<root>", EntryType::Root, g_top_level_entries);
263
264FormatEntity::Entry::Entry(llvm::StringRef s)
265 : string(s.data(), s.size()), printf_format(), children(),
266 type(Type::String), fmt(lldb::eFormatDefault), number(0), deref(false) {}
267
268FormatEntity::Entry::Entry(char ch)
269 : string(1, ch), printf_format(), children(), type(Type::String),
270 fmt(lldb::eFormatDefault), number(0), deref(false) {}
271
272void FormatEntity::Entry::AppendChar(char ch) {
273 if (children.empty() || children.back().type != Entry::Type::String)
274 children.push_back(Entry(ch));
275 else
276 children.back().string.append(1, ch);
277}
278
279void FormatEntity::Entry::AppendText(const llvm::StringRef &s) {
280 if (children.empty() || children.back().type != Entry::Type::String)
281 children.push_back(Entry(s));
282 else
283 children.back().string.append(s.data(), s.size());
284}
285
286void FormatEntity::Entry::AppendText(const char *cstr) {
287 return AppendText(llvm::StringRef(cstr));
288}
289
290Status FormatEntity::Parse(const llvm::StringRef &format_str, Entry &entry) {
291 entry.Clear();
292 entry.type = Entry::Type::Root;
293 llvm::StringRef modifiable_format(format_str);
294 return ParseInternal(modifiable_format, entry, 0);
295}
296
297#define ENUM_TO_CSTR(eee) \
298 case FormatEntity::Entry::Type::eee: \
299 return #eee
300
301const char *FormatEntity::Entry::TypeToCString(Type t) {
302 switch (t) {
303 ENUM_TO_CSTR(Invalid);
304 ENUM_TO_CSTR(ParentNumber);
305 ENUM_TO_CSTR(ParentString);
306 ENUM_TO_CSTR(EscapeCode);
307 ENUM_TO_CSTR(Root);
308 ENUM_TO_CSTR(String);
309 ENUM_TO_CSTR(Scope);
310 ENUM_TO_CSTR(Variable);
311 ENUM_TO_CSTR(VariableSynthetic);
312 ENUM_TO_CSTR(ScriptVariable);
313 ENUM_TO_CSTR(ScriptVariableSynthetic);
314 ENUM_TO_CSTR(AddressLoad);
315 ENUM_TO_CSTR(AddressFile);
316 ENUM_TO_CSTR(AddressLoadOrFile);
317 ENUM_TO_CSTR(ProcessID);
318 ENUM_TO_CSTR(ProcessFile);
319 ENUM_TO_CSTR(ScriptProcess);
320 ENUM_TO_CSTR(ThreadID);
321 ENUM_TO_CSTR(ThreadProtocolID);
322 ENUM_TO_CSTR(ThreadIndexID);
323 ENUM_TO_CSTR(ThreadName);
324 ENUM_TO_CSTR(ThreadQueue);
325 ENUM_TO_CSTR(ThreadStopReason);
326 ENUM_TO_CSTR(ThreadStopReasonRaw);
327 ENUM_TO_CSTR(ThreadReturnValue);
328 ENUM_TO_CSTR(ThreadCompletedExpression);
329 ENUM_TO_CSTR(ScriptThread);
330 ENUM_TO_CSTR(ThreadInfo);
331 ENUM_TO_CSTR(TargetArch);
332 ENUM_TO_CSTR(ScriptTarget);
333 ENUM_TO_CSTR(ModuleFile);
334 ENUM_TO_CSTR(File);
335 ENUM_TO_CSTR(Lang);
336 ENUM_TO_CSTR(FrameIndex);
337 ENUM_TO_CSTR(FrameNoDebug);
338 ENUM_TO_CSTR(FrameRegisterPC);
339 ENUM_TO_CSTR(FrameRegisterSP);
340 ENUM_TO_CSTR(FrameRegisterFP);
341 ENUM_TO_CSTR(FrameRegisterFlags);
342 ENUM_TO_CSTR(FrameRegisterByName);
343 ENUM_TO_CSTR(FrameIsArtificial);
344 ENUM_TO_CSTR(ScriptFrame);
345 ENUM_TO_CSTR(FunctionID);
346 ENUM_TO_CSTR(FunctionDidChange);
347 ENUM_TO_CSTR(FunctionInitialFunction);
348 ENUM_TO_CSTR(FunctionName);
349 ENUM_TO_CSTR(FunctionNameWithArgs);
350 ENUM_TO_CSTR(FunctionNameNoArgs);
351 ENUM_TO_CSTR(FunctionMangledName);
352 ENUM_TO_CSTR(FunctionAddrOffset);
353 ENUM_TO_CSTR(FunctionAddrOffsetConcrete);
354 ENUM_TO_CSTR(FunctionLineOffset);
355 ENUM_TO_CSTR(FunctionPCOffset);
356 ENUM_TO_CSTR(FunctionInitial);
357 ENUM_TO_CSTR(FunctionChanged);
358 ENUM_TO_CSTR(FunctionIsOptimized);
359 ENUM_TO_CSTR(LineEntryFile);
360 ENUM_TO_CSTR(LineEntryLineNumber);
361 ENUM_TO_CSTR(LineEntryColumn);
362 ENUM_TO_CSTR(LineEntryStartAddress);
363 ENUM_TO_CSTR(LineEntryEndAddress);
364 ENUM_TO_CSTR(CurrentPCArrow);
365 }
366 return "???";
367}
368
369#undef ENUM_TO_CSTR
370
371void FormatEntity::Entry::Dump(Stream &s, int depth) const {
372 s.Printf("%*.*s%-20s: ", depth * 2, depth * 2, "", TypeToCString(type));
373 if (fmt != eFormatDefault)
374 s.Printf("lldb-format = %s, ", FormatManager::GetFormatAsCString(fmt));
375 if (!string.empty())
376 s.Printf("string = \"%s\"", string.c_str());
377 if (!printf_format.empty())
378 s.Printf("printf_format = \"%s\"", printf_format.c_str());
379 if (number != 0)
380 s.Printf("number = %" PRIu64"llu" " (0x%" PRIx64"llx" "), ", number, number);
381 if (deref)
382 s.Printf("deref = true, ");
383 s.EOL();
384 for (const auto &child : children) {
385 child.Dump(s, depth + 1);
386 }
387}
388
389template <typename T>
390static bool RunScriptFormatKeyword(Stream &s, const SymbolContext *sc,
391 const ExecutionContext *exe_ctx, T t,
392 const char *script_function_name) {
393 Target *target = Target::GetTargetFromContexts(exe_ctx, sc);
394
395 if (target) {
396 ScriptInterpreter *script_interpreter =
397 target->GetDebugger().GetScriptInterpreter();
398 if (script_interpreter) {
399 Status error;
400 std::string script_output;
401
402 if (script_interpreter->RunScriptFormatKeyword(script_function_name, t,
403 script_output, error) &&
404 error.Success()) {
405 s.Printf("%s", script_output.c_str());
406 return true;
407 } else {
408 s.Printf("<error: %s>", error.AsCString());
409 }
410 }
411 }
412 return false;
413}
414
415static bool DumpAddressAndContent(Stream &s, const SymbolContext *sc,
416 const ExecutionContext *exe_ctx,
417 const Address &addr,
418 bool print_file_addr_or_load_addr) {
419 Target *target = Target::GetTargetFromContexts(exe_ctx, sc);
420 addr_t vaddr = LLDB_INVALID_ADDRESS0xffffffffffffffffULL;
421 if (exe_ctx && !target->GetSectionLoadList().IsEmpty())
422 vaddr = addr.GetLoadAddress(target);
423 if (vaddr == LLDB_INVALID_ADDRESS0xffffffffffffffffULL)
424 vaddr = addr.GetFileAddress();
425
426 if (vaddr != LLDB_INVALID_ADDRESS0xffffffffffffffffULL) {
427 int addr_width = 0;
428 if (exe_ctx && target) {
429 addr_width = target->GetArchitecture().GetAddressByteSize() * 2;
430 }
431 if (addr_width == 0)
432 addr_width = 16;
433 if (print_file_addr_or_load_addr) {
434 ExecutionContextScope *exe_scope = nullptr;
435 if (exe_ctx)
436 exe_scope = exe_ctx->GetBestExecutionContextScope();
437 addr.Dump(&s, exe_scope, Address::DumpStyleLoadAddress,
438 Address::DumpStyleModuleWithFileAddress, 0);
439 } else {
440 s.Printf("0x%*.*" PRIx64"llx", addr_width, addr_width, vaddr);
441 }
442 return true;
443 }
444 return false;
445}
446
447static bool DumpAddressOffsetFromFunction(Stream &s, const SymbolContext *sc,
448 const ExecutionContext *exe_ctx,
449 const Address &format_addr,
450 bool concrete_only, bool no_padding,
451 bool print_zero_offsets) {
452 if (format_addr.IsValid()) {
453 Address func_addr;
454
455 if (sc) {
456 if (sc->function) {
457 func_addr = sc->function->GetAddressRange().GetBaseAddress();
458 if (sc->block && !concrete_only) {
459 // Check to make sure we aren't in an inline function. If we are, use
460 // the inline block range that contains "format_addr" since blocks
461 // can be discontiguous.
462 Block *inline_block = sc->block->GetContainingInlinedBlock();
463 AddressRange inline_range;
464 if (inline_block && inline_block->GetRangeContainingAddress(
465 format_addr, inline_range))
466 func_addr = inline_range.GetBaseAddress();
467 }
468 } else if (sc->symbol && sc->symbol->ValueIsAddress())
469 func_addr = sc->symbol->GetAddressRef();
470 }
471
472 if (func_addr.IsValid()) {
473 const char *addr_offset_padding = no_padding ? "" : " ";
474
475 if (func_addr.GetSection() == format_addr.GetSection()) {
476 addr_t func_file_addr = func_addr.GetFileAddress();
477 addr_t addr_file_addr = format_addr.GetFileAddress();
478 if (addr_file_addr > func_file_addr ||
479 (addr_file_addr == func_file_addr && print_zero_offsets)) {
480 s.Printf("%s+%s%" PRIu64"llu", addr_offset_padding, addr_offset_padding,
481 addr_file_addr - func_file_addr);
482 } else if (addr_file_addr < func_file_addr) {
483 s.Printf("%s-%s%" PRIu64"llu", addr_offset_padding, addr_offset_padding,
484 func_file_addr - addr_file_addr);
485 }
486 return true;
487 } else {
488 Target *target = Target::GetTargetFromContexts(exe_ctx, sc);
489 if (target) {
490 addr_t func_load_addr = func_addr.GetLoadAddress(target);
491 addr_t addr_load_addr = format_addr.GetLoadAddress(target);
492 if (addr_load_addr > func_load_addr ||
493 (addr_load_addr == func_load_addr && print_zero_offsets)) {
494 s.Printf("%s+%s%" PRIu64"llu", addr_offset_padding, addr_offset_padding,
495 addr_load_addr - func_load_addr);
496 } else if (addr_load_addr < func_load_addr) {
497 s.Printf("%s-%s%" PRIu64"llu", addr_offset_padding, addr_offset_padding,
498 func_load_addr - addr_load_addr);
499 }
500 return true;
501 }
502 }
503 }
504 }
505 return false;
506}
507
508static bool ScanBracketedRange(llvm::StringRef subpath,
509 size_t &close_bracket_index,
510 const char *&var_name_final_if_array_range,
511 int64_t &index_lower, int64_t &index_higher) {
512 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS(1u << 29)));
513 close_bracket_index = llvm::StringRef::npos;
514 const size_t open_bracket_index = subpath.find('[');
515 if (open_bracket_index == llvm::StringRef::npos) {
516 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] no bracketed range, skipping entirely"
); } while (0)
517 "[ScanBracketedRange] no bracketed range, skipping entirely")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] no bracketed range, skipping entirely"
); } while (0)
;
518 return false;
519 }
520
521 close_bracket_index = subpath.find(']', open_bracket_index + 1);
522
523 if (close_bracket_index == llvm::StringRef::npos) {
524 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] no bracketed range, skipping entirely"
); } while (0)
525 "[ScanBracketedRange] no bracketed range, skipping entirely")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] no bracketed range, skipping entirely"
); } while (0)
;
526 return false;
527 } else {
528 var_name_final_if_array_range = subpath.data() + open_bracket_index;
529
530 if (close_bracket_index - open_bracket_index == 1) {
531 LLDB_LOGF(do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] '[]' detected.. going from 0 to end of data"
); } while (0)
532 log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] '[]' detected.. going from 0 to end of data"
); } while (0)
533 "[ScanBracketedRange] '[]' detected.. going from 0 to end of data")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] '[]' detected.. going from 0 to end of data"
); } while (0)
;
534 index_lower = 0;
535 } else {
536 const size_t separator_index = subpath.find('-', open_bracket_index + 1);
537
538 if (separator_index == llvm::StringRef::npos) {
539 const char *index_lower_cstr = subpath.data() + open_bracket_index + 1;
540 index_lower = ::strtoul(index_lower_cstr, nullptr, 0);
541 index_higher = index_lower;
542 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] [%" "lld" "] detected, high index is same"
, index_lower); } while (0)
543 "[ScanBracketedRange] [%" PRId64do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] [%" "lld" "] detected, high index is same"
, index_lower); } while (0)
544 "] detected, high index is same",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] [%" "lld" "] detected, high index is same"
, index_lower); } while (0)
545 index_lower)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] [%" "lld" "] detected, high index is same"
, index_lower); } while (0)
;
546 } else {
547 const char *index_lower_cstr = subpath.data() + open_bracket_index + 1;
548 const char *index_higher_cstr = subpath.data() + separator_index + 1;
549 index_lower = ::strtoul(index_lower_cstr, nullptr, 0);
550 index_higher = ::strtoul(index_higher_cstr, nullptr, 0);
551 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] [%" "lld" "-%"
"lld" "] detected", index_lower, index_higher); } while (0)
552 "[ScanBracketedRange] [%" PRId64 "-%" PRId64 "] detected",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] [%" "lld" "-%"
"lld" "] detected", index_lower, index_higher); } while (0)
553 index_lower, index_higher)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] [%" "lld" "-%"
"lld" "] detected", index_lower, index_higher); } while (0)
;
554 }
555 if (index_lower > index_higher && index_higher > 0) {
556 LLDB_LOGF(log, "[ScanBracketedRange] swapping indices")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ScanBracketedRange] swapping indices"
); } while (0)
;
557 const int64_t temp = index_lower;
558 index_lower = index_higher;
559 index_higher = temp;
560 }
561 }
562 }
563 return true;
564}
565
566static bool DumpFile(Stream &s, const FileSpec &file, FileKind file_kind) {
567 switch (file_kind) {
568 case FileKind::FileError:
569 break;
570
571 case FileKind::Basename:
572 if (file.GetFilename()) {
573 s << file.GetFilename();
574 return true;
575 }
576 break;
577
578 case FileKind::Dirname:
579 if (file.GetDirectory()) {
580 s << file.GetDirectory();
581 return true;
582 }
583 break;
584
585 case FileKind::Fullpath:
586 if (file) {
587 s << file;
588 return true;
589 }
590 break;
591 }
592 return false;
593}
594
595static bool DumpRegister(Stream &s, StackFrame *frame, RegisterKind reg_kind,
596 uint32_t reg_num, Format format) {
597 if (frame) {
598 RegisterContext *reg_ctx = frame->GetRegisterContext().get();
599
600 if (reg_ctx) {
601 const uint32_t lldb_reg_num =
602 reg_ctx->ConvertRegisterKindToRegisterNumber(reg_kind, reg_num);
603 if (lldb_reg_num != LLDB_INVALID_REGNUM0xffffffffU) {
604 const RegisterInfo *reg_info =
605 reg_ctx->GetRegisterInfoAtIndex(lldb_reg_num);
606 if (reg_info) {
607 RegisterValue reg_value;
608 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
609 DumpRegisterValue(reg_value, &s, reg_info, false, false, format);
610 return true;
611 }
612 }
613 }
614 }
615 }
616 return false;
617}
618
619static ValueObjectSP ExpandIndexedExpression(ValueObject *valobj, size_t index,
620 bool deref_pointer) {
621 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS(1u << 29)));
622 const char *ptr_deref_format = "[%d]";
623 std::string ptr_deref_buffer(10, 0);
624 ::sprintf(&ptr_deref_buffer[0], ptr_deref_format, index);
625 LLDB_LOGF(log, "[ExpandIndexedExpression] name to deref: %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ExpandIndexedExpression] name to deref: %s"
, ptr_deref_buffer.c_str()); } while (0)
626 ptr_deref_buffer.c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ExpandIndexedExpression] name to deref: %s"
, ptr_deref_buffer.c_str()); } while (0)
;
627 ValueObject::GetValueForExpressionPathOptions options;
628 ValueObject::ExpressionPathEndResultType final_value_type;
629 ValueObject::ExpressionPathScanEndReason reason_to_stop;
630 ValueObject::ExpressionPathAftermath what_next =
631 (deref_pointer ? ValueObject::eExpressionPathAftermathDereference
632 : ValueObject::eExpressionPathAftermathNothing);
633 ValueObjectSP item = valobj->GetValueForExpressionPath(
634 ptr_deref_buffer.c_str(), &reason_to_stop, &final_value_type, options,
635 &what_next);
636 if (!item) {
637 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ExpandIndexedExpression] ERROR: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
638 "[ExpandIndexedExpression] ERROR: why stopping = %d,"do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ExpandIndexedExpression] ERROR: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
639 " final_value_type %d",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ExpandIndexedExpression] ERROR: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
640 reason_to_stop, final_value_type)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ExpandIndexedExpression] ERROR: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
;
641 } else {
642 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ExpandIndexedExpression] ALL RIGHT: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
643 "[ExpandIndexedExpression] ALL RIGHT: why stopping = %d,"do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ExpandIndexedExpression] ALL RIGHT: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
644 " final_value_type %d",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ExpandIndexedExpression] ALL RIGHT: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
645 reason_to_stop, final_value_type)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[ExpandIndexedExpression] ALL RIGHT: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
;
646 }
647 return item;
648}
649
650static char ConvertValueObjectStyleToChar(
651 ValueObject::ValueObjectRepresentationStyle style) {
652 switch (style) {
653 case ValueObject::eValueObjectRepresentationStyleLanguageSpecific:
654 return '@';
655 case ValueObject::eValueObjectRepresentationStyleValue:
656 return 'V';
657 case ValueObject::eValueObjectRepresentationStyleLocation:
658 return 'L';
659 case ValueObject::eValueObjectRepresentationStyleSummary:
660 return 'S';
661 case ValueObject::eValueObjectRepresentationStyleChildrenCount:
662 return '#';
663 case ValueObject::eValueObjectRepresentationStyleType:
664 return 'T';
665 case ValueObject::eValueObjectRepresentationStyleName:
666 return 'N';
667 case ValueObject::eValueObjectRepresentationStyleExpressionPath:
668 return '>';
669 }
670 return '\0';
671}
672
673static bool DumpValue(Stream &s, const SymbolContext *sc,
674 const ExecutionContext *exe_ctx,
675 const FormatEntity::Entry &entry, ValueObject *valobj) {
676 if (valobj == nullptr)
677 return false;
678
679 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_DATAFORMATTERS(1u << 29)));
680 Format custom_format = eFormatInvalid;
681 ValueObject::ValueObjectRepresentationStyle val_obj_display =
682 entry.string.empty()
683 ? ValueObject::eValueObjectRepresentationStyleValue
684 : ValueObject::eValueObjectRepresentationStyleSummary;
685
686 bool do_deref_pointer = entry.deref;
687 bool is_script = false;
688 switch (entry.type) {
689 case FormatEntity::Entry::Type::ScriptVariable:
690 is_script = true;
691 break;
692
693 case FormatEntity::Entry::Type::Variable:
694 custom_format = entry.fmt;
695 val_obj_display = (ValueObject::ValueObjectRepresentationStyle)entry.number;
696 break;
697
698 case FormatEntity::Entry::Type::ScriptVariableSynthetic:
699 is_script = true;
700 LLVM_FALLTHROUGH[[gnu::fallthrough]];
701 case FormatEntity::Entry::Type::VariableSynthetic:
702 custom_format = entry.fmt;
703 val_obj_display = (ValueObject::ValueObjectRepresentationStyle)entry.number;
704 if (!valobj->IsSynthetic()) {
705 valobj = valobj->GetSyntheticValue().get();
706 if (valobj == nullptr)
707 return false;
708 }
709 break;
710
711 default:
712 return false;
713 }
714
715 if (valobj == nullptr)
716 return false;
717
718 ValueObject::ExpressionPathAftermath what_next =
719 (do_deref_pointer ? ValueObject::eExpressionPathAftermathDereference
720 : ValueObject::eExpressionPathAftermathNothing);
721 ValueObject::GetValueForExpressionPathOptions options;
722 options.DontCheckDotVsArrowSyntax()
723 .DoAllowBitfieldSyntax()
724 .DoAllowFragileIVar()
725 .SetSyntheticChildrenTraversal(
726 ValueObject::GetValueForExpressionPathOptions::
727 SyntheticChildrenTraversal::Both);
728 ValueObject *target = nullptr;
729 const char *var_name_final_if_array_range = nullptr;
730 size_t close_bracket_index = llvm::StringRef::npos;
731 int64_t index_lower = -1;
732 int64_t index_higher = -1;
733 bool is_array_range = false;
734 bool was_plain_var = false;
735 bool was_var_format = false;
736 bool was_var_indexed = false;
737 ValueObject::ExpressionPathScanEndReason reason_to_stop =
738 ValueObject::eExpressionPathScanEndReasonEndOfString;
739 ValueObject::ExpressionPathEndResultType final_value_type =
740 ValueObject::eExpressionPathEndResultTypePlain;
741
742 if (is_script) {
743 return RunScriptFormatKeyword(s, sc, exe_ctx, valobj, entry.string.c_str());
744 }
745
746 llvm::StringRef subpath(entry.string);
747 // simplest case ${var}, just print valobj's value
748 if (entry.string.empty()) {
749 if (entry.printf_format.empty() && entry.fmt == eFormatDefault &&
750 entry.number == ValueObject::eValueObjectRepresentationStyleValue)
751 was_plain_var = true;
752 else
753 was_var_format = true;
754 target = valobj;
755 } else // this is ${var.something} or multiple .something nested
756 {
757 if (entry.string[0] == '[')
758 was_var_indexed = true;
759 ScanBracketedRange(subpath, close_bracket_index,
760 var_name_final_if_array_range, index_lower,
761 index_higher);
762
763 Status error;
764
765 const std::string &expr_path = entry.string;
766
767 LLDB_LOGF(log, "[Debugger::FormatPrompt] symbol to expand: %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] symbol to expand: %s"
, expr_path.c_str()); } while (0)
768 expr_path.c_str())do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] symbol to expand: %s"
, expr_path.c_str()); } while (0)
;
769
770 target =
771 valobj
772 ->GetValueForExpressionPath(expr_path.c_str(), &reason_to_stop,
773 &final_value_type, options, &what_next)
774 .get();
775
776 if (!target) {
777 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ERROR: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
778 "[Debugger::FormatPrompt] ERROR: why stopping = %d,"do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ERROR: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
779 " final_value_type %d",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ERROR: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
780 reason_to_stop, final_value_type)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ERROR: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
;
781 return false;
782 } else {
783 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ALL RIGHT: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
784 "[Debugger::FormatPrompt] ALL RIGHT: why stopping = %d,"do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ALL RIGHT: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
785 " final_value_type %d",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ALL RIGHT: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
786 reason_to_stop, final_value_type)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ALL RIGHT: why stopping = %d,"
" final_value_type %d", reason_to_stop, final_value_type); }
while (0)
;
787 target = target
788 ->GetQualifiedRepresentationIfAvailable(
789 target->GetDynamicValueType(), true)
790 .get();
791 }
792 }
793
794 is_array_range =
795 (final_value_type ==
796 ValueObject::eExpressionPathEndResultTypeBoundedRange ||
797 final_value_type ==
798 ValueObject::eExpressionPathEndResultTypeUnboundedRange);
799
800 do_deref_pointer =
801 (what_next == ValueObject::eExpressionPathAftermathDereference);
802
803 if (do_deref_pointer && !is_array_range) {
804 // I have not deref-ed yet, let's do it
805 // this happens when we are not going through
806 // GetValueForVariableExpressionPath to get to the target ValueObject
807 Status error;
808 target = target->Dereference(error).get();
809 if (error.Fail()) {
810 LLDB_LOGF(log, "[Debugger::FormatPrompt] ERROR: %s\n",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ERROR: %s\n"
, error.AsCString("unknown")); } while (0)
811 error.AsCString("unknown"))do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ERROR: %s\n"
, error.AsCString("unknown")); } while (0)
;
812 return false;
813 }
814 do_deref_pointer = false;
815 }
816
817 if (!target) {
818 LLDB_LOGF(log, "[Debugger::FormatPrompt] could not calculate target for "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] could not calculate target for "
"prompt expression"); } while (0)
819 "prompt expression")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] could not calculate target for "
"prompt expression"); } while (0)
;
820 return false;
821 }
822
823 // we do not want to use the summary for a bitfield of type T:n if we were
824 // originally dealing with just a T - that would get us into an endless
825 // recursion
826 if (target->IsBitfield() && was_var_indexed) {
827 // TODO: check for a (T:n)-specific summary - we should still obey that
828 StreamString bitfield_name;
829 bitfield_name.Printf("%s:%d", target->GetTypeName().AsCString(),
830 target->GetBitfieldBitSize());
831 auto type_sp = std::make_shared<TypeNameSpecifierImpl>(
832 bitfield_name.GetString(), false);
833 if (val_obj_display ==
834 ValueObject::eValueObjectRepresentationStyleSummary &&
835 !DataVisualization::GetSummaryForType(type_sp))
836 val_obj_display = ValueObject::eValueObjectRepresentationStyleValue;
837 }
838
839 // TODO use flags for these
840 const uint32_t type_info_flags =
841 target->GetCompilerType().GetTypeInfo(nullptr);
842 bool is_array = (type_info_flags & eTypeIsArray) != 0;
843 bool is_pointer = (type_info_flags & eTypeIsPointer) != 0;
844 bool is_aggregate = target->GetCompilerType().IsAggregateType();
845
846 if ((is_array || is_pointer) && (!is_array_range) &&
847 val_obj_display ==
848 ValueObject::eValueObjectRepresentationStyleValue) // this should be
849 // wrong, but there
850 // are some
851 // exceptions
852 {
853 StreamString str_temp;
854 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] I am into array || pointer && !range"
); } while (0)
855 "[Debugger::FormatPrompt] I am into array || pointer && !range")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] I am into array || pointer && !range"
); } while (0)
;
856
857 if (target->HasSpecialPrintableRepresentation(val_obj_display,
858 custom_format)) {
859 // try to use the special cases
860 bool success = target->DumpPrintableRepresentation(
861 str_temp, val_obj_display, custom_format);
862 LLDB_LOGF(log, "[Debugger::FormatPrompt] special cases did%s match",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] special cases did%s match"
, success ? "" : "n't"); } while (0)
863 success ? "" : "n't")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] special cases did%s match"
, success ? "" : "n't"); } while (0)
;
864
865 // should not happen
866 if (success)
867 s << str_temp.GetString();
868 return true;
869 } else {
870 if (was_plain_var) // if ${var}
871 {
872 s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
873 } else if (is_pointer) // if pointer, value is the address stored
874 {
875 target->DumpPrintableRepresentation(
876 s, val_obj_display, custom_format,
877 ValueObject::PrintableRepresentationSpecialCases::eDisable);
878 }
879 return true;
880 }
881 }
882
883 // if directly trying to print ${var}, and this is an aggregate, display a
884 // nice type @ location message
885 if (is_aggregate && was_plain_var) {
886 s << target->GetTypeName() << " @ " << target->GetLocationAsCString();
887 return true;
888 }
889
890 // if directly trying to print ${var%V}, and this is an aggregate, do not let
891 // the user do it
892 if (is_aggregate &&
893 ((was_var_format &&
894 val_obj_display ==
895 ValueObject::eValueObjectRepresentationStyleValue))) {
896 s << "<invalid use of aggregate type>";
897 return true;
898 }
899
900 if (!is_array_range) {
901 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] dumping ordinary printable output"
); } while (0)
902 "[Debugger::FormatPrompt] dumping ordinary printable output")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] dumping ordinary printable output"
); } while (0)
;
903 return target->DumpPrintableRepresentation(s, val_obj_display,
904 custom_format);
905 } else {
906 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] checking if I can handle as array"
); } while (0)
907 "[Debugger::FormatPrompt] checking if I can handle as array")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] checking if I can handle as array"
); } while (0)
;
908 if (!is_array && !is_pointer)
909 return false;
910 LLDB_LOGF(log, "[Debugger::FormatPrompt] handle as array")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] handle as array"
); } while (0)
;
911 StreamString special_directions_stream;
912 llvm::StringRef special_directions;
913 if (close_bracket_index != llvm::StringRef::npos &&
914 subpath.size() > close_bracket_index) {
915 ConstString additional_data(subpath.drop_front(close_bracket_index + 1));
916 special_directions_stream.Printf("${%svar%s", do_deref_pointer ? "*" : "",
917 additional_data.GetCString());
918
919 if (entry.fmt != eFormatDefault) {
920 const char format_char =
921 FormatManager::GetFormatAsFormatChar(entry.fmt);
922 if (format_char != '\0')
923 special_directions_stream.Printf("%%%c", format_char);
924 else {
925 const char *format_cstr =
926 FormatManager::GetFormatAsCString(entry.fmt);
927 special_directions_stream.Printf("%%%s", format_cstr);
928 }
929 } else if (entry.number != 0) {
930 const char style_char = ConvertValueObjectStyleToChar(
931 (ValueObject::ValueObjectRepresentationStyle)entry.number);
932 if (style_char)
933 special_directions_stream.Printf("%%%c", style_char);
934 }
935 special_directions_stream.PutChar('}');
936 special_directions =
937 llvm::StringRef(special_directions_stream.GetString());
938 }
939
940 // let us display items index_lower thru index_higher of this array
941 s.PutChar('[');
942
943 if (index_higher < 0)
944 index_higher = valobj->GetNumChildren() - 1;
945
946 uint32_t max_num_children =
947 target->GetTargetSP()->GetMaximumNumberOfChildrenToDisplay();
948
949 bool success = true;
950 for (int64_t index = index_lower; index <= index_higher; ++index) {
951 ValueObject *item = ExpandIndexedExpression(target, index, false).get();
952
953 if (!item) {
954 LLDB_LOGF(log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ERROR in getting child item at "
"index %" "lld", index); } while (0)
955 "[Debugger::FormatPrompt] ERROR in getting child item at "do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ERROR in getting child item at "
"index %" "lld", index); } while (0)
956 "index %" PRId64,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ERROR in getting child item at "
"index %" "lld", index); } while (0)
957 index)do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] ERROR in getting child item at "
"index %" "lld", index); } while (0)
;
958 } else {
959 LLDB_LOGF(do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] special_directions for child item: %s"
, special_directions.data() ? special_directions.data() : "")
; } while (0)
960 log,do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] special_directions for child item: %s"
, special_directions.data() ? special_directions.data() : "")
; } while (0)
961 "[Debugger::FormatPrompt] special_directions for child item: %s",do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] special_directions for child item: %s"
, special_directions.data() ? special_directions.data() : "")
; } while (0)
962 special_directions.data() ? special_directions.data() : "")do { ::lldb_private::Log *log_private = (log); if (log_private
) log_private->Printf("[Debugger::FormatPrompt] special_directions for child item: %s"
, special_directions.data() ? special_directions.data() : "")
; } while (0)
;
963 }
964
965 if (special_directions.empty()) {
966 success &= item->DumpPrintableRepresentation(s, val_obj_display,
967 custom_format);
968 } else {
969 success &= FormatEntity::FormatStringRef(
970 special_directions, s, sc, exe_ctx, nullptr, item, false, false);
971 }
972
973 if (--max_num_children == 0) {
974 s.PutCString(", ...");
975 break;
976 }
977
978 if (index < index_higher)
979 s.PutChar(',');
980 }
981 s.PutChar(']');
982 return success;
983 }
984}
985
986static bool DumpRegister(Stream &s, StackFrame *frame, const char *reg_name,
987 Format format) {
988 if (frame) {
989 RegisterContext *reg_ctx = frame->GetRegisterContext().get();
990
991 if (reg_ctx) {
992 const RegisterInfo *reg_info = reg_ctx->GetRegisterInfoByName(reg_name);
993 if (reg_info) {
994 RegisterValue reg_value;
995 if (reg_ctx->ReadRegister(reg_info, reg_value)) {
996 DumpRegisterValue(reg_value, &s, reg_info, false, false, format);
997 return true;
998 }
999 }
1000 }
1001 }
1002 return false;
1003}
1004
1005static bool FormatThreadExtendedInfoRecurse(
1006 const FormatEntity::Entry &entry,
1007 const StructuredData::ObjectSP &thread_info_dictionary,
1008 const SymbolContext *sc, const ExecutionContext *exe_ctx, Stream &s) {
1009 llvm::StringRef path(entry.string);
1010
1011 StructuredData::ObjectSP value =
1012 thread_info_dictionary->GetObjectForDotSeparatedPath(path);
1013
1014 if (value) {
1015 if (value->GetType() == eStructuredDataTypeInteger) {
1016 const char *token_format = "0x%4.4" PRIx64"llx";
1017 if (!entry.printf_format.empty())
1018 token_format = entry.printf_format.c_str();
1019 s.Printf(token_format, value->GetAsInteger()->GetValue());
1020 return true;
1021 } else if (value->GetType() == eStructuredDataTypeFloat) {
1022 s.Printf("%f", value->GetAsFloat()->GetValue());
1023 return true;
1024 } else if (value->GetType() == eStructuredDataTypeString) {
1025 s.Format("{0}", value->GetAsString()->GetValue());
1026 return true;
1027 } else if (value->GetType() == eStructuredDataTypeArray) {
1028 if (value->GetAsArray()->GetSize() > 0) {
1029 s.Printf("%zu", value->GetAsArray()->GetSize());
1030 return true;
1031 }
1032 } else if (value->GetType() == eStructuredDataTypeDictionary) {
1033 s.Printf("%zu",
1034 value->GetAsDictionary()->GetKeys()->GetAsArray()->GetSize());
1035 return true;
1036 }
1037 }
1038
1039 return false;
1040}
1041
1042static inline bool IsToken(const char *var_name_begin, const char *var) {
1043 return (::strncmp(var_name_begin, var, strlen(var)) == 0);
1044}
1045
1046bool FormatEntity::FormatStringRef(const llvm::StringRef &format_str, Stream &s,
1047 const SymbolContext *sc,
1048 const ExecutionContext *exe_ctx,
1049 const Address *addr, ValueObject *valobj,
1050 bool function_changed,
1051 bool initial_function) {
1052 if (!format_str.empty()) {
1053 FormatEntity::Entry root;
1054 Status error = FormatEntity::Parse(format_str, root);
1055 if (error.Success()) {
1056 return FormatEntity::Format(root, s, sc, exe_ctx, addr, valobj,
1057 function_changed, initial_function);
1058 }
1059 }
1060 return false;
1061}
1062
1063bool FormatEntity::FormatCString(const char *format, Stream &s,
1064 const SymbolContext *sc,
1065 const ExecutionContext *exe_ctx,
1066 const Address *addr, ValueObject *valobj,
1067 bool function_changed, bool initial_function) {
1068 if (format && format[0]) {
1069 FormatEntity::Entry root;
1070 llvm::StringRef format_str(format);
1071 Status error = FormatEntity::Parse(format_str, root);
1072 if (error.Success()) {
1073 return FormatEntity::Format(root, s, sc, exe_ctx, addr, valobj,
1074 function_changed, initial_function);
1075 }
1076 }
1077 return false;
1078}
1079
1080bool FormatEntity::Format(const Entry &entry, Stream &s,
1081 const SymbolContext *sc,
1082 const ExecutionContext *exe_ctx, const Address *addr,
1083 ValueObject *valobj, bool function_changed,
1084 bool initial_function) {
1085 switch (entry.type) {
1
Control jumps to 'case FunctionNameWithArgs:' at line 1597
1086 case Entry::Type::Invalid:
1087 case Entry::Type::ParentNumber: // Only used for
1088 // FormatEntity::Entry::Definition encoding
1089 case Entry::Type::ParentString: // Only used for
1090 // FormatEntity::Entry::Definition encoding
1091 return false;
1092 case Entry::Type::EscapeCode:
1093 if (exe_ctx) {
1094 if (Target *target = exe_ctx->GetTargetPtr()) {
1095 Debugger &debugger = target->GetDebugger();
1096 if (debugger.GetUseColor()) {
1097 s.PutCString(entry.string);
1098 }
1099 }
1100 }
1101 // Always return true, so colors being disabled is transparent.
1102 return true;
1103
1104 case Entry::Type::Root:
1105 for (const auto &child : entry.children) {
1106 if (!Format(child, s, sc, exe_ctx, addr, valobj, function_changed,
1107 initial_function)) {
1108 return false; // If any item of root fails, then the formatting fails
1109 }
1110 }
1111 return true; // Only return true if all items succeeded
1112
1113 case Entry::Type::String:
1114 s.PutCString(entry.string);
1115 return true;
1116
1117 case Entry::Type::Scope: {
1118 StreamString scope_stream;
1119 bool success = false;
1120 for (const auto &child : entry.children) {
1121 success = Format(child, scope_stream, sc, exe_ctx, addr, valobj,
1122 function_changed, initial_function);
1123 if (!success)
1124 break;
1125 }
1126 // Only if all items in a scope succeed, then do we print the output into
1127 // the main stream
1128 if (success)
1129 s.Write(scope_stream.GetString().data(), scope_stream.GetString().size());
1130 }
1131 return true; // Scopes always successfully print themselves
1132
1133 case Entry::Type::Variable:
1134 case Entry::Type::VariableSynthetic:
1135 case Entry::Type::ScriptVariable:
1136 case Entry::Type::ScriptVariableSynthetic:
1137 return DumpValue(s, sc, exe_ctx, entry, valobj);
1138
1139 case Entry::Type::AddressFile:
1140 case Entry::Type::AddressLoad:
1141 case Entry::Type::AddressLoadOrFile:
1142 return (
1143 addr != nullptr && addr->IsValid() &&
1144 DumpAddressAndContent(s, sc, exe_ctx, *addr,
1145 entry.type == Entry::Type::AddressLoadOrFile));
1146
1147 case Entry::Type::ProcessID:
1148 if (exe_ctx) {
1149 Process *process = exe_ctx->GetProcessPtr();
1150 if (process) {
1151 const char *format = "%" PRIu64"llu";
1152 if (!entry.printf_format.empty())
1153 format = entry.printf_format.c_str();
1154 s.Printf(format, process->GetID());
1155 return true;
1156 }
1157 }
1158 return false;
1159
1160 case Entry::Type::ProcessFile:
1161 if (exe_ctx) {
1162 Process *process = exe_ctx->GetProcessPtr();
1163 if (process) {
1164 Module *exe_module = process->GetTarget().GetExecutableModulePointer();
1165 if (exe_module) {
1166 if (DumpFile(s, exe_module->GetFileSpec(), (FileKind)entry.number))
1167 return true;
1168 }
1169 }
1170 }
1171 return false;
1172
1173 case Entry::Type::ScriptProcess:
1174 if (exe_ctx) {
1175 Process *process = exe_ctx->GetProcessPtr();
1176 if (process)
1177 return RunScriptFormatKeyword(s, sc, exe_ctx, process,
1178 entry.string.c_str());
1179 }
1180 return false;
1181
1182 case Entry::Type::ThreadID:
1183 if (exe_ctx) {
1184 Thread *thread = exe_ctx->GetThreadPtr();
1185 if (thread) {
1186 const char *format = "0x%4.4" PRIx64"llx";
1187 if (!entry.printf_format.empty()) {
1188 // Watch for the special "tid" format...
1189 if (entry.printf_format == "tid") {
1190 // TODO(zturner): Rather than hardcoding this to be platform
1191 // specific, it should be controlled by a setting and the default
1192 // value of the setting can be different depending on the platform.
1193 Target &target = thread->GetProcess()->GetTarget();
1194 ArchSpec arch(target.GetArchitecture());
1195 llvm::Triple::OSType ostype = arch.IsValid()
1196 ? arch.GetTriple().getOS()
1197 : llvm::Triple::UnknownOS;
1198 if ((ostype == llvm::Triple::FreeBSD) ||
1199 (ostype == llvm::Triple::Linux) ||
1200 (ostype == llvm::Triple::NetBSD) ||
1201 (ostype == llvm::Triple::OpenBSD)) {
1202 format = "%" PRIu64"llu";
1203 }
1204 } else {
1205 format = entry.printf_format.c_str();
1206 }
1207 }
1208 s.Printf(format, thread->GetID());
1209 return true;
1210 }
1211 }
1212 return false;
1213
1214 case Entry::Type::ThreadProtocolID:
1215 if (exe_ctx) {
1216 Thread *thread = exe_ctx->GetThreadPtr();
1217 if (thread) {
1218 const char *format = "0x%4.4" PRIx64"llx";
1219 if (!entry.printf_format.empty())
1220 format = entry.printf_format.c_str();
1221 s.Printf(format, thread->GetProtocolID());
1222 return true;
1223 }
1224 }
1225 return false;
1226
1227 case Entry::Type::ThreadIndexID:
1228 if (exe_ctx) {
1229 Thread *thread = exe_ctx->GetThreadPtr();
1230 if (thread) {
1231 const char *format = "%" PRIu32"u";
1232 if (!entry.printf_format.empty())
1233 format = entry.printf_format.c_str();
1234 s.Printf(format, thread->GetIndexID());
1235 return true;
1236 }
1237 }
1238 return false;
1239
1240 case Entry::Type::ThreadName:
1241 if (exe_ctx) {
1242 Thread *thread = exe_ctx->GetThreadPtr();
1243 if (thread) {
1244 const char *cstr = thread->GetName();
1245 if (cstr && cstr[0]) {
1246 s.PutCString(cstr);
1247 return true;
1248 }
1249 }
1250 }
1251 return false;
1252
1253 case Entry::Type::ThreadQueue:
1254 if (exe_ctx) {
1255 Thread *thread = exe_ctx->GetThreadPtr();
1256 if (thread) {
1257 const char *cstr = thread->GetQueueName();
1258 if (cstr && cstr[0]) {
1259 s.PutCString(cstr);
1260 return true;
1261 }
1262 }
1263 }
1264 return false;
1265
1266 case Entry::Type::ThreadStopReason:
1267 if (exe_ctx) {
1268 if (Thread *thread = exe_ctx->GetThreadPtr()) {
1269 std::string stop_description = thread->GetStopDescription();
1270 if (!stop_description.empty()) {
1271 s.PutCString(stop_description);
1272 return true;
1273 }
1274 }
1275 }
1276 return false;
1277
1278 case Entry::Type::ThreadStopReasonRaw:
1279 if (exe_ctx) {
1280 if (Thread *thread = exe_ctx->GetThreadPtr()) {
1281 std::string stop_description = thread->GetStopDescriptionRaw();
1282 if (!stop_description.empty()) {
1283 s.PutCString(stop_description);
1284 return true;
1285 }
1286 }
1287 }
1288 return false;
1289
1290 case Entry::Type::ThreadReturnValue:
1291 if (exe_ctx) {
1292 Thread *thread = exe_ctx->GetThreadPtr();
1293 if (thread) {
1294 StopInfoSP stop_info_sp = thread->GetStopInfo();
1295 if (stop_info_sp && stop_info_sp->IsValid()) {
1296 ValueObjectSP return_valobj_sp =
1297 StopInfo::GetReturnValueObject(stop_info_sp);
1298 if (return_valobj_sp) {
1299 return_valobj_sp->Dump(s);
1300 return true;
1301 }
1302 }
1303 }
1304 }
1305 return false;
1306
1307 case Entry::Type::ThreadCompletedExpression:
1308 if (exe_ctx) {
1309 Thread *thread = exe_ctx->GetThreadPtr();
1310 if (thread) {
1311 StopInfoSP stop_info_sp = thread->GetStopInfo();
1312 if (stop_info_sp && stop_info_sp->IsValid()) {
1313 ExpressionVariableSP expression_var_sp =
1314 StopInfo::GetExpressionVariable(stop_info_sp);
1315 if (expression_var_sp && expression_var_sp->GetValueObject()) {
1316 expression_var_sp->GetValueObject()->Dump(s);
1317 return true;
1318 }
1319 }
1320 }
1321 }
1322 return false;
1323
1324 case Entry::Type::ScriptThread:
1325 if (exe_ctx) {
1326 Thread *thread = exe_ctx->GetThreadPtr();
1327 if (thread)
1328 return RunScriptFormatKeyword(s, sc, exe_ctx, thread,
1329 entry.string.c_str());
1330 }
1331 return false;
1332
1333 case Entry::Type::ThreadInfo:
1334 if (exe_ctx) {
1335 Thread *thread = exe_ctx->GetThreadPtr();
1336 if (thread) {
1337 StructuredData::ObjectSP object_sp = thread->GetExtendedInfo();
1338 if (object_sp &&
1339 object_sp->GetType() == eStructuredDataTypeDictionary) {
1340 if (FormatThreadExtendedInfoRecurse(entry, object_sp, sc, exe_ctx, s))
1341 return true;
1342 }
1343 }
1344 }
1345 return false;
1346
1347 case Entry::Type::TargetArch:
1348 if (exe_ctx) {
1349 Target *target = exe_ctx->GetTargetPtr();
1350 if (target) {
1351 const ArchSpec &arch = target->GetArchitecture();
1352 if (arch.IsValid()) {
1353 s.PutCString(arch.GetArchitectureName());
1354 return true;
1355 }
1356 }
1357 }
1358 return false;
1359
1360 case Entry::Type::ScriptTarget:
1361 if (exe_ctx) {
1362 Target *target = exe_ctx->GetTargetPtr();
1363 if (target)
1364 return RunScriptFormatKeyword(s, sc, exe_ctx, target,
1365 entry.string.c_str());
1366 }
1367 return false;
1368
1369 case Entry::Type::ModuleFile:
1370 if (sc) {
1371 Module *module = sc->module_sp.get();
1372 if (module) {
1373 if (DumpFile(s, module->GetFileSpec(), (FileKind)entry.number))
1374 return true;
1375 }
1376 }
1377 return false;
1378
1379 case Entry::Type::File:
1380 if (sc) {
1381 CompileUnit *cu = sc->comp_unit;
1382 if (cu) {
1383 if (DumpFile(s, cu->GetPrimaryFile(), (FileKind)entry.number))
1384 return true;
1385 }
1386 }
1387 return false;
1388
1389 case Entry::Type::Lang:
1390 if (sc) {
1391 CompileUnit *cu = sc->comp_unit;
1392 if (cu) {
1393 const char *lang_name =
1394 Language::GetNameForLanguageType(cu->GetLanguage());
1395 if (lang_name) {
1396 s.PutCString(lang_name);
1397 return true;
1398 }
1399 }
1400 }
1401 return false;
1402
1403 case Entry::Type::FrameIndex:
1404 if (exe_ctx) {
1405 StackFrame *frame = exe_ctx->GetFramePtr();
1406 if (frame) {
1407 const char *format = "%" PRIu32"u";
1408 if (!entry.printf_format.empty())
1409 format = entry.printf_format.c_str();
1410 s.Printf(format, frame->GetFrameIndex());
1411 return true;
1412 }
1413 }
1414 return false;
1415
1416 case Entry::Type::FrameRegisterPC:
1417 if (exe_ctx) {
1418 StackFrame *frame = exe_ctx->GetFramePtr();
1419 if (frame) {
1420 const Address &pc_addr = frame->GetFrameCodeAddress();
1421 if (pc_addr.IsValid()) {
1422 if (DumpAddressAndContent(s, sc, exe_ctx, pc_addr, false))
1423 return true;
1424 }
1425 }
1426 }
1427 return false;
1428
1429 case Entry::Type::FrameRegisterSP:
1430 if (exe_ctx) {
1431 StackFrame *frame = exe_ctx->GetFramePtr();
1432 if (frame) {
1433 if (DumpRegister(s, frame, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_SP1,
1434 (lldb::Format)entry.number))
1435 return true;
1436 }
1437 }
1438 return false;
1439
1440 case Entry::Type::FrameRegisterFP:
1441 if (exe_ctx) {
1442 StackFrame *frame = exe_ctx->GetFramePtr();
1443 if (frame) {
1444 if (DumpRegister(s, frame, eRegisterKindGeneric, LLDB_REGNUM_GENERIC_FP2,
1445 (lldb::Format)entry.number))
1446 return true;
1447 }
1448 }
1449 return false;
1450
1451 case Entry::Type::FrameRegisterFlags:
1452 if (exe_ctx) {
1453 StackFrame *frame = exe_ctx->GetFramePtr();
1454 if (frame) {
1455 if (DumpRegister(s, frame, eRegisterKindGeneric,
1456 LLDB_REGNUM_GENERIC_FLAGS4, (lldb::Format)entry.number))
1457 return true;
1458 }
1459 }
1460 return false;
1461
1462 case Entry::Type::FrameNoDebug:
1463 if (exe_ctx) {
1464 StackFrame *frame = exe_ctx->GetFramePtr();
1465 if (frame) {
1466 return !frame->HasDebugInformation();
1467 }
1468 }
1469 return true;
1470
1471 case Entry::Type::FrameRegisterByName:
1472 if (exe_ctx) {
1473 StackFrame *frame = exe_ctx->GetFramePtr();
1474 if (frame) {
1475 if (DumpRegister(s, frame, entry.string.c_str(),
1476 (lldb::Format)entry.number))
1477 return true;
1478 }
1479 }
1480 return false;
1481
1482 case Entry::Type::FrameIsArtificial: {
1483 if (exe_ctx)
1484 if (StackFrame *frame = exe_ctx->GetFramePtr())
1485 return frame->IsArtificial();
1486 return false;
1487 }
1488
1489 case Entry::Type::ScriptFrame:
1490 if (exe_ctx) {
1491 StackFrame *frame = exe_ctx->GetFramePtr();
1492 if (frame)
1493 return RunScriptFormatKeyword(s, sc, exe_ctx, frame,
1494 entry.string.c_str());
1495 }
1496 return false;
1497
1498 case Entry::Type::FunctionID:
1499 if (sc) {
1500 if (sc->function) {
1501 s.Printf("function{0x%8.8" PRIx64"llx" "}", sc->function->GetID());
1502 return true;
1503 } else if (sc->symbol) {
1504 s.Printf("symbol[%u]", sc->symbol->GetID());
1505 return true;
1506 }
1507 }
1508 return false;
1509
1510 case Entry::Type::FunctionDidChange:
1511 return function_changed;
1512
1513 case Entry::Type::FunctionInitialFunction:
1514 return initial_function;
1515
1516 case Entry::Type::FunctionName: {
1517 if (!sc)
1518 return false;
1519
1520 Language *language_plugin = nullptr;
1521 bool language_plugin_handled = false;
1522 StreamString ss;
1523
1524 if (sc->function)
1525 language_plugin = Language::FindPlugin(sc->function->GetLanguage());
1526 else if (sc->symbol)
1527 language_plugin = Language::FindPlugin(sc->symbol->GetLanguage());
1528
1529 if (language_plugin)
1530 language_plugin_handled = language_plugin->GetFunctionDisplayName(
1531 sc, exe_ctx, Language::FunctionNameRepresentation::eName, ss);
1532
1533 if (language_plugin_handled) {
1534 s << ss.GetString();
1535 return true;
1536 } else {
1537 const char *name = nullptr;
1538 if (sc->function)
1539 name = sc->function->GetName().AsCString(nullptr);
1540 else if (sc->symbol)
1541 name = sc->symbol->GetName().AsCString(nullptr);
1542
1543 if (name) {
1544 s.PutCString(name);
1545
1546 if (sc->block) {
1547 Block *inline_block = sc->block->GetContainingInlinedBlock();
1548 if (inline_block) {
1549 const InlineFunctionInfo *inline_info =
1550 sc->block->GetInlinedFunctionInfo();
1551 if (inline_info) {
1552 s.PutCString(" [inlined] ");
1553 inline_info->GetName().Dump(&s);
1554 }
1555 }
1556 }
1557 return true;
1558 }
1559 }
1560 }
1561 return false;
1562
1563 case Entry::Type::FunctionNameNoArgs: {
1564 if (!sc)
1565 return false;
1566
1567 Language *language_plugin = nullptr;
1568 bool language_plugin_handled = false;
1569 StreamString ss;
1570 if (sc->function)
1571 language_plugin = Language::FindPlugin(sc->function->GetLanguage());
1572 else if (sc->symbol)
1573 language_plugin = Language::FindPlugin(sc->symbol->GetLanguage());
1574
1575 if (language_plugin)
1576 language_plugin_handled = language_plugin->GetFunctionDisplayName(
1577 sc, exe_ctx, Language::FunctionNameRepresentation::eNameWithNoArgs,
1578 ss);
1579
1580 if (language_plugin_handled) {
1581 s << ss.GetString();
1582 return true;
1583 } else {
1584 ConstString name;
1585 if (sc->function)
1586 name = sc->function->GetNameNoArguments();
1587 else if (sc->symbol)
1588 name = sc->symbol->GetNameNoArguments();
1589 if (name) {
1590 s.PutCString(name.GetCString());
1591 return true;
1592 }
1593 }
1594 }
1595 return false;
1596
1597 case Entry::Type::FunctionNameWithArgs: {
1598 if (!sc)
2
Assuming 'sc' is non-null
3
Taking false branch
1599 return false;
1600
1601 Language *language_plugin = nullptr;
1602 bool language_plugin_handled = false;
1603 StreamString ss;
1604 if (sc->function)
4
Assuming field 'function' is non-null
5
Taking true branch
1605 language_plugin = Language::FindPlugin(sc->function->GetLanguage());
1606 else if (sc->symbol)
1607 language_plugin = Language::FindPlugin(sc->symbol->GetLanguage());
1608
1609 if (language_plugin)
6
Assuming 'language_plugin' is null
7
Taking false branch
1610 language_plugin_handled = language_plugin->GetFunctionDisplayName(
1611 sc, exe_ctx, Language::FunctionNameRepresentation::eNameWithArgs, ss);
1612
1613 if (language_plugin_handled
7.1
'language_plugin_handled' is false
7.1
'language_plugin_handled' is false
7.1
'language_plugin_handled' is false
7.1
'language_plugin_handled' is false
) {
8
Taking false branch
1614 s << ss.GetString();
1615 return true;
1616 } else {
1617 // Print the function name with arguments in it
1618 if (sc->function
8.1
Field 'function' is non-null
8.1
Field 'function' is non-null
8.1
Field 'function' is non-null
8.1
Field 'function' is non-null
) {
9
Taking true branch
1619 ExecutionContextScope *exe_scope =
12
'exe_scope' initialized to a null pointer value
1620 exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr;
10
Assuming 'exe_ctx' is null
11
'?' condition is false
1621 const char *cstr = sc->function->GetName().AsCString(nullptr);
13
Calling 'ConstString::AsCString'
16
Returning from 'ConstString::AsCString'
1622 if (cstr
16.1
'cstr' is non-null
16.1
'cstr' is non-null
16.1
'cstr' is non-null
16.1
'cstr' is non-null
) {
17
Taking true branch
1623 const InlineFunctionInfo *inline_info = nullptr;
1624 VariableListSP variable_list_sp;
1625 bool get_function_vars = true;
1626 if (sc->block) {
18
Assuming field 'block' is non-null
19
Taking true branch
1627 Block *inline_block = sc->block->GetContainingInlinedBlock();
1628
1629 if (inline_block) {
20
Assuming 'inline_block' is non-null
21
Taking true branch
1630 get_function_vars = false;
1631 inline_info = sc->block->GetInlinedFunctionInfo();
1632 if (inline_info)
22
Assuming 'inline_info' is null
23
Taking false branch
1633 variable_list_sp = inline_block->GetBlockVariableList(true);
1634 }
1635 }
1636
1637 if (get_function_vars
23.1
'get_function_vars' is false
23.1
'get_function_vars' is false
23.1
'get_function_vars' is false
23.1
'get_function_vars' is false
) {
24
Taking false branch
1638 variable_list_sp =
1639 sc->function->GetBlock(true).GetBlockVariableList(true);
1640 }
1641
1642 if (inline_info
24.1
'inline_info' is null
24.1
'inline_info' is null
24.1
'inline_info' is null
24.1
'inline_info' is null
) {
25
Taking false branch
1643 s.PutCString(cstr);
1644 s.PutCString(" [inlined] ");
1645 cstr = inline_info->GetName().GetCString();
1646 }
1647
1648 VariableList args;
1649 if (variable_list_sp)
26
Taking false branch
1650 variable_list_sp->AppendVariablesWithScope(
1651 eValueTypeVariableArgument, args);
1652 if (args.GetSize() > 0) {
27
Assuming the condition is true
28
Taking true branch
1653 const char *open_paren = strchr(cstr, '(');
1654 const char *close_paren = nullptr;
1655 const char *generic = strchr(cstr, '<');
1656 // if before the arguments list begins there is a template sign
1657 // then scan to the end of the generic args before you try to find
1658 // the arguments list
1659 if (generic && open_paren && generic < open_paren) {
29
Assuming 'generic' is null
1660 int generic_depth = 1;
1661 ++generic;
1662 for (; *generic && generic_depth > 0; generic++) {
1663 if (*generic == '<')
1664 generic_depth++;
1665 if (*generic == '>')
1666 generic_depth--;
1667 }
1668 if (*generic)
1669 open_paren = strchr(generic, '(');
1670 else
1671 open_paren = nullptr;
1672 }
1673 if (open_paren) {
30
Assuming 'open_paren' is null
31
Taking false branch
1674 if (IsToken(open_paren, "(anonymous namespace)")) {
1675 open_paren =
1676 strchr(open_paren + strlen("(anonymous namespace)"), '(');
1677 if (open_paren)
1678 close_paren = strchr(open_paren, ')');
1679 } else
1680 close_paren = strchr(open_paren, ')');
1681 }
1682
1683 if (open_paren
31.1
'open_paren' is null
31.1
'open_paren' is null
31.1
'open_paren' is null
31.1
'open_paren' is null
)
32
Taking false branch
1684 s.Write(cstr, open_paren - cstr + 1);
1685 else {
1686 s.PutCString(cstr);
1687 s.PutChar('(');
1688 }
1689 const size_t num_args = args.GetSize();
1690 for (size_t arg_idx = 0; arg_idx < num_args; ++arg_idx) {
33
Assuming 'arg_idx' is < 'num_args'
34
Loop condition is true. Entering loop body
1691 std::string buffer;
1692
1693 VariableSP var_sp(args.GetVariableAtIndex(arg_idx));
1694 ValueObjectSP var_value_sp(
1695 ValueObjectVariable::Create(exe_scope, var_sp));
1696 StreamString ss;
1697 llvm::StringRef var_representation;
1698 const char *var_name = var_value_sp->GetName().GetCString();
1699 if (var_value_sp->GetCompilerType().IsValid()) {
35
Calling 'CompilerType::IsValid'
39
Returning from 'CompilerType::IsValid'
40
Taking true branch
1700 if (var_value_sp && exe_scope->CalculateTarget())
41
Calling 'shared_ptr::operator bool'
43
Returning from 'shared_ptr::operator bool'
44
Called C++ object pointer is null
1701 var_value_sp =
1702 var_value_sp->GetQualifiedRepresentationIfAvailable(
1703 exe_scope->CalculateTarget()
1704 ->TargetProperties::GetPreferDynamicValue(),
1705 exe_scope->CalculateTarget()
1706 ->TargetProperties::GetEnableSyntheticValue());
1707 if (var_value_sp->GetCompilerType().IsAggregateType() &&
1708 DataVisualization::ShouldPrintAsOneLiner(*var_value_sp)) {
1709 static StringSummaryFormat format(
1710 TypeSummaryImpl::Flags()
1711 .SetHideItemNames(false)
1712 .SetShowMembersOneLiner(true),
1713 "");
1714 format.FormatObject(var_value_sp.get(), buffer,
1715 TypeSummaryOptions());
1716 var_representation = buffer;
1717 } else
1718 var_value_sp->DumpPrintableRepresentation(
1719 ss,
1720 ValueObject::ValueObjectRepresentationStyle::
1721 eValueObjectRepresentationStyleSummary,
1722 eFormatDefault,
1723 ValueObject::PrintableRepresentationSpecialCases::eAllow,
1724 false);
1725 }
1726
1727 if (!ss.GetString().empty())
1728 var_representation = ss.GetString();
1729 if (arg_idx > 0)
1730 s.PutCString(", ");
1731 if (var_value_sp->GetError().Success()) {
1732 if (!var_representation.empty())
1733 s.Printf("%s=%s", var_name, var_representation.str().c_str());
1734 else
1735 s.Printf("%s=%s at %s", var_name,
1736 var_value_sp->GetTypeName().GetCString(),
1737 var_value_sp->GetLocationAsCString());
1738 } else
1739 s.Printf("%s=<unavailable>", var_name);
1740 }
1741
1742 if (close_paren)
1743 s.PutCString(close_paren);
1744 else
1745 s.PutChar(')');
1746
1747 } else {
1748 s.PutCString(cstr);
1749 }
1750 return true;
1751 }
1752 } else if (sc->symbol) {
1753 const char *cstr = sc->symbol->GetName().AsCString(nullptr);
1754 if (cstr) {
1755 s.PutCString(cstr);
1756 return true;
1757 }
1758 }
1759 }
1760 }
1761 return false;
1762
1763 case Entry::Type::FunctionMangledName: {
1764 if (!sc)
1765 return false;
1766
1767 const char *name = nullptr;
1768 if (sc->symbol)
1769 name =
1770 sc->symbol->GetMangled().GetName(Mangled::ePreferMangled).AsCString();
1771 else if (sc->function)
1772 name = sc->function->GetMangled()
1773 .GetName(Mangled::ePreferMangled)
1774 .AsCString();
1775
1776 if (!name)
1777 return false;
1778 s.PutCString(name);
1779
1780 if (sc->block && sc->block->GetContainingInlinedBlock()) {
1781 if (const InlineFunctionInfo *inline_info =
1782 sc->block->GetInlinedFunctionInfo()) {
1783 s.PutCString(" [inlined] ");
1784 inline_info->GetName().Dump(&s);
1785 }
1786 }
1787 return true;
1788 }
1789 case Entry::Type::FunctionAddrOffset:
1790 if (addr) {
1791 if (DumpAddressOffsetFromFunction(s, sc, exe_ctx, *addr, false, false,
1792 false))
1793 return true;
1794 }
1795 return false;
1796
1797 case Entry::Type::FunctionAddrOffsetConcrete:
1798 if (addr) {
1799 if (DumpAddressOffsetFromFunction(s, sc, exe_ctx, *addr, true, true,
1800 true))
1801 return true;
1802 }
1803 return false;
1804
1805 case Entry::Type::FunctionLineOffset:
1806 if (sc)
1807 return (DumpAddressOffsetFromFunction(
1808 s, sc, exe_ctx, sc->line_entry.range.GetBaseAddress(), false, false,
1809 false));
1810 return false;
1811
1812 case Entry::Type::FunctionPCOffset:
1813 if (exe_ctx) {
1814 StackFrame *frame = exe_ctx->GetFramePtr();
1815 if (frame) {
1816 if (DumpAddressOffsetFromFunction(s, sc, exe_ctx,
1817 frame->GetFrameCodeAddress(), false,
1818 false, false))
1819 return true;
1820 }
1821 }
1822 return false;
1823
1824 case Entry::Type::FunctionChanged:
1825 return function_changed;
1826
1827 case Entry::Type::FunctionIsOptimized: {
1828 bool is_optimized = false;
1829 if (sc && sc->function && sc->function->GetIsOptimized()) {
1830 is_optimized = true;
1831 }
1832 return is_optimized;
1833 }
1834
1835 case Entry::Type::FunctionInitial:
1836 return initial_function;
1837
1838 case Entry::Type::LineEntryFile:
1839 if (sc && sc->line_entry.IsValid()) {
1840 Module *module = sc->module_sp.get();
1841 if (module) {
1842 if (DumpFile(s, sc->line_entry.file, (FileKind)entry.number))
1843 return true;
1844 }
1845 }
1846 return false;
1847
1848 case Entry::Type::LineEntryLineNumber:
1849 if (sc && sc->line_entry.IsValid()) {
1850 const char *format = "%" PRIu32"u";
1851 if (!entry.printf_format.empty())
1852 format = entry.printf_format.c_str();
1853 s.Printf(format, sc->line_entry.line);
1854 return true;
1855 }
1856 return false;
1857
1858 case Entry::Type::LineEntryColumn:
1859 if (sc && sc->line_entry.IsValid() && sc->line_entry.column) {
1860 const char *format = "%" PRIu32"u";
1861 if (!entry.printf_format.empty())
1862 format = entry.printf_format.c_str();
1863 s.Printf(format, sc->line_entry.column);
1864 return true;
1865 }
1866 return false;
1867
1868 case Entry::Type::LineEntryStartAddress:
1869 case Entry::Type::LineEntryEndAddress:
1870 if (sc && sc->line_entry.range.GetBaseAddress().IsValid()) {
1871 Address addr = sc->line_entry.range.GetBaseAddress();
1872
1873 if (entry.type == Entry::Type::LineEntryEndAddress)
1874 addr.Slide(sc->line_entry.range.GetByteSize());
1875 if (DumpAddressAndContent(s, sc, exe_ctx, addr, false))
1876 return true;
1877 }
1878 return false;
1879
1880 case Entry::Type::CurrentPCArrow:
1881 if (addr && exe_ctx && exe_ctx->GetFramePtr()) {
1882 RegisterContextSP reg_ctx =
1883 exe_ctx->GetFramePtr()->GetRegisterContextSP();
1884 if (reg_ctx) {
1885 addr_t pc_loadaddr = reg_ctx->GetPC();
1886 if (pc_loadaddr != LLDB_INVALID_ADDRESS0xffffffffffffffffULL) {
1887 Address pc;
1888 pc.SetLoadAddress(pc_loadaddr, exe_ctx->GetTargetPtr());
1889 if (pc == *addr) {
1890 s.Printf("-> ");
1891 return true;
1892 }
1893 }
1894 }
1895 s.Printf(" ");
1896 return true;
1897 }
1898 return false;
1899 }
1900 return false;
1901}
1902
1903static bool DumpCommaSeparatedChildEntryNames(Stream &s,
1904 const Definition *parent) {
1905 if (parent->children) {
1906 const size_t n = parent->num_children;
1907 for (size_t i = 0; i < n; ++i) {
1908 if (i > 0)
1909 s.PutCString(", ");
1910 s.Printf("\"%s\"", parent->children[i].name);
1911 }
1912 return true;
1913 }
1914 return false;
1915}
1916
1917static Status ParseEntry(const llvm::StringRef &format_str,
1918 const Definition *parent, FormatEntity::Entry &entry) {
1919 Status error;
1920
1921 const size_t sep_pos = format_str.find_first_of(".[:");
1922 const char sep_char =
1923 (sep_pos == llvm::StringRef::npos) ? '\0' : format_str[sep_pos];
1924 llvm::StringRef key = format_str.substr(0, sep_pos);
1925
1926 const size_t n = parent->num_children;
1927 for (size_t i = 0; i < n; ++i) {
1928 const Definition *entry_def = parent->children + i;
1929 if (key.equals(entry_def->name) || entry_def->name[0] == '*') {
1930 llvm::StringRef value;
1931 if (sep_char)
1932 value =
1933 format_str.substr(sep_pos + (entry_def->keep_separator ? 0 : 1));
1934 switch (entry_def->type) {
1935 case FormatEntity::Entry::Type::ParentString:
1936 entry.string = format_str.str();
1937 return error; // Success
1938
1939 case FormatEntity::Entry::Type::ParentNumber:
1940 entry.number = entry_def->data;
1941 return error; // Success
1942
1943 case FormatEntity::Entry::Type::EscapeCode:
1944 entry.type = entry_def->type;
1945 entry.string = entry_def->string;
1946 return error; // Success
1947
1948 default:
1949 entry.type = entry_def->type;
1950 break;
1951 }
1952
1953 if (value.empty()) {
1954 if (entry_def->type == FormatEntity::Entry::Type::Invalid) {
1955 if (entry_def->children) {
1956 StreamString error_strm;
1957 error_strm.Printf("'%s' can't be specified on its own, you must "
1958 "access one of its children: ",
1959 entry_def->name);
1960 DumpCommaSeparatedChildEntryNames(error_strm, entry_def);
1961 error.SetErrorStringWithFormat("%s", error_strm.GetData());
1962 } else if (sep_char == ':') {
1963 // Any value whose separator is a with a ':' means this value has a
1964 // string argument that needs to be stored in the entry (like
1965 // "${script.var:}"). In this case the string value is the empty
1966 // string which is ok.
1967 } else {
1968 error.SetErrorStringWithFormat("%s", "invalid entry definitions");
1969 }
1970 }
1971 } else {
1972 if (entry_def->children) {
1973 error = ParseEntry(value, entry_def, entry);
1974 } else if (sep_char == ':') {
1975 // Any value whose separator is a with a ':' means this value has a
1976 // string argument that needs to be stored in the entry (like
1977 // "${script.var:modulename.function}")
1978 entry.string = value.str();
1979 } else {
1980 error.SetErrorStringWithFormat(
1981 "'%s' followed by '%s' but it has no children", key.str().c_str(),
1982 value.str().c_str());
1983 }
1984 }
1985 return error;
1986 }
1987 }
1988 StreamString error_strm;
1989 if (parent->type == FormatEntity::Entry::Type::Root)
1990 error_strm.Printf(
1991 "invalid top level item '%s'. Valid top level items are: ",
1992 key.str().c_str());
1993 else
1994 error_strm.Printf("invalid member '%s' in '%s'. Valid members are: ",
1995 key.str().c_str(), parent->name);
1996 DumpCommaSeparatedChildEntryNames(error_strm, parent);
1997 error.SetErrorStringWithFormat("%s", error_strm.GetData());
1998 return error;
1999}
2000
2001static const Definition *FindEntry(const llvm::StringRef &format_str,
2002 const Definition *parent,
2003 llvm::StringRef &remainder) {
2004 Status error;
2005
2006 std::pair<llvm::StringRef, llvm::StringRef> p = format_str.split('.');
2007 const size_t n = parent->num_children;
2008 for (size_t i = 0; i < n; ++i) {
2009 const Definition *entry_def = parent->children + i;
2010 if (p.first.equals(entry_def->name) || entry_def->name[0] == '*') {
2011 if (p.second.empty()) {
2012 if (format_str.back() == '.')
2013 remainder = format_str.drop_front(format_str.size() - 1);
2014 else
2015 remainder = llvm::StringRef(); // Exact match
2016 return entry_def;
2017 } else {
2018 if (entry_def->children) {
2019 return FindEntry(p.second, entry_def, remainder);
2020 } else {
2021 remainder = p.second;
2022 return entry_def;
2023 }
2024 }
2025 }
2026 }
2027 remainder = format_str;
2028 return parent;
2029}
2030
2031Status FormatEntity::ParseInternal(llvm::StringRef &format, Entry &parent_entry,
2032 uint32_t depth) {
2033 Status error;
2034 while (!format.empty() && error.Success()) {
2035 const size_t non_special_chars = format.find_first_of("${}\\");
2036
2037 if (non_special_chars == llvm::StringRef::npos) {
2038 // No special characters, just string bytes so add them and we are done
2039 parent_entry.AppendText(format);
2040 return error;
2041 }
2042
2043 if (non_special_chars > 0) {
2044 // We have a special character, so add all characters before these as a
2045 // plain string
2046 parent_entry.AppendText(format.substr(0, non_special_chars));
2047 format = format.drop_front(non_special_chars);
2048 }
2049
2050 switch (format[0]) {
2051 case '\0':
2052 return error;
2053
2054 case '{': {
2055 format = format.drop_front(); // Skip the '{'
2056 Entry scope_entry(Entry::Type::Scope);
2057 error = FormatEntity::ParseInternal(format, scope_entry, depth + 1);
2058 if (error.Fail())
2059 return error;
2060 parent_entry.AppendEntry(std::move(scope_entry));
2061 } break;
2062
2063 case '}':
2064 if (depth == 0)
2065 error.SetErrorString("unmatched '}' character");
2066 else
2067 format =
2068 format
2069 .drop_front(); // Skip the '}' as we are at the end of the scope
2070 return error;
2071
2072 case '\\': {
2073 format = format.drop_front(); // Skip the '\' character
2074 if (format.empty()) {
2075 error.SetErrorString(
2076 "'\\' character was not followed by another character");
2077 return error;
2078 }
2079
2080 const char desens_char = format[0];
2081 format = format.drop_front(); // Skip the desensitized char character
2082 switch (desens_char) {
2083 case 'a':
2084 parent_entry.AppendChar('\a');
2085 break;
2086 case 'b':
2087 parent_entry.AppendChar('\b');
2088 break;
2089 case 'f':
2090 parent_entry.AppendChar('\f');
2091 break;
2092 case 'n':
2093 parent_entry.AppendChar('\n');
2094 break;
2095 case 'r':
2096 parent_entry.AppendChar('\r');
2097 break;
2098 case 't':
2099 parent_entry.AppendChar('\t');
2100 break;
2101 case 'v':
2102 parent_entry.AppendChar('\v');
2103 break;
2104 case '\'':
2105 parent_entry.AppendChar('\'');
2106 break;
2107 case '\\':
2108 parent_entry.AppendChar('\\');
2109 break;
2110 case '0':
2111 // 1 to 3 octal chars
2112 {
2113 // Make a string that can hold onto the initial zero char, up to 3
2114 // octal digits, and a terminating NULL.
2115 char oct_str[5] = {0, 0, 0, 0, 0};
2116
2117 int i;
2118 for (i = 0; (format[i] >= '0' && format[i] <= '7') && i < 4; ++i)
2119 oct_str[i] = format[i];
2120
2121 // We don't want to consume the last octal character since the main
2122 // for loop will do this for us, so we advance p by one less than i
2123 // (even if i is zero)
2124 format = format.drop_front(i);
2125 unsigned long octal_value = ::strtoul(oct_str, nullptr, 8);
2126 if (octal_value <= UINT8_MAX0xff) {
2127 parent_entry.AppendChar((char)octal_value);
2128 } else {
2129 error.SetErrorString("octal number is larger than a single byte");
2130 return error;
2131 }
2132 }
2133 break;
2134
2135 case 'x':
2136 // hex number in the format
2137 if (isxdigit(format[0])) {
2138 // Make a string that can hold onto two hex chars plus a
2139 // NULL terminator
2140 char hex_str[3] = {0, 0, 0};
2141 hex_str[0] = format[0];
2142
2143 format = format.drop_front();
2144
2145 if (isxdigit(format[0])) {
2146 hex_str[1] = format[0];
2147 format = format.drop_front();
2148 }
2149
2150 unsigned long hex_value = strtoul(hex_str, nullptr, 16);
2151 if (hex_value <= UINT8_MAX0xff) {
2152 parent_entry.AppendChar((char)hex_value);
2153 } else {
2154 error.SetErrorString("hex number is larger than a single byte");
2155 return error;
2156 }
2157 } else {
2158 parent_entry.AppendChar(desens_char);
2159 }
2160 break;
2161
2162 default:
2163 // Just desensitize any other character by just printing what came
2164 // after the '\'
2165 parent_entry.AppendChar(desens_char);
2166 break;
2167 }
2168 } break;
2169
2170 case '$':
2171 if (format.size() == 1) {
2172 // '$' at the end of a format string, just print the '$'
2173 parent_entry.AppendText("$");
2174 } else {
2175 format = format.drop_front(); // Skip the '$'
2176
2177 if (format[0] == '{') {
2178 format = format.drop_front(); // Skip the '{'
2179
2180 llvm::StringRef variable, variable_format;
2181 error = FormatEntity::ExtractVariableInfo(format, variable,
2182 variable_format);
2183 if (error.Fail())
2184 return error;
2185 bool verify_is_thread_id = false;
2186 Entry entry;
2187 if (!variable_format.empty()) {
2188 entry.printf_format = variable_format.str();
2189
2190 // If the format contains a '%' we are going to assume this is a
2191 // printf style format. So if you want to format your thread ID
2192 // using "0x%llx" you can use: ${thread.id%0x%llx}
2193 //
2194 // If there is no '%' in the format, then it is assumed to be a
2195 // LLDB format name, or one of the extended formats specified in
2196 // the switch statement below.
2197
2198 if (entry.printf_format.find('%') == std::string::npos) {
2199 bool clear_printf = false;
2200
2201 if (FormatManager::GetFormatFromCString(
2202 entry.printf_format.c_str(), false, entry.fmt)) {
2203 // We have an LLDB format, so clear the printf format
2204 clear_printf = true;
2205 } else if (entry.printf_format.size() == 1) {
2206 switch (entry.printf_format[0]) {
2207 case '@': // if this is an @ sign, print ObjC description
2208 entry.number = ValueObject::
2209 eValueObjectRepresentationStyleLanguageSpecific;
2210 clear_printf = true;
2211 break;
2212 case 'V': // if this is a V, print the value using the default
2213 // format
2214 entry.number =
2215 ValueObject::eValueObjectRepresentationStyleValue;
2216 clear_printf = true;
2217 break;
2218 case 'L': // if this is an L, print the location of the value
2219 entry.number =
2220 ValueObject::eValueObjectRepresentationStyleLocation;
2221 clear_printf = true;
2222 break;
2223 case 'S': // if this is an S, print the summary after all
2224 entry.number =
2225 ValueObject::eValueObjectRepresentationStyleSummary;
2226 clear_printf = true;
2227 break;
2228 case '#': // if this is a '#', print the number of children
2229 entry.number =
2230 ValueObject::eValueObjectRepresentationStyleChildrenCount;
2231 clear_printf = true;
2232 break;
2233 case 'T': // if this is a 'T', print the type
2234 entry.number =
2235 ValueObject::eValueObjectRepresentationStyleType;
2236 clear_printf = true;
2237 break;
2238 case 'N': // if this is a 'N', print the name
2239 entry.number =
2240 ValueObject::eValueObjectRepresentationStyleName;
2241 clear_printf = true;
2242 break;
2243 case '>': // if this is a '>', print the expression path
2244 entry.number = ValueObject::
2245 eValueObjectRepresentationStyleExpressionPath;
2246 clear_printf = true;
2247 break;
2248 default:
2249 error.SetErrorStringWithFormat("invalid format: '%s'",
2250 entry.printf_format.c_str());
2251 return error;
2252 }
2253 } else if (FormatManager::GetFormatFromCString(
2254 entry.printf_format.c_str(), true, entry.fmt)) {
2255 clear_printf = true;
2256 } else if (entry.printf_format == "tid") {
2257 verify_is_thread_id = true;
2258 } else {
2259 error.SetErrorStringWithFormat("invalid format: '%s'",
2260 entry.printf_format.c_str());
2261 return error;
2262 }
2263
2264 // Our format string turned out to not be a printf style format
2265 // so lets clear the string
2266 if (clear_printf)
2267 entry.printf_format.clear();
2268 }
2269 }
2270
2271 // Check for dereferences
2272 if (variable[0] == '*') {
2273 entry.deref = true;
2274 variable = variable.drop_front();
2275 }
2276
2277 error = ParseEntry(variable, &g_root, entry);
2278 if (error.Fail())
2279 return error;
2280
2281 if (verify_is_thread_id) {
2282 if (entry.type != Entry::Type::ThreadID &&
2283 entry.type != Entry::Type::ThreadProtocolID) {
2284 error.SetErrorString("the 'tid' format can only be used on "
2285 "${thread.id} and ${thread.protocol_id}");
2286 }
2287 }
2288
2289 switch (entry.type) {
2290 case Entry::Type::Variable:
2291 case Entry::Type::VariableSynthetic:
2292 if (entry.number == 0) {
2293 if (entry.string.empty())
2294 entry.number =
2295 ValueObject::eValueObjectRepresentationStyleValue;
2296 else
2297 entry.number =
2298 ValueObject::eValueObjectRepresentationStyleSummary;
2299 }
2300 break;
2301 default:
2302 // Make sure someone didn't try to dereference anything but ${var}
2303 // or ${svar}
2304 if (entry.deref) {
2305 error.SetErrorStringWithFormat(
2306 "${%s} can't be dereferenced, only ${var} and ${svar} can.",
2307 variable.str().c_str());
2308 return error;
2309 }
2310 }
2311 parent_entry.AppendEntry(std::move(entry));
2312 }
2313 }
2314 break;
2315 }
2316 }
2317 return error;
2318}
2319
2320Status FormatEntity::ExtractVariableInfo(llvm::StringRef &format_str,
2321 llvm::StringRef &variable_name,
2322 llvm::StringRef &variable_format) {
2323 Status error;
2324 variable_name = llvm::StringRef();
2325 variable_format = llvm::StringRef();
2326
2327 const size_t paren_pos = format_str.find('}');
2328 if (paren_pos != llvm::StringRef::npos) {
2329 const size_t percent_pos = format_str.find('%');
2330 if (percent_pos < paren_pos) {
2331 if (percent_pos > 0) {
2332 if (percent_pos > 1)
2333 variable_name = format_str.substr(0, percent_pos);
2334 variable_format =
2335 format_str.substr(percent_pos + 1, paren_pos - (percent_pos + 1));
2336 }
2337 } else {
2338 variable_name = format_str.substr(0, paren_pos);
2339 }
2340 // Strip off elements and the formatting and the trailing '}'
2341 format_str = format_str.substr(paren_pos + 1);
2342 } else {
2343 error.SetErrorStringWithFormat(
2344 "missing terminating '}' character for '${%s'",
2345 format_str.str().c_str());
2346 }
2347 return error;
2348}
2349
2350bool FormatEntity::FormatFileSpec(const FileSpec &file_spec, Stream &s,
2351 llvm::StringRef variable_name,
2352 llvm::StringRef variable_format) {
2353 if (variable_name.empty() || variable_name.equals(".fullpath")) {
2354 file_spec.Dump(s.AsRawOstream());
2355 return true;
2356 } else if (variable_name.equals(".basename")) {
2357 s.PutCString(file_spec.GetFilename().GetStringRef());
2358 return true;
2359 } else if (variable_name.equals(".dirname")) {
2360 s.PutCString(file_spec.GetFilename().GetStringRef());
2361 return true;
2362 }
2363 return false;
2364}
2365
2366static std::string MakeMatch(const llvm::StringRef &prefix,
2367 const char *suffix) {
2368 std::string match(prefix.str());
2369 match.append(suffix);
2370 return match;
2371}
2372
2373static void AddMatches(const Definition *def, const llvm::StringRef &prefix,
2374 const llvm::StringRef &match_prefix,
2375 StringList &matches) {
2376 const size_t n = def->num_children;
2377 if (n > 0) {
2378 for (size_t i = 0; i < n; ++i) {
2379 std::string match = prefix.str();
2380 if (match_prefix.empty())
2381 matches.AppendString(MakeMatch(prefix, def->children[i].name));
2382 else if (strncmp(def->children[i].name, match_prefix.data(),
2383 match_prefix.size()) == 0)
2384 matches.AppendString(
2385 MakeMatch(prefix, def->children[i].name + match_prefix.size()));
2386 }
2387 }
2388}
2389
2390void FormatEntity::AutoComplete(CompletionRequest &request) {
2391 llvm::StringRef str = request.GetCursorArgumentPrefix();
2392
2393 const size_t dollar_pos = str.rfind('$');
2394 if (dollar_pos == llvm::StringRef::npos)
2395 return;
2396
2397 // Hitting TAB after $ at the end of the string add a "{"
2398 if (dollar_pos == str.size() - 1) {
2399 std::string match = str.str();
2400 match.append("{");
2401 request.AddCompletion(match);
2402 return;
2403 }
2404
2405 if (str[dollar_pos + 1] != '{')
2406 return;
2407
2408 const size_t close_pos = str.find('}', dollar_pos + 2);
2409 if (close_pos != llvm::StringRef::npos)
2410 return;
2411
2412 const size_t format_pos = str.find('%', dollar_pos + 2);
2413 if (format_pos != llvm::StringRef::npos)
2414 return;
2415
2416 llvm::StringRef partial_variable(str.substr(dollar_pos + 2));
2417 if (partial_variable.empty()) {
2418 // Suggest all top level entities as we are just past "${"
2419 StringList new_matches;
2420 AddMatches(&g_root, str, llvm::StringRef(), new_matches);
2421 request.AddCompletions(new_matches);
2422 return;
2423 }
2424
2425 // We have a partially specified variable, find it
2426 llvm::StringRef remainder;
2427 const Definition *entry_def = FindEntry(partial_variable, &g_root, remainder);
2428 if (!entry_def)
2429 return;
2430
2431 const size_t n = entry_def->num_children;
2432
2433 if (remainder.empty()) {
2434 // Exact match
2435 if (n > 0) {
2436 // "${thread.info" <TAB>
2437 request.AddCompletion(MakeMatch(str, "."));
2438 } else {
2439 // "${thread.id" <TAB>
2440 request.AddCompletion(MakeMatch(str, "}"));
2441 }
2442 } else if (remainder.equals(".")) {
2443 // "${thread." <TAB>
2444 StringList new_matches;
2445 AddMatches(entry_def, str, llvm::StringRef(), new_matches);
2446 request.AddCompletions(new_matches);
2447 } else {
2448 // We have a partial match
2449 // "${thre" <TAB>
2450 StringList new_matches;
2451 AddMatches(entry_def, str, remainder, new_matches);
2452 request.AddCompletions(new_matches);
2453 }
2454}

/usr/src/gnu/usr.bin/clang/liblldbCore/../../../llvm/lldb/include/lldb/Utility/ConstString.h

1//===-- ConstString.h -------------------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLDB_UTILITY_CONSTSTRING_H
10#define LLDB_UTILITY_CONSTSTRING_H
11
12#include "llvm/ADT/DenseMapInfo.h"
13#include "llvm/ADT/StringRef.h"
14#include "llvm/Support/FormatVariadic.h"
15#include "llvm/Support/YAMLTraits.h"
16
17#include <cstddef>
18
19namespace lldb_private {
20class Stream;
21}
22namespace llvm {
23class raw_ostream;
24}
25
26namespace lldb_private {
27
28/// \class ConstString ConstString.h "lldb/Utility/ConstString.h"
29/// A uniqued constant string class.
30///
31/// Provides an efficient way to store strings as uniqued strings. After the
32/// strings are uniqued, finding strings that are equal to one another is very
33/// fast as just the pointers need to be compared. It also allows for many
34/// common strings from many different sources to be shared to keep the memory
35/// footprint low.
36///
37/// No reference counting is done on strings that are added to the string
38/// pool, once strings are added they are in the string pool for the life of
39/// the program.
40class ConstString {
41public:
42 /// Default constructor
43 ///
44 /// Initializes the string to an empty string.
45 ConstString() = default;
46
47 explicit ConstString(const llvm::StringRef &s);
48
49 /// Construct with C String value
50 ///
51 /// Constructs this object with a C string by looking to see if the
52 /// C string already exists in the global string pool. If it doesn't
53 /// exist, it is added to the string pool.
54 ///
55 /// \param[in] cstr
56 /// A NULL terminated C string to add to the string pool.
57 explicit ConstString(const char *cstr);
58
59 /// Construct with C String value with max length
60 ///
61 /// Constructs this object with a C string with a length. If \a max_cstr_len
62 /// is greater than the actual length of the string, the string length will
63 /// be truncated. This allows substrings to be created without the need to
64 /// NULL terminate the string as it is passed into this function.
65 ///
66 /// \param[in] cstr
67 /// A pointer to the first character in the C string. The C
68 /// string can be NULL terminated in a buffer that contains
69 /// more characters than the length of the string, or the
70 /// string can be part of another string and a new substring
71 /// can be created.
72 ///
73 /// \param[in] max_cstr_len
74 /// The max length of \a cstr. If the string length of \a cstr
75 /// is less than \a max_cstr_len, then the string will be
76 /// truncated. If the string length of \a cstr is greater than
77 /// \a max_cstr_len, then only max_cstr_len bytes will be used
78 /// from \a cstr.
79 explicit ConstString(const char *cstr, size_t max_cstr_len);
80
81 /// C string equality binary predicate function object for ConstString
82 /// objects.
83 struct StringIsEqual {
84 /// C equality test.
85 ///
86 /// Two C strings are equal when they are contained in ConstString objects
87 /// when their pointer values are equal to each other.
88 ///
89 /// \return
90 /// Returns \b true if the C string in \a lhs is equal to
91 /// the C string value in \a rhs, \b false otherwise.
92 bool operator()(const char *lhs, const char *rhs) const {
93 return lhs == rhs;
94 }
95 };
96
97 /// Convert to bool operator.
98 ///
99 /// This allows code to check a ConstString object to see if it contains a
100 /// valid string using code such as:
101 ///
102 /// \code
103 /// ConstString str(...);
104 /// if (str)
105 /// { ...
106 /// \endcode
107 ///
108 /// \return
109 /// /b True this object contains a valid non-empty C string, \b
110 /// false otherwise.
111 explicit operator bool() const { return !IsEmpty(); }
112
113 /// Equal to operator
114 ///
115 /// Returns true if this string is equal to the string in \a rhs. This
116 /// operation is very fast as it results in a pointer comparison since all
117 /// strings are in a uniqued in a global string pool.
118 ///
119 /// \param[in] rhs
120 /// Another string object to compare this object to.
121 ///
122 /// \return
123 /// true if this object is equal to \a rhs.
124 /// false if this object is not equal to \a rhs.
125 bool operator==(ConstString rhs) const {
126 // We can do a pointer compare to compare these strings since they must
127 // come from the same pool in order to be equal.
128 return m_string == rhs.m_string;
129 }
130
131 /// Equal to operator against a non-ConstString value.
132 ///
133 /// Returns true if this string is equal to the string in \a rhs. This
134 /// overload is usually slower than comparing against a ConstString value.
135 /// However, if the rhs string not already a ConstString and it is impractical
136 /// to turn it into a non-temporary variable, then this overload is faster.
137 ///
138 /// \param[in] rhs
139 /// Another string object to compare this object to.
140 ///
141 /// \return
142 /// \b true if this object is equal to \a rhs.
143 /// \b false if this object is not equal to \a rhs.
144 bool operator==(const char *rhs) const {
145 // ConstString differentiates between empty strings and nullptr strings, but
146 // StringRef doesn't. Therefore we have to do this check manually now.
147 if (m_string == nullptr && rhs != nullptr)
148 return false;
149 if (m_string != nullptr && rhs == nullptr)
150 return false;
151
152 return GetStringRef() == rhs;
153 }
154
155 /// Not equal to operator
156 ///
157 /// Returns true if this string is not equal to the string in \a rhs. This
158 /// operation is very fast as it results in a pointer comparison since all
159 /// strings are in a uniqued in a global string pool.
160 ///
161 /// \param[in] rhs
162 /// Another string object to compare this object to.
163 ///
164 /// \return
165 /// \b true if this object is not equal to \a rhs.
166 /// \b false if this object is equal to \a rhs.
167 bool operator!=(ConstString rhs) const { return m_string != rhs.m_string; }
168
169 /// Not equal to operator against a non-ConstString value.
170 ///
171 /// Returns true if this string is not equal to the string in \a rhs. This
172 /// overload is usually slower than comparing against a ConstString value.
173 /// However, if the rhs string not already a ConstString and it is impractical
174 /// to turn it into a non-temporary variable, then this overload is faster.
175 ///
176 /// \param[in] rhs
177 /// Another string object to compare this object to.
178 ///
179 /// \return \b true if this object is not equal to \a rhs, false otherwise.
180 bool operator!=(const char *rhs) const { return !(*this == rhs); }
181
182 bool operator<(ConstString rhs) const;
183
184 /// Get the string value as a C string.
185 ///
186 /// Get the value of the contained string as a NULL terminated C string
187 /// value.
188 ///
189 /// If \a value_if_empty is nullptr, then nullptr will be returned.
190 ///
191 /// \return Returns \a value_if_empty if the string is empty, otherwise
192 /// the C string value contained in this object.
193 const char *AsCString(const char *value_if_empty = nullptr) const {
194 return (IsEmpty() ? value_if_empty : m_string);
14
'?' condition is false
15
Returning pointer, which participates in a condition later
195 }
196
197 /// Get the string value as a llvm::StringRef
198 ///
199 /// \return
200 /// Returns a new llvm::StringRef object filled in with the
201 /// needed data.
202 llvm::StringRef GetStringRef() const {
203 return llvm::StringRef(m_string, GetLength());
204 }
205
206 /// Get the string value as a C string.
207 ///
208 /// Get the value of the contained string as a NULL terminated C string
209 /// value. Similar to the ConstString::AsCString() function, yet this
210 /// function will always return nullptr if the string is not valid. So this
211 /// function is a direct accessor to the string pointer value.
212 ///
213 /// \return
214 /// Returns nullptr the string is invalid, otherwise the C string
215 /// value contained in this object.
216 const char *GetCString() const { return m_string; }
217
218 /// Get the length in bytes of string value.
219 ///
220 /// The string pool stores the length of the string, so we can avoid calling
221 /// strlen() on the pointer value with this function.
222 ///
223 /// \return
224 /// Returns the number of bytes that this string occupies in
225 /// memory, not including the NULL termination byte.
226 size_t GetLength() const;
227
228 /// Clear this object's state.
229 ///
230 /// Clear any contained string and reset the value to the empty string
231 /// value.
232 void Clear() { m_string = nullptr; }
233
234 /// Equal to operator
235 ///
236 /// Returns true if this string is equal to the string in \a rhs. If case
237 /// sensitive equality is tested, this operation is very fast as it results
238 /// in a pointer comparison since all strings are in a uniqued in a global
239 /// string pool.
240 ///
241 /// \param[in] lhs
242 /// The Left Hand Side const ConstString object reference.
243 ///
244 /// \param[in] rhs
245 /// The Right Hand Side const ConstString object reference.
246 ///
247 /// \param[in] case_sensitive
248 /// Case sensitivity. If true, case sensitive equality
249 /// will be tested, otherwise character case will be ignored
250 ///
251 /// \return \b true if this object is equal to \a rhs, \b false otherwise.
252 static bool Equals(ConstString lhs, ConstString rhs,
253 const bool case_sensitive = true);
254
255 /// Compare two string objects.
256 ///
257 /// Compares the C string values contained in \a lhs and \a rhs and returns
258 /// an integer result.
259 ///
260 /// NOTE: only call this function when you want a true string
261 /// comparison. If you want string equality use the, use the == operator as
262 /// it is much more efficient. Also if you want string inequality, use the
263 /// != operator for the same reasons.
264 ///
265 /// \param[in] lhs
266 /// The Left Hand Side const ConstString object reference.
267 ///
268 /// \param[in] rhs
269 /// The Right Hand Side const ConstString object reference.
270 ///
271 /// \param[in] case_sensitive
272 /// Case sensitivity of compare. If true, case sensitive compare
273 /// will be performed, otherwise character case will be ignored
274 ///
275 /// \return -1 if lhs < rhs, 0 if lhs == rhs, 1 if lhs > rhs
276 static int Compare(ConstString lhs, ConstString rhs,
277 const bool case_sensitive = true);
278
279 /// Dump the object description to a stream.
280 ///
281 /// Dump the string value to the stream \a s. If the contained string is
282 /// empty, print \a value_if_empty to the stream instead. If \a
283 /// value_if_empty is nullptr, then nothing will be dumped to the stream.
284 ///
285 /// \param[in] s
286 /// The stream that will be used to dump the object description.
287 ///
288 /// \param[in] value_if_empty
289 /// The value to dump if the string is empty. If nullptr, nothing
290 /// will be output to the stream.
291 void Dump(Stream *s, const char *value_if_empty = nullptr) const;
292
293 /// Dump the object debug description to a stream.
294 ///
295 /// \param[in] s
296 /// The stream that will be used to dump the object description.
297 void DumpDebug(Stream *s) const;
298
299 /// Test for empty string.
300 ///
301 /// \return
302 /// \b true if the contained string is empty.
303 /// \b false if the contained string is not empty.
304 bool IsEmpty() const { return m_string == nullptr || m_string[0] == '\0'; }
305
306 /// Test for null string.
307 ///
308 /// \return
309 /// \b true if there is no string associated with this instance.
310 /// \b false if there is a string associated with this instance.
311 bool IsNull() const { return m_string == nullptr; }
312
313 /// Set the C string value.
314 ///
315 /// Set the string value in the object by uniquing the \a cstr string value
316 /// in our global string pool.
317 ///
318 /// If the C string already exists in the global string pool, it finds the
319 /// current entry and returns the existing value. If it doesn't exist, it is
320 /// added to the string pool.
321 ///
322 /// \param[in] cstr
323 /// A NULL terminated C string to add to the string pool.
324 void SetCString(const char *cstr);
325
326 void SetString(const llvm::StringRef &s);
327
328 /// Set the C string value and its mangled counterpart.
329 ///
330 /// Object files and debug symbols often use mangled string to represent the
331 /// linkage name for a symbol, function or global. The string pool can
332 /// efficiently store these values and their counterparts so when we run
333 /// into another instance of a mangled name, we can avoid calling the name
334 /// demangler over and over on the same strings and then trying to unique
335 /// them.
336 ///
337 /// \param[in] demangled
338 /// The demangled string to correlate with the \a mangled name.
339 ///
340 /// \param[in] mangled
341 /// The already uniqued mangled ConstString to correlate the
342 /// soon to be uniqued version of \a demangled.
343 void SetStringWithMangledCounterpart(llvm::StringRef demangled,
344 ConstString mangled);
345
346 /// Retrieve the mangled or demangled counterpart for a mangled or demangled
347 /// ConstString.
348 ///
349 /// Object files and debug symbols often use mangled string to represent the
350 /// linkage name for a symbol, function or global. The string pool can
351 /// efficiently store these values and their counterparts so when we run
352 /// into another instance of a mangled name, we can avoid calling the name
353 /// demangler over and over on the same strings and then trying to unique
354 /// them.
355 ///
356 /// \param[in] counterpart
357 /// A reference to a ConstString object that might get filled in
358 /// with the demangled/mangled counterpart.
359 ///
360 /// \return
361 /// /b True if \a counterpart was filled in with the counterpart
362 /// /b false otherwise.
363 bool GetMangledCounterpart(ConstString &counterpart) const;
364
365 /// Set the C string value with length.
366 ///
367 /// Set the string value in the object by uniquing \a cstr_len bytes
368 /// starting at the \a cstr string value in our global string pool. If trim
369 /// is true, then \a cstr_len indicates a maximum length of the CString and
370 /// if the actual length of the string is less, then it will be trimmed.
371 ///
372 /// If the C string already exists in the global string pool, it finds the
373 /// current entry and returns the existing value. If it doesn't exist, it is
374 /// added to the string pool.
375 ///
376 /// \param[in] cstr
377 /// A NULL terminated C string to add to the string pool.
378 ///
379 /// \param[in] cstr_len
380 /// The maximum length of the C string.
381 void SetCStringWithLength(const char *cstr, size_t cstr_len);
382
383 /// Set the C string value with the minimum length between \a fixed_cstr_len
384 /// and the actual length of the C string. This can be used for data
385 /// structures that have a fixed length to store a C string where the string
386 /// might not be NULL terminated if the string takes the entire buffer.
387 void SetTrimmedCStringWithLength(const char *cstr, size_t fixed_cstr_len);
388
389 /// Get the memory cost of this object.
390 ///
391 /// Return the size in bytes that this object takes in memory. This returns
392 /// the size in bytes of this object, which does not include any the shared
393 /// string values it may refer to.
394 ///
395 /// \return
396 /// The number of bytes that this object occupies in memory.
397 ///
398 /// \see ConstString::StaticMemorySize ()
399 size_t MemorySize() const { return sizeof(ConstString); }
400
401 /// Get the size in bytes of the current global string pool.
402 ///
403 /// Reports the size in bytes of all shared C string values, containers and
404 /// any other values as a byte size for the entire string pool.
405 ///
406 /// \return
407 /// The number of bytes that the global string pool occupies
408 /// in memory.
409 static size_t StaticMemorySize();
410
411protected:
412 template <typename T> friend struct ::llvm::DenseMapInfo;
413 /// Only used by DenseMapInfo.
414 static ConstString FromStringPoolPointer(const char *ptr) {
415 ConstString s;
416 s.m_string = ptr;
417 return s;
418 };
419
420 const char *m_string = nullptr;
421};
422
423/// Stream the string value \a str to the stream \a s
424Stream &operator<<(Stream &s, ConstString str);
425
426} // namespace lldb_private
427
428namespace llvm {
429template <> struct format_provider<lldb_private::ConstString> {
430 static void format(const lldb_private::ConstString &CS, llvm::raw_ostream &OS,
431 llvm::StringRef Options);
432};
433
434/// DenseMapInfo implementation.
435/// \{
436template <> struct DenseMapInfo<lldb_private::ConstString> {
437 static inline lldb_private::ConstString getEmptyKey() {
438 return lldb_private::ConstString::FromStringPoolPointer(
439 DenseMapInfo<const char *>::getEmptyKey());
440 }
441 static inline lldb_private::ConstString getTombstoneKey() {
442 return lldb_private::ConstString::FromStringPoolPointer(
443 DenseMapInfo<const char *>::getTombstoneKey());
444 }
445 static unsigned getHashValue(lldb_private::ConstString val) {
446 return DenseMapInfo<const char *>::getHashValue(val.m_string);
447 }
448 static bool isEqual(lldb_private::ConstString LHS,
449 lldb_private::ConstString RHS) {
450 return LHS == RHS;
451 }
452};
453/// \}
454
455namespace yaml {
456template <> struct ScalarTraits<lldb_private::ConstString> {
457 static void output(const lldb_private::ConstString &, void *, raw_ostream &);
458 static StringRef input(StringRef, void *, lldb_private::ConstString &);
459 static QuotingType mustQuote(StringRef S) { return QuotingType::Double; }
460};
461} // namespace yaml
462
463inline raw_ostream &operator<<(raw_ostream &os, lldb_private::ConstString s) {
464 os << s.GetStringRef();
465 return os;
466}
467} // namespace llvm
468
469LLVM_YAML_IS_SEQUENCE_VECTOR(lldb_private::ConstString)namespace llvm { namespace yaml { static_assert( !std::is_fundamental
<lldb_private::ConstString>::value && !std::is_same
<lldb_private::ConstString, std::string>::value &&
!std::is_same<lldb_private::ConstString, llvm::StringRef>
::value, "only use LLVM_YAML_IS_SEQUENCE_VECTOR for types you control"
); template <> struct SequenceElementTraits<lldb_private
::ConstString> { static const bool flow = false; }; } }
470
471#endif // LLDB_UTILITY_CONSTSTRING_H

/usr/src/gnu/usr.bin/clang/liblldbCore/../../../llvm/lldb/include/lldb/Symbol/CompilerType.h

1//===-- CompilerType.h ------------------------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef LLDB_SYMBOL_COMPILERTYPE_H
10#define LLDB_SYMBOL_COMPILERTYPE_H
11
12#include <functional>
13#include <string>
14#include <vector>
15
16#include "lldb/lldb-private.h"
17#include "llvm/ADT/APSInt.h"
18
19namespace lldb_private {
20
21class DataExtractor;
22
23/// Generic representation of a type in a programming language.
24///
25/// This class serves as an abstraction for a type inside one of the TypeSystems
26/// implemented by the language plugins. It does not have any actual logic in it
27/// but only stores an opaque pointer and a pointer to the TypeSystem that
28/// gives meaning to this opaque pointer. All methods of this class should call
29/// their respective method in the TypeSystem interface and pass the opaque
30/// pointer along.
31///
32/// \see lldb_private::TypeSystem
33class CompilerType {
34public:
35 /// Creates a CompilerType with the given TypeSystem and opaque compiler type.
36 ///
37 /// This constructor should only be called from the respective TypeSystem
38 /// implementation.
39 ///
40 /// \see lldb_private::TypeSystemClang::GetType(clang::QualType)
41 CompilerType(TypeSystem *type_system, lldb::opaque_compiler_type_t type)
42 : m_type(type), m_type_system(type_system) {
43 assert(Verify() && "verification failed")((void)0);
44 }
45
46 CompilerType(const CompilerType &rhs)
47 : m_type(rhs.m_type), m_type_system(rhs.m_type_system) {}
48
49 CompilerType() = default;
50
51 /// Operators.
52 /// \{
53 const CompilerType &operator=(const CompilerType &rhs) {
54 m_type = rhs.m_type;
55 m_type_system = rhs.m_type_system;
56 return *this;
57 }
58
59 bool operator<(const CompilerType &rhs) const {
60 if (m_type_system == rhs.m_type_system)
61 return m_type < rhs.m_type;
62 return m_type_system < rhs.m_type_system;
63 }
64 /// \}
65
66 /// Tests.
67 /// \{
68 explicit operator bool() const {
69 return m_type != nullptr && m_type_system != nullptr;
70 }
71
72 bool IsValid() const { return m_type != nullptr && m_type_system != nullptr; }
36
Assuming the condition is true
37
Assuming the condition is true
38
Returning the value 1, which participates in a condition later
73
74 bool IsArrayType(CompilerType *element_type = nullptr,
75 uint64_t *size = nullptr,
76 bool *is_incomplete = nullptr) const;
77
78 bool IsVectorType(CompilerType *element_type = nullptr,
79 uint64_t *size = nullptr) const;
80
81 bool IsArrayOfScalarType() const;
82
83 bool IsAggregateType() const;
84
85 bool IsAnonymousType() const;
86
87 bool IsScopedEnumerationType() const;
88
89 bool IsBeingDefined() const;
90
91 bool IsCharType() const;
92
93 bool IsCompleteType() const;
94
95 bool IsConst() const;
96
97 bool IsCStringType(uint32_t &length) const;
98
99 bool IsDefined() const;
100
101 bool IsFloatingPointType(uint32_t &count, bool &is_complex) const;
102
103 bool IsFunctionType() const;
104
105 uint32_t IsHomogeneousAggregate(CompilerType *base_type_ptr) const;
106
107 size_t GetNumberOfFunctionArguments() const;
108
109 CompilerType GetFunctionArgumentAtIndex(const size_t index) const;
110
111 bool IsVariadicFunctionType() const;
112
113 bool IsFunctionPointerType() const;
114
115 bool
116 IsBlockPointerType(CompilerType *function_pointer_type_ptr = nullptr) const;
117
118 bool IsIntegerType(bool &is_signed) const;
119
120 bool IsEnumerationType(bool &is_signed) const;
121
122 bool IsIntegerOrEnumerationType(bool &is_signed) const;
123
124 bool IsPolymorphicClass() const;
125
126 /// \param target_type Can pass nullptr.
127 bool IsPossibleDynamicType(CompilerType *target_type, bool check_cplusplus,
128 bool check_objc) const;
129
130 bool IsPointerToScalarType() const;
131
132 bool IsRuntimeGeneratedType() const;
133
134 bool IsPointerType(CompilerType *pointee_type = nullptr) const;
135
136 bool IsPointerOrReferenceType(CompilerType *pointee_type = nullptr) const;
137
138 bool IsReferenceType(CompilerType *pointee_type = nullptr,
139 bool *is_rvalue = nullptr) const;
140
141 bool ShouldTreatScalarValueAsAddress() const;
142
143 bool IsScalarType() const;
144
145 bool IsTypedefType() const;
146
147 bool IsVoidType() const;
148 /// \}
149
150 /// Type Completion.
151 /// \{
152 bool GetCompleteType() const;
153 /// \}
154
155 /// AST related queries.
156 /// \{
157 size_t GetPointerByteSize() const;
158 /// \}
159
160 /// Accessors.
161 /// \{
162 TypeSystem *GetTypeSystem() const { return m_type_system; }
163
164 ConstString GetTypeName() const;
165
166 ConstString GetDisplayTypeName() const;
167
168 uint32_t
169 GetTypeInfo(CompilerType *pointee_or_element_compiler_type = nullptr) const;
170
171 lldb::LanguageType GetMinimumLanguage();
172
173 lldb::opaque_compiler_type_t GetOpaqueQualType() const { return m_type; }
174
175 lldb::TypeClass GetTypeClass() const;
176
177 void SetCompilerType(TypeSystem *type_system,
178 lldb::opaque_compiler_type_t type);
179
180 unsigned GetTypeQualifiers() const;
181 /// \}
182
183 /// Creating related types.
184 /// \{
185 CompilerType GetArrayElementType(ExecutionContextScope *exe_scope) const;
186
187 CompilerType GetArrayType(uint64_t size) const;
188
189 CompilerType GetCanonicalType() const;
190
191 CompilerType GetFullyUnqualifiedType() const;
192
193 CompilerType GetEnumerationIntegerType() const;
194
195 /// Returns -1 if this isn't a function of if the function doesn't
196 /// have a prototype Returns a value >= 0 if there is a prototype.
197 int GetFunctionArgumentCount() const;
198
199 CompilerType GetFunctionArgumentTypeAtIndex(size_t idx) const;
200
201 CompilerType GetFunctionReturnType() const;
202
203 size_t GetNumMemberFunctions() const;
204
205 TypeMemberFunctionImpl GetMemberFunctionAtIndex(size_t idx);
206
207 /// If this type is a reference to a type (L value or R value reference),
208 /// return a new type with the reference removed, else return the current type
209 /// itself.
210 CompilerType GetNonReferenceType() const;
211
212 /// If this type is a pointer type, return the type that the pointer points
213 /// to, else return an invalid type.
214 CompilerType GetPointeeType() const;
215
216 /// Return a new CompilerType that is a pointer to this type
217 CompilerType GetPointerType() const;
218
219 /// Return a new CompilerType that is a L value reference to this type if this
220 /// type is valid and the type system supports L value references, else return
221 /// an invalid type.
222 CompilerType GetLValueReferenceType() const;
223
224 /// Return a new CompilerType that is a R value reference to this type if this
225 /// type is valid and the type system supports R value references, else return
226 /// an invalid type.
227 CompilerType GetRValueReferenceType() const;
228
229 /// Return a new CompilerType adds a const modifier to this type if this type
230 /// is valid and the type system supports const modifiers, else return an
231 /// invalid type.
232 CompilerType AddConstModifier() const;
233
234 /// Return a new CompilerType adds a volatile modifier to this type if this
235 /// type is valid and the type system supports volatile modifiers, else return
236 /// an invalid type.
237 CompilerType AddVolatileModifier() const;
238
239 /// Return a new CompilerType that is the atomic type of this type. If this
240 /// type is not valid or the type system doesn't support atomic types, this
241 /// returns an invalid type.
242 CompilerType GetAtomicType() const;
243
244 /// Return a new CompilerType adds a restrict modifier to this type if this
245 /// type is valid and the type system supports restrict modifiers, else return
246 /// an invalid type.
247 CompilerType AddRestrictModifier() const;
248
249 /// Create a typedef to this type using "name" as the name of the typedef this
250 /// type is valid and the type system supports typedefs, else return an
251 /// invalid type.
252 /// \param payload The typesystem-specific \p lldb::Type payload.
253 CompilerType CreateTypedef(const char *name,
254 const CompilerDeclContext &decl_ctx,
255 uint32_t payload) const;
256
257 /// If the current object represents a typedef type, get the underlying type
258 CompilerType GetTypedefedType() const;
259
260 /// Create related types using the current type's AST
261 CompilerType GetBasicTypeFromAST(lldb::BasicType basic_type) const;
262 /// \}
263
264 /// Exploring the type.
265 /// \{
266 struct IntegralTemplateArgument;
267
268 /// Return the size of the type in bytes.
269 llvm::Optional<uint64_t> GetByteSize(ExecutionContextScope *exe_scope) const;
270 /// Return the size of the type in bits.
271 llvm::Optional<uint64_t> GetBitSize(ExecutionContextScope *exe_scope) const;
272
273 lldb::Encoding GetEncoding(uint64_t &count) const;
274
275 lldb::Format GetFormat() const;
276
277 llvm::Optional<size_t>
278 GetTypeBitAlign(ExecutionContextScope *exe_scope) const;
279
280 uint32_t GetNumChildren(bool omit_empty_base_classes,
281 const ExecutionContext *exe_ctx) const;
282
283 lldb::BasicType GetBasicTypeEnumeration() const;
284
285 static lldb::BasicType GetBasicTypeEnumeration(ConstString name);
286
287 /// If this type is an enumeration, iterate through all of its enumerators
288 /// using a callback. If the callback returns true, keep iterating, else abort
289 /// the iteration.
290 void ForEachEnumerator(
291 std::function<bool(const CompilerType &integer_type, ConstString name,
292 const llvm::APSInt &value)> const &callback) const;
293
294 uint32_t GetNumFields() const;
295
296 CompilerType GetFieldAtIndex(size_t idx, std::string &name,
297 uint64_t *bit_offset_ptr,
298 uint32_t *bitfield_bit_size_ptr,
299 bool *is_bitfield_ptr) const;
300
301 uint32_t GetNumDirectBaseClasses() const;
302
303 uint32_t GetNumVirtualBaseClasses() const;
304
305 CompilerType GetDirectBaseClassAtIndex(size_t idx,
306 uint32_t *bit_offset_ptr) const;
307
308 CompilerType GetVirtualBaseClassAtIndex(size_t idx,
309 uint32_t *bit_offset_ptr) const;
310
311 uint32_t GetIndexOfFieldWithName(const char *name,
312 CompilerType *field_compiler_type = nullptr,
313 uint64_t *bit_offset_ptr = nullptr,
314 uint32_t *bitfield_bit_size_ptr = nullptr,
315 bool *is_bitfield_ptr = nullptr) const;
316
317 CompilerType GetChildCompilerTypeAtIndex(
318 ExecutionContext *exe_ctx, size_t idx, bool transparent_pointers,
319 bool omit_empty_base_classes, bool ignore_array_bounds,
320 std::string &child_name, uint32_t &child_byte_size,
321 int32_t &child_byte_offset, uint32_t &child_bitfield_bit_size,
322 uint32_t &child_bitfield_bit_offset, bool &child_is_base_class,
323 bool &child_is_deref_of_parent, ValueObject *valobj,
324 uint64_t &language_flags) const;
325
326 /// Lookup a child given a name. This function will match base class names and
327 /// member member names in "clang_type" only, not descendants.
328 uint32_t GetIndexOfChildWithName(const char *name,
329 bool omit_empty_base_classes) const;
330
331 /// Lookup a child member given a name. This function will match member names
332 /// only and will descend into "clang_type" children in search for the first
333 /// member in this class, or any base class that matches "name".
334 /// TODO: Return all matches for a given name by returning a
335 /// vector<vector<uint32_t>>
336 /// so we catch all names that match a given child name, not just the first.
337 size_t
338 GetIndexOfChildMemberWithName(const char *name, bool omit_empty_base_classes,
339 std::vector<uint32_t> &child_indexes) const;
340
341 size_t GetNumTemplateArguments() const;
342
343 lldb::TemplateArgumentKind GetTemplateArgumentKind(size_t idx) const;
344 CompilerType GetTypeTemplateArgument(size_t idx) const;
345
346 /// Returns the value of the template argument and its type.
347 llvm::Optional<IntegralTemplateArgument>
348 GetIntegralTemplateArgument(size_t idx) const;
349
350 CompilerType GetTypeForFormatters() const;
351
352 LazyBool ShouldPrintAsOneLiner(ValueObject *valobj) const;
353
354 bool IsMeaninglessWithoutDynamicResolution() const;
355 /// \}
356
357 /// Dumping types.
358 /// \{
359#ifndef NDEBUG1
360 /// Convenience LLVM-style dump method for use in the debugger only.
361 /// Don't call this function from actual code.
362 LLVM_DUMP_METHOD__attribute__((noinline)) void dump() const;
363#endif
364
365 void DumpValue(ExecutionContext *exe_ctx, Stream *s, lldb::Format format,
366 const DataExtractor &data, lldb::offset_t data_offset,
367 size_t data_byte_size, uint32_t bitfield_bit_size,
368 uint32_t bitfield_bit_offset, bool show_types,
369 bool show_summary, bool verbose, uint32_t depth);
370
371 bool DumpTypeValue(Stream *s, lldb::Format format, const DataExtractor &data,
372 lldb::offset_t data_offset, size_t data_byte_size,
373 uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset,
374 ExecutionContextScope *exe_scope);
375
376 void DumpSummary(ExecutionContext *exe_ctx, Stream *s,
377 const DataExtractor &data, lldb::offset_t data_offset,
378 size_t data_byte_size);
379
380 /// Dump to stdout.
381 void DumpTypeDescription(lldb::DescriptionLevel level =
382 lldb::eDescriptionLevelFull) const;
383
384 /// Print a description of the type to a stream. The exact implementation
385 /// varies, but the expectation is that eDescriptionLevelFull returns a
386 /// source-like representation of the type, whereas eDescriptionLevelVerbose
387 /// does a dump of the underlying AST if applicable.
388 void DumpTypeDescription(Stream *s, lldb::DescriptionLevel level =
389 lldb::eDescriptionLevelFull) const;
390 /// \}
391
392 bool GetValueAsScalar(const DataExtractor &data, lldb::offset_t data_offset,
393 size_t data_byte_size, Scalar &value,
394 ExecutionContextScope *exe_scope) const;
395 void Clear() {
396 m_type = nullptr;
397 m_type_system = nullptr;
398 }
399
400private:
401#ifndef NDEBUG1
402 /// If the type is valid, ask the TypeSystem to verify the integrity
403 /// of the type to catch CompilerTypes that mix and match invalid
404 /// TypeSystem/Opaque type pairs.
405 bool Verify() const;
406#endif
407
408 lldb::opaque_compiler_type_t m_type = nullptr;
409 TypeSystem *m_type_system = nullptr;
410};
411
412bool operator==(const CompilerType &lhs, const CompilerType &rhs);
413bool operator!=(const CompilerType &lhs, const CompilerType &rhs);
414
415struct CompilerType::IntegralTemplateArgument {
416 llvm::APSInt value;
417 CompilerType type;
418};
419
420} // namespace lldb_private
421
422#endif // LLDB_SYMBOL_COMPILERTYPE_H

/usr/include/c++/v1/__memory/shared_ptr.h

1// -*- C++ -*-
2//===----------------------------------------------------------------------===//
3//
4// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
5// See https://llvm.org/LICENSE.txt for license information.
6// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7//
8//===----------------------------------------------------------------------===//
9
10#ifndef _LIBCPP___MEMORY_SHARED_PTR_H
11#define _LIBCPP___MEMORY_SHARED_PTR_H
12
13#include <__availability>
14#include <__config>
15#include <__functional_base>
16#include <__functional/binary_function.h>
17#include <__functional/operations.h>
18#include <__functional/reference_wrapper.h>
19#include <__memory/addressof.h>
20#include <__memory/allocation_guard.h>
21#include <__memory/allocator_traits.h>
22#include <__memory/allocator.h>
23#include <__memory/compressed_pair.h>
24#include <__memory/pointer_traits.h>
25#include <__memory/unique_ptr.h>
26#include <__utility/forward.h>
27#include <cstddef>
28#include <cstdlib> // abort
29#include <iosfwd>
30#include <stdexcept>
31#include <typeinfo>
32#include <type_traits>
33#include <utility>
34#if !defined(_LIBCPP_HAS_NO_ATOMIC_HEADER)
35# include <atomic>
36#endif
37
38#if _LIBCPP_STD_VER14 <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
39# include <__memory/auto_ptr.h>
40#endif
41
42#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
43#pragma GCC system_header
44#endif
45
46_LIBCPP_PUSH_MACROSpush_macro("min") push_macro("max")
47#include <__undef_macros>
48
49_LIBCPP_BEGIN_NAMESPACE_STDnamespace std { inline namespace __1 {
50
51template <class _Alloc>
52class __allocator_destructor
53{
54 typedef _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) allocator_traits<_Alloc> __alloc_traits;
55public:
56 typedef _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) typename __alloc_traits::pointer pointer;
57 typedef _LIBCPP_NODEBUG_TYPE__attribute__((nodebug)) typename __alloc_traits::size_type size_type;
58private:
59 _Alloc& __alloc_;
60 size_type __s_;
61public:
62 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
__allocator_destructor(_Alloc& __a, size_type __s)
63 _NOEXCEPTnoexcept
64 : __alloc_(__a), __s_(__s) {}
65 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
66 void operator()(pointer __p) _NOEXCEPTnoexcept
67 {__alloc_traits::deallocate(__alloc_, __p, __s_);}
68};
69
70// NOTE: Relaxed and acq/rel atomics (for increment and decrement respectively)
71// should be sufficient for thread safety.
72// See https://llvm.org/PR22803
73#if defined(__clang__1) && __has_builtin(__atomic_add_fetch)1 \
74 && defined(__ATOMIC_RELAXED0) \
75 && defined(__ATOMIC_ACQ_REL4)
76# define _LIBCPP_HAS_BUILTIN_ATOMIC_SUPPORT
77#elif defined(_LIBCPP_COMPILER_GCC)
78# define _LIBCPP_HAS_BUILTIN_ATOMIC_SUPPORT
79#endif
80
81template <class _ValueType>
82inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
83_ValueType __libcpp_relaxed_load(_ValueType const* __value) {
84#if !defined(_LIBCPP_HAS_NO_THREADS) && \
85 defined(__ATOMIC_RELAXED0) && \
86 (__has_builtin(__atomic_load_n)1 || defined(_LIBCPP_COMPILER_GCC))
87 return __atomic_load_n(__value, __ATOMIC_RELAXED0);
88#else
89 return *__value;
90#endif
91}
92
93template <class _ValueType>
94inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
95_ValueType __libcpp_acquire_load(_ValueType const* __value) {
96#if !defined(_LIBCPP_HAS_NO_THREADS) && \
97 defined(__ATOMIC_ACQUIRE2) && \
98 (__has_builtin(__atomic_load_n)1 || defined(_LIBCPP_COMPILER_GCC))
99 return __atomic_load_n(__value, __ATOMIC_ACQUIRE2);
100#else
101 return *__value;
102#endif
103}
104
105template <class _Tp>
106inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_Tp
107__libcpp_atomic_refcount_increment(_Tp& __t) _NOEXCEPTnoexcept
108{
109#if defined(_LIBCPP_HAS_BUILTIN_ATOMIC_SUPPORT) && !defined(_LIBCPP_HAS_NO_THREADS)
110 return __atomic_add_fetch(&__t, 1, __ATOMIC_RELAXED0);
111#else
112 return __t += 1;
113#endif
114}
115
116template <class _Tp>
117inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_Tp
118__libcpp_atomic_refcount_decrement(_Tp& __t) _NOEXCEPTnoexcept
119{
120#if defined(_LIBCPP_HAS_BUILTIN_ATOMIC_SUPPORT) && !defined(_LIBCPP_HAS_NO_THREADS)
121 return __atomic_add_fetch(&__t, -1, __ATOMIC_ACQ_REL4);
122#else
123 return __t -= 1;
124#endif
125}
126
127class _LIBCPP_EXCEPTION_ABI__attribute__ ((__visibility__("default"))) bad_weak_ptr
128 : public std::exception
129{
130public:
131 bad_weak_ptr() _NOEXCEPTnoexcept = default;
132 bad_weak_ptr(const bad_weak_ptr&) _NOEXCEPTnoexcept = default;
133 virtual ~bad_weak_ptr() _NOEXCEPTnoexcept;
134 virtual const char* what() const _NOEXCEPTnoexcept;
135};
136
137_LIBCPP_NORETURN[[noreturn]] inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
138void __throw_bad_weak_ptr()
139{
140#ifndef _LIBCPP_NO_EXCEPTIONS
141 throw bad_weak_ptr();
142#else
143 _VSTDstd::__1::abort();
144#endif
145}
146
147template<class _Tp> class _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) weak_ptr;
148
149class _LIBCPP_TYPE_VIS__attribute__ ((__visibility__("default"))) __shared_count
150{
151 __shared_count(const __shared_count&);
152 __shared_count& operator=(const __shared_count&);
153
154protected:
155 long __shared_owners_;
156 virtual ~__shared_count();
157private:
158 virtual void __on_zero_shared() _NOEXCEPTnoexcept = 0;
159
160public:
161 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
162 explicit __shared_count(long __refs = 0) _NOEXCEPTnoexcept
163 : __shared_owners_(__refs) {}
164
165#if defined(_LIBCPP_BUILDING_LIBRARY) && \
166 defined(_LIBCPP_DEPRECATED_ABI_LEGACY_LIBRARY_DEFINITIONS_FOR_INLINE_FUNCTIONS)
167 void __add_shared() _NOEXCEPTnoexcept;
168 bool __release_shared() _NOEXCEPTnoexcept;
169#else
170 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
171 void __add_shared() _NOEXCEPTnoexcept {
172 __libcpp_atomic_refcount_increment(__shared_owners_);
173 }
174 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
175 bool __release_shared() _NOEXCEPTnoexcept {
176 if (__libcpp_atomic_refcount_decrement(__shared_owners_) == -1) {
177 __on_zero_shared();
178 return true;
179 }
180 return false;
181 }
182#endif
183 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
184 long use_count() const _NOEXCEPTnoexcept {
185 return __libcpp_relaxed_load(&__shared_owners_) + 1;
186 }
187};
188
189class _LIBCPP_TYPE_VIS__attribute__ ((__visibility__("default"))) __shared_weak_count
190 : private __shared_count
191{
192 long __shared_weak_owners_;
193
194public:
195 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
196 explicit __shared_weak_count(long __refs = 0) _NOEXCEPTnoexcept
197 : __shared_count(__refs),
198 __shared_weak_owners_(__refs) {}
199protected:
200 virtual ~__shared_weak_count();
201
202public:
203#if defined(_LIBCPP_BUILDING_LIBRARY) && \
204 defined(_LIBCPP_DEPRECATED_ABI_LEGACY_LIBRARY_DEFINITIONS_FOR_INLINE_FUNCTIONS)
205 void __add_shared() _NOEXCEPTnoexcept;
206 void __add_weak() _NOEXCEPTnoexcept;
207 void __release_shared() _NOEXCEPTnoexcept;
208#else
209 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
210 void __add_shared() _NOEXCEPTnoexcept {
211 __shared_count::__add_shared();
212 }
213 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
214 void __add_weak() _NOEXCEPTnoexcept {
215 __libcpp_atomic_refcount_increment(__shared_weak_owners_);
216 }
217 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
218 void __release_shared() _NOEXCEPTnoexcept {
219 if (__shared_count::__release_shared())
220 __release_weak();
221 }
222#endif
223 void __release_weak() _NOEXCEPTnoexcept;
224 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
225 long use_count() const _NOEXCEPTnoexcept {return __shared_count::use_count();}
226 __shared_weak_count* lock() _NOEXCEPTnoexcept;
227
228 virtual const void* __get_deleter(const type_info&) const _NOEXCEPTnoexcept;
229private:
230 virtual void __on_zero_shared_weak() _NOEXCEPTnoexcept = 0;
231};
232
233template <class _Tp, class _Dp, class _Alloc>
234class __shared_ptr_pointer
235 : public __shared_weak_count
236{
237 __compressed_pair<__compressed_pair<_Tp, _Dp>, _Alloc> __data_;
238public:
239 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
240 __shared_ptr_pointer(_Tp __p, _Dp __d, _Alloc __a)
241 : __data_(__compressed_pair<_Tp, _Dp>(__p, _VSTDstd::__1::move(__d)), _VSTDstd::__1::move(__a)) {}
242
243#ifndef _LIBCPP_NO_RTTI
244 virtual const void* __get_deleter(const type_info&) const _NOEXCEPTnoexcept;
245#endif
246
247private:
248 virtual void __on_zero_shared() _NOEXCEPTnoexcept;
249 virtual void __on_zero_shared_weak() _NOEXCEPTnoexcept;
250};
251
252#ifndef _LIBCPP_NO_RTTI
253
254template <class _Tp, class _Dp, class _Alloc>
255const void*
256__shared_ptr_pointer<_Tp, _Dp, _Alloc>::__get_deleter(const type_info& __t) const _NOEXCEPTnoexcept
257{
258 return __t == typeid(_Dp) ? _VSTDstd::__1::addressof(__data_.first().second()) : nullptr;
259}
260
261#endif // _LIBCPP_NO_RTTI
262
263template <class _Tp, class _Dp, class _Alloc>
264void
265__shared_ptr_pointer<_Tp, _Dp, _Alloc>::__on_zero_shared() _NOEXCEPTnoexcept
266{
267 __data_.first().second()(__data_.first().first());
268 __data_.first().second().~_Dp();
269}
270
271template <class _Tp, class _Dp, class _Alloc>
272void
273__shared_ptr_pointer<_Tp, _Dp, _Alloc>::__on_zero_shared_weak() _NOEXCEPTnoexcept
274{
275 typedef typename __allocator_traits_rebind<_Alloc, __shared_ptr_pointer>::type _Al;
276 typedef allocator_traits<_Al> _ATraits;
277 typedef pointer_traits<typename _ATraits::pointer> _PTraits;
278
279 _Al __a(__data_.second());
280 __data_.second().~_Alloc();
281 __a.deallocate(_PTraits::pointer_to(*this), 1);
282}
283
284template <class _Tp, class _Alloc>
285struct __shared_ptr_emplace
286 : __shared_weak_count
287{
288 template<class ..._Args>
289 _LIBCPP_HIDE_FROM_ABI__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
290 explicit __shared_ptr_emplace(_Alloc __a, _Args&& ...__args)
291 : __storage_(_VSTDstd::__1::move(__a))
292 {
293#if _LIBCPP_STD_VER14 > 17
294 using _TpAlloc = typename __allocator_traits_rebind<_Alloc, _Tp>::type;
295 _TpAlloc __tmp(*__get_alloc());
296 allocator_traits<_TpAlloc>::construct(__tmp, __get_elem(), _VSTDstd::__1::forward<_Args>(__args)...);
297#else
298 ::new ((void*)__get_elem()) _Tp(_VSTDstd::__1::forward<_Args>(__args)...);
299#endif
300 }
301
302 _LIBCPP_HIDE_FROM_ABI__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
303 _Alloc* __get_alloc() _NOEXCEPTnoexcept { return __storage_.__get_alloc(); }
304
305 _LIBCPP_HIDE_FROM_ABI__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
306 _Tp* __get_elem() _NOEXCEPTnoexcept { return __storage_.__get_elem(); }
307
308private:
309 virtual void __on_zero_shared() _NOEXCEPTnoexcept {
310#if _LIBCPP_STD_VER14 > 17
311 using _TpAlloc = typename __allocator_traits_rebind<_Alloc, _Tp>::type;
312 _TpAlloc __tmp(*__get_alloc());
313 allocator_traits<_TpAlloc>::destroy(__tmp, __get_elem());
314#else
315 __get_elem()->~_Tp();
316#endif
317 }
318
319 virtual void __on_zero_shared_weak() _NOEXCEPTnoexcept {
320 using _ControlBlockAlloc = typename __allocator_traits_rebind<_Alloc, __shared_ptr_emplace>::type;
321 using _ControlBlockPointer = typename allocator_traits<_ControlBlockAlloc>::pointer;
322 _ControlBlockAlloc __tmp(*__get_alloc());
323 __storage_.~_Storage();
324 allocator_traits<_ControlBlockAlloc>::deallocate(__tmp,
325 pointer_traits<_ControlBlockPointer>::pointer_to(*this), 1);
326 }
327
328 // This class implements the control block for non-array shared pointers created
329 // through `std::allocate_shared` and `std::make_shared`.
330 //
331 // In previous versions of the library, we used a compressed pair to store
332 // both the _Alloc and the _Tp. This implies using EBO, which is incompatible
333 // with Allocator construction for _Tp. To allow implementing P0674 in C++20,
334 // we now use a properly aligned char buffer while making sure that we maintain
335 // the same layout that we had when we used a compressed pair.
336 using _CompressedPair = __compressed_pair<_Alloc, _Tp>;
337 struct _ALIGNAS_TYPE(_CompressedPair)alignas(_CompressedPair) _Storage {
338 char __blob_[sizeof(_CompressedPair)];
339
340 _LIBCPP_HIDE_FROM_ABI__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
explicit _Storage(_Alloc&& __a) {
341 ::new ((void*)__get_alloc()) _Alloc(_VSTDstd::__1::move(__a));
342 }
343 _LIBCPP_HIDE_FROM_ABI__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
~_Storage() {
344 __get_alloc()->~_Alloc();
345 }
346 _Alloc* __get_alloc() _NOEXCEPTnoexcept {
347 _CompressedPair *__as_pair = reinterpret_cast<_CompressedPair*>(__blob_);
348 typename _CompressedPair::_Base1* __first = _CompressedPair::__get_first_base(__as_pair);
349 _Alloc *__alloc = reinterpret_cast<_Alloc*>(__first);
350 return __alloc;
351 }
352 _LIBCPP_NO_CFI__attribute__((__no_sanitize__("cfi"))) _Tp* __get_elem() _NOEXCEPTnoexcept {
353 _CompressedPair *__as_pair = reinterpret_cast<_CompressedPair*>(__blob_);
354 typename _CompressedPair::_Base2* __second = _CompressedPair::__get_second_base(__as_pair);
355 _Tp *__elem = reinterpret_cast<_Tp*>(__second);
356 return __elem;
357 }
358 };
359
360 static_assert(_LIBCPP_ALIGNOF(_Storage)alignof(_Storage) == _LIBCPP_ALIGNOF(_CompressedPair)alignof(_CompressedPair), "");
361 static_assert(sizeof(_Storage) == sizeof(_CompressedPair), "");
362 _Storage __storage_;
363};
364
365struct __shared_ptr_dummy_rebind_allocator_type;
366template <>
367class _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) allocator<__shared_ptr_dummy_rebind_allocator_type>
368{
369public:
370 template <class _Other>
371 struct rebind
372 {
373 typedef allocator<_Other> other;
374 };
375};
376
377template<class _Tp> class _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) enable_shared_from_this;
378
379template<class _Tp, class _Up>
380struct __compatible_with
381#if _LIBCPP_STD_VER14 > 14
382 : is_convertible<remove_extent_t<_Tp>*, remove_extent_t<_Up>*> {};
383#else
384 : is_convertible<_Tp*, _Up*> {};
385#endif // _LIBCPP_STD_VER > 14
386
387template <class _Ptr, class = void>
388struct __is_deletable : false_type { };
389template <class _Ptr>
390struct __is_deletable<_Ptr, decltype(delete declval<_Ptr>())> : true_type { };
391
392template <class _Ptr, class = void>
393struct __is_array_deletable : false_type { };
394template <class _Ptr>
395struct __is_array_deletable<_Ptr, decltype(delete[] declval<_Ptr>())> : true_type { };
396
397template <class _Dp, class _Pt,
398 class = decltype(declval<_Dp>()(declval<_Pt>()))>
399static true_type __well_formed_deleter_test(int);
400
401template <class, class>
402static false_type __well_formed_deleter_test(...);
403
404template <class _Dp, class _Pt>
405struct __well_formed_deleter : decltype(__well_formed_deleter_test<_Dp, _Pt>(0)) {};
406
407template<class _Dp, class _Tp, class _Yp>
408struct __shared_ptr_deleter_ctor_reqs
409{
410 static const bool value = __compatible_with<_Tp, _Yp>::value &&
411 is_move_constructible<_Dp>::value &&
412 __well_formed_deleter<_Dp, _Tp*>::value;
413};
414
415#if defined(_LIBCPP_ABI_ENABLE_SHARED_PTR_TRIVIAL_ABI)
416# define _LIBCPP_SHARED_PTR_TRIVIAL_ABI __attribute__((trivial_abi))
417#else
418# define _LIBCPP_SHARED_PTR_TRIVIAL_ABI
419#endif
420
421template<class _Tp>
422class _LIBCPP_SHARED_PTR_TRIVIAL_ABI _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) shared_ptr
423{
424public:
425#if _LIBCPP_STD_VER14 > 14
426 typedef weak_ptr<_Tp> weak_type;
427 typedef remove_extent_t<_Tp> element_type;
428#else
429 typedef _Tp element_type;
430#endif
431
432private:
433 element_type* __ptr_;
434 __shared_weak_count* __cntrl_;
435
436 struct __nat {int __for_bool_;};
437public:
438 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
439 _LIBCPP_CONSTEXPRconstexpr shared_ptr() _NOEXCEPTnoexcept;
440 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
441 _LIBCPP_CONSTEXPRconstexpr shared_ptr(nullptr_t) _NOEXCEPTnoexcept;
442
443 template<class _Yp, class = _EnableIf<
444 _And<
445 __compatible_with<_Yp, _Tp>
446 // In C++03 we get errors when trying to do SFINAE with the
447 // delete operator, so we always pretend that it's deletable.
448 // The same happens on GCC.
449#if !defined(_LIBCPP_CXX03_LANG) && !defined(_LIBCPP_COMPILER_GCC)
450 , _If<is_array<_Tp>::value, __is_array_deletable<_Yp*>, __is_deletable<_Yp*> >
451#endif
452 >::value
453 > >
454 explicit shared_ptr(_Yp* __p) : __ptr_(__p) {
455 unique_ptr<_Yp> __hold(__p);
456 typedef typename __shared_ptr_default_allocator<_Yp>::type _AllocT;
457 typedef __shared_ptr_pointer<_Yp*, __shared_ptr_default_delete<_Tp, _Yp>, _AllocT > _CntrlBlk;
458 __cntrl_ = new _CntrlBlk(__p, __shared_ptr_default_delete<_Tp, _Yp>(), _AllocT());
459 __hold.release();
460 __enable_weak_this(__p, __p);
461 }
462
463 template<class _Yp, class _Dp>
464 shared_ptr(_Yp* __p, _Dp __d,
465 typename enable_if<__shared_ptr_deleter_ctor_reqs<_Dp, _Yp, element_type>::value, __nat>::type = __nat());
466 template<class _Yp, class _Dp, class _Alloc>
467 shared_ptr(_Yp* __p, _Dp __d, _Alloc __a,
468 typename enable_if<__shared_ptr_deleter_ctor_reqs<_Dp, _Yp, element_type>::value, __nat>::type = __nat());
469 template <class _Dp> shared_ptr(nullptr_t __p, _Dp __d);
470 template <class _Dp, class _Alloc> shared_ptr(nullptr_t __p, _Dp __d, _Alloc __a);
471 template<class _Yp> _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
shared_ptr(const shared_ptr<_Yp>& __r, element_type* __p) _NOEXCEPTnoexcept;
472 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
473 shared_ptr(const shared_ptr& __r) _NOEXCEPTnoexcept;
474 template<class _Yp>
475 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
476 shared_ptr(const shared_ptr<_Yp>& __r,
477 typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type = __nat())
478 _NOEXCEPTnoexcept;
479 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
480 shared_ptr(shared_ptr&& __r) _NOEXCEPTnoexcept;
481 template<class _Yp> _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
shared_ptr(shared_ptr<_Yp>&& __r,
482 typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type = __nat())
483 _NOEXCEPTnoexcept;
484 template<class _Yp> explicit shared_ptr(const weak_ptr<_Yp>& __r,
485 typename enable_if<is_convertible<_Yp*, element_type*>::value, __nat>::type= __nat());
486#if _LIBCPP_STD_VER14 <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
487 template<class _Yp>
488 shared_ptr(auto_ptr<_Yp>&& __r,
489 typename enable_if<is_convertible<_Yp*, element_type*>::value, __nat>::type = __nat());
490#endif
491 template <class _Yp, class _Dp>
492 shared_ptr(unique_ptr<_Yp, _Dp>&&,
493 typename enable_if
494 <
495 !is_lvalue_reference<_Dp>::value &&
496 is_convertible<typename unique_ptr<_Yp, _Dp>::pointer, element_type*>::value,
497 __nat
498 >::type = __nat());
499 template <class _Yp, class _Dp>
500 shared_ptr(unique_ptr<_Yp, _Dp>&&,
501 typename enable_if
502 <
503 is_lvalue_reference<_Dp>::value &&
504 is_convertible<typename unique_ptr<_Yp, _Dp>::pointer, element_type*>::value,
505 __nat
506 >::type = __nat());
507
508 ~shared_ptr();
509
510 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
511 shared_ptr& operator=(const shared_ptr& __r) _NOEXCEPTnoexcept;
512 template<class _Yp>
513 typename enable_if
514 <
515 __compatible_with<_Yp, element_type>::value,
516 shared_ptr&
517 >::type
518 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
519 operator=(const shared_ptr<_Yp>& __r) _NOEXCEPTnoexcept;
520 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
521 shared_ptr& operator=(shared_ptr&& __r) _NOEXCEPTnoexcept;
522 template<class _Yp>
523 typename enable_if
524 <
525 __compatible_with<_Yp, element_type>::value,
526 shared_ptr&
527 >::type
528 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
529 operator=(shared_ptr<_Yp>&& __r);
530#if _LIBCPP_STD_VER14 <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
531 template<class _Yp>
532 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
533 typename enable_if
534 <
535 !is_array<_Yp>::value &&
536 is_convertible<_Yp*, element_type*>::value,
537 shared_ptr
538 >::type&
539 operator=(auto_ptr<_Yp>&& __r);
540#endif
541 template <class _Yp, class _Dp>
542 typename enable_if
543 <
544 is_convertible<typename unique_ptr<_Yp, _Dp>::pointer, element_type*>::value,
545 shared_ptr&
546 >::type
547 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
548 operator=(unique_ptr<_Yp, _Dp>&& __r);
549
550 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
551 void swap(shared_ptr& __r) _NOEXCEPTnoexcept;
552 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
553 void reset() _NOEXCEPTnoexcept;
554 template<class _Yp>
555 typename enable_if
556 <
557 __compatible_with<_Yp, element_type>::value,
558 void
559 >::type
560 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
561 reset(_Yp* __p);
562 template<class _Yp, class _Dp>
563 typename enable_if
564 <
565 __compatible_with<_Yp, element_type>::value,
566 void
567 >::type
568 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
569 reset(_Yp* __p, _Dp __d);
570 template<class _Yp, class _Dp, class _Alloc>
571 typename enable_if
572 <
573 __compatible_with<_Yp, element_type>::value,
574 void
575 >::type
576 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
577 reset(_Yp* __p, _Dp __d, _Alloc __a);
578
579 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
580 element_type* get() const _NOEXCEPTnoexcept {return __ptr_;}
581 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
582 typename add_lvalue_reference<element_type>::type operator*() const _NOEXCEPTnoexcept
583 {return *__ptr_;}
584 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
585 element_type* operator->() const _NOEXCEPTnoexcept
586 {
587 static_assert(!is_array<_Tp>::value,
588 "std::shared_ptr<T>::operator-> is only valid when T is not an array type.");
589 return __ptr_;
590 }
591 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
592 long use_count() const _NOEXCEPTnoexcept {return __cntrl_ ? __cntrl_->use_count() : 0;}
593 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
594 bool unique() const _NOEXCEPTnoexcept {return use_count() == 1;}
595 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
596 explicit operator bool() const _NOEXCEPTnoexcept {return get() != nullptr;}
42
Returning the value 1, which participates in a condition later
597 template <class _Up>
598 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
599 bool owner_before(shared_ptr<_Up> const& __p) const _NOEXCEPTnoexcept
600 {return __cntrl_ < __p.__cntrl_;}
601 template <class _Up>
602 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
603 bool owner_before(weak_ptr<_Up> const& __p) const _NOEXCEPTnoexcept
604 {return __cntrl_ < __p.__cntrl_;}
605 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
606 bool
607 __owner_equivalent(const shared_ptr& __p) const
608 {return __cntrl_ == __p.__cntrl_;}
609
610#if _LIBCPP_STD_VER14 > 14
611 typename add_lvalue_reference<element_type>::type
612 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
613 operator[](ptrdiff_t __i) const
614 {
615 static_assert(is_array<_Tp>::value,
616 "std::shared_ptr<T>::operator[] is only valid when T is an array type.");
617 return __ptr_[__i];
618 }
619#endif
620
621#ifndef _LIBCPP_NO_RTTI
622 template <class _Dp>
623 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
624 _Dp* __get_deleter() const _NOEXCEPTnoexcept
625 {return static_cast<_Dp*>(__cntrl_
626 ? const_cast<void *>(__cntrl_->__get_deleter(typeid(_Dp)))
627 : nullptr);}
628#endif // _LIBCPP_NO_RTTI
629
630 template<class _Yp, class _CntrlBlk>
631 static shared_ptr<_Tp>
632 __create_with_control_block(_Yp* __p, _CntrlBlk* __cntrl) _NOEXCEPTnoexcept
633 {
634 shared_ptr<_Tp> __r;
635 __r.__ptr_ = __p;
636 __r.__cntrl_ = __cntrl;
637 __r.__enable_weak_this(__r.__ptr_, __r.__ptr_);
638 return __r;
639 }
640
641private:
642 template <class _Yp, bool = is_function<_Yp>::value>
643 struct __shared_ptr_default_allocator
644 {
645 typedef allocator<_Yp> type;
646 };
647
648 template <class _Yp>
649 struct __shared_ptr_default_allocator<_Yp, true>
650 {
651 typedef allocator<__shared_ptr_dummy_rebind_allocator_type> type;
652 };
653
654 template <class _Yp, class _OrigPtr>
655 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
656 typename enable_if<is_convertible<_OrigPtr*,
657 const enable_shared_from_this<_Yp>*
658 >::value,
659 void>::type
660 __enable_weak_this(const enable_shared_from_this<_Yp>* __e,
661 _OrigPtr* __ptr) _NOEXCEPTnoexcept
662 {
663 typedef typename remove_cv<_Yp>::type _RawYp;
664 if (__e && __e->__weak_this_.expired())
665 {
666 __e->__weak_this_ = shared_ptr<_RawYp>(*this,
667 const_cast<_RawYp*>(static_cast<const _Yp*>(__ptr)));
668 }
669 }
670
671 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
void __enable_weak_this(...) _NOEXCEPTnoexcept {}
672
673 template <class, class _Yp>
674 struct __shared_ptr_default_delete
675 : default_delete<_Yp> {};
676
677 template <class _Yp, class _Un, size_t _Sz>
678 struct __shared_ptr_default_delete<_Yp[_Sz], _Un>
679 : default_delete<_Yp[]> {};
680
681 template <class _Yp, class _Un>
682 struct __shared_ptr_default_delete<_Yp[], _Un>
683 : default_delete<_Yp[]> {};
684
685 template <class _Up> friend class _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) shared_ptr;
686 template <class _Up> friend class _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) weak_ptr;
687};
688
689#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
690template<class _Tp>
691shared_ptr(weak_ptr<_Tp>) -> shared_ptr<_Tp>;
692template<class _Tp, class _Dp>
693shared_ptr(unique_ptr<_Tp, _Dp>) -> shared_ptr<_Tp>;
694#endif
695
696template<class _Tp>
697inline
698_LIBCPP_CONSTEXPRconstexpr
699shared_ptr<_Tp>::shared_ptr() _NOEXCEPTnoexcept
700 : __ptr_(nullptr),
701 __cntrl_(nullptr)
702{
703}
704
705template<class _Tp>
706inline
707_LIBCPP_CONSTEXPRconstexpr
708shared_ptr<_Tp>::shared_ptr(nullptr_t) _NOEXCEPTnoexcept
709 : __ptr_(nullptr),
710 __cntrl_(nullptr)
711{
712}
713
714template<class _Tp>
715template<class _Yp, class _Dp>
716shared_ptr<_Tp>::shared_ptr(_Yp* __p, _Dp __d,
717 typename enable_if<__shared_ptr_deleter_ctor_reqs<_Dp, _Yp, element_type>::value, __nat>::type)
718 : __ptr_(__p)
719{
720#ifndef _LIBCPP_NO_EXCEPTIONS
721 try
722 {
723#endif // _LIBCPP_NO_EXCEPTIONS
724 typedef typename __shared_ptr_default_allocator<_Yp>::type _AllocT;
725 typedef __shared_ptr_pointer<_Yp*, _Dp, _AllocT > _CntrlBlk;
726#ifndef _LIBCPP_CXX03_LANG
727 __cntrl_ = new _CntrlBlk(__p, _VSTDstd::__1::move(__d), _AllocT());
728#else
729 __cntrl_ = new _CntrlBlk(__p, __d, _AllocT());
730#endif // not _LIBCPP_CXX03_LANG
731 __enable_weak_this(__p, __p);
732#ifndef _LIBCPP_NO_EXCEPTIONS
733 }
734 catch (...)
735 {
736 __d(__p);
737 throw;
738 }
739#endif // _LIBCPP_NO_EXCEPTIONS
740}
741
742template<class _Tp>
743template<class _Dp>
744shared_ptr<_Tp>::shared_ptr(nullptr_t __p, _Dp __d)
745 : __ptr_(nullptr)
746{
747#ifndef _LIBCPP_NO_EXCEPTIONS
748 try
749 {
750#endif // _LIBCPP_NO_EXCEPTIONS
751 typedef typename __shared_ptr_default_allocator<_Tp>::type _AllocT;
752 typedef __shared_ptr_pointer<nullptr_t, _Dp, _AllocT > _CntrlBlk;
753#ifndef _LIBCPP_CXX03_LANG
754 __cntrl_ = new _CntrlBlk(__p, _VSTDstd::__1::move(__d), _AllocT());
755#else
756 __cntrl_ = new _CntrlBlk(__p, __d, _AllocT());
757#endif // not _LIBCPP_CXX03_LANG
758#ifndef _LIBCPP_NO_EXCEPTIONS
759 }
760 catch (...)
761 {
762 __d(__p);
763 throw;
764 }
765#endif // _LIBCPP_NO_EXCEPTIONS
766}
767
768template<class _Tp>
769template<class _Yp, class _Dp, class _Alloc>
770shared_ptr<_Tp>::shared_ptr(_Yp* __p, _Dp __d, _Alloc __a,
771 typename enable_if<__shared_ptr_deleter_ctor_reqs<_Dp, _Yp, element_type>::value, __nat>::type)
772 : __ptr_(__p)
773{
774#ifndef _LIBCPP_NO_EXCEPTIONS
775 try
776 {
777#endif // _LIBCPP_NO_EXCEPTIONS
778 typedef __shared_ptr_pointer<_Yp*, _Dp, _Alloc> _CntrlBlk;
779 typedef typename __allocator_traits_rebind<_Alloc, _CntrlBlk>::type _A2;
780 typedef __allocator_destructor<_A2> _D2;
781 _A2 __a2(__a);
782 unique_ptr<_CntrlBlk, _D2> __hold2(__a2.allocate(1), _D2(__a2, 1));
783 ::new ((void*)_VSTDstd::__1::addressof(*__hold2.get()))
784#ifndef _LIBCPP_CXX03_LANG
785 _CntrlBlk(__p, _VSTDstd::__1::move(__d), __a);
786#else
787 _CntrlBlk(__p, __d, __a);
788#endif // not _LIBCPP_CXX03_LANG
789 __cntrl_ = _VSTDstd::__1::addressof(*__hold2.release());
790 __enable_weak_this(__p, __p);
791#ifndef _LIBCPP_NO_EXCEPTIONS
792 }
793 catch (...)
794 {
795 __d(__p);
796 throw;
797 }
798#endif // _LIBCPP_NO_EXCEPTIONS
799}
800
801template<class _Tp>
802template<class _Dp, class _Alloc>
803shared_ptr<_Tp>::shared_ptr(nullptr_t __p, _Dp __d, _Alloc __a)
804 : __ptr_(nullptr)
805{
806#ifndef _LIBCPP_NO_EXCEPTIONS
807 try
808 {
809#endif // _LIBCPP_NO_EXCEPTIONS
810 typedef __shared_ptr_pointer<nullptr_t, _Dp, _Alloc> _CntrlBlk;
811 typedef typename __allocator_traits_rebind<_Alloc, _CntrlBlk>::type _A2;
812 typedef __allocator_destructor<_A2> _D2;
813 _A2 __a2(__a);
814 unique_ptr<_CntrlBlk, _D2> __hold2(__a2.allocate(1), _D2(__a2, 1));
815 ::new ((void*)_VSTDstd::__1::addressof(*__hold2.get()))
816#ifndef _LIBCPP_CXX03_LANG
817 _CntrlBlk(__p, _VSTDstd::__1::move(__d), __a);
818#else
819 _CntrlBlk(__p, __d, __a);
820#endif // not _LIBCPP_CXX03_LANG
821 __cntrl_ = _VSTDstd::__1::addressof(*__hold2.release());
822#ifndef _LIBCPP_NO_EXCEPTIONS
823 }
824 catch (...)
825 {
826 __d(__p);
827 throw;
828 }
829#endif // _LIBCPP_NO_EXCEPTIONS
830}
831
832template<class _Tp>
833template<class _Yp>
834inline
835shared_ptr<_Tp>::shared_ptr(const shared_ptr<_Yp>& __r, element_type *__p) _NOEXCEPTnoexcept
836 : __ptr_(__p),
837 __cntrl_(__r.__cntrl_)
838{
839 if (__cntrl_)
840 __cntrl_->__add_shared();
841}
842
843template<class _Tp>
844inline
845shared_ptr<_Tp>::shared_ptr(const shared_ptr& __r) _NOEXCEPTnoexcept
846 : __ptr_(__r.__ptr_),
847 __cntrl_(__r.__cntrl_)
848{
849 if (__cntrl_)
850 __cntrl_->__add_shared();
851}
852
853template<class _Tp>
854template<class _Yp>
855inline
856shared_ptr<_Tp>::shared_ptr(const shared_ptr<_Yp>& __r,
857 typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type)
858 _NOEXCEPTnoexcept
859 : __ptr_(__r.__ptr_),
860 __cntrl_(__r.__cntrl_)
861{
862 if (__cntrl_)
863 __cntrl_->__add_shared();
864}
865
866template<class _Tp>
867inline
868shared_ptr<_Tp>::shared_ptr(shared_ptr&& __r) _NOEXCEPTnoexcept
869 : __ptr_(__r.__ptr_),
870 __cntrl_(__r.__cntrl_)
871{
872 __r.__ptr_ = nullptr;
873 __r.__cntrl_ = nullptr;
874}
875
876template<class _Tp>
877template<class _Yp>
878inline
879shared_ptr<_Tp>::shared_ptr(shared_ptr<_Yp>&& __r,
880 typename enable_if<__compatible_with<_Yp, element_type>::value, __nat>::type)
881 _NOEXCEPTnoexcept
882 : __ptr_(__r.__ptr_),
883 __cntrl_(__r.__cntrl_)
884{
885 __r.__ptr_ = nullptr;
886 __r.__cntrl_ = nullptr;
887}
888
889#if _LIBCPP_STD_VER14 <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
890template<class _Tp>
891template<class _Yp>
892shared_ptr<_Tp>::shared_ptr(auto_ptr<_Yp>&& __r,
893 typename enable_if<is_convertible<_Yp*, element_type*>::value, __nat>::type)
894 : __ptr_(__r.get())
895{
896 typedef __shared_ptr_pointer<_Yp*, default_delete<_Yp>, allocator<_Yp> > _CntrlBlk;
897 __cntrl_ = new _CntrlBlk(__r.get(), default_delete<_Yp>(), allocator<_Yp>());
898 __enable_weak_this(__r.get(), __r.get());
899 __r.release();
900}
901#endif
902
903template<class _Tp>
904template <class _Yp, class _Dp>
905shared_ptr<_Tp>::shared_ptr(unique_ptr<_Yp, _Dp>&& __r,
906 typename enable_if
907 <
908 !is_lvalue_reference<_Dp>::value &&
909 is_convertible<typename unique_ptr<_Yp, _Dp>::pointer, element_type*>::value,
910 __nat
911 >::type)
912 : __ptr_(__r.get())
913{
914#if _LIBCPP_STD_VER14 > 11
915 if (__ptr_ == nullptr)
916 __cntrl_ = nullptr;
917 else
918#endif
919 {
920 typedef typename __shared_ptr_default_allocator<_Yp>::type _AllocT;
921 typedef __shared_ptr_pointer<typename unique_ptr<_Yp, _Dp>::pointer, _Dp, _AllocT > _CntrlBlk;
922 __cntrl_ = new _CntrlBlk(__r.get(), __r.get_deleter(), _AllocT());
923 __enable_weak_this(__r.get(), __r.get());
924 }
925 __r.release();
926}
927
928template<class _Tp>
929template <class _Yp, class _Dp>
930shared_ptr<_Tp>::shared_ptr(unique_ptr<_Yp, _Dp>&& __r,
931 typename enable_if
932 <
933 is_lvalue_reference<_Dp>::value &&
934 is_convertible<typename unique_ptr<_Yp, _Dp>::pointer, element_type*>::value,
935 __nat
936 >::type)
937 : __ptr_(__r.get())
938{
939#if _LIBCPP_STD_VER14 > 11
940 if (__ptr_ == nullptr)
941 __cntrl_ = nullptr;
942 else
943#endif
944 {
945 typedef typename __shared_ptr_default_allocator<_Yp>::type _AllocT;
946 typedef __shared_ptr_pointer<typename unique_ptr<_Yp, _Dp>::pointer,
947 reference_wrapper<typename remove_reference<_Dp>::type>,
948 _AllocT > _CntrlBlk;
949 __cntrl_ = new _CntrlBlk(__r.get(), _VSTDstd::__1::ref(__r.get_deleter()), _AllocT());
950 __enable_weak_this(__r.get(), __r.get());
951 }
952 __r.release();
953}
954
955template<class _Tp>
956shared_ptr<_Tp>::~shared_ptr()
957{
958 if (__cntrl_)
959 __cntrl_->__release_shared();
960}
961
962template<class _Tp>
963inline
964shared_ptr<_Tp>&
965shared_ptr<_Tp>::operator=(const shared_ptr& __r) _NOEXCEPTnoexcept
966{
967 shared_ptr(__r).swap(*this);
968 return *this;
969}
970
971template<class _Tp>
972template<class _Yp>
973inline
974typename enable_if
975<
976 __compatible_with<_Yp, typename shared_ptr<_Tp>::element_type>::value,
977 shared_ptr<_Tp>&
978>::type
979shared_ptr<_Tp>::operator=(const shared_ptr<_Yp>& __r) _NOEXCEPTnoexcept
980{
981 shared_ptr(__r).swap(*this);
982 return *this;
983}
984
985template<class _Tp>
986inline
987shared_ptr<_Tp>&
988shared_ptr<_Tp>::operator=(shared_ptr&& __r) _NOEXCEPTnoexcept
989{
990 shared_ptr(_VSTDstd::__1::move(__r)).swap(*this);
991 return *this;
992}
993
994template<class _Tp>
995template<class _Yp>
996inline
997typename enable_if
998<
999 __compatible_with<_Yp, typename shared_ptr<_Tp>::element_type>::value,
1000 shared_ptr<_Tp>&
1001>::type
1002shared_ptr<_Tp>::operator=(shared_ptr<_Yp>&& __r)
1003{
1004 shared_ptr(_VSTDstd::__1::move(__r)).swap(*this);
1005 return *this;
1006}
1007
1008#if _LIBCPP_STD_VER14 <= 14 || defined(_LIBCPP_ENABLE_CXX17_REMOVED_AUTO_PTR)
1009template<class _Tp>
1010template<class _Yp>
1011inline
1012typename enable_if
1013<
1014 !is_array<_Yp>::value &&
1015 is_convertible<_Yp*, typename shared_ptr<_Tp>::element_type*>::value,
1016 shared_ptr<_Tp>
1017>::type&
1018shared_ptr<_Tp>::operator=(auto_ptr<_Yp>&& __r)
1019{
1020 shared_ptr(_VSTDstd::__1::move(__r)).swap(*this);
1021 return *this;
1022}
1023#endif
1024
1025template<class _Tp>
1026template <class _Yp, class _Dp>
1027inline
1028typename enable_if
1029<
1030 is_convertible<typename unique_ptr<_Yp, _Dp>::pointer,
1031 typename shared_ptr<_Tp>::element_type*>::value,
1032 shared_ptr<_Tp>&
1033>::type
1034shared_ptr<_Tp>::operator=(unique_ptr<_Yp, _Dp>&& __r)
1035{
1036 shared_ptr(_VSTDstd::__1::move(__r)).swap(*this);
1037 return *this;
1038}
1039
1040template<class _Tp>
1041inline
1042void
1043shared_ptr<_Tp>::swap(shared_ptr& __r) _NOEXCEPTnoexcept
1044{
1045 _VSTDstd::__1::swap(__ptr_, __r.__ptr_);
1046 _VSTDstd::__1::swap(__cntrl_, __r.__cntrl_);
1047}
1048
1049template<class _Tp>
1050inline
1051void
1052shared_ptr<_Tp>::reset() _NOEXCEPTnoexcept
1053{
1054 shared_ptr().swap(*this);
1055}
1056
1057template<class _Tp>
1058template<class _Yp>
1059inline
1060typename enable_if
1061<
1062 __compatible_with<_Yp, typename shared_ptr<_Tp>::element_type>::value,
1063 void
1064>::type
1065shared_ptr<_Tp>::reset(_Yp* __p)
1066{
1067 shared_ptr(__p).swap(*this);
1068}
1069
1070template<class _Tp>
1071template<class _Yp, class _Dp>
1072inline
1073typename enable_if
1074<
1075 __compatible_with<_Yp, typename shared_ptr<_Tp>::element_type>::value,
1076 void
1077>::type
1078shared_ptr<_Tp>::reset(_Yp* __p, _Dp __d)
1079{
1080 shared_ptr(__p, __d).swap(*this);
1081}
1082
1083template<class _Tp>
1084template<class _Yp, class _Dp, class _Alloc>
1085inline
1086typename enable_if
1087<
1088 __compatible_with<_Yp, typename shared_ptr<_Tp>::element_type>::value,
1089 void
1090>::type
1091shared_ptr<_Tp>::reset(_Yp* __p, _Dp __d, _Alloc __a)
1092{
1093 shared_ptr(__p, __d, __a).swap(*this);
1094}
1095
1096//
1097// std::allocate_shared and std::make_shared
1098//
1099template<class _Tp, class _Alloc, class ..._Args, class = _EnableIf<!is_array<_Tp>::value> >
1100_LIBCPP_HIDE_FROM_ABI__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1101shared_ptr<_Tp> allocate_shared(const _Alloc& __a, _Args&& ...__args)
1102{
1103 using _ControlBlock = __shared_ptr_emplace<_Tp, _Alloc>;
1104 using _ControlBlockAllocator = typename __allocator_traits_rebind<_Alloc, _ControlBlock>::type;
1105 __allocation_guard<_ControlBlockAllocator> __guard(__a, 1);
1106 ::new ((void*)_VSTDstd::__1::addressof(*__guard.__get())) _ControlBlock(__a, _VSTDstd::__1::forward<_Args>(__args)...);
1107 auto __control_block = __guard.__release_ptr();
1108 return shared_ptr<_Tp>::__create_with_control_block((*__control_block).__get_elem(), _VSTDstd::__1::addressof(*__control_block));
1109}
1110
1111template<class _Tp, class ..._Args, class = _EnableIf<!is_array<_Tp>::value> >
1112_LIBCPP_HIDE_FROM_ABI__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1113shared_ptr<_Tp> make_shared(_Args&& ...__args)
1114{
1115 return _VSTDstd::__1::allocate_shared<_Tp>(allocator<_Tp>(), _VSTDstd::__1::forward<_Args>(__args)...);
1116}
1117
1118template<class _Tp, class _Up>
1119inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1120bool
1121operator==(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPTnoexcept
1122{
1123 return __x.get() == __y.get();
1124}
1125
1126template<class _Tp, class _Up>
1127inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1128bool
1129operator!=(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPTnoexcept
1130{
1131 return !(__x == __y);
1132}
1133
1134template<class _Tp, class _Up>
1135inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1136bool
1137operator<(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPTnoexcept
1138{
1139#if _LIBCPP_STD_VER14 <= 11
1140 typedef typename common_type<_Tp*, _Up*>::type _Vp;
1141 return less<_Vp>()(__x.get(), __y.get());
1142#else
1143 return less<>()(__x.get(), __y.get());
1144#endif
1145
1146}
1147
1148template<class _Tp, class _Up>
1149inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1150bool
1151operator>(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPTnoexcept
1152{
1153 return __y < __x;
1154}
1155
1156template<class _Tp, class _Up>
1157inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1158bool
1159operator<=(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPTnoexcept
1160{
1161 return !(__y < __x);
1162}
1163
1164template<class _Tp, class _Up>
1165inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1166bool
1167operator>=(const shared_ptr<_Tp>& __x, const shared_ptr<_Up>& __y) _NOEXCEPTnoexcept
1168{
1169 return !(__x < __y);
1170}
1171
1172template<class _Tp>
1173inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1174bool
1175operator==(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPTnoexcept
1176{
1177 return !__x;
1178}
1179
1180template<class _Tp>
1181inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1182bool
1183operator==(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPTnoexcept
1184{
1185 return !__x;
1186}
1187
1188template<class _Tp>
1189inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1190bool
1191operator!=(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPTnoexcept
1192{
1193 return static_cast<bool>(__x);
1194}
1195
1196template<class _Tp>
1197inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1198bool
1199operator!=(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPTnoexcept
1200{
1201 return static_cast<bool>(__x);
1202}
1203
1204template<class _Tp>
1205inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1206bool
1207operator<(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPTnoexcept
1208{
1209 return less<_Tp*>()(__x.get(), nullptr);
1210}
1211
1212template<class _Tp>
1213inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1214bool
1215operator<(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPTnoexcept
1216{
1217 return less<_Tp*>()(nullptr, __x.get());
1218}
1219
1220template<class _Tp>
1221inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1222bool
1223operator>(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPTnoexcept
1224{
1225 return nullptr < __x;
1226}
1227
1228template<class _Tp>
1229inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1230bool
1231operator>(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPTnoexcept
1232{
1233 return __x < nullptr;
1234}
1235
1236template<class _Tp>
1237inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1238bool
1239operator<=(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPTnoexcept
1240{
1241 return !(nullptr < __x);
1242}
1243
1244template<class _Tp>
1245inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1246bool
1247operator<=(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPTnoexcept
1248{
1249 return !(__x < nullptr);
1250}
1251
1252template<class _Tp>
1253inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1254bool
1255operator>=(const shared_ptr<_Tp>& __x, nullptr_t) _NOEXCEPTnoexcept
1256{
1257 return !(__x < nullptr);
1258}
1259
1260template<class _Tp>
1261inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1262bool
1263operator>=(nullptr_t, const shared_ptr<_Tp>& __x) _NOEXCEPTnoexcept
1264{
1265 return !(nullptr < __x);
1266}
1267
1268template<class _Tp>
1269inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1270void
1271swap(shared_ptr<_Tp>& __x, shared_ptr<_Tp>& __y) _NOEXCEPTnoexcept
1272{
1273 __x.swap(__y);
1274}
1275
1276template<class _Tp, class _Up>
1277inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1278shared_ptr<_Tp>
1279static_pointer_cast(const shared_ptr<_Up>& __r) _NOEXCEPTnoexcept
1280{
1281 return shared_ptr<_Tp>(__r,
1282 static_cast<
1283 typename shared_ptr<_Tp>::element_type*>(__r.get()));
1284}
1285
1286template<class _Tp, class _Up>
1287inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1288shared_ptr<_Tp>
1289dynamic_pointer_cast(const shared_ptr<_Up>& __r) _NOEXCEPTnoexcept
1290{
1291 typedef typename shared_ptr<_Tp>::element_type _ET;
1292 _ET* __p = dynamic_cast<_ET*>(__r.get());
1293 return __p ? shared_ptr<_Tp>(__r, __p) : shared_ptr<_Tp>();
1294}
1295
1296template<class _Tp, class _Up>
1297shared_ptr<_Tp>
1298const_pointer_cast(const shared_ptr<_Up>& __r) _NOEXCEPTnoexcept
1299{
1300 typedef typename shared_ptr<_Tp>::element_type _RTp;
1301 return shared_ptr<_Tp>(__r, const_cast<_RTp*>(__r.get()));
1302}
1303
1304template<class _Tp, class _Up>
1305shared_ptr<_Tp>
1306reinterpret_pointer_cast(const shared_ptr<_Up>& __r) _NOEXCEPTnoexcept
1307{
1308 return shared_ptr<_Tp>(__r,
1309 reinterpret_cast<
1310 typename shared_ptr<_Tp>::element_type*>(__r.get()));
1311}
1312
1313#ifndef _LIBCPP_NO_RTTI
1314
1315template<class _Dp, class _Tp>
1316inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1317_Dp*
1318get_deleter(const shared_ptr<_Tp>& __p) _NOEXCEPTnoexcept
1319{
1320 return __p.template __get_deleter<_Dp>();
1321}
1322
1323#endif // _LIBCPP_NO_RTTI
1324
1325template<class _Tp>
1326class _LIBCPP_SHARED_PTR_TRIVIAL_ABI _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) weak_ptr
1327{
1328public:
1329 typedef _Tp element_type;
1330private:
1331 element_type* __ptr_;
1332 __shared_weak_count* __cntrl_;
1333
1334public:
1335 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1336 _LIBCPP_CONSTEXPRconstexpr weak_ptr() _NOEXCEPTnoexcept;
1337 template<class _Yp> _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
weak_ptr(shared_ptr<_Yp> const& __r,
1338 typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type = 0)
1339 _NOEXCEPTnoexcept;
1340 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1341 weak_ptr(weak_ptr const& __r) _NOEXCEPTnoexcept;
1342 template<class _Yp> _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
weak_ptr(weak_ptr<_Yp> const& __r,
1343 typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type = 0)
1344 _NOEXCEPTnoexcept;
1345
1346 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1347 weak_ptr(weak_ptr&& __r) _NOEXCEPTnoexcept;
1348 template<class _Yp> _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
weak_ptr(weak_ptr<_Yp>&& __r,
1349 typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type = 0)
1350 _NOEXCEPTnoexcept;
1351 ~weak_ptr();
1352
1353 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1354 weak_ptr& operator=(weak_ptr const& __r) _NOEXCEPTnoexcept;
1355 template<class _Yp>
1356 typename enable_if
1357 <
1358 is_convertible<_Yp*, element_type*>::value,
1359 weak_ptr&
1360 >::type
1361 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1362 operator=(weak_ptr<_Yp> const& __r) _NOEXCEPTnoexcept;
1363
1364 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1365 weak_ptr& operator=(weak_ptr&& __r) _NOEXCEPTnoexcept;
1366 template<class _Yp>
1367 typename enable_if
1368 <
1369 is_convertible<_Yp*, element_type*>::value,
1370 weak_ptr&
1371 >::type
1372 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1373 operator=(weak_ptr<_Yp>&& __r) _NOEXCEPTnoexcept;
1374
1375 template<class _Yp>
1376 typename enable_if
1377 <
1378 is_convertible<_Yp*, element_type*>::value,
1379 weak_ptr&
1380 >::type
1381 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1382 operator=(shared_ptr<_Yp> const& __r) _NOEXCEPTnoexcept;
1383
1384 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1385 void swap(weak_ptr& __r) _NOEXCEPTnoexcept;
1386 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1387 void reset() _NOEXCEPTnoexcept;
1388
1389 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1390 long use_count() const _NOEXCEPTnoexcept
1391 {return __cntrl_ ? __cntrl_->use_count() : 0;}
1392 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1393 bool expired() const _NOEXCEPTnoexcept
1394 {return __cntrl_ == nullptr || __cntrl_->use_count() == 0;}
1395 shared_ptr<_Tp> lock() const _NOEXCEPTnoexcept;
1396 template<class _Up>
1397 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1398 bool owner_before(const shared_ptr<_Up>& __r) const _NOEXCEPTnoexcept
1399 {return __cntrl_ < __r.__cntrl_;}
1400 template<class _Up>
1401 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1402 bool owner_before(const weak_ptr<_Up>& __r) const _NOEXCEPTnoexcept
1403 {return __cntrl_ < __r.__cntrl_;}
1404
1405 template <class _Up> friend class _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) weak_ptr;
1406 template <class _Up> friend class _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) shared_ptr;
1407};
1408
1409#ifndef _LIBCPP_HAS_NO_DEDUCTION_GUIDES
1410template<class _Tp>
1411weak_ptr(shared_ptr<_Tp>) -> weak_ptr<_Tp>;
1412#endif
1413
1414template<class _Tp>
1415inline
1416_LIBCPP_CONSTEXPRconstexpr
1417weak_ptr<_Tp>::weak_ptr() _NOEXCEPTnoexcept
1418 : __ptr_(nullptr),
1419 __cntrl_(nullptr)
1420{
1421}
1422
1423template<class _Tp>
1424inline
1425weak_ptr<_Tp>::weak_ptr(weak_ptr const& __r) _NOEXCEPTnoexcept
1426 : __ptr_(__r.__ptr_),
1427 __cntrl_(__r.__cntrl_)
1428{
1429 if (__cntrl_)
1430 __cntrl_->__add_weak();
1431}
1432
1433template<class _Tp>
1434template<class _Yp>
1435inline
1436weak_ptr<_Tp>::weak_ptr(shared_ptr<_Yp> const& __r,
1437 typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type)
1438 _NOEXCEPTnoexcept
1439 : __ptr_(__r.__ptr_),
1440 __cntrl_(__r.__cntrl_)
1441{
1442 if (__cntrl_)
1443 __cntrl_->__add_weak();
1444}
1445
1446template<class _Tp>
1447template<class _Yp>
1448inline
1449weak_ptr<_Tp>::weak_ptr(weak_ptr<_Yp> const& __r,
1450 typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type)
1451 _NOEXCEPTnoexcept
1452 : __ptr_(__r.__ptr_),
1453 __cntrl_(__r.__cntrl_)
1454{
1455 if (__cntrl_)
1456 __cntrl_->__add_weak();
1457}
1458
1459template<class _Tp>
1460inline
1461weak_ptr<_Tp>::weak_ptr(weak_ptr&& __r) _NOEXCEPTnoexcept
1462 : __ptr_(__r.__ptr_),
1463 __cntrl_(__r.__cntrl_)
1464{
1465 __r.__ptr_ = nullptr;
1466 __r.__cntrl_ = nullptr;
1467}
1468
1469template<class _Tp>
1470template<class _Yp>
1471inline
1472weak_ptr<_Tp>::weak_ptr(weak_ptr<_Yp>&& __r,
1473 typename enable_if<is_convertible<_Yp*, _Tp*>::value, __nat*>::type)
1474 _NOEXCEPTnoexcept
1475 : __ptr_(__r.__ptr_),
1476 __cntrl_(__r.__cntrl_)
1477{
1478 __r.__ptr_ = nullptr;
1479 __r.__cntrl_ = nullptr;
1480}
1481
1482template<class _Tp>
1483weak_ptr<_Tp>::~weak_ptr()
1484{
1485 if (__cntrl_)
1486 __cntrl_->__release_weak();
1487}
1488
1489template<class _Tp>
1490inline
1491weak_ptr<_Tp>&
1492weak_ptr<_Tp>::operator=(weak_ptr const& __r) _NOEXCEPTnoexcept
1493{
1494 weak_ptr(__r).swap(*this);
1495 return *this;
1496}
1497
1498template<class _Tp>
1499template<class _Yp>
1500inline
1501typename enable_if
1502<
1503 is_convertible<_Yp*, _Tp*>::value,
1504 weak_ptr<_Tp>&
1505>::type
1506weak_ptr<_Tp>::operator=(weak_ptr<_Yp> const& __r) _NOEXCEPTnoexcept
1507{
1508 weak_ptr(__r).swap(*this);
1509 return *this;
1510}
1511
1512template<class _Tp>
1513inline
1514weak_ptr<_Tp>&
1515weak_ptr<_Tp>::operator=(weak_ptr&& __r) _NOEXCEPTnoexcept
1516{
1517 weak_ptr(_VSTDstd::__1::move(__r)).swap(*this);
1518 return *this;
1519}
1520
1521template<class _Tp>
1522template<class _Yp>
1523inline
1524typename enable_if
1525<
1526 is_convertible<_Yp*, _Tp*>::value,
1527 weak_ptr<_Tp>&
1528>::type
1529weak_ptr<_Tp>::operator=(weak_ptr<_Yp>&& __r) _NOEXCEPTnoexcept
1530{
1531 weak_ptr(_VSTDstd::__1::move(__r)).swap(*this);
1532 return *this;
1533}
1534
1535template<class _Tp>
1536template<class _Yp>
1537inline
1538typename enable_if
1539<
1540 is_convertible<_Yp*, _Tp*>::value,
1541 weak_ptr<_Tp>&
1542>::type
1543weak_ptr<_Tp>::operator=(shared_ptr<_Yp> const& __r) _NOEXCEPTnoexcept
1544{
1545 weak_ptr(__r).swap(*this);
1546 return *this;
1547}
1548
1549template<class _Tp>
1550inline
1551void
1552weak_ptr<_Tp>::swap(weak_ptr& __r) _NOEXCEPTnoexcept
1553{
1554 _VSTDstd::__1::swap(__ptr_, __r.__ptr_);
1555 _VSTDstd::__1::swap(__cntrl_, __r.__cntrl_);
1556}
1557
1558template<class _Tp>
1559inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1560void
1561swap(weak_ptr<_Tp>& __x, weak_ptr<_Tp>& __y) _NOEXCEPTnoexcept
1562{
1563 __x.swap(__y);
1564}
1565
1566template<class _Tp>
1567inline
1568void
1569weak_ptr<_Tp>::reset() _NOEXCEPTnoexcept
1570{
1571 weak_ptr().swap(*this);
1572}
1573
1574template<class _Tp>
1575template<class _Yp>
1576shared_ptr<_Tp>::shared_ptr(const weak_ptr<_Yp>& __r,
1577 typename enable_if<is_convertible<_Yp*, element_type*>::value, __nat>::type)
1578 : __ptr_(__r.__ptr_),
1579 __cntrl_(__r.__cntrl_ ? __r.__cntrl_->lock() : __r.__cntrl_)
1580{
1581 if (__cntrl_ == nullptr)
1582 __throw_bad_weak_ptr();
1583}
1584
1585template<class _Tp>
1586shared_ptr<_Tp>
1587weak_ptr<_Tp>::lock() const _NOEXCEPTnoexcept
1588{
1589 shared_ptr<_Tp> __r;
1590 __r.__cntrl_ = __cntrl_ ? __cntrl_->lock() : __cntrl_;
1591 if (__r.__cntrl_)
1592 __r.__ptr_ = __ptr_;
1593 return __r;
1594}
1595
1596#if _LIBCPP_STD_VER14 > 14
1597template <class _Tp = void> struct owner_less;
1598#else
1599template <class _Tp> struct owner_less;
1600#endif
1601
1602
1603_LIBCPP_SUPPRESS_DEPRECATED_PUSHGCC diagnostic push GCC diagnostic ignored "-Wdeprecated" GCC
diagnostic ignored "-Wdeprecated-declarations"
1604template <class _Tp>
1605struct _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) owner_less<shared_ptr<_Tp> >
1606#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
1607 : binary_function<shared_ptr<_Tp>, shared_ptr<_Tp>, bool>
1608#endif
1609{
1610_LIBCPP_SUPPRESS_DEPRECATED_POPGCC diagnostic pop
1611#if _LIBCPP_STD_VER14 <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
1612 _LIBCPP_DEPRECATED_IN_CXX17 typedef bool result_type;
1613 _LIBCPP_DEPRECATED_IN_CXX17 typedef shared_ptr<_Tp> first_argument_type;
1614 _LIBCPP_DEPRECATED_IN_CXX17 typedef shared_ptr<_Tp> second_argument_type;
1615#endif
1616 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1617 bool operator()(shared_ptr<_Tp> const& __x, shared_ptr<_Tp> const& __y) const _NOEXCEPTnoexcept
1618 {return __x.owner_before(__y);}
1619 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1620 bool operator()(shared_ptr<_Tp> const& __x, weak_ptr<_Tp> const& __y) const _NOEXCEPTnoexcept
1621 {return __x.owner_before(__y);}
1622 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1623 bool operator()( weak_ptr<_Tp> const& __x, shared_ptr<_Tp> const& __y) const _NOEXCEPTnoexcept
1624 {return __x.owner_before(__y);}
1625};
1626
1627_LIBCPP_SUPPRESS_DEPRECATED_PUSHGCC diagnostic push GCC diagnostic ignored "-Wdeprecated" GCC
diagnostic ignored "-Wdeprecated-declarations"
1628template <class _Tp>
1629struct _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) owner_less<weak_ptr<_Tp> >
1630#if !defined(_LIBCPP_ABI_NO_BINDER_BASES)
1631 : binary_function<weak_ptr<_Tp>, weak_ptr<_Tp>, bool>
1632#endif
1633{
1634_LIBCPP_SUPPRESS_DEPRECATED_POPGCC diagnostic pop
1635#if _LIBCPP_STD_VER14 <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
1636 _LIBCPP_DEPRECATED_IN_CXX17 typedef bool result_type;
1637 _LIBCPP_DEPRECATED_IN_CXX17 typedef weak_ptr<_Tp> first_argument_type;
1638 _LIBCPP_DEPRECATED_IN_CXX17 typedef weak_ptr<_Tp> second_argument_type;
1639#endif
1640 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1641 bool operator()( weak_ptr<_Tp> const& __x, weak_ptr<_Tp> const& __y) const _NOEXCEPTnoexcept
1642 {return __x.owner_before(__y);}
1643 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1644 bool operator()(shared_ptr<_Tp> const& __x, weak_ptr<_Tp> const& __y) const _NOEXCEPTnoexcept
1645 {return __x.owner_before(__y);}
1646 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1647 bool operator()( weak_ptr<_Tp> const& __x, shared_ptr<_Tp> const& __y) const _NOEXCEPTnoexcept
1648 {return __x.owner_before(__y);}
1649};
1650
1651#if _LIBCPP_STD_VER14 > 14
1652template <>
1653struct _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) owner_less<void>
1654{
1655 template <class _Tp, class _Up>
1656 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1657 bool operator()( shared_ptr<_Tp> const& __x, shared_ptr<_Up> const& __y) const _NOEXCEPTnoexcept
1658 {return __x.owner_before(__y);}
1659 template <class _Tp, class _Up>
1660 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1661 bool operator()( shared_ptr<_Tp> const& __x, weak_ptr<_Up> const& __y) const _NOEXCEPTnoexcept
1662 {return __x.owner_before(__y);}
1663 template <class _Tp, class _Up>
1664 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1665 bool operator()( weak_ptr<_Tp> const& __x, shared_ptr<_Up> const& __y) const _NOEXCEPTnoexcept
1666 {return __x.owner_before(__y);}
1667 template <class _Tp, class _Up>
1668 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1669 bool operator()( weak_ptr<_Tp> const& __x, weak_ptr<_Up> const& __y) const _NOEXCEPTnoexcept
1670 {return __x.owner_before(__y);}
1671 typedef void is_transparent;
1672};
1673#endif
1674
1675template<class _Tp>
1676class _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) enable_shared_from_this
1677{
1678 mutable weak_ptr<_Tp> __weak_this_;
1679protected:
1680 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
_LIBCPP_CONSTEXPRconstexpr
1681 enable_shared_from_this() _NOEXCEPTnoexcept {}
1682 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1683 enable_shared_from_this(enable_shared_from_this const&) _NOEXCEPTnoexcept {}
1684 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1685 enable_shared_from_this& operator=(enable_shared_from_this const&) _NOEXCEPTnoexcept
1686 {return *this;}
1687 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1688 ~enable_shared_from_this() {}
1689public:
1690 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1691 shared_ptr<_Tp> shared_from_this()
1692 {return shared_ptr<_Tp>(__weak_this_);}
1693 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1694 shared_ptr<_Tp const> shared_from_this() const
1695 {return shared_ptr<const _Tp>(__weak_this_);}
1696
1697#if _LIBCPP_STD_VER14 > 14
1698 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1699 weak_ptr<_Tp> weak_from_this() _NOEXCEPTnoexcept
1700 { return __weak_this_; }
1701
1702 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1703 weak_ptr<const _Tp> weak_from_this() const _NOEXCEPTnoexcept
1704 { return __weak_this_; }
1705#endif // _LIBCPP_STD_VER > 14
1706
1707 template <class _Up> friend class shared_ptr;
1708};
1709
1710template <class _Tp> struct _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) hash;
1711
1712template <class _Tp>
1713struct _LIBCPP_TEMPLATE_VIS__attribute__ ((__type_visibility__("default"))) hash<shared_ptr<_Tp> >
1714{
1715#if _LIBCPP_STD_VER14 <= 17 || defined(_LIBCPP_ENABLE_CXX20_REMOVED_BINDER_TYPEDEFS)
1716 _LIBCPP_DEPRECATED_IN_CXX17 typedef shared_ptr<_Tp> argument_type;
1717 _LIBCPP_DEPRECATED_IN_CXX17 typedef size_t result_type;
1718#endif
1719
1720 _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1721 size_t operator()(const shared_ptr<_Tp>& __ptr) const _NOEXCEPTnoexcept
1722 {
1723 return hash<typename shared_ptr<_Tp>::element_type*>()(__ptr.get());
1724 }
1725};
1726
1727template<class _CharT, class _Traits, class _Yp>
1728inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1729basic_ostream<_CharT, _Traits>&
1730operator<<(basic_ostream<_CharT, _Traits>& __os, shared_ptr<_Yp> const& __p);
1731
1732
1733#if !defined(_LIBCPP_HAS_NO_ATOMIC_HEADER)
1734
1735class _LIBCPP_TYPE_VIS__attribute__ ((__visibility__("default"))) __sp_mut
1736{
1737 void* __lx;
1738public:
1739 void lock() _NOEXCEPTnoexcept;
1740 void unlock() _NOEXCEPTnoexcept;
1741
1742private:
1743 _LIBCPP_CONSTEXPRconstexpr __sp_mut(void*) _NOEXCEPTnoexcept;
1744 __sp_mut(const __sp_mut&);
1745 __sp_mut& operator=(const __sp_mut&);
1746
1747 friend _LIBCPP_FUNC_VIS__attribute__ ((__visibility__("default"))) __sp_mut& __get_sp_mut(const void*);
1748};
1749
1750_LIBCPP_FUNC_VIS__attribute__ ((__visibility__("default"))) _LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1751__sp_mut& __get_sp_mut(const void*);
1752
1753template <class _Tp>
1754inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1755bool
1756atomic_is_lock_free(const shared_ptr<_Tp>*)
1757{
1758 return false;
1759}
1760
1761template <class _Tp>
1762_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1763shared_ptr<_Tp>
1764atomic_load(const shared_ptr<_Tp>* __p)
1765{
1766 __sp_mut& __m = __get_sp_mut(__p);
1767 __m.lock();
1768 shared_ptr<_Tp> __q = *__p;
1769 __m.unlock();
1770 return __q;
1771}
1772
1773template <class _Tp>
1774inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1775_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1776shared_ptr<_Tp>
1777atomic_load_explicit(const shared_ptr<_Tp>* __p, memory_order)
1778{
1779 return atomic_load(__p);
1780}
1781
1782template <class _Tp>
1783_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1784void
1785atomic_store(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r)
1786{
1787 __sp_mut& __m = __get_sp_mut(__p);
1788 __m.lock();
1789 __p->swap(__r);
1790 __m.unlock();
1791}
1792
1793template <class _Tp>
1794inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1795_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1796void
1797atomic_store_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r, memory_order)
1798{
1799 atomic_store(__p, __r);
1800}
1801
1802template <class _Tp>
1803_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1804shared_ptr<_Tp>
1805atomic_exchange(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r)
1806{
1807 __sp_mut& __m = __get_sp_mut(__p);
1808 __m.lock();
1809 __p->swap(__r);
1810 __m.unlock();
1811 return __r;
1812}
1813
1814template <class _Tp>
1815inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1816_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1817shared_ptr<_Tp>
1818atomic_exchange_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp> __r, memory_order)
1819{
1820 return atomic_exchange(__p, __r);
1821}
1822
1823template <class _Tp>
1824_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1825bool
1826atomic_compare_exchange_strong(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v, shared_ptr<_Tp> __w)
1827{
1828 shared_ptr<_Tp> __temp;
1829 __sp_mut& __m = __get_sp_mut(__p);
1830 __m.lock();
1831 if (__p->__owner_equivalent(*__v))
1832 {
1833 _VSTDstd::__1::swap(__temp, *__p);
1834 *__p = __w;
1835 __m.unlock();
1836 return true;
1837 }
1838 _VSTDstd::__1::swap(__temp, *__v);
1839 *__v = *__p;
1840 __m.unlock();
1841 return false;
1842}
1843
1844template <class _Tp>
1845inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1846_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1847bool
1848atomic_compare_exchange_weak(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v, shared_ptr<_Tp> __w)
1849{
1850 return atomic_compare_exchange_strong(__p, __v, __w);
1851}
1852
1853template <class _Tp>
1854inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1855_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1856bool
1857atomic_compare_exchange_strong_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v,
1858 shared_ptr<_Tp> __w, memory_order, memory_order)
1859{
1860 return atomic_compare_exchange_strong(__p, __v, __w);
1861}
1862
1863template <class _Tp>
1864inline _LIBCPP_INLINE_VISIBILITY__attribute__ ((__visibility__("hidden"))) __attribute__ ((__exclude_from_explicit_instantiation__
))
1865_LIBCPP_AVAILABILITY_ATOMIC_SHARED_PTR
1866bool
1867atomic_compare_exchange_weak_explicit(shared_ptr<_Tp>* __p, shared_ptr<_Tp>* __v,
1868 shared_ptr<_Tp> __w, memory_order, memory_order)
1869{
1870 return atomic_compare_exchange_weak(__p, __v, __w);
1871}
1872
1873#endif // !defined(_LIBCPP_HAS_NO_ATOMIC_HEADER)
1874
1875_LIBCPP_END_NAMESPACE_STD} }
1876
1877_LIBCPP_POP_MACROSpop_macro("min") pop_macro("max")
1878
1879#endif // _LIBCPP___MEMORY_SHARED_PTR_H